fern-api 3.37.3 → 3.37.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/cli.cjs +6 -6
  2. package/package.json +1 -1
package/cli.cjs CHANGED
@@ -1145,7 +1145,7 @@ ${TI_.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&ZPc(th
1145
1145
  `+o_n.default.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?o_n.default.cyan(WI_(t,this.opt.mask)):o_n.default.italic(o_n.default.dim("[hidden]")):this.opt.mask?WI_(t,this.opt.mask):o_n.default.italic(o_n.default.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 KHo=ce(GT(),1);var WC_=ce(qjc(),1),HHo=require("child_process"),x2n=require("fs"),GHo=ce(require("path"),1),GC_=ce(require("os"),1),HC_=require("crypto"),b0c=ce(LC_(),1);var LHo=class extends Error{originalError;constructor(t){super(`Failed to create temporary file. ${t.message}`),this.originalError=t}};var vWa=class extends Error{originalError;constructor(t){super(`Failed to launch editor. ${t.message}`),this.originalError=t}};var VHo=class extends Error{originalError;constructor(t){super(`Failed to read temporary file. ${t.message}`),this.originalError=t}};var WHo=class extends Error{originalError;constructor(t){super(`Failed to remove temporary file. ${t.message}`),this.originalError=t}};function xHo(e="",t,r){let i=new v0c(e,r);i.runAsync((n,a)=>{if(n)setImmediate(t,n,void 0);else try{i.cleanup(),setImmediate(t,void 0,a)}catch(o){setImmediate(t,o,void 0)}})}function VC_(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}function IxM(e){let t=[],r="";for(let i=0;i<e.length;i++){let n=e.charAt(i);i>0&&n===" "&&e[i-1]!=="\\"&&r.length>0?(t.push(r),r=""):r=`${r}${n}`}return r.length>0&&t.push(r),t}var v0c=class{text="";tempFile;editor;lastExitStatus=0;fileOptions={};get temp_file(){return console.log("DEPRECATED: temp_file. Use tempFile moving forward."),this.tempFile}get last_exit_status(){return console.log("DEPRECATED: last_exit_status. Use lastExitStatus moving forward."),this.lastExitStatus}constructor(t="",r){this.text=t,r&&(this.fileOptions=r),this.determineEditor(),this.createTemporaryFile()}run(){return this.launchEditor(),this.readTemporaryFile(),this.text}runAsync(t){try{this.launchEditorAsync(()=>{try{this.readTemporaryFile(),setImmediate(t,void 0,this.text)}catch(r){setImmediate(t,r,void 0)}})}catch(r){setImmediate(t,r,void 0)}}cleanup(){this.removeTemporaryFile()}determineEditor(){let t=process.env.VISUAL?process.env.VISUAL:process.env.EDITOR?process.env.EDITOR:process.platform.startsWith("win")?"notepad":"vim",r=IxM(t).map(n=>n.replace("\\ "," ")),i=r.shift();this.editor={args:r,bin:i}}createTemporaryFile(){try{let t=this.fileOptions.dir??GC_.default.tmpdir(),r=(0,HC_.randomUUID)(),i=VC_(this.fileOptions.prefix),n=VC_(this.fileOptions.postfix),a=`${i}${r}${n}`,o=GHo.default.resolve(t,a),c=GHo.default.resolve(t)+GHo.default.sep;if(!o.startsWith(c))throw new Error("Resolved temporary file escaped the base directory");this.tempFile=o;let d={encoding:"utf8",flag:"wx"};Object.prototype.hasOwnProperty.call(this.fileOptions,"mode")&&(d.mode=this.fileOptions.mode),(0,x2n.writeFileSync)(this.tempFile,this.text,d)}catch(t){throw new LHo(t)}}readTemporaryFile(){try{let t=(0,x2n.readFileSync)(this.tempFile);if(t.length===0)this.text="";else{let r=(0,WC_.detect)(t)??"utf8";b0c.default.encodingExists(r)||(r="utf8"),this.text=b0c.default.decode(t,r)}}catch(t){throw new VHo(t)}}removeTemporaryFile(){try{(0,x2n.unlinkSync)(this.tempFile)}catch(t){throw new WHo(t)}}launchEditor(){try{let t=(0,HHo.spawnSync)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"});this.lastExitStatus=t.status??0}catch(t){throw new vWa(t)}}launchEditorAsync(t){try{(0,HHo.spawn)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"}).on("exit",i=>{this.lastExitStatus=i,setImmediate(t)})}catch(r){throw new vWa(r)}}};var xC_=ce(Wbe(),1);var gWa=class extends HT{_run(t){this.done=t,this.editorResult=new xC_.Subject;let r=E4(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"?KHo.default.dim("Received"):KHo.default.dim("Press <enter> to launch your preferred editor."),t&&(r=KHo.default.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),xHo(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 XC_=require("stream");var $C_=ce(require("readline"),1),YC_=ce(JC_(),1),l_n=class{constructor(t){this.rl||=$C_.default.createInterface(qxM(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 qxM(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 YC_.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var OWa=class extends l_n{constructor(t={}){super(t),this.log=new XC_.Writable({write:(r,i,n)=>{this.writeLog(r),n()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return iWa(this.rl,this.bottomBar.split(`
1146
1146
  `).length),this}updateBottomBar(t){return iWa(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+`
1147
1147
  `}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&&hHo(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var WO=ce(Wbe(),1),eq_=ce(j8a(),1);var JHo=ce(Wbe(),1),ZC_=ce(j8a(),1),$Ho=function(e,t,r){return typeof e[t]!="function"?(0,JHo.of)(e):(0,JHo.from)((0,ZC_.default)(e[t])(r).then(i=>(e[t]=i,e)))};var kC_={set:(e,t="",r)=>{let i=e;t.split(".").forEach((n,a,o)=>{n==="__proto__"||n==="constructor"||(a===o.length-1?i[n]=r:(!(n in i)||typeof i[n]!="object")&&(i[n]={}),i=i[n])})},get:(e,t="",r)=>{let i=a=>String.prototype.split.call(t,a).filter(Boolean).reduce((o,c)=>o!=null?o[c]:o,e),n=i(/[,[\]]+?/)||i(/[,.[\]]+?/);return n===void 0||n===e?r:n}},K2n=class extends l_n{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=typeof r=="object"?{...r}:{};let i;return Array.isArray(t)?i=(0,WO.from)(t):(0,WO.isObservable)(t)?i=t:Object.values(t).every(n=>typeof n=="object"&&!Array.isArray(n)&&n!=null)?i=(0,WO.from)(Object.entries(t).map(([n,a])=>({name:n,...a}))):i=(0,WO.from)([t]),this.process=i.pipe((0,WO.concatMap)(this.processQuestion.bind(this)),(0,WO.publish)()),this.process.connect(),this.process.pipe((0,WO.reduce)((n,a)=>(kC_.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,WO.defer)(()=>(0,WO.of)(t).pipe((0,WO.concatMap)(this.setDefaultType.bind(this)),(0,WO.concatMap)(this.filterIfRunnable.bind(this)),(0,WO.concatMap)(()=>$Ho(t,"message",this.answers)),(0,WO.concatMap)(()=>$Ho(t,"default",this.answers)),(0,WO.concatMap)(()=>$Ho(t,"choices",this.answers)),(0,WO.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,WO.defer)(()=>(0,WO.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,WO.defer)(()=>(0,WO.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&kC_.get(this.answers,t.name)!==void 0)return WO.EMPTY;if(t.when===!1)return WO.EMPTY;if(typeof t.when!="function")return(0,WO.of)(t);let{answers:r}=this;return(0,WO.defer)(()=>(0,WO.from)((0,eq_.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,WO.filter)(i=>i!=null)))}};function tq_(e){let t=function(r,i){let n;try{n=new K2n(t.prompts,e)}catch(o){return Promise.reject(o)}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",aWa),this.registerPrompt("input",a_n),this.registerPrompt("number",oWa),this.registerPrompt("confirm",uWa),this.registerPrompt("rawlist",sWa),this.registerPrompt("expand",cWa),this.registerPrompt("checkbox",lWa),this.registerPrompt("password",fWa),this.registerPrompt("editor",gWa)},t.restoreDefaultPrompts(),t}var O0c=tq_();function RxM(e,t){O0c.registerPrompt(e,t)}function zxM(){O0c.restoreDefaultPrompts()}var NxM={prompt:O0c,ui:{BottomBar:OWa,Prompt:K2n},createPromptModule:tq_,registerPrompt:RxM,restoreDefaultPrompts:zxM,Separator:kJ},YHo=NxM;var J2n=require("path");function iq_(){let e=FxM();return async t=>{for(let r of t)r.module=e(r.filename);return t}}function FxM(e=process.argv[1]?(0,J2n.dirname)(process.argv[1]):process.cwd(),t=J2n.sep==="\\"){let r=t?rq_(e):e;return i=>{if(!i)return;let n=t?rq_(i):i,{dir:a,base:o,ext:c}=J2n.posix.parse(n);(c===".js"||c===".mjs"||c===".cjs")&&(o=o.slice(0,-1*c.length));let d=decodeURIComponent(o);a||(a=".");let s=a.lastIndexOf("/node_modules");if(s>-1)return`${a.slice(s+14).replace(/\//g,".")}:${d}`;if(a.startsWith(r)){let u=a.slice(r.length+1).replace(/\//g,".");return u?`${u}:${d}`:d}return d}}function rq_(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var A0c=e=>{if("flags"in e){let t=nq_(e.flags),r=aq_(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([n,a])=>[n,oq_(a)])),i=Object.fromEntries(Object.entries(t).map(([n,a])=>[n,QxM(n,a,r[n])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}};function QxM(e,t,r){return{key:e,enabled:typeof t=="string"?!0:t,variant:typeof t=="string"?t:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:r?JSON.stringify(r):void 0,description:void 0}}}var nq_=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,f_n(r)]).filter(([,t])=>t!==void 0)),aq_=e=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter(r=>{let i=t[r];return i.enabled&&i.metadata&&i.metadata.payload!==void 0}).map(r=>{let i=t[r].metadata?.payload;return[r,i?oq_(i):void 0]}))};var f_n=e=>e===void 0?void 0:e.variant??e.enabled,oq_=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var XHo="0123456789abcdef",ZHo=class e{constructor(t){this.bytes=t}static ofInner(t){if(t.length===16)return new e(t);throw new TypeError("not 128-bit length")}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/256,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;default: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)}throw new SyntaxError("could not parse UUID string")}toString(){let t="";for(let r=0;r<this.bytes.length;r++)t+=XHo.charAt(this.bytes[r]>>>4),t+=XHo.charAt(15&this.bytes[r]),(r===3||r===5||r===7||r===9)&&(t+="-");return t}toHex(){let t="";for(let r=0;r<this.bytes.length;r++)t+=XHo.charAt(this.bytes[r]>>>4),t+=XHo.charAt(15&this.bytes[r]);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}},m0c=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??UxM()}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))return;this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter())}return ZHo.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}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,ZHo.ofInner(t)}},UxM=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),uq_,CJt=()=>LxM().toString(),LxM=()=>(uq_||(uq_=new m0c)).generate();var VxM=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],sq_=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return VxM.concat(t).some(i=>{let n=i.toLowerCase();return r.indexOf(n)!==-1})};var t$=(function(e){return e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.FeatureFlagDetails="feature_flag_details",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",e.BootstrapFeatureFlags="bootstrap_feature_flags",e.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionStartTimestamp="session_start_timestamp",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",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e})({});var GxM=Array.isArray,cq_=Object.prototype,pO9=cq_.hasOwnProperty,P0c=cq_.toString,lq_=GxM||function(e){return P0c.call(e)==="[object Array]"};var $2n=e=>e===void 0,AWa=e=>P0c.call(e)=="[object String]",fq_=e=>AWa(e)&&e.trim().length===0;var dq_=e=>P0c.call(e)=="[object Number]";var j0c=e=>e instanceof Error;function HxM(e,t){try{return e instanceof t}catch{return!1}}function mWa(e){return e===null||typeof e!="object"}function d_n(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function pq_(e){return d_n(e,"ErrorEvent")}function kHo(e){return!$2n(Event)&&HxM(e,Event)}function _q_(e){return d_n(e,"Object")}function PWa(e,t,r,i,n){return t>r&&(i.warn("min cannot be greater than max."),t=r),dq_(e)?e>r?(i.warn(" cannot be greater than max: "+r+". Using max value instead."),r):e<t?(i.warn(" cannot be less than min: "+t+". Using min value instead."),t):e:(i.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+n),PWa(n||r,t,r,i))}var xxM=864e5,e7o=class{constructor(t){this._buckets={},this._onBucketRateLimited=t._onBucketRateLimited,this._bucketSize=PWa(t.bucketSize,0,100,t._logger),this._refillRate=PWa(t.refillRate,0,this._bucketSize,t._logger),this._refillInterval=PWa(t.refillInterval,0,xxM,t._logger)}_applyRefill(t,r){let i=r-t.lastAccess,n=Math.floor(i/this._refillInterval);if(n>0){let a=n*this._refillRate;t.tokens=Math.min(t.tokens+a,this._bucketSize),t.lastAccess=t.lastAccess+n*this._refillInterval}}consumeRateLimit(t){let r=Date.now(),i=String(t),n=this._buckets[i];return n?this._applyRefill(n,r):(n={tokens:this._bucketSize,lastAccess:r},this._buckets[i]=n),n.tokens===0?!0:(n.tokens--,n.tokens===0&&this._onBucketRateLimited?.(t),n.tokens===0)}stop(){this._buckets={}}};var t7o=class{add(t){let r=CJt();return this.promiseByIds[r]=t,t.catch(()=>{}).finally(()=>{delete this.promiseByIds[r]}),t}async join(){let t=Object.values(this.promiseByIds),r=t.length;for(;r>0;)await Promise.all(t),t=Object.values(this.promiseByIds),r=t.length}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={}}};function KxM(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var hq_=(e,t,r)=>{function i(a,...o){t(()=>{let c=r[a];c(e,...o)})}return{info:(...a)=>{i("log",...a)},warn:(...a)=>{i("warn",...a)},error:(...a)=>{i("error",...a)},critical:(...a)=>{r.error(e,...a)},createLogger:a=>hq_(`${e} ${a}`,t,r)}},JxM=e=>e();function yq_(e,t=JxM){return hq_(e,t,KxM())}var X2n="Mobile",i7o="iOS",Y2n="Android",bq_="Tablet",wO9=Y2n+" "+bq_;var $xM="Apple",EO9=$xM+" Watch",vq_="Safari",n7o="BlackBerry",gq_="Samsung",YxM=gq_+"Browser",XxM=gq_+" Internet",a7o="Chrome",ZxM=a7o+" OS",kxM=a7o+" "+i7o,Oq_="Internet Explorer",eKM=Oq_+" "+X2n,E0c="Opera",SO9=E0c+" Mini",Aq_="Edge",tKM="Microsoft "+Aq_,S0c="Firefox",rKM=S0c+" "+i7o,M0c="Nintendo",D0c="PlayStation",r7o="Xbox",iKM=Y2n+" "+X2n,nKM=X2n+" "+vq_,jWa="Windows",aKM=jWa+" Phone";var mq_="Generic",MO9=mq_+" "+X2n.toLowerCase(),DO9=mq_+" "+bq_.toLowerCase(),oKM="Konqueror",vG="(\\d+(\\.\\d+)?)",w0c=new RegExp("Version/"+vG),BO9=new RegExp(r7o,"i"),IO9=new RegExp(D0c+" \\w+","i"),CO9=new RegExp(M0c+" \\w+","i"),uKM=new RegExp(n7o+"|PlayBook|BB10","i"),sKM={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000","5.1":"XP","5.2":"XP","6.0":"Vista","6.1":"7","6.2":"8","6.3":"8.1","6.4":"10","10.0":"10"};var qO9={[eKM]:[new RegExp("rv:"+vG)],[tKM]:[new RegExp(Aq_+"?\\/"+vG)],[a7o]:[new RegExp("("+a7o+"|CrMo)\\/"+vG)],[kxM]:[new RegExp("CriOS\\/"+vG)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+vG)],[vq_]:[w0c],[nKM]:[w0c],[E0c]:[new RegExp("("+E0c+"|OPR)\\/"+vG)],[S0c]:[new RegExp(S0c+"\\/"+vG)],[rKM]:[new RegExp("FxiOS\\/"+vG)],[oKM]:[new RegExp("Konqueror[:/]?"+vG,"i")],[n7o]:[new RegExp(n7o+" "+vG),w0c],[iKM]:[new RegExp("android\\s"+vG,"i")],[XxM]:[new RegExp(YxM+"\\/"+vG)],[Oq_]:[new RegExp("(rv:|MSIE )"+vG)],Mozilla:[new RegExp("rv:"+vG)]};var TO9=[[new RegExp(r7o+"; "+r7o+" (.*?)[);]","i"),e=>[r7o,e&&e[1]||""]],[new RegExp(M0c,"i"),[M0c,""]],[new RegExp(D0c,"i"),[D0c,""]],[uKM,[n7o,""]],[new RegExp(jWa,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[aKM,""];if(new RegExp(X2n).test(t)&&!/IEMobile\b/.test(t))return[jWa+" "+X2n,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let i=r[1],n=sKM[i]||"";return/arm/i.test(t)&&(n="RT"),[jWa,n]}return[jWa,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[i7o,t.join(".")]}return[i7o,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=$2n(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+Y2n+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Y2n+")","i"),e=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[Y2n,t.join(".")]}return[Y2n,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,e=>{let t=["Mac OS X",""];if(e&&e[1]){let r=[e[1],e[2],e[3]||"0"];t[1]=r.join(".")}return t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[ZxM,""]],[/Linux|debian/i,["Linux",""]]];var Pq_="utf8";function jq_(e,t){if(!e||typeof e!="string"||cKM(e))throw new Error(t)}function cKM(e){return e.trim().length===0}function wq_(e){return e?.replace(/\/+$/,"")}async function Eq_(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 o7o(){return new Date().toISOString()}function p_n(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var Sq_=e=>e instanceof Error;function B0c(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var u7o=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)}};function Mq_(){return"CompressionStream"in globalThis}async function I0c(e,t=!0){try{let i=new Blob([e],{type:"text/plain"}).stream().pipeThrough(new CompressionStream("gzip"));return await new Response(i).blob()}catch(r){return t&&console.error("Failed to gzip compress data",r),null}}var Z2n=class extends Error{constructor(t,r){super("HTTP error while fetching PostHog: status="+t.status+", reqByteLength="+r),this.response=t,this.reqByteLength=r,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}},wWa=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function Dq_(e){if(e instanceof Z2n){let t="";try{t=await e.text}catch{}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error("Error while flushing PostHog",e);return Promise.resolve()}function C0c(e){return typeof e=="object"&&(e instanceof Z2n||e instanceof wWa)}function Bq_(e){return typeof e=="object"&&e instanceof Z2n&&e.status===413}var EWa=class{constructor(t,r={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new t7o,this._events=new u7o,this._isInitialized=!1,jq_(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=wq_(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.preloadFeatureFlags=r.preloadFeatureFlags??!0,this.defaultOptIn=r.defaultOptIn??!0,this.disableSurveys=r.disableSurveys??!1,this._retryOptions={retryCount:r.fetchRetryCount??3,retryDelay:r.fetchRetryDelay??3e3,retryCheck:C0c},this.requestTimeout=r.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r.featureFlagsRequestTimeoutMs??3e3,this.remoteConfigRequestTimeoutMs=r.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=r.disableGeoip??!0,this.disabled=r.disabled??!1,this.historicalMigration=r?.historicalMigration??!1,this.evaluationEnvironments=r?.evaluationEnvironments,this._initPromise=Promise.resolve(),this._isInitialized=!0,this._logger=yq_("[PostHog]",this.logMsgIfDebug.bind(this)),this.disableCompression=!Mq_()||(r?.disableCompression??!1)}logMsgIfDebug(t){this.isDebug&&t()}wrap(t){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return t();this._initPromise.then(()=>t())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(t$.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(t$.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(t$.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(i,n)=>this._logger.info(i,n));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(t){return{distinct_id:t.distinct_id,event:t.event,properties:{...t.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(t){return this.promiseQueue.add(t)}identifyStateless(t,r,i){this.wrap(()=>{let n={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",n,i)})}async identifyStatelessImmediate(t,r,i){let n={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};await this.sendImmediate("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)})}async captureStatelessImmediate(t,r,i,n){let a=this.buildPayload({distinct_id:t,event:r,properties:i});await this.sendImmediate("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)})}async aliasStatelessImmediate(t,r,i,n){let a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...i||{},distinct_id:r,alias:t}});await this.sendImmediate("alias",a,n)}groupIdentifyStateless(t,r,i,n,a,o){this.wrap(()=>{let c=this.buildPayload({distinct_id:a||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:i||{},...o||{}}});this.enqueue("capture",c,n)})}async getRemoteConfig(){await this._initPromise;let t=this.host;t==="https://us.i.posthog.com"?t="https://us-assets.i.posthog.com":t==="https://eu.i.posthog.com"&&(t="https://eu-assets.i.posthog.com");let r=`${t}/array/${this.apiKey}/config`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(r,i,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(n=>n.json()).catch(n=>{this._logger.error("Remote config could not be loaded",n),this._events.emit("error",n)})}async getFlags(t,r={},i={},n={},a={},o=!0){await this._initPromise;let c=o?"&config=true":"",d=`${this.host}/flags/?v=2${c}`,s={token:this.apiKey,distinct_id:t,groups:r,person_properties:i,group_properties:n,...a};this.evaluationEnvironments&&this.evaluationEnvironments.length>0&&(s.evaluation_environments=this.evaluationEnvironments);let u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(s)};return this._logger.info("Flags URL",d),this.fetchWithRetry(d,u,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(f=>f.json()).then(f=>A0c(f)).catch(f=>{this._events.emit("error",f)})}async getFeatureFlagStateless(t,r,i={},n={},a={},o){await this._initPromise;let c=await this.getFeatureFlagDetailStateless(t,r,i,n,a,o);if(c===void 0)return{response:void 0,requestId:void 0};let d=f_n(c.response);return d===void 0&&(d=!1),{response:d,requestId:c.requestId}}async getFeatureFlagDetailStateless(t,r,i={},n={},a={},o){await this._initPromise;let c=await this.getFeatureFlagDetailsStateless(r,i,n,a,o,[t]);return c===void 0?void 0:{response:c.flags[t],requestId:c.requestId,evaluatedAt:c.evaluatedAt}}async getFeatureFlagPayloadStateless(t,r,i={},n={},a={},o){await this._initPromise;let c=await this.getFeatureFlagPayloadsStateless(r,i,n,a,o,[t]);if(!c)return;let d=c[t];return d===void 0?null:d}async getFeatureFlagPayloadsStateless(t,r={},i={},n={},a,o){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a,o)).payloads}async getFeatureFlagsStateless(t,r={},i={},n={},a,o){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a,o)}async getFeatureFlagsAndPayloadsStateless(t,r={},i={},n={},a,o){await this._initPromise;let c=await this.getFeatureFlagDetailsStateless(t,r,i,n,a,o);return c?{flags:c.featureFlags,payloads:c.featureFlagPayloads,requestId:c.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(t,r={},i={},n={},a,o){await this._initPromise;let c={};(a??this.disableGeoip)&&(c.geoip_disable=!0),o&&(c.flag_keys_to_evaluate=o);let d=await this.getFlags(t,r,i,n,c);if(d!==void 0)return d.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),d.quotaLimited?.includes("feature_flags")?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:d?.requestId}):d}async getSurveysStateless(){if(await this._initPromise,this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let t=`${this.host}/api/surveys/?token=${this.apiKey}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},n=(await this.fetchWithRetry(t,r).then(a=>{if(a.status!==200||!a.json){let o=`Surveys API could not be loaded: ${a.status}`,c=new Error(o);this._logger.error(c),this._events.emit("error",new Error(o));return}return a.json()}).catch(a=>{this._logger.error("Surveys API could not be loaded",a),this._events.emit("error",a)}))?.surveys;return n&&this._logger.info("Surveys fetched from API: ",JSON.stringify(n)),n??[]}get props(){return this._props||(this._props=this.getPersistedProperty(t$.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(t$.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(t$.Props,this.props)})}enqueue(t,r,i){this.wrap(()=>{if(this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let n=this.prepareMessage(t,r,i),a=this.getPersistedProperty(t$.Queue)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.info("Queue is full, the oldest event is dropped.")),a.push({message:n}),this.setPersistedProperty(t$.Queue,a),this._events.emit(t,n),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=p_n(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,i){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let n={api_key:this.apiKey,batch:[this.prepareMessage(t,r,i)],sent_at:o7o()};this.historicalMigration&&(n.historical_migration=!0);let a=JSON.stringify(n),o=`${this.host}/batch/`,c=this.disableCompression?null:await I0c(a,this.isDebug),d={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...c!==null&&{"Content-Encoding":"gzip"}},body:c||a};try{await this.fetchWithRetry(o,d)}catch(s){this._events.emit("error",s)}}prepareMessage(t,r,i){let n={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:i?.timestamp?i?.timestamp:o7o(),uuid:i?.uuid?i.uuid:CJt()};return(i?.disableGeoip??this.disableGeoip)&&(n.properties||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId),n}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.flush().catch(async t=>{await Dq_(t)})}async flush(){let t=B0c([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),B0c([t]).then(()=>{this.flushPromise===t&&(this.flushPromise=null)}),t}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(t$.Queue)||[];if(!t.length)return;let r=[],i=t.length;for(;t.length>0&&r.length<i;){let n=t.slice(0,this.maxBatchSize),a=n.map(_=>_.message),o=()=>{let h=(this.getPersistedProperty(t$.Queue)||[]).slice(n.length);this.setPersistedProperty(t$.Queue,h),t=h},c={api_key:this.apiKey,batch:a,sent_at:o7o()};this.historicalMigration&&(c.historical_migration=!0);let d=JSON.stringify(c),s=`${this.host}/batch/`,u=this.disableCompression?null:await I0c(d,this.isDebug),f={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...u!==null&&{"Content-Encoding":"gzip"}},body:u||d},p={retryCheck:_=>Bq_(_)?!1:C0c(_)};try{await this.fetchWithRetry(s,f,p)}catch(_){if(Bq_(_)&&a.length>1){this.maxBatchSize=Math.max(1,Math.floor(a.length/2)),this._logger.warn(`Received 413 when sending batch of size ${a.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw _ instanceof wWa||o(),this._events.emit("error",_),_}o(),r.push(...a)}this._events.emit("flush",r)}async fetchWithRetry(t,r,i,n){AbortSignal.timeout??=function(c){let d=new AbortController;return setTimeout(()=>d.abort(),c),d.signal};let a=r.body?r.body:"",o=-1;try{o=a instanceof Blob?a.size:Buffer.byteLength(a,Pq_)}catch{a instanceof Blob?o=a.size:o=new TextEncoder().encode(a).length}return await Eq_(async()=>{let c=null;try{c=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(s){throw new wWa(s)}if(!(r.mode==="no-cors")&&(c.status<200||c.status>=400))throw new Z2n(c,o);return c},{...this._retryOptions,...i})}async _shutdown(t=3e4){await this._initPromise;let r=!1;this.clearFlushTimer();let i=async()=>{try{for(await this.promiseQueue.join();!((this.getPersistedProperty(t$.Queue)||[]).length===0||(await this.flush(),r)););}catch(n){if(!C0c(n))throw n;await Dq_(n)}};return Promise.race([new Promise((n,a)=>{p_n(()=>{this._logger.error("Timed out while shutting down PostHog"),r=!0,a("Timeout while shutting down PostHog. Some events may not have been sent.")},t)}),i()])}async shutdown(t=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(t).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}};var r$={};Zt(r$,{DOMExceptionCoercer:()=>T0c,ErrorCoercer:()=>R0c,ErrorEventCoercer:()=>z0c,ErrorPropertiesBuilder:()=>q0c,EventCoercer:()=>Q0c,ObjectCoercer:()=>F0c,PrimitiveCoercer:()=>U0c,PromiseRejectionEventCoercer:()=>L0c,ReduceableCache:()=>V0c,StringCoercer:()=>N0c,chromeStackLineParser:()=>qq_,createStackParser:()=>PKM,geckoStackLineParser:()=>Rq_,nodeStackLineParser:()=>Qq_,opera10StackLineParser:()=>zq_,opera11StackLineParser:()=>Nq_,reverseAndStripFrames:()=>Vq_,winjsStackLineParser:()=>Tq_});var s7o,Iq_,c7o;function Cq_(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);return c7o&&r.length===Iq_||(Iq_=r.length,c7o=r.reduce((i,n)=>{s7o||(s7o={});let a=s7o[n];if(a)i[a[0]]=a[1];else{let o=e(n);for(let c=o.length-1;c>=0;c--){let s=o[c]?.filename,u=t[n];if(s&&u){i[s]=u,s7o[n]=[s,u];break}}}return i},{})),c7o}var lKM=4,q0c=class{constructor(t,r,i=[]){this.coercers=t,this.stackParser=r,this.modifiers=i}buildFromUnknown(t,r={}){let n=r&&r.mechanism||{handled:!0,type:"generic"},o=this.buildCoercingContext(n,r,0).apply(t),c=this.buildParsingContext(),d=this.parseStacktrace(o,c);return{$exception_list:this.convertToExceptionList(d,n),$exception_level:"error"}}async modifyFrames(t){for(let r of t)r.stacktrace&&r.stacktrace.frames&&lq_(r.stacktrace.frames)&&(r.stacktrace.frames=await this.applyModifiers(r.stacktrace.frames));return t}coerceFallback(t){return{type:"Error",value:"Unknown error",stack:t.syntheticException?.stack,synthetic:!0}}parseStacktrace(t,r){let i;t.cause!=null&&(i=this.parseStacktrace(t.cause,r));let n;return t.stack!=""&&t.stack!=null&&(n=this.applyChunkIds(this.stackParser(t.stack,t.synthetic?1:0),r.chunkIdMap)),{...t,cause:i,stack:n}}applyChunkIds(t,r){return t.map(i=>(i.filename&&r&&(i.chunk_id=r[i.filename]),i))}applyCoercers(t,r){for(let i of this.coercers)if(i.match(t))return i.coerce(t,r);return this.coerceFallback(r)}async applyModifiers(t){let r=t;for(let i of this.modifiers)r=await i(r);return r}convertToExceptionList(t,r){let i={type:t.type,value:t.value,mechanism:{type:r.type??"generic",handled:r.handled??!0,synthetic:t.synthetic??!1}};t.stack&&(i.stacktrace={type:"raw",frames:t.stack});let n=[i];return t.cause!=null&&n.push(...this.convertToExceptionList(t.cause,{...r,handled:!0})),n}buildParsingContext(){return{chunkIdMap:Cq_(this.stackParser)}}buildCoercingContext(t,r,i=0){let n=(o,c)=>{if(c<=lKM){let d=this.buildCoercingContext(t,r,c);return this.applyCoercers(o,d)}};return{...r,syntheticException:i==0?r.syntheticException:void 0,mechanism:t,apply:o=>n(o,i),next:o=>n(o,i+1)}}};var M4="?";function qJt(e,t,r,i,n){let a={platform:e,filename:t,function:r==="<anonymous>"?M4:r,in_app:!0};return $2n(i)||(a.lineno=i),$2n(n)||(a.colno=n),a}var l7o=(e,t)=>{let r=e.indexOf("safari-extension")!==-1,i=e.indexOf("safari-web-extension")!==-1;return r||i?[e.indexOf("@")!==-1?e.split("@")[0]:M4,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var fKM=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,dKM=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,pKM=/\((\S*)(?::(\d+))(?::(\d+))\)/,qq_=(e,t)=>{let r=fKM.exec(e);if(r){let[,n,a,o]=r;return qJt(t,n,M4,+a,+o)}let i=dKM.exec(e);if(i){if(i[2]&&i[2].indexOf("eval")===0){let c=pKM.exec(i[2]);c&&(i[2]=c[1],i[3]=c[2],i[4]=c[3])}let[a,o]=l7o(i[1]||M4,i[2]);return qJt(t,o,a,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}};var _KM=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,Tq_=(e,t)=>{let r=_KM.exec(e);return r?qJt(t,r[2],r[1]||M4,+r[3],r[4]?+r[4]:void 0):void 0};var hKM=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,yKM=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Rq_=(e,t)=>{let r=hKM.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let o=yKM.exec(r[3]);o&&(r[1]=r[1]||"eval",r[3]=o[1],r[4]=o[2],r[5]="")}let n=r[3],a=r[1]||M4;return[a,n]=l7o(a,n),qJt(t,n,a,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var bKM=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,zq_=(e,t)=>{let r=bKM.exec(e);return r?qJt(t,r[2],r[3]||M4,+r[1]):void 0},vKM=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,Nq_=(e,t)=>{let r=vKM.exec(e);return r?qJt(t,r[5],r[3]||r[4]||M4,+r[1],+r[2]):void 0};var gKM=/^\s*[-]{4,}$/,OKM=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,Qq_=(e,t)=>{let r=e.match(OKM);if(r){let i,n,a,o,c;if(r[1]){a=r[1];let u=a.lastIndexOf(".");if(a[u-1]==="."&&u--,u>0){i=a.slice(0,u),n=a.slice(u+1);let f=i.indexOf(".Module");f>0&&(a=a.slice(f+1),i=i.slice(0,f))}o=void 0}n&&(o=i,c=n),n==="<anonymous>"&&(c=void 0,a=void 0),a===void 0&&(c=c||M4,a=o?`${o}.${c}`:c);let d=r[2]?.startsWith("file://")?r[2].slice(7):r[2],s=r[5]==="native";return d?.match(/\/[A-Z]:/)&&(d=d.slice(1)),!d&&r[5]&&!s&&(d=r[5]),{filename:d?decodeURI(d):void 0,module:void 0,function:a,lineno:Fq_(r[3]),colno:Fq_(r[4]),in_app:AKM(d||"",s),platform:t}}if(e.match(gKM))return{filename:e,platform:t}};function AKM(e,t=!1){return!(t||e&&!e.startsWith("/")&&!e.match(/^[A-Z]:/)&&!e.startsWith(".")&&!e.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&e!==void 0&&!e.includes("node_modules/")}function Fq_(e){return parseInt(e||"",10)||void 0}var Uq_=/\(error: (.*)\)/,Lq_=50;function Vq_(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,Lq_).map(r=>({...r,filename:r.filename||mKM(t).filename,function:r.function||M4}))}function mKM(e){return e[e.length-1]||{}}function PKM(e,...t){return(r,i=0)=>{let n=[],a=r.split(`
1148
- `);for(let o=i;o<a.length;o++){let c=a[o];if(c.length>1024)continue;let d=Uq_.test(c)?c.replace(Uq_,"$1"):c;if(!d.match(/\S*Error: /)){for(let s of t){let u=s(d,e);if(u){n.push(u);break}}if(n.length>=Lq_)break}}return Vq_(n)}}var T0c=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let i=AWa(t.stack);return{type:this.getType(t),value:this.getValue(t),stack:i?t.stack:void 0,cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return this.isDOMError(t)?"DOMError":"DOMException"}getValue(t){let r=t.name||(this.isDOMError(t)?"DOMError":"DOMException");return t.message?`${r}: ${t.message}`:r}isDOMException(t){return d_n(t,"DOMException")}isDOMError(t){return d_n(t,"DOMError")}};var R0c=class{match(t){return j0c(t)}coerce(t,r){return{type:this.getType(t),value:this.getMessage(t,r),stack:this.getStack(t),cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return t.name||t.constructor.name}getMessage(t,r){let i=t.message;return i.error&&typeof i.error.message=="string"?String(i.error.message):String(i)}getStack(t){return t.stacktrace||t.stack||void 0}};var z0c=class{constructor(){}match(t){return pq_(t)&&t.error!=null}coerce(t,r){let i=r.apply(t.error);return i||{type:"ErrorEvent",value:t.message,stack:r.syntheticException?.stack,synthetic:!0}}};var jKM=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,N0c=class{match(t){return typeof t=="string"}coerce(t,r){let[i,n]=this.getInfos(t);return{type:i??"Error",value:n??t,stack:r.syntheticException?.stack,synthetic:!0}}getInfos(t){let r="Error",i=t,n=t.match(jKM);return n&&(r=n[1],i=n[2]),[r,i]}};var Wq_=["fatal","error","warning","log","info","debug"];function f7o(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let i=r.length;i>0;i--){let n=r.slice(0,i).join(", ");if(!(n.length>t))return i===r.length||n.length<=t?n:`${n.slice(0,t)}...`}return""}var F0c=class{match(t){return typeof t=="object"&&t!==null}coerce(t,r){let i=this.getErrorPropertyFromObject(t);return i?r.apply(i):{type:this.getType(t),value:this.getValue(t),stack:r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){return kHo(t)?t.constructor.name:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){let n=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(n+=` with message: '${t.message}'`),n}if("message"in t&&typeof t.message=="string")return t.message;let r=this.getObjectClassName(t),i=f7o(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${i}`}isSeverityLevel(t){return AWa(t)&&!fq_(t)&&Wq_.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let i=t[r];if(Sq_(i))return i}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var Q0c=class{match(t){return kHo(t)}coerce(t,r){let i=t.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${f7o(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var U0c=class{match(t){return mWa(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var L0c=class{match(t){return d_n(t,"PromiseRejectionEvent")}coerce(t,r){let i=this.getUnhandledRejectionReason(t);return mWa(i)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(i)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(i)}getUnhandledRejectionReason(t){if(mWa(t))return t;try{if("reason"in t)return t.reason;if("detail"in t&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var V0c=class{constructor(t){this._maxSize=t,this._cache=new Map}get(t){let r=this._cache.get(t);if(r!==void 0)return this._cache.delete(t),this._cache.set(t,r),r}set(t,r){this._cache.set(t,r)}reduce(){for(;this._cache.size>=this._maxSize;){let t=this._cache.keys().next().value;t&&this._cache.delete(t)}}};var xq_=require("fs"),Kq_=require("readline"),d7o=new r$.ReduceableCache(25),Jq_=new r$.ReduceableCache(20),W0c=7,wKM=1e3,EKM=1e4;async function $q_(e){let t={};for(let n=e.length-1;n>=0;n--){let a=e[n],o=a?.filename;if(!a||typeof o!="string"||typeof a.lineno!="number"||BKM(o)||IKM(a))continue;t[o]||(t[o]=[]),t[o].push(a.lineno)}let r=Object.keys(t);if(r.length==0)return e;let i=[];for(let n of r){if(Jq_.get(n))continue;let a=t[n];if(!a)continue;a.sort((d,s)=>d-s);let o=qKM(a);if(o.every(d=>CKM(n,d)))continue;let c=TKM(d7o,n,{});i.push(SKM(n,o,c))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&MKM(e,d7o),d7o.reduce(),e}function SKM(e,t,r){return new Promise(i=>{let n=(0,xq_.createReadStream)(e),a=(0,Kq_.createInterface)({input:n});function o(){n.destroy(),i()}let c=0,d=0,s=t[d];if(s===void 0)return void o();let u=s[0],f=s[1];function p(){Jq_.set(e,1),a.close(),a.removeAllListeners(),o()}n.on("error",p),a.on("error",p),a.on("close",o),a.on("line",_=>{if(c++,!(c<u)&&(r[c]=RKM(_,0),c>=f)){if(d===t.length-1){a.close(),a.removeAllListeners();return}d++;let h=t[d];if(h===void 0){a.close(),a.removeAllListeners();return}u=h[0],f=h[1]}})})}function MKM(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let i=t.get(r.filename);if(i===void 0)continue;DKM(r.lineno,r,i)}}function DKM(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=Yq_(e);n<e;n++){let a=r[n];if(a===void 0)return void Gq_(t);t.pre_context.push(a)}if(r[e]===void 0)return void Gq_(t);t.context_line=r[e];let i=Xq_(e);t.post_context=[];for(let n=e+1;n<=i;n++){let a=r[n];if(a===void 0)break;t.post_context.push(a)}}function Gq_(e){delete e.pre_context,delete e.context_line,delete e.post_context}function BKM(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function IKM(e){return e.lineno!==void 0&&e.lineno>EKM||e.colno!==void 0&&e.colno>wKM}function CKM(e,t){let r=d7o.get(e);if(r===void 0)return!1;for(let i=t[0];i<=t[1];i++)if(r[i]===void 0)return!1;return!0}function qKM(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=Hq_(r),n=[];for(;;){if(t===e.length-1){n.push(i);break}let a=e[t+1];if(typeof a!="number")break;a<=i[1]?i[1]=a+W0c:(n.push(i),i=Hq_(a)),t++}return n}function Hq_(e){return[Yq_(e),Xq_(e)]}function Yq_(e){return Math.max(1,e-W0c)}function Xq_(e){return e+W0c}function TKM(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function RKM(e,t){let r=e,i=r.length;if(i<=150)return r;t>i&&(t=i);let n=Math.max(t-60,0);n<5&&(n=0);let a=Math.min(n+140,i);return a>i-5&&(a=i),a===i&&(n=Math.max(a-140,0)),r=r.slice(n,a),n>0&&(r=`...${r}`),a<i&&(r+="..."),r}function zKM(e,t){let r=!1;return Object.assign(i=>{let a=global.process.listeners("uncaughtException").filter(o=>o.name!=="domainUncaughtExceptionClear"&&o._posthogErrorHandler!==!0).length===0;e(i,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&a&&(r=!0,t(i))},{_posthogErrorHandler:!0})}function Zq_(e,t){globalThis.process?.on("uncaughtException",zKM(e,t))}function kq_(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var NKM=2e3,_Fi=class e{constructor(t,r,i){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=i,this._rateLimiter=new e7o({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static async buildEventMessage(t,r,i,n){let a={...n};i||(a.$process_person_profile=!1);let o=this.errorPropertiesBuilder.buildFromUnknown(t,r);return o.$exception_list=await this.errorPropertiesBuilder.modifyFrames(o.$exception_list),{event:"$exception",distinctId:i||CJt(),properties:{...o,...a}}}startAutocaptureIfEnabled(){this.isEnabled()&&(Zq_(this.onException.bind(this),this.onFatalError.bind(this)),kq_(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{let i=await e.buildEventMessage(t,r),a=i.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(a)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:a}):this.client.capture(i)})())}async onFatalError(t){console.error(t),await this.client.shutdown(NKM),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var e1_="5.17.4";async function t1_(e){let t=globalThis.crypto?.subtle;if(!t)throw new Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}var FKM=6e4,QKM=1152921504606847e3,UKM=["is_not"],k2n=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},s0=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},TJt=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},p7o=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:i,timeout:n,host:a,customHeaders:o,...c}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,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=c.fetch||fetch,this.onError=c.onError,this.customHeaders=o,this.onLoad=c.onLoad,this.cacheProvider=c.cacheProvider,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,i={},n={},a={}){await this.loadFeatureFlags();let o,c;if(!this.loadedSuccessfullyOnce)return o;if(c=this.featureFlagsByKey[t],c!==void 0)try{o=(await this.computeFlagAndPayloadLocally(c,r,i,n,a)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${o}`))}catch(d){d instanceof TJt||d instanceof s0?this.logMsgIfDebug(()=>console.debug(`${d.name} when computing flag locally: ${t}: ${d.message}`)):d instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${d}`))}return o}async getAllFlagsAndPayloads(t,r={},i={},n={},a){await this.loadFeatureFlags();let o={},c={},d=this.featureFlags.length==0,s=a?a.map(f=>this.featureFlagsByKey[f]).filter(Boolean):this.featureFlags,u={};return await Promise.all(s.map(async f=>{try{let{value:p,payload:_}=await this.computeFlagAndPayloadLocally(f,t,r,i,n,void 0,u);o[f.key]=p,_&&(c[f.key]=_)}catch(p){p instanceof TJt||p instanceof s0?this.logMsgIfDebug(()=>console.debug(`${p.name} when computing flag locally: ${f.key}: ${p.message}`)):p instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${f.key}: ${p}`)),d=!0}})),{response:o,payloads:c,fallbackToFlags:d}}async computeFlagAndPayloadLocally(t,r,i={},n={},a={},o,c,d=!1){if(d||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=o!==void 0?o:await this.computeFlagValueLocally(t,r,i,n,a,c);let u=this.getFeatureFlagPayload(t.key,s);return{value:s,payload:u}}async computeFlagValueLocally(t,r,i={},n={},a={},o={}){if(t.ensure_experience_continuity)throw new s0("Flag has experience continuity enabled");if(!t.active)return!1;let d=(t.filters||{}).aggregation_group_type_index;if(d==null)return await this.matchFeatureFlagProperties(t,r,n,o);{let s=this.groupTypeMapping[String(d)];if(!s)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${d} for feature flag ${t.key}`)),new s0("Flag has unknown group type index");if(!(s in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let u=a[s];return await this.matchFeatureFlagProperties(t,i[s],u,o)}}getFeatureFlagPayload(t,r){let i=null;if(r!==!1&&r!=null&&(typeof r=="boolean"?i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]||null:typeof r=="string"&&(i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]||null),i!=null)){if(typeof i=="object")return i;if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}return null}async evaluateFlagDependency(t,r,i,n){let a=t.key;if(!this.featureFlagsByKey)throw new s0("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new s0(`Flag dependency property for '${a}' is missing required 'dependency_chain' field`);let o=t.dependency_chain;if(!Array.isArray(o))throw new s0(`Flag dependency property for '${a}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new s0(`Circular dependency detected for flag '${a}' (empty dependency chain)`);for(let d of o){if(!(d in n)){let u=this.featureFlagsByKey[d];if(u)if(u.active)try{let f=await this.matchFeatureFlagProperties(u,r,i,n);n[d]=f}catch(f){throw new s0(`Error evaluating flag dependency '${d}' for flag '${a}': ${f}`)}else n[d]=!1;else throw new s0(`Missing flag dependency '${d}' for flag '${a}'`)}if(n[d]==null)throw new s0(`Dependency '${d}' could not be evaluated`)}let c=n[a];return this.flagEvaluatesToExpectedValue(t.value,c)}flagEvaluatesToExpectedValue(t,r){return typeof t=="boolean"?t===r||typeof r=="string"&&r!==""&&t===!0:typeof t=="string"?r===t:!1}async matchFeatureFlagProperties(t,r,i,n={}){let a=t.filters||{},o=a.groups||[],c=!1,d;for(let s of o)try{if(await this.isConditionMatch(t,r,s,i,n)){let u=s.variant,f=a.multivariate?.variants||[];d=u&&f.some(p=>p.key===u)?u:await this.getMatchingVariant(t,r)||!0;break}}catch(u){if(u instanceof TJt)throw u;if(u instanceof s0)c=!0;else throw u}if(d!==void 0)return d;if(c)throw new s0("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,i,n,a={}){let o=i.rollout_percentage,c=d=>{this.logMsgIfDebug(()=>console.warn(d))};if((i.properties||[]).length>0){for(let d of i.properties){let s=d.type,u=!1;if(u=s==="cohort"?o1_(d,n,this.cohorts,this.debugMode):s==="flag"?await this.evaluateFlagDependency(d,r,n,a):a1_(d,n,c),!u)return!1}if(o==null)return!0}return!(o!=null&&await r1_(t.key,r)>o/100)}async getMatchingVariant(t,r){let i=await r1_(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(c=>{n=i+c.rollout_percentage/100,r.push({valueMin:i,valueMax:n,key:c.key}),i=n}),r}updateFlagState(t){this.featureFlags=t.flags,this.featureFlagsByKey=t.flags.reduce((r,i)=>(r[i.key]=i,r),{}),this.groupTypeMapping=t.groupTypeMapping,this.cohorts=t.cohorts,this.loadedSuccessfullyOnce=!0}async loadFromCache(t){if(!this.cacheProvider)return!1;try{let r=await this.cacheProvider.getFlagDefinitions();return r?(this.updateFlagState(r),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${t} (${r.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),!0):!1}catch(r){return this.onError?.(new Error(`Failed to load from cache: ${r}`)),!1}}async loadFeatureFlags(t=!1){if(!(this.loadedSuccessfullyOnce&&!t))return this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(r=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${r}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(FKM,this.pollingInterval*2**this.backOffCount):this.pollingInterval}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let t=!0;if(this.cacheProvider)try{t=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(i){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${i}`))}if(!t&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let r=await this._requestFeatureFlagDefinitions();if(!r)return;switch(r.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=r.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0;return;case 401:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new k2n(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={};return;case 403:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new k2n(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new k2n(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let i=await r.json()??{};if(!("flags"in i))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(i)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let n={flags:i.flags??[],groupTypeMapping:i.group_type_mapping||{},cohorts:i.cohorts||{}};if(this.updateFlagState(n),this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(n)}catch(a){this.onError?.(new Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length);break}default:return}}catch(t){t instanceof k2n&&this.onError?.(t)}}getPersonalApiKeyRequestOptions(t="GET",r){let i={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(i["If-None-Match"]=r),{method:t,headers:i}}_requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),i=null;if(this.timeout&&typeof this.timeout=="number"){let n=new AbortController;i=p_n(()=>{n.abort()},this.timeout),r.signal=n.signal}try{let n=this.fetch;return n(t,r)}finally{clearTimeout(i)}}async stopPoller(t=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await Promise.race([r,new Promise((i,n)=>setTimeout(()=>n(new Error(`Cache shutdown timeout after ${t}ms`)),t))])}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};async function r1_(e,t,r=""){let i=await t1_(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/QKM}function a1_(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 s0("Operator is_not_set is not supported")}else throw new s0(`Property ${i} not found in propertyValues`);let o=t[i];if(o==null&&!UKM.includes(a))return r&&r(`Property ${i} cannot have a value of null/undefined with the ${a} operator`),!1;function c(s,u){return Array.isArray(s)?s.map(f=>String(f).toLowerCase()).includes(String(u).toLowerCase()):String(s).toLowerCase()===String(u).toLowerCase()}function d(s,u,f){if(f==="gt")return s>u;if(f==="gte")return s>=u;if(f==="lt")return s<u;if(f==="lte")return s<=u;throw new Error(`Invalid operator: ${f}`)}switch(a){case"exact":return c(n,o);case"is_not":return!c(n,o);case"is_set":return i in t;case"icontains":return String(o).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(o).toLowerCase().includes(String(n).toLowerCase());case"regex":return i1_(String(n))&&String(o).match(String(n))!==null;case"not_regex":return i1_(String(n))&&String(o).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||o==null?d(String(o),String(n),a):typeof o=="string"?d(o,String(n),a):d(o,s,a)}case"is_date_after":case"is_date_before":{if(typeof n=="boolean")throw new s0("Date operations cannot be performed on boolean values");let s=VKM(String(n));if(s==null&&(s=n1_(n)),s==null)throw new s0(`Invalid date: ${n}`);let u=n1_(o);return["is_date_before"].includes(a)?u<s:u>s}default:throw new s0(`Unknown operator: ${a}`)}}function LKM(e,t){if(!(e in t))throw new TJt(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function o1_(e,t,r,i=!1){let n=String(e.value);LKM(n,r);let a=r[n];return u1_(a,t,r,i)}function u1_(e,t,r,i=!1){if(!e)return!0;let n=e.type,a=e.values;if(!a||a.length===0)return!0;let o=!1;if("values"in a[0]){for(let c of a)try{let d=u1_(c,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof TJt)throw d;if(d instanceof s0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new s0("Can't match cohort without a given cohort property value");return n==="AND"}for(let c of a)try{let d;if(c.type==="cohort")d=o1_(c,t,r,i);else if(c.type==="flag"){i&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${c.key||"unknown"}'`);continue}else d=a1_(c,t);let s=c.negation||!1;if(n==="AND"){if(!d&&!s||d&&s)return!1}else if(d&&!s||!d&&s)return!0}catch(d){if(d instanceof TJt)throw d;if(d instanceof s0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new s0("can't match cohort without a given cohort property value");return n==="AND"}function i1_(e){try{return new RegExp(e),!0}catch{return!1}}function n1_(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 s0(`${e} is in an invalid date format`)}throw new s0(`The date provided ${e} must be a string, number, or date object`)}function VKM(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(!r)return null;{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()-7*n);else if(a=="m")i.setUTCMonth(i.getUTCMonth()-n);else{if(a!="y")return null;i.setUTCFullYear(i.getUTCFullYear()-n)}return i}}var _7o=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var WKM=100,s1_=3e4,GKM=5e4,h7o=class extends EWa{constructor(t,r={}){if(super(t,r),this._memoryStorage=new _7o,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,WKM):s1_,r.personalApiKey){if(r.personalApiKey.includes("phc_"))throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');r.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new p7o({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:n=>{this._events.emit("error",n)},onLoad:n=>{this._events.emit("localEvaluationFlagsLoaded",n)},customHeaders:this.getCustomHeaders(),cacheProvider:r.flagDefinitionCacheProvider}))}this.errorTracking=new _Fi(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||GKM}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):fetch(t,r)}getLibraryVersion(){return e1_}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(t){typeof t=="string"&&this._logger.warn("Called capture() with a string as the first argument when an object was expected."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:i,properties:n,options:a})=>super.captureStateless(r,i,n,{timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid})).catch(r=>{r&&console.error(r)}))}async captureImmediate(t){return typeof t=="string"&&this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:i,properties:n,options:a})=>super.captureStatelessImmediate(r,i,n,{timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid})).catch(r=>{r&&console.error(r)}))}identify({distinctId:t,properties:r={},disableGeoip:i}){let{$set:n,$set_once:a,$anon_distinct_id:o,...c}=r,u={$set:n||c,$set_once:a||{},$anon_distinct_id:o??void 0};super.identifyStateless(t,u,{disableGeoip:i})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:i}){let{$set:n,$set_once:a,$anon_distinct_id:o,...c}=r,u={$set:n||c,$set_once:a||{},$anon_distinct_id:o??void 0};super.identifyStatelessImmediate(t,u,{disableGeoip:i})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async aliasImmediate(t){await super.aliasStatelessImmediate(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(t=s1_){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let i=setTimeout(()=>{n(),r(!1)},t),n=this._events.on("localEvaluationFlagsLoaded",a=>{clearTimeout(i),n(),r(a>0)})})}async getFeatureFlag(t,r,i){let{groups:n,disableGeoip:a}=i||{},{onlyEvaluateLocally:o,sendFeatureFlagEvents:c,personProperties:d,groupProperties:s}=i||{},u=this.addLocalPersonAndGroupProperties(r,n,d,s);d=u.allPersonProperties,s=u.allGroupProperties,o==null&&(o=!1),c==null&&(c=this.options.sendFeatureFlagEvent??!0);let f=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,d,s),p=f!==void 0,_,h,y;if(!p&&!o){let v=await super.getFeatureFlagDetailStateless(t,r,n,d,s,a);if(v===void 0)return;y=v.response,f=f_n(y),_=v?.requestId,h=v?.evaluatedAt}let b=`${t}_${f}`;return c&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(b))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(b):this.distinctIdHasSentFlagCalls[r]=[b],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:f,$feature_flag_id:y?.metadata?.id,$feature_flag_version:y?.metadata?.version,$feature_flag_reason:y?.reason?.description??y?.reason?.code,locally_evaluated:p,[`$feature/${t}`]:f,$feature_flag_request_id:_,$feature_flag_evaluated_at:h},groups:n,disableGeoip:a})),f}async getFeatureFlagPayload(t,r,i,n){let{groups:a,disableGeoip:o}=n||{},{onlyEvaluateLocally:c,personProperties:d,groupProperties:s}=n||{},u=this.addLocalPersonAndGroupProperties(r,a,d,s);d=u.allPersonProperties,s=u.allGroupProperties;let f;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let h=this.featureFlagsPoller?.featureFlagsByKey[t];if(h)try{let y=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(h,r,a,d,s,i);y&&(i=y.value,f=y.payload)}catch(y){if(y instanceof TJt||y instanceof s0)this._logger?.info(`${y.name} when computing flag locally: ${h.key}: ${y.message}`);else throw y}}return c==null&&(c=!1),!(f!==void 0)&&!c&&(f=await super.getFeatureFlagPayloadStateless(t,r,a,d,s,o)),f}async getRemoteConfigPayload(t){if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let r=await this._requestRemoteConfigPayload(t);if(!r)return;let i=await r.json();if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}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,flagKeys:a}=r||{},{onlyEvaluateLocally:o,personProperties:c,groupProperties:d}=r||{},s=this.addLocalPersonAndGroupProperties(t,i,c,d);c=s.allPersonProperties,d=s.allGroupProperties,o==null&&(o=!1);let u=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,c,d,a),f={},p={},_=!0;if(u&&(f=u.response,p=u.payloads,_=u.fallbackToFlags),_&&!o){let h=await super.getFeatureFlagsAndPayloadsStateless(t,i,c,d,n,a);f={...f,...h.flags||{}},p={...p,...h.payloads||{}}}return{featureFlags:f,featureFlagPayloads:p}}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)}withContext(t,r,i){return this.context?this.context.run(t,r,i):r()}getContext(){return this.context?.get()}async _shutdown(t){return this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown(),super._shutdown(t)}async _requestRemoteConfigPayload(t){if(!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config?token=${encodeURIComponent(this.apiKey)}`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},n=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let a=new AbortController;n=p_n(()=>{a.abort()},this.options.requestTimeout),i.signal=a.signal}try{return await this.fetch(r,i)}catch(a){this._events.emit("error",a);return}finally{n&&clearTimeout(n)}}extractPropertiesFromEvent(t,r){if(!t)return{personProperties:{},groupProperties:{}};let i={},n={};for(let[a,o]of Object.entries(t))if(_q_(o)&&r&&a in r){let c={};for(let[d,s]of Object.entries(o))c[String(d)]=String(s);n[String(a)]=c}else i[String(a)]=String(o);return{personProperties:i,groupProperties:n}}async getFeatureFlagsForEvent(t,r,i,n){let a=n?.personProperties||{},o=n?.groupProperties||{},c=n?.flagKeys;if(n?.onlyEvaluateLocally??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let s={};for(let[u,f]of Object.entries(r||{}))s[u]=String(f);return await this.getAllFlags(t,{groups:s,personProperties:a,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:c})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let s={};for(let[u,f]of Object.entries(r||{}))s[u]=String(f);return await this.getAllFlags(t,{groups:s,personProperties:a,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:c})}return(await super.getFeatureFlagsStateless(t,r,a,o,i)).flags}addLocalPersonAndGroupProperties(t,r,i,n){let a={distinct_id:t,...i||{}},o={};if(r)for(let c of Object.keys(r))o[c]={$group_key:r[c],...n?.[c]||{}};return{allPersonProperties:a,allGroupProperties:o}}captureException(t,r,i){let n=new Error("PostHog syntheticException");this.addPendingPromise(_Fi.buildEventMessage(t,{syntheticException:n},r,i).then(a=>this.capture(a)))}async captureExceptionImmediate(t,r,i){let n=new Error("PostHog syntheticException");this.addPendingPromise(_Fi.buildEventMessage(t,{syntheticException:n},r,i).then(a=>this.captureImmediate(a)))}async prepareEventMessage(t){let{distinctId:r,event:i,properties:n,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s}=t,u=this.context?.get(),f=r||u?.distinctId,p={...u?.properties||{},...n||{}};f||(f=CJt(),p.$process_person_profile=!1),u?.sessionId&&!p.$session_id&&(p.$session_id=u.sessionId);let _=this._runBeforeSend({distinctId:f,event:i,properties:p,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s});if(!_)return Promise.reject(null);let h=await Promise.resolve().then(async()=>{if(o){let y=typeof o=="object"?o:void 0;return await this.getFeatureFlagsForEvent(_.distinctId,a,d,y)}return _.event,{}}).then(y=>{let b={};if(y)for(let[O,A]of Object.entries(y))b[`$feature/${O}`]=A;let v=Object.keys(y||{}).filter(O=>y?.[O]!==!1).sort();return v.length>0&&(b.$active_feature_flags=v),b}).catch(()=>({})).then(y=>({...y,..._.properties||{},$groups:_.groups||a}));return _.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof h.$raw_user_agent=="string"&&sq_(h.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(_.event="$bot_pageview",h.$browser_type="bot"),{distinctId:_.distinctId,event:_.event,properties:h,options:{timestamp:_.timestamp,disableGeoip:_.disableGeoip,uuid:_.uuid}}}_runBeforeSend(t){let r=this.options.before_send;if(!r)return t;let i=Array.isArray(r)?r:[r],n=t;for(let a of i){if(n=a(n),!n)return this._logger.info(`Event '${t.event}' was rejected in beforeSend function`),null;if(!n.properties||Object.keys(n.properties).length===0){let o=`Event '${n.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(o)}}return n}};var c1_=require("async_hooks"),y7o=class{constructor(){this.storage=new c1_.AsyncLocalStorage}get(){return this.storage.getStore()}run(t,r,i){if(i?.fresh===!0)return this.storage.run(t,r);{let a=this.get()||{},o={distinctId:t.distinctId??a.distinctId,sessionId:t.sessionId??a.sessionId,properties:{...a.properties||{},...t.properties||{}}};return this.storage.run(o,r)}}};var l1_="posthog-node";function HKM(e,{organization:t,projectId:r,prefix:i,severityAllowList:n=["error"],sendExceptionsToPostHog:a=!0}={}){return o=>{if(!(n==="*"||n.includes(o.level)))return o;o.tags||(o.tags={});let d=o.tags[G0c.POSTHOG_ID_TAG];if(d===void 0)return o;let s=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${d}`,s).toString();o.tags["PostHog Person URL"]=u;let f=o.exception?.values||[],p=f.map(h=>({...h,stacktrace:h.stacktrace?{...h.stacktrace,type:"raw",frames:(h.stacktrace.frames||[]).map(y=>({...y,platform:"node:javascript"}))}:void 0})),_={$exception_message:f[0]?.value||o.message,$exception_type:f[0]?.type,$exception_level:o.level,$exception_list:p,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:f[0]?.value||o.message,$sentry_exception_type:f[0]?.type,$sentry_tags:o.tags};return t&&r&&(_.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+o.event_id),a&&e.capture({event:"$exception",distinctId:d,properties:_}),o}}var G0c=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,i,n,a){this.name=l1_,this.name=l1_,this.setupOnce=function(o,c){let d=c()?.getClient()?.getDsn()?.projectId;o(HKM(t,{organization:r,projectId:d,prefix:i,severityAllowList:n,sendExceptionsToPostHog:a??!0}))}}};_Fi.errorPropertiesBuilder=new r$.ErrorPropertiesBuilder([new r$.EventCoercer,new r$.ErrorCoercer,new r$.ObjectCoercer,new r$.StringCoercer,new r$.PrimitiveCoercer],r$.createStackParser("node:javascript",r$.nodeStackLineParser),[iq_(),$q_]);var ekn=class extends h7o{getLibraryId(){return"posthog-node"}initializeContext(){return new y7o}};var b7o=class{posthog;constructor({posthogApiKey:t}){this.posthog=new ekn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"3.37.3",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var SWa=class{async sendEvent(){}async identify(){}async flush(){}};var tkn=require("fs/promises"),_1_=require("os"),h1_=require("path");var f1_=ce(require("crypto")),g7o=new Uint8Array(256),v7o=g7o.length;function H0c(){return v7o>g7o.length-16&&(f1_.default.randomFillSync(g7o),v7o=0),g7o.slice(v7o,v7o+=16)}var D4=[];for(let e=0;e<256;++e)D4.push((e+256).toString(16).slice(1));function d1_(e,t=0){return D4[e[t+0]]+D4[e[t+1]]+D4[e[t+2]]+D4[e[t+3]]+"-"+D4[e[t+4]]+D4[e[t+5]]+"-"+D4[e[t+6]]+D4[e[t+7]]+"-"+D4[e[t+8]]+D4[e[t+9]]+"-"+D4[e[t+10]]+D4[e[t+11]]+D4[e[t+12]]+D4[e[t+13]]+D4[e[t+14]]+D4[e[t+15]]}var p1_=ce(require("crypto")),x0c={randomUUID:p1_.default.randomUUID};function xKM(e,t,r){if(x0c.randomUUID&&!t&&!e)return x0c.randomUUID();e=e||{};let i=e.random||(e.rng||H0c)();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 d1_(i)}var Hbe=xKM;var KKM="id",JKM=".fern",MWa=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new ekn(r),this.userId=t==null?void 0:Fvc(t),this.token=t}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){let r=await this.getUserEmail();this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"3.37.3",...t,...t.properties,usingAccessToken:!1,...r!=null?{userEmail:r}:{}}})}async flush(){await this.posthog.flush()}userEmail;async getUserEmail(){if(this.userEmail!==null){if(this.userEmail!=null)return this.userEmail;if(this.token==null){this.userEmail=null;return}try{let t=await g4({token:this.token.value}).user.getMyself();if(t.ok&&t.body.email!=null)return this.userEmail=t.body.email,this.userEmail}catch{}this.userEmail=null}}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=It(Sr.of((0,_1_.homedir)()),Xe.of(JKM),Xe.of(KKM));await mi(t)||(await(0,tkn.mkdir)((0,h1_.dirname)(t),{recursive:!0}),await(0,tkn.writeFile)(t,Hbe())),this.persistedDistinctId=(await(0,tkn.readFile)(t)).toString()}return this.persistedDistinctId}};var K0c;async function rkn(){return K0c==null&&(K0c=await $KM()),K0c}async function $KM(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new SWa;let r=await U8o();return r!=null?new MWa({token:r,posthogApiKey:e}):await fZn()!=null?new b7o({posthogApiKey:e}):new MWa({token:void 0,posthogApiKey:e})}catch{return new SWa}}function DWa(e,t){return function(){return e.apply(t,arguments)}}var{toString:YKM}=Object.prototype,{getPrototypeOf:$0c}=Object,{iterator:A7o,toStringTag:b1_}=Symbol,m7o=(e=>t=>{let r=YKM.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),YVt=e=>(e=e.toLowerCase(),t=>m7o(t)===e),P7o=e=>t=>typeof t===e,{isArray:nkn}=Array,ikn=P7o("undefined");function BWa(e){return e!==null&&!ikn(e)&&e.constructor!==null&&!ikn(e.constructor)&&i$(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var v1_=YVt("ArrayBuffer");function XKM(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&v1_(e.buffer),t}var ZKM=P7o("string"),i$=P7o("function"),g1_=P7o("number"),IWa=e=>e!==null&&typeof e=="object",kKM=e=>e===!0||e===!1,O7o=e=>{if(m7o(e)!=="object")return!1;let t=$0c(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(b1_ in e)&&!(A7o in e)},eJM=e=>{if(!IWa(e)||BWa(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},tJM=YVt("Date"),rJM=YVt("File"),iJM=YVt("Blob"),nJM=YVt("FileList"),aJM=e=>IWa(e)&&i$(e.pipe),oJM=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||i$(e.append)&&((t=m7o(e))==="formdata"||t==="object"&&i$(e.toString)&&e.toString()==="[object FormData]"))},uJM=YVt("URLSearchParams"),[sJM,cJM,lJM,fJM]=["ReadableStream","Request","Response","Headers"].map(YVt),dJM=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function CWa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),nkn(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{if(BWa(e))return;let a=r?Object.getOwnPropertyNames(e):Object.keys(e),o=a.length,c;for(i=0;i<o;i++)c=a[i],t.call(null,e[c],c,e)}}function O1_(e,t){if(BWa(e))return null;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 __n=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,A1_=e=>!ikn(e)&&e!==__n;function J0c(){let{caseless:e,skipUndefined:t}=A1_(this)&&this||{},r={},i=(n,a)=>{let o=e&&O1_(r,a)||a;O7o(r[o])&&O7o(n)?r[o]=J0c(r[o],n):O7o(n)?r[o]=J0c({},n):nkn(n)?r[o]=n.slice():(!t||!ikn(n))&&(r[o]=n)};for(let n=0,a=arguments.length;n<a;n++)arguments[n]&&CWa(arguments[n],i);return r}var pJM=(e,t,r,{allOwnKeys:i}={})=>(CWa(t,(n,a)=>{r&&i$(n)?e[a]=DWa(n,r):e[a]=n},{allOwnKeys:i}),e),_JM=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),hJM=(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)},yJM=(e,t,r,i)=>{let n,a,o,c={};if(t=t||{},e==null)return t;do{for(n=Object.getOwnPropertyNames(e),a=n.length;a-- >0;)o=n[a],(!i||i(o,e,t))&&!c[o]&&(t[o]=e[o],c[o]=!0);e=r!==!1&&$0c(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},bJM=(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},vJM=e=>{if(!e)return null;if(nkn(e))return e;let t=e.length;if(!g1_(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},gJM=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&$0c(Uint8Array)),OJM=(e,t)=>{let i=(e&&e[A7o]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},AJM=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},mJM=YVt("HTMLFormElement"),PJM=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),y1_=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),jJM=YVt("RegExp"),m1_=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};CWa(r,(n,a)=>{let o;(o=t(n,a,e))!==!1&&(i[a]=o||n)}),Object.defineProperties(e,i)},wJM=e=>{m1_(e,(t,r)=>{if(i$(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(i$(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+"'")})}})},EJM=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return nkn(e)?i(e):i(String(e).split(t)),r},SJM=()=>{},MJM=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function DJM(e){return!!(e&&i$(e.append)&&e[b1_]==="FormData"&&e[A7o])}var BJM=e=>{let t=new Array(10),r=(i,n)=>{if(IWa(i)){if(t.indexOf(i)>=0)return;if(BWa(i))return i;if(!("toJSON"in i)){t[n]=i;let a=nkn(i)?[]:{};return CWa(i,(o,c)=>{let d=r(o,n+1);!ikn(d)&&(a[c]=d)}),t[n]=void 0,a}}return i};return r(e,0)},IJM=YVt("AsyncFunction"),CJM=e=>e&&(IWa(e)||i$(e))&&i$(e.then)&&i$(e.catch),P1_=((e,t)=>e?setImmediate:t?((r,i)=>(__n.addEventListener("message",({source:n,data:a})=>{n===__n&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),__n.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",i$(__n.postMessage)),qJM=typeof queueMicrotask<"u"?queueMicrotask.bind(__n):typeof process<"u"&&process.nextTick||P1_,TJM=e=>e!=null&&i$(e[A7o]),rr={isArray:nkn,isArrayBuffer:v1_,isBuffer:BWa,isFormData:oJM,isArrayBufferView:XKM,isString:ZKM,isNumber:g1_,isBoolean:kKM,isObject:IWa,isPlainObject:O7o,isEmptyObject:eJM,isReadableStream:sJM,isRequest:cJM,isResponse:lJM,isHeaders:fJM,isUndefined:ikn,isDate:tJM,isFile:rJM,isBlob:iJM,isRegExp:jJM,isFunction:i$,isStream:aJM,isURLSearchParams:uJM,isTypedArray:gJM,isFileList:nJM,forEach:CWa,merge:J0c,extend:pJM,trim:dJM,stripBOM:_JM,inherits:hJM,toFlatObject:yJM,kindOf:m7o,kindOfTest:YVt,endsWith:bJM,toArray:vJM,forEachEntry:OJM,matchAll:AJM,isHTMLForm:mJM,hasOwnProperty:y1_,hasOwnProp:y1_,reduceDescriptors:m1_,freezeMethods:wJM,toObjectSet:EJM,toCamelCase:PJM,noop:SJM,toFiniteNumber:MJM,findKey:O1_,global:__n,isContextDefined:A1_,isSpecCompliantForm:DJM,toJSONObject:BJM,isAsyncFn:IJM,isThenable:CJM,setImmediate:P1_,asap:qJM,isIterable:TJM};function akn(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)}rr.inherits(akn,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:rr.toJSONObject(this.config),code:this.code,status:this.status}}});var j1_=akn.prototype,w1_={};["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=>{w1_[e]={value:e}});Object.defineProperties(akn,w1_);Object.defineProperty(j1_,"isAxiosError",{value:!0});akn.from=(e,t,r,i,n,a)=>{let o=Object.create(j1_);rr.toFlatObject(e,o,function(u){return u!==Error.prototype},s=>s!=="isAxiosError");let c=e&&e.message?e.message:"Error",d=t==null&&e?e.code:t;return akn.call(o,c,d,r,i,n),e&&o.cause==null&&Object.defineProperty(o,"cause",{value:e,configurable:!0}),o.name=e&&e.name||"Error",a&&Object.assign(o,a),o};var Ma=akn;var E1_=ce(EXn(),1),j7o=E1_.default;function Y0c(e){return rr.isPlainObject(e)||rr.isArray(e)}function M1_(e){return rr.endsWith(e,"[]")?e.slice(0,-2):e}function S1_(e,t,r){return e?e.concat(t).map(function(n,a){return n=M1_(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function RJM(e){return rr.isArray(e)&&!e.some(Y0c)}var zJM=rr.toFlatObject(rr,{},null,function(t){return/^is[A-Z]/.test(t)});function NJM(e,t,r){if(!rr.isObject(e))throw new TypeError("target must be an object");t=t||new(j7o||FormData),r=rr.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,b){return!rr.isUndefined(b[y])});let i=r.metaTokens,n=r.visitor||u,a=r.dots,o=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&rr.isSpecCompliantForm(t);if(!rr.isFunction(n))throw new TypeError("visitor must be a function");function s(h){if(h===null)return"";if(rr.isDate(h))return h.toISOString();if(rr.isBoolean(h))return h.toString();if(!d&&rr.isBlob(h))throw new Ma("Blob is not supported. Use a Buffer instead.");return rr.isArrayBuffer(h)||rr.isTypedArray(h)?d&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function u(h,y,b){let v=h;if(h&&!b&&typeof h=="object"){if(rr.endsWith(y,"{}"))y=i?y:y.slice(0,-2),h=JSON.stringify(h);else if(rr.isArray(h)&&RJM(h)||(rr.isFileList(h)||rr.endsWith(y,"[]"))&&(v=rr.toArray(h)))return y=M1_(y),v.forEach(function(A,g){!(rr.isUndefined(A)||A===null)&&t.append(o===!0?S1_([y],g,a):o===null?y:y+"[]",s(A))}),!1}return Y0c(h)?!0:(t.append(S1_(b,y,a),s(h)),!1)}let f=[],p=Object.assign(zJM,{defaultVisitor:u,convertValue:s,isVisitable:Y0c});function _(h,y){if(!rr.isUndefined(h)){if(f.indexOf(h)!==-1)throw Error("Circular reference detected in "+y.join("."));f.push(h),rr.forEach(h,function(v,O){(!(rr.isUndefined(v)||v===null)&&n.call(t,v,rr.isString(O)?O.trim():O,y,p))===!0&&_(v,y?y.concat(O):[O])}),f.pop()}}if(!rr.isObject(e))throw new TypeError("data must be an object");return _(e),t}var M7i=NJM;function D1_(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function B1_(e,t){this._pairs=[],e&&M7i(e,this,t)}var I1_=B1_.prototype;I1_.append=function(t,r){this._pairs.push([t,r])};I1_.toString=function(t){let r=t?function(i){return t.call(this,i,D1_)}:D1_;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var C1_=B1_;function FJM(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function h_n(e,t,r){if(!t)return e;let i=r&&r.encode||FJM;rr.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=rr.isURLSearchParams(t)?t.toString():new C1_(t,r).toString(i),a){let o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var X0c=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){rr.forEach(this.handlers,function(i){i!==null&&t(i)})}},Z0c=X0c;var okn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var z1_=ce(require("crypto"),1);var q1_=ce(require("url"),1),T1_=q1_.default.URLSearchParams;var k0c="abcdefghijklmnopqrstuvwxyz",R1_="0123456789",N1_={DIGIT:R1_,ALPHA:k0c,ALPHA_DIGIT:k0c+k0c.toUpperCase()+R1_},QJM=(e=16,t=N1_.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);z1_.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},F1_={isNode:!0,classes:{URLSearchParams:T1_,FormData:j7o,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:N1_,generateString:QJM,protocols:["http","https","file","data"]};var rwc={};Zt(rwc,{hasBrowserEnv:()=>twc,hasStandardBrowserEnv:()=>UJM,hasStandardBrowserWebWorkerEnv:()=>LJM,navigator:()=>ewc,origin:()=>VJM});var twc=typeof window<"u"&&typeof document<"u",ewc=typeof navigator=="object"&&navigator||void 0,UJM=twc&&(!ewc||["ReactNative","NativeScript","NS"].indexOf(ewc.product)<0),LJM=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",VJM=twc&&window.location.href||"http://localhost";var YA={...rwc,...F1_};function iwc(e,t){return M7i(e,new YA.classes.URLSearchParams,{visitor:function(r,i,n,a){return YA.isNode&&rr.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function WJM(e){return rr.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function GJM(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 HJM(e){function t(r,i,n,a){let o=r[a++];if(o==="__proto__")return!0;let c=Number.isFinite(+o),d=a>=r.length;return o=!o&&rr.isArray(n)?n.length:o,d?(rr.hasOwnProp(n,o)?n[o]=[n[o],i]:n[o]=i,!c):((!n[o]||!rr.isObject(n[o]))&&(n[o]=[]),t(r,i,n[o],a)&&rr.isArray(n[o])&&(n[o]=GJM(n[o])),!c)}if(rr.isFormData(e)&&rr.isFunction(e.entries)){let r={};return rr.forEachEntry(e,(i,n)=>{t(WJM(i),n,r,0)}),r}return null}var w7o=HJM;function xJM(e,t,r){if(rr.isString(e))try{return(t||JSON.parse)(e),rr.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var nwc={transitional:okn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=rr.isObject(t);if(a&&rr.isHTMLForm(t)&&(t=new FormData(t)),rr.isFormData(t))return n?JSON.stringify(w7o(t)):t;if(rr.isArrayBuffer(t)||rr.isBuffer(t)||rr.isStream(t)||rr.isFile(t)||rr.isBlob(t)||rr.isReadableStream(t))return t;if(rr.isArrayBufferView(t))return t.buffer;if(rr.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return iwc(t,this.formSerializer).toString();if((c=rr.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return M7i(c?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),xJM(t)):t}],transformResponse:[function(t){let r=this.transitional||nwc.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(rr.isResponse(t)||rr.isReadableStream(t))return t;if(t&&rr.isString(t)&&(i&&!this.responseType||n)){let o=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t,this.parseReviver)}catch(c){if(o)throw c.name==="SyntaxError"?Ma.from(c,Ma.ERR_BAD_RESPONSE,this,null,this.response):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:YA.classes.FormData,Blob:YA.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};rr.forEach(["delete","get","head","post","put","patch"],e=>{nwc.headers[e]={}});var ukn=nwc;var KJM=rr.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"]),Q1_=e=>{let t={},r,i,n;return e&&e.split(`
1148
+ `);for(let o=i;o<a.length;o++){let c=a[o];if(c.length>1024)continue;let d=Uq_.test(c)?c.replace(Uq_,"$1"):c;if(!d.match(/\S*Error: /)){for(let s of t){let u=s(d,e);if(u){n.push(u);break}}if(n.length>=Lq_)break}}return Vq_(n)}}var T0c=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let i=AWa(t.stack);return{type:this.getType(t),value:this.getValue(t),stack:i?t.stack:void 0,cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return this.isDOMError(t)?"DOMError":"DOMException"}getValue(t){let r=t.name||(this.isDOMError(t)?"DOMError":"DOMException");return t.message?`${r}: ${t.message}`:r}isDOMException(t){return d_n(t,"DOMException")}isDOMError(t){return d_n(t,"DOMError")}};var R0c=class{match(t){return j0c(t)}coerce(t,r){return{type:this.getType(t),value:this.getMessage(t,r),stack:this.getStack(t),cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return t.name||t.constructor.name}getMessage(t,r){let i=t.message;return i.error&&typeof i.error.message=="string"?String(i.error.message):String(i)}getStack(t){return t.stacktrace||t.stack||void 0}};var z0c=class{constructor(){}match(t){return pq_(t)&&t.error!=null}coerce(t,r){let i=r.apply(t.error);return i||{type:"ErrorEvent",value:t.message,stack:r.syntheticException?.stack,synthetic:!0}}};var jKM=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,N0c=class{match(t){return typeof t=="string"}coerce(t,r){let[i,n]=this.getInfos(t);return{type:i??"Error",value:n??t,stack:r.syntheticException?.stack,synthetic:!0}}getInfos(t){let r="Error",i=t,n=t.match(jKM);return n&&(r=n[1],i=n[2]),[r,i]}};var Wq_=["fatal","error","warning","log","info","debug"];function f7o(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let i=r.length;i>0;i--){let n=r.slice(0,i).join(", ");if(!(n.length>t))return i===r.length||n.length<=t?n:`${n.slice(0,t)}...`}return""}var F0c=class{match(t){return typeof t=="object"&&t!==null}coerce(t,r){let i=this.getErrorPropertyFromObject(t);return i?r.apply(i):{type:this.getType(t),value:this.getValue(t),stack:r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){return kHo(t)?t.constructor.name:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){let n=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(n+=` with message: '${t.message}'`),n}if("message"in t&&typeof t.message=="string")return t.message;let r=this.getObjectClassName(t),i=f7o(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${i}`}isSeverityLevel(t){return AWa(t)&&!fq_(t)&&Wq_.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let i=t[r];if(Sq_(i))return i}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var Q0c=class{match(t){return kHo(t)}coerce(t,r){let i=t.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${f7o(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var U0c=class{match(t){return mWa(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var L0c=class{match(t){return d_n(t,"PromiseRejectionEvent")}coerce(t,r){let i=this.getUnhandledRejectionReason(t);return mWa(i)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(i)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(i)}getUnhandledRejectionReason(t){if(mWa(t))return t;try{if("reason"in t)return t.reason;if("detail"in t&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var V0c=class{constructor(t){this._maxSize=t,this._cache=new Map}get(t){let r=this._cache.get(t);if(r!==void 0)return this._cache.delete(t),this._cache.set(t,r),r}set(t,r){this._cache.set(t,r)}reduce(){for(;this._cache.size>=this._maxSize;){let t=this._cache.keys().next().value;t&&this._cache.delete(t)}}};var xq_=require("fs"),Kq_=require("readline"),d7o=new r$.ReduceableCache(25),Jq_=new r$.ReduceableCache(20),W0c=7,wKM=1e3,EKM=1e4;async function $q_(e){let t={};for(let n=e.length-1;n>=0;n--){let a=e[n],o=a?.filename;if(!a||typeof o!="string"||typeof a.lineno!="number"||BKM(o)||IKM(a))continue;t[o]||(t[o]=[]),t[o].push(a.lineno)}let r=Object.keys(t);if(r.length==0)return e;let i=[];for(let n of r){if(Jq_.get(n))continue;let a=t[n];if(!a)continue;a.sort((d,s)=>d-s);let o=qKM(a);if(o.every(d=>CKM(n,d)))continue;let c=TKM(d7o,n,{});i.push(SKM(n,o,c))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&MKM(e,d7o),d7o.reduce(),e}function SKM(e,t,r){return new Promise(i=>{let n=(0,xq_.createReadStream)(e),a=(0,Kq_.createInterface)({input:n});function o(){n.destroy(),i()}let c=0,d=0,s=t[d];if(s===void 0)return void o();let u=s[0],f=s[1];function p(){Jq_.set(e,1),a.close(),a.removeAllListeners(),o()}n.on("error",p),a.on("error",p),a.on("close",o),a.on("line",_=>{if(c++,!(c<u)&&(r[c]=RKM(_,0),c>=f)){if(d===t.length-1){a.close(),a.removeAllListeners();return}d++;let h=t[d];if(h===void 0){a.close(),a.removeAllListeners();return}u=h[0],f=h[1]}})})}function MKM(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let i=t.get(r.filename);if(i===void 0)continue;DKM(r.lineno,r,i)}}function DKM(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=Yq_(e);n<e;n++){let a=r[n];if(a===void 0)return void Gq_(t);t.pre_context.push(a)}if(r[e]===void 0)return void Gq_(t);t.context_line=r[e];let i=Xq_(e);t.post_context=[];for(let n=e+1;n<=i;n++){let a=r[n];if(a===void 0)break;t.post_context.push(a)}}function Gq_(e){delete e.pre_context,delete e.context_line,delete e.post_context}function BKM(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function IKM(e){return e.lineno!==void 0&&e.lineno>EKM||e.colno!==void 0&&e.colno>wKM}function CKM(e,t){let r=d7o.get(e);if(r===void 0)return!1;for(let i=t[0];i<=t[1];i++)if(r[i]===void 0)return!1;return!0}function qKM(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=Hq_(r),n=[];for(;;){if(t===e.length-1){n.push(i);break}let a=e[t+1];if(typeof a!="number")break;a<=i[1]?i[1]=a+W0c:(n.push(i),i=Hq_(a)),t++}return n}function Hq_(e){return[Yq_(e),Xq_(e)]}function Yq_(e){return Math.max(1,e-W0c)}function Xq_(e){return e+W0c}function TKM(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function RKM(e,t){let r=e,i=r.length;if(i<=150)return r;t>i&&(t=i);let n=Math.max(t-60,0);n<5&&(n=0);let a=Math.min(n+140,i);return a>i-5&&(a=i),a===i&&(n=Math.max(a-140,0)),r=r.slice(n,a),n>0&&(r=`...${r}`),a<i&&(r+="..."),r}function zKM(e,t){let r=!1;return Object.assign(i=>{let a=global.process.listeners("uncaughtException").filter(o=>o.name!=="domainUncaughtExceptionClear"&&o._posthogErrorHandler!==!0).length===0;e(i,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&a&&(r=!0,t(i))},{_posthogErrorHandler:!0})}function Zq_(e,t){globalThis.process?.on("uncaughtException",zKM(e,t))}function kq_(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var NKM=2e3,_Fi=class e{constructor(t,r,i){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=i,this._rateLimiter=new e7o({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static async buildEventMessage(t,r,i,n){let a={...n};i||(a.$process_person_profile=!1);let o=this.errorPropertiesBuilder.buildFromUnknown(t,r);return o.$exception_list=await this.errorPropertiesBuilder.modifyFrames(o.$exception_list),{event:"$exception",distinctId:i||CJt(),properties:{...o,...a}}}startAutocaptureIfEnabled(){this.isEnabled()&&(Zq_(this.onException.bind(this),this.onFatalError.bind(this)),kq_(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{let i=await e.buildEventMessage(t,r),a=i.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(a)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:a}):this.client.capture(i)})())}async onFatalError(t){console.error(t),await this.client.shutdown(NKM),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var e1_="5.17.4";async function t1_(e){let t=globalThis.crypto?.subtle;if(!t)throw new Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}var FKM=6e4,QKM=1152921504606847e3,UKM=["is_not"],k2n=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},s0=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},TJt=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},p7o=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:i,timeout:n,host:a,customHeaders:o,...c}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,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=c.fetch||fetch,this.onError=c.onError,this.customHeaders=o,this.onLoad=c.onLoad,this.cacheProvider=c.cacheProvider,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,i={},n={},a={}){await this.loadFeatureFlags();let o,c;if(!this.loadedSuccessfullyOnce)return o;if(c=this.featureFlagsByKey[t],c!==void 0)try{o=(await this.computeFlagAndPayloadLocally(c,r,i,n,a)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${o}`))}catch(d){d instanceof TJt||d instanceof s0?this.logMsgIfDebug(()=>console.debug(`${d.name} when computing flag locally: ${t}: ${d.message}`)):d instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${d}`))}return o}async getAllFlagsAndPayloads(t,r={},i={},n={},a){await this.loadFeatureFlags();let o={},c={},d=this.featureFlags.length==0,s=a?a.map(f=>this.featureFlagsByKey[f]).filter(Boolean):this.featureFlags,u={};return await Promise.all(s.map(async f=>{try{let{value:p,payload:_}=await this.computeFlagAndPayloadLocally(f,t,r,i,n,void 0,u);o[f.key]=p,_&&(c[f.key]=_)}catch(p){p instanceof TJt||p instanceof s0?this.logMsgIfDebug(()=>console.debug(`${p.name} when computing flag locally: ${f.key}: ${p.message}`)):p instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${f.key}: ${p}`)),d=!0}})),{response:o,payloads:c,fallbackToFlags:d}}async computeFlagAndPayloadLocally(t,r,i={},n={},a={},o,c,d=!1){if(d||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=o!==void 0?o:await this.computeFlagValueLocally(t,r,i,n,a,c);let u=this.getFeatureFlagPayload(t.key,s);return{value:s,payload:u}}async computeFlagValueLocally(t,r,i={},n={},a={},o={}){if(t.ensure_experience_continuity)throw new s0("Flag has experience continuity enabled");if(!t.active)return!1;let d=(t.filters||{}).aggregation_group_type_index;if(d==null)return await this.matchFeatureFlagProperties(t,r,n,o);{let s=this.groupTypeMapping[String(d)];if(!s)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${d} for feature flag ${t.key}`)),new s0("Flag has unknown group type index");if(!(s in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let u=a[s];return await this.matchFeatureFlagProperties(t,i[s],u,o)}}getFeatureFlagPayload(t,r){let i=null;if(r!==!1&&r!=null&&(typeof r=="boolean"?i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]||null:typeof r=="string"&&(i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]||null),i!=null)){if(typeof i=="object")return i;if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}return null}async evaluateFlagDependency(t,r,i,n){let a=t.key;if(!this.featureFlagsByKey)throw new s0("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new s0(`Flag dependency property for '${a}' is missing required 'dependency_chain' field`);let o=t.dependency_chain;if(!Array.isArray(o))throw new s0(`Flag dependency property for '${a}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new s0(`Circular dependency detected for flag '${a}' (empty dependency chain)`);for(let d of o){if(!(d in n)){let u=this.featureFlagsByKey[d];if(u)if(u.active)try{let f=await this.matchFeatureFlagProperties(u,r,i,n);n[d]=f}catch(f){throw new s0(`Error evaluating flag dependency '${d}' for flag '${a}': ${f}`)}else n[d]=!1;else throw new s0(`Missing flag dependency '${d}' for flag '${a}'`)}if(n[d]==null)throw new s0(`Dependency '${d}' could not be evaluated`)}let c=n[a];return this.flagEvaluatesToExpectedValue(t.value,c)}flagEvaluatesToExpectedValue(t,r){return typeof t=="boolean"?t===r||typeof r=="string"&&r!==""&&t===!0:typeof t=="string"?r===t:!1}async matchFeatureFlagProperties(t,r,i,n={}){let a=t.filters||{},o=a.groups||[],c=!1,d;for(let s of o)try{if(await this.isConditionMatch(t,r,s,i,n)){let u=s.variant,f=a.multivariate?.variants||[];d=u&&f.some(p=>p.key===u)?u:await this.getMatchingVariant(t,r)||!0;break}}catch(u){if(u instanceof TJt)throw u;if(u instanceof s0)c=!0;else throw u}if(d!==void 0)return d;if(c)throw new s0("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,i,n,a={}){let o=i.rollout_percentage,c=d=>{this.logMsgIfDebug(()=>console.warn(d))};if((i.properties||[]).length>0){for(let d of i.properties){let s=d.type,u=!1;if(u=s==="cohort"?o1_(d,n,this.cohorts,this.debugMode):s==="flag"?await this.evaluateFlagDependency(d,r,n,a):a1_(d,n,c),!u)return!1}if(o==null)return!0}return!(o!=null&&await r1_(t.key,r)>o/100)}async getMatchingVariant(t,r){let i=await r1_(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(c=>{n=i+c.rollout_percentage/100,r.push({valueMin:i,valueMax:n,key:c.key}),i=n}),r}updateFlagState(t){this.featureFlags=t.flags,this.featureFlagsByKey=t.flags.reduce((r,i)=>(r[i.key]=i,r),{}),this.groupTypeMapping=t.groupTypeMapping,this.cohorts=t.cohorts,this.loadedSuccessfullyOnce=!0}async loadFromCache(t){if(!this.cacheProvider)return!1;try{let r=await this.cacheProvider.getFlagDefinitions();return r?(this.updateFlagState(r),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${t} (${r.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),!0):!1}catch(r){return this.onError?.(new Error(`Failed to load from cache: ${r}`)),!1}}async loadFeatureFlags(t=!1){if(!(this.loadedSuccessfullyOnce&&!t))return this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(r=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${r}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(FKM,this.pollingInterval*2**this.backOffCount):this.pollingInterval}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let t=!0;if(this.cacheProvider)try{t=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(i){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${i}`))}if(!t&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let r=await this._requestFeatureFlagDefinitions();if(!r)return;switch(r.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=r.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0;return;case 401:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new k2n(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={};return;case 403:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new k2n(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new k2n(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let i=await r.json()??{};if(!("flags"in i))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(i)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let n={flags:i.flags??[],groupTypeMapping:i.group_type_mapping||{},cohorts:i.cohorts||{}};if(this.updateFlagState(n),this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(n)}catch(a){this.onError?.(new Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length);break}default:return}}catch(t){t instanceof k2n&&this.onError?.(t)}}getPersonalApiKeyRequestOptions(t="GET",r){let i={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(i["If-None-Match"]=r),{method:t,headers:i}}_requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),i=null;if(this.timeout&&typeof this.timeout=="number"){let n=new AbortController;i=p_n(()=>{n.abort()},this.timeout),r.signal=n.signal}try{let n=this.fetch;return n(t,r)}finally{clearTimeout(i)}}async stopPoller(t=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await Promise.race([r,new Promise((i,n)=>setTimeout(()=>n(new Error(`Cache shutdown timeout after ${t}ms`)),t))])}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};async function r1_(e,t,r=""){let i=await t1_(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/QKM}function a1_(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 s0("Operator is_not_set is not supported")}else throw new s0(`Property ${i} not found in propertyValues`);let o=t[i];if(o==null&&!UKM.includes(a))return r&&r(`Property ${i} cannot have a value of null/undefined with the ${a} operator`),!1;function c(s,u){return Array.isArray(s)?s.map(f=>String(f).toLowerCase()).includes(String(u).toLowerCase()):String(s).toLowerCase()===String(u).toLowerCase()}function d(s,u,f){if(f==="gt")return s>u;if(f==="gte")return s>=u;if(f==="lt")return s<u;if(f==="lte")return s<=u;throw new Error(`Invalid operator: ${f}`)}switch(a){case"exact":return c(n,o);case"is_not":return!c(n,o);case"is_set":return i in t;case"icontains":return String(o).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(o).toLowerCase().includes(String(n).toLowerCase());case"regex":return i1_(String(n))&&String(o).match(String(n))!==null;case"not_regex":return i1_(String(n))&&String(o).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||o==null?d(String(o),String(n),a):typeof o=="string"?d(o,String(n),a):d(o,s,a)}case"is_date_after":case"is_date_before":{if(typeof n=="boolean")throw new s0("Date operations cannot be performed on boolean values");let s=VKM(String(n));if(s==null&&(s=n1_(n)),s==null)throw new s0(`Invalid date: ${n}`);let u=n1_(o);return["is_date_before"].includes(a)?u<s:u>s}default:throw new s0(`Unknown operator: ${a}`)}}function LKM(e,t){if(!(e in t))throw new TJt(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function o1_(e,t,r,i=!1){let n=String(e.value);LKM(n,r);let a=r[n];return u1_(a,t,r,i)}function u1_(e,t,r,i=!1){if(!e)return!0;let n=e.type,a=e.values;if(!a||a.length===0)return!0;let o=!1;if("values"in a[0]){for(let c of a)try{let d=u1_(c,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof TJt)throw d;if(d instanceof s0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new s0("Can't match cohort without a given cohort property value");return n==="AND"}for(let c of a)try{let d;if(c.type==="cohort")d=o1_(c,t,r,i);else if(c.type==="flag"){i&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${c.key||"unknown"}'`);continue}else d=a1_(c,t);let s=c.negation||!1;if(n==="AND"){if(!d&&!s||d&&s)return!1}else if(d&&!s||!d&&s)return!0}catch(d){if(d instanceof TJt)throw d;if(d instanceof s0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new s0("can't match cohort without a given cohort property value");return n==="AND"}function i1_(e){try{return new RegExp(e),!0}catch{return!1}}function n1_(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 s0(`${e} is in an invalid date format`)}throw new s0(`The date provided ${e} must be a string, number, or date object`)}function VKM(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(!r)return null;{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()-7*n);else if(a=="m")i.setUTCMonth(i.getUTCMonth()-n);else{if(a!="y")return null;i.setUTCFullYear(i.getUTCFullYear()-n)}return i}}var _7o=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var WKM=100,s1_=3e4,GKM=5e4,h7o=class extends EWa{constructor(t,r={}){if(super(t,r),this._memoryStorage=new _7o,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,WKM):s1_,r.personalApiKey){if(r.personalApiKey.includes("phc_"))throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');r.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new p7o({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:n=>{this._events.emit("error",n)},onLoad:n=>{this._events.emit("localEvaluationFlagsLoaded",n)},customHeaders:this.getCustomHeaders(),cacheProvider:r.flagDefinitionCacheProvider}))}this.errorTracking=new _Fi(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||GKM}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):fetch(t,r)}getLibraryVersion(){return e1_}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(t){typeof t=="string"&&this._logger.warn("Called capture() with a string as the first argument when an object was expected."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:i,properties:n,options:a})=>super.captureStateless(r,i,n,{timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid})).catch(r=>{r&&console.error(r)}))}async captureImmediate(t){return typeof t=="string"&&this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:i,properties:n,options:a})=>super.captureStatelessImmediate(r,i,n,{timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid})).catch(r=>{r&&console.error(r)}))}identify({distinctId:t,properties:r={},disableGeoip:i}){let{$set:n,$set_once:a,$anon_distinct_id:o,...c}=r,u={$set:n||c,$set_once:a||{},$anon_distinct_id:o??void 0};super.identifyStateless(t,u,{disableGeoip:i})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:i}){let{$set:n,$set_once:a,$anon_distinct_id:o,...c}=r,u={$set:n||c,$set_once:a||{},$anon_distinct_id:o??void 0};super.identifyStatelessImmediate(t,u,{disableGeoip:i})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async aliasImmediate(t){await super.aliasStatelessImmediate(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(t=s1_){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let i=setTimeout(()=>{n(),r(!1)},t),n=this._events.on("localEvaluationFlagsLoaded",a=>{clearTimeout(i),n(),r(a>0)})})}async getFeatureFlag(t,r,i){let{groups:n,disableGeoip:a}=i||{},{onlyEvaluateLocally:o,sendFeatureFlagEvents:c,personProperties:d,groupProperties:s}=i||{},u=this.addLocalPersonAndGroupProperties(r,n,d,s);d=u.allPersonProperties,s=u.allGroupProperties,o==null&&(o=!1),c==null&&(c=this.options.sendFeatureFlagEvent??!0);let f=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,d,s),p=f!==void 0,_,h,y;if(!p&&!o){let v=await super.getFeatureFlagDetailStateless(t,r,n,d,s,a);if(v===void 0)return;y=v.response,f=f_n(y),_=v?.requestId,h=v?.evaluatedAt}let b=`${t}_${f}`;return c&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(b))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(b):this.distinctIdHasSentFlagCalls[r]=[b],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:f,$feature_flag_id:y?.metadata?.id,$feature_flag_version:y?.metadata?.version,$feature_flag_reason:y?.reason?.description??y?.reason?.code,locally_evaluated:p,[`$feature/${t}`]:f,$feature_flag_request_id:_,$feature_flag_evaluated_at:h},groups:n,disableGeoip:a})),f}async getFeatureFlagPayload(t,r,i,n){let{groups:a,disableGeoip:o}=n||{},{onlyEvaluateLocally:c,personProperties:d,groupProperties:s}=n||{},u=this.addLocalPersonAndGroupProperties(r,a,d,s);d=u.allPersonProperties,s=u.allGroupProperties;let f;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let h=this.featureFlagsPoller?.featureFlagsByKey[t];if(h)try{let y=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(h,r,a,d,s,i);y&&(i=y.value,f=y.payload)}catch(y){if(y instanceof TJt||y instanceof s0)this._logger?.info(`${y.name} when computing flag locally: ${h.key}: ${y.message}`);else throw y}}return c==null&&(c=!1),!(f!==void 0)&&!c&&(f=await super.getFeatureFlagPayloadStateless(t,r,a,d,s,o)),f}async getRemoteConfigPayload(t){if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let r=await this._requestRemoteConfigPayload(t);if(!r)return;let i=await r.json();if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}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,flagKeys:a}=r||{},{onlyEvaluateLocally:o,personProperties:c,groupProperties:d}=r||{},s=this.addLocalPersonAndGroupProperties(t,i,c,d);c=s.allPersonProperties,d=s.allGroupProperties,o==null&&(o=!1);let u=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,c,d,a),f={},p={},_=!0;if(u&&(f=u.response,p=u.payloads,_=u.fallbackToFlags),_&&!o){let h=await super.getFeatureFlagsAndPayloadsStateless(t,i,c,d,n,a);f={...f,...h.flags||{}},p={...p,...h.payloads||{}}}return{featureFlags:f,featureFlagPayloads:p}}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)}withContext(t,r,i){return this.context?this.context.run(t,r,i):r()}getContext(){return this.context?.get()}async _shutdown(t){return this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown(),super._shutdown(t)}async _requestRemoteConfigPayload(t){if(!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config?token=${encodeURIComponent(this.apiKey)}`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},n=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let a=new AbortController;n=p_n(()=>{a.abort()},this.options.requestTimeout),i.signal=a.signal}try{return await this.fetch(r,i)}catch(a){this._events.emit("error",a);return}finally{n&&clearTimeout(n)}}extractPropertiesFromEvent(t,r){if(!t)return{personProperties:{},groupProperties:{}};let i={},n={};for(let[a,o]of Object.entries(t))if(_q_(o)&&r&&a in r){let c={};for(let[d,s]of Object.entries(o))c[String(d)]=String(s);n[String(a)]=c}else i[String(a)]=String(o);return{personProperties:i,groupProperties:n}}async getFeatureFlagsForEvent(t,r,i,n){let a=n?.personProperties||{},o=n?.groupProperties||{},c=n?.flagKeys;if(n?.onlyEvaluateLocally??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let s={};for(let[u,f]of Object.entries(r||{}))s[u]=String(f);return await this.getAllFlags(t,{groups:s,personProperties:a,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:c})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let s={};for(let[u,f]of Object.entries(r||{}))s[u]=String(f);return await this.getAllFlags(t,{groups:s,personProperties:a,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:c})}return(await super.getFeatureFlagsStateless(t,r,a,o,i)).flags}addLocalPersonAndGroupProperties(t,r,i,n){let a={distinct_id:t,...i||{}},o={};if(r)for(let c of Object.keys(r))o[c]={$group_key:r[c],...n?.[c]||{}};return{allPersonProperties:a,allGroupProperties:o}}captureException(t,r,i){let n=new Error("PostHog syntheticException");this.addPendingPromise(_Fi.buildEventMessage(t,{syntheticException:n},r,i).then(a=>this.capture(a)))}async captureExceptionImmediate(t,r,i){let n=new Error("PostHog syntheticException");this.addPendingPromise(_Fi.buildEventMessage(t,{syntheticException:n},r,i).then(a=>this.captureImmediate(a)))}async prepareEventMessage(t){let{distinctId:r,event:i,properties:n,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s}=t,u=this.context?.get(),f=r||u?.distinctId,p={...u?.properties||{},...n||{}};f||(f=CJt(),p.$process_person_profile=!1),u?.sessionId&&!p.$session_id&&(p.$session_id=u.sessionId);let _=this._runBeforeSend({distinctId:f,event:i,properties:p,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s});if(!_)return Promise.reject(null);let h=await Promise.resolve().then(async()=>{if(o){let y=typeof o=="object"?o:void 0;return await this.getFeatureFlagsForEvent(_.distinctId,a,d,y)}return _.event,{}}).then(y=>{let b={};if(y)for(let[O,A]of Object.entries(y))b[`$feature/${O}`]=A;let v=Object.keys(y||{}).filter(O=>y?.[O]!==!1).sort();return v.length>0&&(b.$active_feature_flags=v),b}).catch(()=>({})).then(y=>({...y,..._.properties||{},$groups:_.groups||a}));return _.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof h.$raw_user_agent=="string"&&sq_(h.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(_.event="$bot_pageview",h.$browser_type="bot"),{distinctId:_.distinctId,event:_.event,properties:h,options:{timestamp:_.timestamp,disableGeoip:_.disableGeoip,uuid:_.uuid}}}_runBeforeSend(t){let r=this.options.before_send;if(!r)return t;let i=Array.isArray(r)?r:[r],n=t;for(let a of i){if(n=a(n),!n)return this._logger.info(`Event '${t.event}' was rejected in beforeSend function`),null;if(!n.properties||Object.keys(n.properties).length===0){let o=`Event '${n.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(o)}}return n}};var c1_=require("async_hooks"),y7o=class{constructor(){this.storage=new c1_.AsyncLocalStorage}get(){return this.storage.getStore()}run(t,r,i){if(i?.fresh===!0)return this.storage.run(t,r);{let a=this.get()||{},o={distinctId:t.distinctId??a.distinctId,sessionId:t.sessionId??a.sessionId,properties:{...a.properties||{},...t.properties||{}}};return this.storage.run(o,r)}}};var l1_="posthog-node";function HKM(e,{organization:t,projectId:r,prefix:i,severityAllowList:n=["error"],sendExceptionsToPostHog:a=!0}={}){return o=>{if(!(n==="*"||n.includes(o.level)))return o;o.tags||(o.tags={});let d=o.tags[G0c.POSTHOG_ID_TAG];if(d===void 0)return o;let s=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${d}`,s).toString();o.tags["PostHog Person URL"]=u;let f=o.exception?.values||[],p=f.map(h=>({...h,stacktrace:h.stacktrace?{...h.stacktrace,type:"raw",frames:(h.stacktrace.frames||[]).map(y=>({...y,platform:"node:javascript"}))}:void 0})),_={$exception_message:f[0]?.value||o.message,$exception_type:f[0]?.type,$exception_level:o.level,$exception_list:p,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:f[0]?.value||o.message,$sentry_exception_type:f[0]?.type,$sentry_tags:o.tags};return t&&r&&(_.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+o.event_id),a&&e.capture({event:"$exception",distinctId:d,properties:_}),o}}var G0c=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,i,n,a){this.name=l1_,this.name=l1_,this.setupOnce=function(o,c){let d=c()?.getClient()?.getDsn()?.projectId;o(HKM(t,{organization:r,projectId:d,prefix:i,severityAllowList:n,sendExceptionsToPostHog:a??!0}))}}};_Fi.errorPropertiesBuilder=new r$.ErrorPropertiesBuilder([new r$.EventCoercer,new r$.ErrorCoercer,new r$.ObjectCoercer,new r$.StringCoercer,new r$.PrimitiveCoercer],r$.createStackParser("node:javascript",r$.nodeStackLineParser),[iq_(),$q_]);var ekn=class extends h7o{getLibraryId(){return"posthog-node"}initializeContext(){return new y7o}};var b7o=class{posthog;constructor({posthogApiKey:t}){this.posthog=new ekn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"3.37.5",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var SWa=class{async sendEvent(){}async identify(){}async flush(){}};var tkn=require("fs/promises"),_1_=require("os"),h1_=require("path");var f1_=ce(require("crypto")),g7o=new Uint8Array(256),v7o=g7o.length;function H0c(){return v7o>g7o.length-16&&(f1_.default.randomFillSync(g7o),v7o=0),g7o.slice(v7o,v7o+=16)}var D4=[];for(let e=0;e<256;++e)D4.push((e+256).toString(16).slice(1));function d1_(e,t=0){return D4[e[t+0]]+D4[e[t+1]]+D4[e[t+2]]+D4[e[t+3]]+"-"+D4[e[t+4]]+D4[e[t+5]]+"-"+D4[e[t+6]]+D4[e[t+7]]+"-"+D4[e[t+8]]+D4[e[t+9]]+"-"+D4[e[t+10]]+D4[e[t+11]]+D4[e[t+12]]+D4[e[t+13]]+D4[e[t+14]]+D4[e[t+15]]}var p1_=ce(require("crypto")),x0c={randomUUID:p1_.default.randomUUID};function xKM(e,t,r){if(x0c.randomUUID&&!t&&!e)return x0c.randomUUID();e=e||{};let i=e.random||(e.rng||H0c)();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 d1_(i)}var Hbe=xKM;var KKM="id",JKM=".fern",MWa=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new ekn(r),this.userId=t==null?void 0:Fvc(t),this.token=t}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){let r=await this.getUserEmail();this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"3.37.5",...t,...t.properties,usingAccessToken:!1,...r!=null?{userEmail:r}:{}}})}async flush(){await this.posthog.flush()}userEmail;async getUserEmail(){if(this.userEmail!==null){if(this.userEmail!=null)return this.userEmail;if(this.token==null){this.userEmail=null;return}try{let t=await g4({token:this.token.value}).user.getMyself();if(t.ok&&t.body.email!=null)return this.userEmail=t.body.email,this.userEmail}catch{}this.userEmail=null}}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=It(Sr.of((0,_1_.homedir)()),Xe.of(JKM),Xe.of(KKM));await mi(t)||(await(0,tkn.mkdir)((0,h1_.dirname)(t),{recursive:!0}),await(0,tkn.writeFile)(t,Hbe())),this.persistedDistinctId=(await(0,tkn.readFile)(t)).toString()}return this.persistedDistinctId}};var K0c;async function rkn(){return K0c==null&&(K0c=await $KM()),K0c}async function $KM(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new SWa;let r=await U8o();return r!=null?new MWa({token:r,posthogApiKey:e}):await fZn()!=null?new b7o({posthogApiKey:e}):new MWa({token:void 0,posthogApiKey:e})}catch{return new SWa}}function DWa(e,t){return function(){return e.apply(t,arguments)}}var{toString:YKM}=Object.prototype,{getPrototypeOf:$0c}=Object,{iterator:A7o,toStringTag:b1_}=Symbol,m7o=(e=>t=>{let r=YKM.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),YVt=e=>(e=e.toLowerCase(),t=>m7o(t)===e),P7o=e=>t=>typeof t===e,{isArray:nkn}=Array,ikn=P7o("undefined");function BWa(e){return e!==null&&!ikn(e)&&e.constructor!==null&&!ikn(e.constructor)&&i$(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var v1_=YVt("ArrayBuffer");function XKM(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&v1_(e.buffer),t}var ZKM=P7o("string"),i$=P7o("function"),g1_=P7o("number"),IWa=e=>e!==null&&typeof e=="object",kKM=e=>e===!0||e===!1,O7o=e=>{if(m7o(e)!=="object")return!1;let t=$0c(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(b1_ in e)&&!(A7o in e)},eJM=e=>{if(!IWa(e)||BWa(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},tJM=YVt("Date"),rJM=YVt("File"),iJM=YVt("Blob"),nJM=YVt("FileList"),aJM=e=>IWa(e)&&i$(e.pipe),oJM=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||i$(e.append)&&((t=m7o(e))==="formdata"||t==="object"&&i$(e.toString)&&e.toString()==="[object FormData]"))},uJM=YVt("URLSearchParams"),[sJM,cJM,lJM,fJM]=["ReadableStream","Request","Response","Headers"].map(YVt),dJM=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function CWa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),nkn(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{if(BWa(e))return;let a=r?Object.getOwnPropertyNames(e):Object.keys(e),o=a.length,c;for(i=0;i<o;i++)c=a[i],t.call(null,e[c],c,e)}}function O1_(e,t){if(BWa(e))return null;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 __n=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,A1_=e=>!ikn(e)&&e!==__n;function J0c(){let{caseless:e,skipUndefined:t}=A1_(this)&&this||{},r={},i=(n,a)=>{let o=e&&O1_(r,a)||a;O7o(r[o])&&O7o(n)?r[o]=J0c(r[o],n):O7o(n)?r[o]=J0c({},n):nkn(n)?r[o]=n.slice():(!t||!ikn(n))&&(r[o]=n)};for(let n=0,a=arguments.length;n<a;n++)arguments[n]&&CWa(arguments[n],i);return r}var pJM=(e,t,r,{allOwnKeys:i}={})=>(CWa(t,(n,a)=>{r&&i$(n)?e[a]=DWa(n,r):e[a]=n},{allOwnKeys:i}),e),_JM=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),hJM=(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)},yJM=(e,t,r,i)=>{let n,a,o,c={};if(t=t||{},e==null)return t;do{for(n=Object.getOwnPropertyNames(e),a=n.length;a-- >0;)o=n[a],(!i||i(o,e,t))&&!c[o]&&(t[o]=e[o],c[o]=!0);e=r!==!1&&$0c(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},bJM=(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},vJM=e=>{if(!e)return null;if(nkn(e))return e;let t=e.length;if(!g1_(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},gJM=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&$0c(Uint8Array)),OJM=(e,t)=>{let i=(e&&e[A7o]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},AJM=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},mJM=YVt("HTMLFormElement"),PJM=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),y1_=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),jJM=YVt("RegExp"),m1_=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};CWa(r,(n,a)=>{let o;(o=t(n,a,e))!==!1&&(i[a]=o||n)}),Object.defineProperties(e,i)},wJM=e=>{m1_(e,(t,r)=>{if(i$(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(i$(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+"'")})}})},EJM=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return nkn(e)?i(e):i(String(e).split(t)),r},SJM=()=>{},MJM=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function DJM(e){return!!(e&&i$(e.append)&&e[b1_]==="FormData"&&e[A7o])}var BJM=e=>{let t=new Array(10),r=(i,n)=>{if(IWa(i)){if(t.indexOf(i)>=0)return;if(BWa(i))return i;if(!("toJSON"in i)){t[n]=i;let a=nkn(i)?[]:{};return CWa(i,(o,c)=>{let d=r(o,n+1);!ikn(d)&&(a[c]=d)}),t[n]=void 0,a}}return i};return r(e,0)},IJM=YVt("AsyncFunction"),CJM=e=>e&&(IWa(e)||i$(e))&&i$(e.then)&&i$(e.catch),P1_=((e,t)=>e?setImmediate:t?((r,i)=>(__n.addEventListener("message",({source:n,data:a})=>{n===__n&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),__n.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",i$(__n.postMessage)),qJM=typeof queueMicrotask<"u"?queueMicrotask.bind(__n):typeof process<"u"&&process.nextTick||P1_,TJM=e=>e!=null&&i$(e[A7o]),rr={isArray:nkn,isArrayBuffer:v1_,isBuffer:BWa,isFormData:oJM,isArrayBufferView:XKM,isString:ZKM,isNumber:g1_,isBoolean:kKM,isObject:IWa,isPlainObject:O7o,isEmptyObject:eJM,isReadableStream:sJM,isRequest:cJM,isResponse:lJM,isHeaders:fJM,isUndefined:ikn,isDate:tJM,isFile:rJM,isBlob:iJM,isRegExp:jJM,isFunction:i$,isStream:aJM,isURLSearchParams:uJM,isTypedArray:gJM,isFileList:nJM,forEach:CWa,merge:J0c,extend:pJM,trim:dJM,stripBOM:_JM,inherits:hJM,toFlatObject:yJM,kindOf:m7o,kindOfTest:YVt,endsWith:bJM,toArray:vJM,forEachEntry:OJM,matchAll:AJM,isHTMLForm:mJM,hasOwnProperty:y1_,hasOwnProp:y1_,reduceDescriptors:m1_,freezeMethods:wJM,toObjectSet:EJM,toCamelCase:PJM,noop:SJM,toFiniteNumber:MJM,findKey:O1_,global:__n,isContextDefined:A1_,isSpecCompliantForm:DJM,toJSONObject:BJM,isAsyncFn:IJM,isThenable:CJM,setImmediate:P1_,asap:qJM,isIterable:TJM};function akn(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)}rr.inherits(akn,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:rr.toJSONObject(this.config),code:this.code,status:this.status}}});var j1_=akn.prototype,w1_={};["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=>{w1_[e]={value:e}});Object.defineProperties(akn,w1_);Object.defineProperty(j1_,"isAxiosError",{value:!0});akn.from=(e,t,r,i,n,a)=>{let o=Object.create(j1_);rr.toFlatObject(e,o,function(u){return u!==Error.prototype},s=>s!=="isAxiosError");let c=e&&e.message?e.message:"Error",d=t==null&&e?e.code:t;return akn.call(o,c,d,r,i,n),e&&o.cause==null&&Object.defineProperty(o,"cause",{value:e,configurable:!0}),o.name=e&&e.name||"Error",a&&Object.assign(o,a),o};var Ma=akn;var E1_=ce(EXn(),1),j7o=E1_.default;function Y0c(e){return rr.isPlainObject(e)||rr.isArray(e)}function M1_(e){return rr.endsWith(e,"[]")?e.slice(0,-2):e}function S1_(e,t,r){return e?e.concat(t).map(function(n,a){return n=M1_(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function RJM(e){return rr.isArray(e)&&!e.some(Y0c)}var zJM=rr.toFlatObject(rr,{},null,function(t){return/^is[A-Z]/.test(t)});function NJM(e,t,r){if(!rr.isObject(e))throw new TypeError("target must be an object");t=t||new(j7o||FormData),r=rr.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,b){return!rr.isUndefined(b[y])});let i=r.metaTokens,n=r.visitor||u,a=r.dots,o=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&rr.isSpecCompliantForm(t);if(!rr.isFunction(n))throw new TypeError("visitor must be a function");function s(h){if(h===null)return"";if(rr.isDate(h))return h.toISOString();if(rr.isBoolean(h))return h.toString();if(!d&&rr.isBlob(h))throw new Ma("Blob is not supported. Use a Buffer instead.");return rr.isArrayBuffer(h)||rr.isTypedArray(h)?d&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function u(h,y,b){let v=h;if(h&&!b&&typeof h=="object"){if(rr.endsWith(y,"{}"))y=i?y:y.slice(0,-2),h=JSON.stringify(h);else if(rr.isArray(h)&&RJM(h)||(rr.isFileList(h)||rr.endsWith(y,"[]"))&&(v=rr.toArray(h)))return y=M1_(y),v.forEach(function(A,g){!(rr.isUndefined(A)||A===null)&&t.append(o===!0?S1_([y],g,a):o===null?y:y+"[]",s(A))}),!1}return Y0c(h)?!0:(t.append(S1_(b,y,a),s(h)),!1)}let f=[],p=Object.assign(zJM,{defaultVisitor:u,convertValue:s,isVisitable:Y0c});function _(h,y){if(!rr.isUndefined(h)){if(f.indexOf(h)!==-1)throw Error("Circular reference detected in "+y.join("."));f.push(h),rr.forEach(h,function(v,O){(!(rr.isUndefined(v)||v===null)&&n.call(t,v,rr.isString(O)?O.trim():O,y,p))===!0&&_(v,y?y.concat(O):[O])}),f.pop()}}if(!rr.isObject(e))throw new TypeError("data must be an object");return _(e),t}var M7i=NJM;function D1_(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function B1_(e,t){this._pairs=[],e&&M7i(e,this,t)}var I1_=B1_.prototype;I1_.append=function(t,r){this._pairs.push([t,r])};I1_.toString=function(t){let r=t?function(i){return t.call(this,i,D1_)}:D1_;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var C1_=B1_;function FJM(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function h_n(e,t,r){if(!t)return e;let i=r&&r.encode||FJM;rr.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=rr.isURLSearchParams(t)?t.toString():new C1_(t,r).toString(i),a){let o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var X0c=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){rr.forEach(this.handlers,function(i){i!==null&&t(i)})}},Z0c=X0c;var okn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var z1_=ce(require("crypto"),1);var q1_=ce(require("url"),1),T1_=q1_.default.URLSearchParams;var k0c="abcdefghijklmnopqrstuvwxyz",R1_="0123456789",N1_={DIGIT:R1_,ALPHA:k0c,ALPHA_DIGIT:k0c+k0c.toUpperCase()+R1_},QJM=(e=16,t=N1_.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);z1_.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},F1_={isNode:!0,classes:{URLSearchParams:T1_,FormData:j7o,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:N1_,generateString:QJM,protocols:["http","https","file","data"]};var rwc={};Zt(rwc,{hasBrowserEnv:()=>twc,hasStandardBrowserEnv:()=>UJM,hasStandardBrowserWebWorkerEnv:()=>LJM,navigator:()=>ewc,origin:()=>VJM});var twc=typeof window<"u"&&typeof document<"u",ewc=typeof navigator=="object"&&navigator||void 0,UJM=twc&&(!ewc||["ReactNative","NativeScript","NS"].indexOf(ewc.product)<0),LJM=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",VJM=twc&&window.location.href||"http://localhost";var YA={...rwc,...F1_};function iwc(e,t){return M7i(e,new YA.classes.URLSearchParams,{visitor:function(r,i,n,a){return YA.isNode&&rr.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function WJM(e){return rr.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function GJM(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 HJM(e){function t(r,i,n,a){let o=r[a++];if(o==="__proto__")return!0;let c=Number.isFinite(+o),d=a>=r.length;return o=!o&&rr.isArray(n)?n.length:o,d?(rr.hasOwnProp(n,o)?n[o]=[n[o],i]:n[o]=i,!c):((!n[o]||!rr.isObject(n[o]))&&(n[o]=[]),t(r,i,n[o],a)&&rr.isArray(n[o])&&(n[o]=GJM(n[o])),!c)}if(rr.isFormData(e)&&rr.isFunction(e.entries)){let r={};return rr.forEachEntry(e,(i,n)=>{t(WJM(i),n,r,0)}),r}return null}var w7o=HJM;function xJM(e,t,r){if(rr.isString(e))try{return(t||JSON.parse)(e),rr.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var nwc={transitional:okn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=rr.isObject(t);if(a&&rr.isHTMLForm(t)&&(t=new FormData(t)),rr.isFormData(t))return n?JSON.stringify(w7o(t)):t;if(rr.isArrayBuffer(t)||rr.isBuffer(t)||rr.isStream(t)||rr.isFile(t)||rr.isBlob(t)||rr.isReadableStream(t))return t;if(rr.isArrayBufferView(t))return t.buffer;if(rr.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return iwc(t,this.formSerializer).toString();if((c=rr.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return M7i(c?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),xJM(t)):t}],transformResponse:[function(t){let r=this.transitional||nwc.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(rr.isResponse(t)||rr.isReadableStream(t))return t;if(t&&rr.isString(t)&&(i&&!this.responseType||n)){let o=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t,this.parseReviver)}catch(c){if(o)throw c.name==="SyntaxError"?Ma.from(c,Ma.ERR_BAD_RESPONSE,this,null,this.response):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:YA.classes.FormData,Blob:YA.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};rr.forEach(["delete","get","head","post","put","patch"],e=>{nwc.headers[e]={}});var ukn=nwc;var KJM=rr.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"]),Q1_=e=>{let t={},r,i,n;return e&&e.split(`
1149
1149
  `).forEach(function(o){n=o.indexOf(":"),r=o.substring(0,n).trim().toLowerCase(),i=o.substring(n+1).trim(),!(!r||t[r]&&KJM[r])&&(r==="set-cookie"?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t};var U1_=Symbol("internals");function qWa(e){return e&&String(e).trim().toLowerCase()}function E7o(e){return e===!1||e==null?e:rr.isArray(e)?e.map(E7o):String(e)}function JJM(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 $JM=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function awc(e,t,r,i,n){if(rr.isFunction(i))return i.call(this,t,r);if(n&&(t=r),!!rr.isString(t)){if(rr.isString(i))return t.indexOf(i)!==-1;if(rr.isRegExp(i))return i.test(t)}}function YJM(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,i)=>r.toUpperCase()+i)}function XJM(e,t){let r=rr.toCamelCase(" "+t);["get","set","has"].forEach(i=>{Object.defineProperty(e,i+r,{value:function(n,a,o){return this[i].call(this,t,n,a,o)},configurable:!0})})}var skn=class{constructor(t){t&&this.set(t)}set(t,r,i){let n=this;function a(c,d,s){let u=qWa(d);if(!u)throw new Error("header name must be a non-empty string");let f=rr.findKey(n,u);(!f||n[f]===void 0||s===!0||s===void 0&&n[f]!==!1)&&(n[f||d]=E7o(c))}let o=(c,d)=>rr.forEach(c,(s,u)=>a(s,u,d));if(rr.isPlainObject(t)||t instanceof this.constructor)o(t,r);else if(rr.isString(t)&&(t=t.trim())&&!$JM(t))o(Q1_(t),r);else if(rr.isObject(t)&&rr.isIterable(t)){let c={},d,s;for(let u of t){if(!rr.isArray(u))throw TypeError("Object iterator must return a key-value pair");c[s=u[0]]=(d=c[s])?rr.isArray(d)?[...d,u[1]]:[d,u[1]]:u[1]}o(c,r)}else t!=null&&a(r,t,i);return this}get(t,r){if(t=qWa(t),t){let i=rr.findKey(this,t);if(i){let n=this[i];if(!r)return n;if(r===!0)return JJM(n);if(rr.isFunction(r))return r.call(this,n,i);if(rr.isRegExp(r))return r.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=qWa(t),t){let i=rr.findKey(this,t);return!!(i&&this[i]!==void 0&&(!r||awc(this,this[i],i,r)))}return!1}delete(t,r){let i=this,n=!1;function a(o){if(o=qWa(o),o){let c=rr.findKey(i,o);c&&(!r||awc(i,i[c],c,r))&&(delete i[c],n=!0)}}return rr.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||awc(this,this[a],a,t,!0))&&(delete this[a],n=!0)}return n}normalize(t){let r=this,i={};return rr.forEach(this,(n,a)=>{let o=rr.findKey(i,a);if(o){r[o]=E7o(n),delete r[a];return}let c=t?YJM(a):String(a).trim();c!==a&&delete r[a],r[c]=E7o(n),i[c]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return rr.forEach(this,(i,n)=>{i!=null&&i!==!1&&(r[n]=t&&rr.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(`
1150
1150
  `)}getSetCookie(){return this.get("set-cookie")||[]}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[U1_]=this[U1_]={accessors:{}}).accessors,n=this.prototype;function a(o){let c=qWa(o);i[c]||(XJM(n,o),i[c]=!0)}return rr.isArray(t)?t.forEach(a):a(t),this}};skn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);rr.reduceDescriptors(skn.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(i){this[r]=i}}});rr.freezeMethods(skn);var JM=skn;function TWa(e,t){let r=this||ukn,i=t||r,n=JM.from(i.headers),a=i.data;return rr.forEach(e,function(c){a=c.call(r,a,n.normalize(),t?t.status:void 0)}),n.normalize(),a}function RWa(e){return!!(e&&e.__CANCEL__)}function L1_(e,t,r){Ma.call(this,e??"canceled",Ma.ERR_CANCELED,t,r),this.name="CanceledError"}rr.inherits(L1_,Ma,{__CANCEL__:!0});var xbe=L1_;function RJt(e,t,r){let i=r.config.validateStatus;!r.status||!i||i(r.status)?e(r):t(new Ma("Request failed with status code "+r.status,[Ma.ERR_BAD_REQUEST,Ma.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function owc(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function uwc(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function y_n(e,t,r){let i=!owc(t);return e&&(i||r==!1)?uwc(e,t):t}var fT_=ce(swc(),1),dT_=ce(require("http"),1),pT_=ce(require("https"),1),_T_=ce(require("util"),1),hT_=ce($1_(),1),yFi=ce(require("zlib"),1);var g_n="1.12.2";function UWa(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var _$M=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function Awc(e,t,r){let i=r&&r.Blob||YA.classes.Blob,n=UWa(e);if(t===void 0&&i&&(t=!0),n==="data"){e=n.length?e.slice(n.length+1):e;let a=_$M.exec(e);if(!a)throw new Ma("Invalid URL",Ma.ERR_INVALID_URL);let o=a[1],c=a[2],d=a[3],s=Buffer.from(decodeURIComponent(d),c?"base64":"utf8");if(t){if(!i)throw new Ma("Blob is not supported",Ma.ERR_NOT_SUPPORT);return new i([s],{type:o})}return s}throw new Ma("Unsupported protocol "+n,Ma.ERR_NOT_SUPPORT)}var A_n=ce(require("stream"),1);var Y1_=ce(require("stream"),1);var mwc=Symbol("internals"),Pwc=class extends Y1_.default.Transform{constructor(t){t=rr.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(i,n)=>!rr.isUndefined(n[i])),super({readableHighWaterMark:t.chunkSize});let r=this[mwc]={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[mwc];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,i){let n=this[mwc],a=n.maxRate,o=this.readableHighWaterMark,c=n.timeWindow,d=1e3/c,s=a/d,u=n.minChunkSize!==!1?Math.max(n.minChunkSize,s*.01):0,f=(_,h)=>{let y=Buffer.byteLength(_);n.bytesSeen+=y,n.bytes+=y,n.isCaptured&&this.emit("progress",n.bytesSeen),this.push(_)?process.nextTick(h):n.onReadCallback=()=>{n.onReadCallback=null,process.nextTick(h)}},p=(_,h)=>{let y=Buffer.byteLength(_),b=null,v=o,O,A=0;if(a){let g=Date.now();(!n.ts||(A=g-n.ts)>=c)&&(n.ts=g,O=s-n.bytes,n.bytes=O<0?-O:0,A=0),O=s-n.bytes}if(a){if(O<=0)return setTimeout(()=>{h(null,_)},c-A);O<v&&(v=O)}v&&y>v&&y-v>u&&(b=_.subarray(v),_=_.subarray(0,v)),f(_,b?()=>{process.nextTick(h,null,b)}:h)};p(t,function _(h,y){if(h)return i(h);y?p(y,_):i(null)})}},jwc=Pwc;var yT_=require("events");var Z1_=ce(require("util"),1),k1_=require("stream");var{asyncIterator:X1_}=Symbol,h$M=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[X1_]?yield*e[X1_]():yield e},S7o=h$M;var y$M=YA.ALPHABET.ALPHA_DIGIT+"-_",LWa=typeof TextEncoder=="function"?new TextEncoder:new Z1_.default.TextEncoder,O_n=`\r
1151
1151
  `,b$M=LWa.encode(O_n),v$M=2,wwc=class{constructor(t,r){let{escapeName:i}=this.constructor,n=rr.isString(r),a=`Content-Disposition: form-data; name="${i(t)}"${!n&&r.name?`; filename="${i(r.name)}"`:""}${O_n}`;n?r=LWa.encode(String(r).replace(/\r?\n|\r\n?/g,O_n)):a+=`Content-Type: ${r.type||"application/octet-stream"}${O_n}`,this.headers=LWa.encode(a+O_n),this.contentLength=n?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+v$M,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;rr.isTypedArray(t)?yield t:yield*S7o(t),yield b$M}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},g$M=(e,t,r)=>{let{tag:i="form-data-boundary",size:n=25,boundary:a=i+"-"+YA.generateString(n,y$M)}=r||{};if(!rr.isFormData(e))throw TypeError("FormData instance required");if(a.length<1||a.length>70)throw Error("boundary must be 10-70 characters long");let o=LWa.encode("--"+a+O_n),c=LWa.encode("--"+a+"--"+O_n),d=c.byteLength,s=Array.from(e.entries()).map(([f,p])=>{let _=new wwc(f,p);return d+=_.size,_});d+=o.byteLength*s.length,d=rr.toFiniteNumber(d);let u={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(d)&&(u["Content-Length"]=d),t&&t(u),k1_.Readable.from((async function*(){for(let f of s)yield o,yield*f.encode();yield c})())},eT_=g$M;var tT_=ce(require("stream"),1),Ewc=class extends tT_.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)}},rT_=Ewc;var O$M=(e,t)=>rr.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,iT_=O$M;function A$M(e,t){e=e||10;let r=new Array(e),i=new Array(e),n=0,a=0,o;return t=t!==void 0?t:1e3,function(d){let s=Date.now(),u=i[a];o||(o=s),r[n]=d,i[n]=s;let f=a,p=0;for(;f!==n;)p+=r[f++],f=f%e;if(n=(n+1)%e,n===a&&(a=(a+1)%e),s-o<t)return;let _=u&&s-u;return _?Math.round(p*1e3/_):void 0}}var nT_=A$M;function m$M(e,t){let r=0,i=1e3/t,n,a,o=(s,u=Date.now())=>{r=u,n=null,a&&(clearTimeout(a),a=null),e(...s)};return[(...s)=>{let u=Date.now(),f=u-r;f>=i?o(s,u):(n=s,a||(a=setTimeout(()=>{a=null,o(n)},i-f)))},()=>n&&o(n)]}var aT_=m$M;var hFi=(e,t,r=3)=>{let i=0,n=nT_(50,250);return aT_(a=>{let o=a.loaded,c=a.lengthComputable?a.total:void 0,d=o-i,s=n(d),u=o<=c;i=o;let f={loaded:o,total:c,progress:c?o/c:void 0,bytes:d,rate:s||void 0,estimated:s&&c&&u?(c-o)/s:void 0,event:a,lengthComputable:c!=null,[t?"download":"upload"]:!0};e(f)},r)},lkn=(e,t)=>{let r=e!=null;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},fkn=e=>(...t)=>rr.asap(()=>e(...t));function Swc(e){if(!e||typeof e!="string"||!e.startsWith("data:"))return 0;let t=e.indexOf(",");if(t<0)return 0;let r=e.slice(5,t),i=e.slice(t+1);if(/;base64/i.test(r)){let a=i.length,o=i.length;for(let p=0;p<o;p++)if(i.charCodeAt(p)===37&&p+2<o){let _=i.charCodeAt(p+1),h=i.charCodeAt(p+2);(_>=48&&_<=57||_>=65&&_<=70||_>=97&&_<=102)&&(h>=48&&h<=57||h>=65&&h<=70||h>=97&&h<=102)&&(a-=2,p+=2)}let c=0,d=o-1,s=p=>p>=2&&i.charCodeAt(p-2)===37&&i.charCodeAt(p-1)===51&&(i.charCodeAt(p)===68||i.charCodeAt(p)===100);d>=0&&(i.charCodeAt(d)===61?(c++,d--):s(d)&&(c++,d-=3)),c===1&&d>=0&&(i.charCodeAt(d)===61||s(d))&&c++;let f=Math.floor(a/4)*3-(c||0);return f>0?f:0}return Buffer.byteLength(i,"utf8")}var oT_={flush:yFi.default.constants.Z_SYNC_FLUSH,finishFlush:yFi.default.constants.Z_SYNC_FLUSH},P$M={flush:yFi.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:yFi.default.constants.BROTLI_OPERATION_FLUSH},uT_=rr.isFunction(yFi.default.createBrotliDecompress),{http:j$M,https:w$M}=hT_.default,E$M=/https:?/,sT_=YA.protocols.map(e=>e+":"),cT_=(e,[t,r])=>(e.on("end",r).on("error",r),t);function S$M(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function bT_(e,t,r){let i=t;if(!i&&i!==!1){let n=fT_.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){bT_(a,t,a.href)}}var M$M=typeof process<"u"&&rr.kindOf(process)==="process",D$M=e=>new Promise((t,r)=>{let i,n,a=(d,s)=>{n||(n=!0,i&&i(d,s))},o=d=>{a(d),t(d)},c=d=>{a(d,!0),r(d)};e(o,c,d=>i=d).catch(c)}),B$M=({address:e,family:t})=>{if(!rr.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},lT_=(e,t)=>B$M(rr.isObject(e)?e:{address:e,family:t}),vT_=M$M&&function(t){return D$M(async function(i,n,a){let{data:o,lookup:c,family:d}=t,{responseType:s,responseEncoding:u}=t,f=t.method.toUpperCase(),p,_=!1,h;if(c){let ee=iT_(c,me=>rr.isArray(me)?me:[me]);c=(me,ve,H)=>{ee(me,ve,(G,Ee,ue)=>{if(G)return H(G);let ge=rr.isArray(Ee)?Ee.map(We=>lT_(We)):[lT_(Ee,ue)];ve.all?H(G,ge):H(G,ge[0].address,ge[0].family)})}}let y=new yT_.EventEmitter,b=()=>{t.cancelToken&&t.cancelToken.unsubscribe(v),t.signal&&t.signal.removeEventListener("abort",v),y.removeAllListeners()};a((ee,me)=>{p=!0,me&&(_=!0,b())});function v(ee){y.emit("abort",!ee||ee.type?new xbe(null,t,h):ee)}y.once("abort",n),(t.cancelToken||t.signal)&&(t.cancelToken&&t.cancelToken.subscribe(v),t.signal&&(t.signal.aborted?v():t.signal.addEventListener("abort",v)));let O=y_n(t.baseURL,t.url,t.allowAbsoluteUrls),A=new URL(O,YA.hasBrowserEnv?YA.origin:void 0),g=A.protocol||sT_[0];if(g==="data:"){if(t.maxContentLength>-1){let me=String(t.url||O||"");if(Swc(me)>t.maxContentLength)return n(new Ma("maxContentLength size of "+t.maxContentLength+" exceeded",Ma.ERR_BAD_RESPONSE,t))}let ee;if(f!=="GET")return RJt(i,n,{status:405,statusText:"method not allowed",headers:{},config:t});try{ee=Awc(t.url,s==="blob",{Blob:t.env&&t.env.Blob})}catch(me){throw Ma.from(me,Ma.ERR_BAD_REQUEST,t)}return s==="text"?(ee=ee.toString(u),(!u||u==="utf8")&&(ee=rr.stripBOM(ee))):s==="stream"&&(ee=A_n.default.Readable.from(ee)),RJt(i,n,{data:ee,status:200,statusText:"OK",headers:new JM,config:t})}if(sT_.indexOf(g)===-1)return n(new Ma("Unsupported protocol "+g,Ma.ERR_BAD_REQUEST,t));let m=JM.from(t.headers).normalize();m.set("User-Agent","axios/"+g_n,!1);let{onUploadProgress:j,onDownloadProgress:S}=t,w=t.maxRate,D,B;if(rr.isSpecCompliantForm(o)){let ee=m.getContentType(/boundary=([-_\w\d]{10,70})/i);o=eT_(o,me=>{m.set(me)},{tag:`axios-${g_n}-boundary`,boundary:ee&&ee[1]||void 0})}else if(rr.isFormData(o)&&rr.isFunction(o.getHeaders)){if(m.set(o.getHeaders()),!m.hasContentLength())try{let ee=await _T_.default.promisify(o.getLength).call(o);Number.isFinite(ee)&&ee>=0&&m.setContentLength(ee)}catch{}}else if(rr.isBlob(o)||rr.isFile(o))o.size&&m.setContentType(o.type||"application/octet-stream"),m.setContentLength(o.size||0),o=A_n.default.Readable.from(S7o(o));else if(o&&!rr.isStream(o)){if(!Buffer.isBuffer(o))if(rr.isArrayBuffer(o))o=Buffer.from(new Uint8Array(o));else if(rr.isString(o))o=Buffer.from(o,"utf-8");else return n(new Ma("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",Ma.ERR_BAD_REQUEST,t));if(m.setContentLength(o.length,!1),t.maxBodyLength>-1&&o.length>t.maxBodyLength)return n(new Ma("Request body larger than maxBodyLength limit",Ma.ERR_BAD_REQUEST,t))}let q=rr.toFiniteNumber(m.getContentLength());rr.isArray(w)?(D=w[0],B=w[1]):D=B=w,o&&(j||D)&&(rr.isStream(o)||(o=A_n.default.Readable.from(o,{objectMode:!1})),o=A_n.default.pipeline([o,new jwc({maxRate:rr.toFiniteNumber(D)})],rr.noop),j&&o.on("progress",cT_(o,lkn(q,hFi(fkn(j),!1,3)))));let U;if(t.auth){let ee=t.auth.username||"",me=t.auth.password||"";U=ee+":"+me}if(!U&&A.username){let ee=A.username,me=A.password;U=ee+":"+me}U&&m.delete("authorization");let R;try{R=h_n(A.pathname+A.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch(ee){let me=new Error(ee.message);return me.config=t,me.url=t.url,me.exists=!0,n(me)}m.set("Accept-Encoding","gzip, compress, deflate"+(uT_?", br":""),!1);let N={path:R,method:f,headers:m.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:U,protocol:g,family:d,beforeRedirect:S$M,beforeRedirects:{}};!rr.isUndefined(c)&&(N.lookup=c),t.socketPath?N.socketPath=t.socketPath:(N.hostname=A.hostname.startsWith("[")?A.hostname.slice(1,-1):A.hostname,N.port=A.port,bT_(N,t.proxy,g+"//"+A.hostname+(A.port?":"+A.port:"")+N.path));let F,x=E$M.test(N.protocol);if(N.agent=x?t.httpsAgent:t.httpAgent,t.transport?F=t.transport:t.maxRedirects===0?F=x?pT_.default:dT_.default:(t.maxRedirects&&(N.maxRedirects=t.maxRedirects),t.beforeRedirect&&(N.beforeRedirects.config=t.beforeRedirect),F=x?w$M:j$M),t.maxBodyLength>-1?N.maxBodyLength=t.maxBodyLength:N.maxBodyLength=1/0,t.insecureHTTPParser&&(N.insecureHTTPParser=t.insecureHTTPParser),h=F.request(N,function(me){if(h.destroyed)return;let ve=[me],H=+me.headers["content-length"];if(S||B){let We=new jwc({maxRate:rr.toFiniteNumber(B)});S&&We.on("progress",cT_(We,lkn(H,hFi(fkn(S),!0,3)))),ve.push(We)}let G=me,Ee=me.req||h;if(t.decompress!==!1&&me.headers["content-encoding"])switch((f==="HEAD"||me.statusCode===204)&&delete me.headers["content-encoding"],(me.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":ve.push(yFi.default.createUnzip(oT_)),delete me.headers["content-encoding"];break;case"deflate":ve.push(new rT_),ve.push(yFi.default.createUnzip(oT_)),delete me.headers["content-encoding"];break;case"br":uT_&&(ve.push(yFi.default.createBrotliDecompress(P$M)),delete me.headers["content-encoding"])}G=ve.length>1?A_n.default.pipeline(ve,rr.noop):ve[0];let ue=A_n.default.finished(G,()=>{ue(),b()}),ge={status:me.statusCode,statusText:me.statusMessage,headers:new JM(me.headers),config:t,request:Ee};if(s==="stream")ge.data=G,RJt(i,n,ge);else{let We=[],se=0;G.on("data",function(Fe){We.push(Fe),se+=Fe.length,t.maxContentLength>-1&&se>t.maxContentLength&&(_=!0,G.destroy(),n(new Ma("maxContentLength size of "+t.maxContentLength+" exceeded",Ma.ERR_BAD_RESPONSE,t,Ee)))}),G.on("aborted",function(){if(_)return;let Fe=new Ma("stream has been aborted",Ma.ERR_BAD_RESPONSE,t,Ee);G.destroy(Fe),n(Fe)}),G.on("error",function(Fe){h.destroyed||n(Ma.from(Fe,null,t,Ee))}),G.on("end",function(){try{let Fe=We.length===1?We[0]:Buffer.concat(We);s!=="arraybuffer"&&(Fe=Fe.toString(u),(!u||u==="utf8")&&(Fe=rr.stripBOM(Fe))),ge.data=Fe}catch(Fe){return n(Ma.from(Fe,null,t,ge.request,ge))}RJt(i,n,ge)})}y.once("abort",We=>{G.destroyed||(G.emit("error",We),G.destroy())})}),y.once("abort",ee=>{n(ee),h.destroy(ee)}),h.on("error",function(me){n(Ma.from(me,null,t,h))}),h.on("socket",function(me){me.setKeepAlive(!0,1e3*60)}),t.timeout){let ee=parseInt(t.timeout,10);if(Number.isNaN(ee)){n(new Ma("error trying to parse `config.timeout` to int",Ma.ERR_BAD_OPTION_VALUE,t,h));return}h.setTimeout(ee,function(){if(p)return;let ve=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",H=t.transitional||okn;t.timeoutErrorMessage&&(ve=t.timeoutErrorMessage),n(new Ma(ve,H.clarifyTimeoutError?Ma.ETIMEDOUT:Ma.ECONNABORTED,t,h)),v()})}if(rr.isStream(o)){let ee=!1,me=!1;o.on("end",()=>{ee=!0}),o.once("error",ve=>{me=!0,h.destroy(ve)}),o.on("close",()=>{!ee&&!me&&v(new xbe("Request stream has been aborted",t,h))}),o.pipe(h)}else h.end(o)})};var gT_=YA.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,YA.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(YA.origin),YA.navigator&&/(msie|trident)/i.test(YA.navigator.userAgent)):()=>!0;var OT_=YA.hasStandardBrowserEnv?{write(e,t,r,i,n,a){let o=[e+"="+encodeURIComponent(t)];rr.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),rr.isString(i)&&o.push("path="+i),rr.isString(n)&&o.push("domain="+n),a===!0&&o.push("secure"),document.cookie=o.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 AT_=e=>e instanceof JM?{...e}:e;function XVt(e,t){t=t||{};let r={};function i(s,u,f,p){return rr.isPlainObject(s)&&rr.isPlainObject(u)?rr.merge.call({caseless:p},s,u):rr.isPlainObject(u)?rr.merge({},u):rr.isArray(u)?u.slice():u}function n(s,u,f,p){if(rr.isUndefined(u)){if(!rr.isUndefined(s))return i(void 0,s,f,p)}else return i(s,u,f,p)}function a(s,u){if(!rr.isUndefined(u))return i(void 0,u)}function o(s,u){if(rr.isUndefined(u)){if(!rr.isUndefined(s))return i(void 0,s)}else return i(void 0,u)}function c(s,u,f){if(f in t)return i(s,u);if(f in e)return i(void 0,s)}let d={url:a,method:a,data:a,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:c,headers:(s,u,f)=>n(AT_(s),AT_(u),f,!0)};return rr.forEach(Object.keys({...e,...t}),function(u){let f=d[u]||n,p=f(e[u],t[u],u);rr.isUndefined(p)&&f!==c||(r[u]=p)}),r}var M7o=e=>{let t=XVt({},e),{data:r,withXSRFToken:i,xsrfHeaderName:n,xsrfCookieName:a,headers:o,auth:c}=t;if(t.headers=o=JM.from(o),t.url=h_n(y_n(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&o.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),rr.isFormData(r)){if(YA.hasStandardBrowserEnv||YA.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if(rr.isFunction(r.getHeaders)){let d=r.getHeaders(),s=["content-type","content-length"];Object.entries(d).forEach(([u,f])=>{s.includes(u.toLowerCase())&&o.set(u,f)})}}if(YA.hasStandardBrowserEnv&&(i&&rr.isFunction(i)&&(i=i(t)),i||i!==!1&&gT_(t.url))){let d=n&&a&&OT_.read(a);d&&o.set(n,d)}return t};var I$M=typeof XMLHttpRequest<"u",mT_=I$M&&function(e){return new Promise(function(r,i){let n=M7o(e),a=n.data,o=JM.from(n.headers).normalize(),{responseType:c,onUploadProgress:d,onDownloadProgress:s}=n,u,f,p,_,h;function y(){_&&_(),h&&h(),n.cancelToken&&n.cancelToken.unsubscribe(u),n.signal&&n.signal.removeEventListener("abort",u)}let b=new XMLHttpRequest;b.open(n.method.toUpperCase(),n.url,!0),b.timeout=n.timeout;function v(){if(!b)return;let A=JM.from("getAllResponseHeaders"in b&&b.getAllResponseHeaders()),m={data:!c||c==="text"||c==="json"?b.responseText:b.response,status:b.status,statusText:b.statusText,headers:A,config:e,request:b};RJt(function(S){r(S),y()},function(S){i(S),y()},m),b=null}"onloadend"in b?b.onloadend=v:b.onreadystatechange=function(){!b||b.readyState!==4||b.status===0&&!(b.responseURL&&b.responseURL.indexOf("file:")===0)||setTimeout(v)},b.onabort=function(){b&&(i(new Ma("Request aborted",Ma.ECONNABORTED,e,b)),b=null)},b.onerror=function(g){let m=g&&g.message?g.message:"Network Error",j=new Ma(m,Ma.ERR_NETWORK,e,b);j.event=g||null,i(j),b=null},b.ontimeout=function(){let g=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded",m=n.transitional||okn;n.timeoutErrorMessage&&(g=n.timeoutErrorMessage),i(new Ma(g,m.clarifyTimeoutError?Ma.ETIMEDOUT:Ma.ECONNABORTED,e,b)),b=null},a===void 0&&o.setContentType(null),"setRequestHeader"in b&&rr.forEach(o.toJSON(),function(g,m){b.setRequestHeader(m,g)}),rr.isUndefined(n.withCredentials)||(b.withCredentials=!!n.withCredentials),c&&c!=="json"&&(b.responseType=n.responseType),s&&([p,h]=hFi(s,!0),b.addEventListener("progress",p)),d&&b.upload&&([f,_]=hFi(d),b.upload.addEventListener("progress",f),b.upload.addEventListener("loadend",_)),(n.cancelToken||n.signal)&&(u=A=>{b&&(i(!A||A.type?new xbe(null,e,b):A),b.abort(),b=null)},n.cancelToken&&n.cancelToken.subscribe(u),n.signal&&(n.signal.aborted?u():n.signal.addEventListener("abort",u)));let O=UWa(n.url);if(O&&YA.protocols.indexOf(O)===-1){i(new Ma("Unsupported protocol "+O+":",Ma.ERR_BAD_REQUEST,e));return}b.send(a||null)})};var C$M=(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,c();let u=s instanceof Error?s:this.reason;i.abort(u instanceof Ma?u:new xbe(u instanceof Error?u.message:u))}},o=t&&setTimeout(()=>{o=null,a(new Ma(`timeout ${t} of ms exceeded`,Ma.ETIMEDOUT))},t),c=()=>{e&&(o&&clearTimeout(o),o=null,e.forEach(s=>{s.unsubscribe?s.unsubscribe(a):s.removeEventListener("abort",a)}),e=null)};e.forEach(s=>s.addEventListener("abort",a));let{signal:d}=i;return d.unsubscribe=()=>rr.asap(c),d}},PT_=C$M;var q$M=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},T$M=async function*(e,t){for await(let r of R$M(e))yield*q$M(r,t)},R$M=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()}},Mwc=(e,t,r,i)=>{let n=T$M(e,t),a=0,o,c=d=>{o||(o=!0,i&&i(d))};return new ReadableStream({async pull(d){try{let{done:s,value:u}=await n.next();if(s){c(),d.close();return}let f=u.byteLength;if(r){let p=a+=f;r(p)}d.enqueue(new Uint8Array(u))}catch(s){throw c(s),s}},cancel(d){return c(d),n.return()}},{highWaterMark:2})};var jT_=64*1024,{isFunction:D7o}=rr,z$M=(({Request:e,Response:t})=>({Request:e,Response:t}))(rr.global),{ReadableStream:wT_,TextEncoder:ET_}=rr.global,ST_=(e,...t)=>{try{return!!e(...t)}catch{return!1}},N$M=e=>{e=rr.merge.call({skipUndefined:!0},z$M,e);let{fetch:t,Request:r,Response:i}=e,n=t?D7o(t):typeof fetch=="function",a=D7o(r),o=D7o(i);if(!n)return!1;let c=n&&D7o(wT_),d=n&&(typeof ET_=="function"?(h=>y=>h.encode(y))(new ET_):async h=>new Uint8Array(await new r(h).arrayBuffer())),s=a&&c&&ST_(()=>{let h=!1,y=new r(YA.origin,{body:new wT_,method:"POST",get duplex(){return h=!0,"half"}}).headers.has("Content-Type");return h&&!y}),u=o&&c&&ST_(()=>rr.isReadableStream(new i("").body)),f={stream:u&&(h=>h.body)};n&&["text","arrayBuffer","blob","formData","stream"].forEach(h=>{!f[h]&&(f[h]=(y,b)=>{let v=y&&y[h];if(v)return v.call(y);throw new Ma(`Response type '${h}' is not supported`,Ma.ERR_NOT_SUPPORT,b)})});let p=async h=>{if(h==null)return 0;if(rr.isBlob(h))return h.size;if(rr.isSpecCompliantForm(h))return(await new r(YA.origin,{method:"POST",body:h}).arrayBuffer()).byteLength;if(rr.isArrayBufferView(h)||rr.isArrayBuffer(h))return h.byteLength;if(rr.isURLSearchParams(h)&&(h=h+""),rr.isString(h))return(await d(h)).byteLength},_=async(h,y)=>{let b=rr.toFiniteNumber(h.getContentLength());return b??p(y)};return async h=>{let{url:y,method:b,data:v,signal:O,cancelToken:A,timeout:g,onDownloadProgress:m,onUploadProgress:j,responseType:S,headers:w,withCredentials:D="same-origin",fetchOptions:B}=M7o(h),q=t||fetch;S=S?(S+"").toLowerCase():"text";let U=PT_([O,A&&A.toAbortSignal()],g),R=null,N=U&&U.unsubscribe&&(()=>{U.unsubscribe()}),F;try{if(j&&s&&b!=="get"&&b!=="head"&&(F=await _(w,v))!==0){let G=new r(y,{method:"POST",body:v,duplex:"half"}),Ee;if(rr.isFormData(v)&&(Ee=G.headers.get("content-type"))&&w.setContentType(Ee),G.body){let[ue,ge]=lkn(F,hFi(fkn(j)));v=Mwc(G.body,jT_,ue,ge)}}rr.isString(D)||(D=D?"include":"omit");let x=a&&"credentials"in r.prototype,ee={...B,signal:U,method:b.toUpperCase(),headers:w.normalize().toJSON(),body:v,duplex:"half",credentials:x?D:void 0};R=a&&new r(y,ee);let me=await(a?q(R,B):q(y,ee)),ve=u&&(S==="stream"||S==="response");if(u&&(m||ve&&N)){let G={};["status","statusText","headers"].forEach(We=>{G[We]=me[We]});let Ee=rr.toFiniteNumber(me.headers.get("content-length")),[ue,ge]=m&&lkn(Ee,hFi(fkn(m),!0))||[];me=new i(Mwc(me.body,jT_,ue,()=>{ge&&ge(),N&&N()}),G)}S=S||"text";let H=await f[rr.findKey(f,S)||"text"](me,h);return!ve&&N&&N(),await new Promise((G,Ee)=>{RJt(G,Ee,{data:H,headers:JM.from(me.headers),status:me.status,statusText:me.statusText,config:h,request:R})})}catch(x){throw N&&N(),x&&x.name==="TypeError"&&/Load failed|fetch/i.test(x.message)?Object.assign(new Ma("Network Error",Ma.ERR_NETWORK,h,R),{cause:x.cause||x}):Ma.from(x,x&&x.code,h,R)}}},F$M=new Map,Dwc=e=>{let t=e?e.env:{},{fetch:r,Request:i,Response:n}=t,a=[i,n,r],o=a.length,c=o,d,s,u=F$M;for(;c--;)d=a[c],s=u.get(d),s===void 0&&u.set(d,s=c?new Map:N$M(t)),u=s;return s},pw9=Dwc();var Bwc={http:vT_,xhr:mT_,fetch:{get:Dwc}};rr.forEach(Bwc,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var MT_=e=>`- ${e}`,U$M=e=>rr.isFunction(e)||e===null||e===!1,B7o={getAdapter:(e,t)=>{e=rr.isArray(e)?e:[e];let{length:r}=e,i,n,a={};for(let o=0;o<r;o++){i=e[o];let c;if(n=i,!U$M(i)&&(n=Bwc[(c=String(i)).toLowerCase()],n===void 0))throw new Ma(`Unknown adapter '${c}'`);if(n&&(rr.isFunction(n)||(n=n.get(t))))break;a[c||"#"+o]=n}if(!n){let o=Object.entries(a).map(([d,s])=>`adapter ${d} `+(s===!1?"is not supported by the environment":"is not available in the build")),c=r?o.length>1?`since :
@@ -1391,7 +1391,7 @@ ${g}${O}${m}${rna}`});function Osu({message:e,error:t,logger:r,logLevel:i=oc.Err
1391
1391
  Run ${Ct.cyan("fern generator upgrade")} to upgrade your generators.`),n.length>2&&(r+=`
1392
1392
  Run ${Ct.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),I7i(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function f4c({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!Oth(e))return;let n=t??"",a=e.filter(c=>c.isUpgradeAvailable);r!=null&&(a=a.slice(0,r+1));let o=a.sort((c,d)=>c.generatorName.localeCompare(d.generatorName)||c.currentVersion.localeCompare(d.currentVersion));for(let c of o)n+=`
1393
1393
  ${await DBD(c.generatorName)} (${c.apiName!=null?"API: "+c.apiName+", ":""}Group: ${c.generatorGroup}) `+Ct.dim(c.currentVersion)+Ct.reset(" \u2192 ")+Ct.green(c.latestVersion);return n+=`
1394
- `,i?I7i(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function DBD(e){let r=await new gth.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 BBD({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await mth({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,u,f)=>{c.versions[s]==null&&(c.versions[s]={});let p=CGi(u.name,f),_=await wVt({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:n,includeMajor:a,context:f});_!=null&&(c.versions[s][u.name]={previousVersion:u.version,latestVersion:_})},generatorFilter:r,groupFilter:i}),c}let o={type:"multiApi",versions:{}};return await mth({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,d,s,u)=>{if(c==null)return;o.versions[c]==null&&(o.versions[c]={}),o.versions[c][d]==null&&(o.versions[c][d]={});let f=CGi(s.name,u),p=await wVt({generatorName:f,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:u});p!=null&&(o.versions[c][d][s.name]={previousVersion:s.version,latestVersion:p})},generatorFilter:r,groupFilter:i}),o}async function mth({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async o=>{let c=await Ube({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(c==null||c.groups==null)return;let d=i!=null?aN(i):void 0;for(let s of c.groups)if(!(n!=null&&s.groupName!==n))for(let u of s.generators)d!=null&&u.name!==d||await r(a.workspaceName,s.groupName,u,o)})}))}function Pth(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[o,c]of Object.entries(a)){r.debug(`Checking if ${o} in group ${n} has an upgrade available...`);let d=S$(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:o,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return i}async function jsu({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let o=[];if(e!=null){let c=await BBD({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(c.type==="multiApi")for(let[d,s]of Object.entries(c.versions))o.push(...Pth(s,d,t.logger));else o.push(...Pth(c.versions,void 0,t.logger))}return o}var tHa=class extends Error{response;request;options;constructor(t,r,i){let n=t.status||t.status===0?t.status:"",a=t.statusText??"",o=`${n} ${a}`.trim(),c=o?`status code ${o}`:"an unknown error";super(`Request failed with ${c}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var ona=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var d4c=(()=>{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})(),jth=typeof globalThis.AbortController=="function",wth=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",Eth=typeof globalThis.ReadableStream=="function",Sth=typeof globalThis.FormData=="function",wsu=["get","post","put","patch","head","delete"],IBD=()=>{};IBD();var Mth={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},Esu=2147483647,Dth=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,Ssu=Symbol("stop"),Bth={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},Ith={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 CBD=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=Dth,t+=new TextEncoder().encode(`Content-Disposition: form-data; name="${r}"`).length,t+=typeof i=="string"?new TextEncoder().encode(i).length:i.size;return t}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if(typeof e=="string")return new TextEncoder().encode(e).length;if(e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).length;if("byteLength"in e)return e.byteLength;if(typeof e=="object"&&e!==null)try{let t=JSON.stringify(e);return new TextEncoder().encode(t).length}catch{return 0}return 0},Cth=(e,t,r)=>{let i,n=0;return e.pipeThrough(new TransformStream({transform(a,o){if(o.enqueue(a),i){n+=i.byteLength;let c=t===0?0:n/t;c>=1&&(c=1-Number.EPSILON),r?.({percent:c,totalBytes:Math.max(t,n),transferredBytes:n},i)}i=a},flush(){i&&(n+=i.byteLength,r?.({percent:1,totalBytes:Math.max(t,n),transferredBytes:n},i))}}))},qth=(e,t)=>{if(!e.body)return e;if(e.status===204)return new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers});let r=Number(e.headers.get("content-length"))||0;return new Response(Cth(e.body,r,t),{status:e.status,statusText:e.statusText,headers:e.headers})},Tth=(e,t,r)=>{if(!e.body)return e;let i=CBD(r??e.body);return new Request(e,{duplex:"half",body:Cth(e.body,i,t)})};var una=e=>e!==null&&typeof e=="object";var rHa=(...e)=>{for(let t of e)if((!una(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return h4c({},...e)},p4c=(e={},t={})=>{let r=new globalThis.Headers(e),i=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(let[a,o]of n.entries())i&&o==="undefined"||o===void 0?r.delete(a):r.set(a,o);return r};function Msu(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:h4c(e[r]??[],t[r]??[])}var _4c=(e={},t={})=>({beforeRequest:Msu(e,t,"beforeRequest"),beforeRetry:Msu(e,t,"beforeRetry"),afterResponse:Msu(e,t,"afterResponse"),beforeError:Msu(e,t,"beforeError")}),h4c=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(una(n)){for(let[a,o]of Object.entries(n))una(o)&&a in t&&(o=h4c(t[a],o)),t={...t,[a]:o};una(n.hooks)&&(i=_4c(i,n.hooks),t.hooks=i),una(n.headers)&&(r=p4c(r,n.headers),t.headers=r)}return t};var zth=e=>wsu.includes(e)?e.toUpperCase():e,qBD=["get","put","head","delete","options","trace"],TBD=[408,413,429,500,502,503,504],RBD=[413,429,503],Rth={limit:2,methods:qBD,statusCodes:TBD,afterStatusCodes:RBD,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},Nth=(e={})=>{if(typeof e=="number")return{...Rth,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{...Rth,...e}};async function y4c(e,t,r,i){return new Promise((n,a)=>{let o=setTimeout(()=>{r&&r.abort(),a(new ona(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function b4c(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 Fth=(e,t)=>{let r={};for(let i in t)!(i in Ith)&&!(i in Bth)&&!(i in e)&&(r[i]=t[i]);return r},Qth=e=>e===void 0?!1:Array.isArray(e)?e.length>0:e instanceof URLSearchParams?e.size>0:typeof e=="object"?Object.keys(e).length>0:typeof e=="string"?e.trim().length>0:!!e;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>Esu)throw new RangeError(`The \`timeout\` option cannot be greater than ${Esu}`);await Promise.resolve();let c=await i._fetch();for(let d of i._options.hooks.afterResponse){let s=await d(i.request,i._options,i._decorateResponse(c.clone()));s instanceof globalThis.Response&&(c=s)}if(i._decorateResponse(c),!c.ok&&i._options.throwHttpErrors){let d=new tHa(c,i.request,i._options);for(let s of i._options.hooks.beforeError)d=await s(d);throw d}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Eth)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return qth(c.clone(),i._options.onDownloadProgress)}return c},o=(i._options.retry.methods.includes(i.request.method.toLowerCase())?i._retry(n):n()).finally(async()=>{let c=i._originalRequest,d=[];c&&!c.bodyUsed&&d.push(c.body?.cancel()),i.request.bodyUsed||d.push(i.request.body?.cancel()),await Promise.all(d)});for(let[c,d]of Object.entries(Mth))c==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(o[c]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||d);let s=await o;if(c==="json"){if(s.status===204)return"";let u=await s.text();return u===""?"":r.parseJson?r.parseJson(u):JSON.parse(u)}return s[c]()});return o}static#e(t){return t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof URLSearchParams)?Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)):t}request;abortController;_retryCount=0;_input;_options;_originalRequest;constructor(t,r={}){if(this._input=t,this._options={...r,headers:p4c(this._input.headers,r.headers),hooks:_4c({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:zth(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:Nth(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(jth&&wth){let i=this._options.signal??this._input.signal;this.abortController=new globalThis.AbortController,this._options.signal=i?AbortSignal.any([i,this.abortController.signal]):this.abortController.signal}if(d4c&&(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),Qth(this._options.searchParams)){let n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(e.#e(this._options.searchParams)).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(Sth&&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)}if(this._options.onUploadProgress){if(typeof this._options.onUploadProgress!="function")throw new TypeError("The `onUploadProgress` option must be a function");if(!d4c)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=Tth(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof ona)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),Esu);if(this._retryCount<1)throw r;await b4c(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})===Ssu)return;return this._retry(t)}}async _fetch(){for(let r of this._options.hooks.beforeRequest){let i=await r(this.request,this._options);if(i instanceof Request){this.request=i;break}if(i instanceof Response)return i}let t=Fth(this.request,this._options);return this._originalRequest=this.request,this.request=this._originalRequest.clone(),this._options.timeout===!1?this._options.fetch(this._originalRequest,t):y4c(this._originalRequest,t,this.abortController,this._options)}};var v4c=e=>{let t=(r,i)=>iHa.create(r,rHa(e,i));for(let r of wsu)t[r]=(i,n)=>iHa.create(i,rHa(e,n,{method:r}));return t.create=r=>v4c(rHa(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),v4c(rHa(e,r))),t.stop=Ssu,t},zBD=v4c(),Uth=zBD;var crh=ce(srh(),1);function P4c(e){let t=(0,crh.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var iih=ce(rih(),1),nih=ce(pbe(),1),z4c=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},N4c=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function F4c(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??P4c(n),o=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,iih.default)(a.toString(),{recursive:!0}),d={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete d.accept,c&&(d.authorization=`${c.type} ${c.token}`);let s;try{s=await Uth(o,{headers:d,keepalive:!0}).json()}catch(f){throw f?.response?.status===404?new z4c(e):f}if(t.allVersions)return s;let u=new N4c(e,r);if(s["dist-tags"][r]){let{time:f}=s;s=s.versions[s["dist-tags"][r]],s.time=f}else if(r){let f=!!s.versions[r];if(i&&!f)for(let[_,h]of Object.entries(s.versions))h.deprecated&&delete s.versions[_];if(!f){let _=Object.keys(s.versions);if(r=nih.default.maxSatisfying(_,r),!r)throw u}let{time:p}=s;if(s=s.versions[r],s.time=p,!s)throw u}return s}async function cHa(e,t){let{version:r}=await F4c(e.toLowerCase(),t);return r}async function jKi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:cHa(e.packageName,{version:t?"prerelease":"latest"})}var aih=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],Usu=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=oc.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new Psu(t,r),this.isLocal=i??!1;let n=this.getPackageName(),a=this.getPackageVersion(),o=this.getCliName();(n==null||a==null||o==null)&&this.exitProgram(),this.environment={packageName:n,packageVersion:a,cliName:o}}getPackageName(){return"fern-api"}getPackageVersion(){return"3.37.3"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${Ct.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new US}failWithoutThrowing(t,r){this.didSucceed=!1,Osu({message:t,error:r,logger:this.logger})}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await rkn()).flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await Ath({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1394
+ `,i?I7i(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function DBD(e){let r=await new gth.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 BBD({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await mth({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,u,f)=>{c.versions[s]==null&&(c.versions[s]={});let p=CGi(u.name,f),_=await wVt({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:n,includeMajor:a,context:f});_!=null&&(c.versions[s][u.name]={previousVersion:u.version,latestVersion:_})},generatorFilter:r,groupFilter:i}),c}let o={type:"multiApi",versions:{}};return await mth({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,d,s,u)=>{if(c==null)return;o.versions[c]==null&&(o.versions[c]={}),o.versions[c][d]==null&&(o.versions[c][d]={});let f=CGi(s.name,u),p=await wVt({generatorName:f,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:u});p!=null&&(o.versions[c][d][s.name]={previousVersion:s.version,latestVersion:p})},generatorFilter:r,groupFilter:i}),o}async function mth({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async o=>{let c=await Ube({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(c==null||c.groups==null)return;let d=i!=null?aN(i):void 0;for(let s of c.groups)if(!(n!=null&&s.groupName!==n))for(let u of s.generators)d!=null&&u.name!==d||await r(a.workspaceName,s.groupName,u,o)})}))}function Pth(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[o,c]of Object.entries(a)){r.debug(`Checking if ${o} in group ${n} has an upgrade available...`);let d=S$(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:o,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return i}async function jsu({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let o=[];if(e!=null){let c=await BBD({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(c.type==="multiApi")for(let[d,s]of Object.entries(c.versions))o.push(...Pth(s,d,t.logger));else o.push(...Pth(c.versions,void 0,t.logger))}return o}var tHa=class extends Error{response;request;options;constructor(t,r,i){let n=t.status||t.status===0?t.status:"",a=t.statusText??"",o=`${n} ${a}`.trim(),c=o?`status code ${o}`:"an unknown error";super(`Request failed with ${c}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var ona=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var d4c=(()=>{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})(),jth=typeof globalThis.AbortController=="function",wth=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",Eth=typeof globalThis.ReadableStream=="function",Sth=typeof globalThis.FormData=="function",wsu=["get","post","put","patch","head","delete"],IBD=()=>{};IBD();var Mth={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},Esu=2147483647,Dth=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,Ssu=Symbol("stop"),Bth={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},Ith={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 CBD=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=Dth,t+=new TextEncoder().encode(`Content-Disposition: form-data; name="${r}"`).length,t+=typeof i=="string"?new TextEncoder().encode(i).length:i.size;return t}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if(typeof e=="string")return new TextEncoder().encode(e).length;if(e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).length;if("byteLength"in e)return e.byteLength;if(typeof e=="object"&&e!==null)try{let t=JSON.stringify(e);return new TextEncoder().encode(t).length}catch{return 0}return 0},Cth=(e,t,r)=>{let i,n=0;return e.pipeThrough(new TransformStream({transform(a,o){if(o.enqueue(a),i){n+=i.byteLength;let c=t===0?0:n/t;c>=1&&(c=1-Number.EPSILON),r?.({percent:c,totalBytes:Math.max(t,n),transferredBytes:n},i)}i=a},flush(){i&&(n+=i.byteLength,r?.({percent:1,totalBytes:Math.max(t,n),transferredBytes:n},i))}}))},qth=(e,t)=>{if(!e.body)return e;if(e.status===204)return new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers});let r=Number(e.headers.get("content-length"))||0;return new Response(Cth(e.body,r,t),{status:e.status,statusText:e.statusText,headers:e.headers})},Tth=(e,t,r)=>{if(!e.body)return e;let i=CBD(r??e.body);return new Request(e,{duplex:"half",body:Cth(e.body,i,t)})};var una=e=>e!==null&&typeof e=="object";var rHa=(...e)=>{for(let t of e)if((!una(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return h4c({},...e)},p4c=(e={},t={})=>{let r=new globalThis.Headers(e),i=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(let[a,o]of n.entries())i&&o==="undefined"||o===void 0?r.delete(a):r.set(a,o);return r};function Msu(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:h4c(e[r]??[],t[r]??[])}var _4c=(e={},t={})=>({beforeRequest:Msu(e,t,"beforeRequest"),beforeRetry:Msu(e,t,"beforeRetry"),afterResponse:Msu(e,t,"afterResponse"),beforeError:Msu(e,t,"beforeError")}),h4c=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(una(n)){for(let[a,o]of Object.entries(n))una(o)&&a in t&&(o=h4c(t[a],o)),t={...t,[a]:o};una(n.hooks)&&(i=_4c(i,n.hooks),t.hooks=i),una(n.headers)&&(r=p4c(r,n.headers),t.headers=r)}return t};var zth=e=>wsu.includes(e)?e.toUpperCase():e,qBD=["get","put","head","delete","options","trace"],TBD=[408,413,429,500,502,503,504],RBD=[413,429,503],Rth={limit:2,methods:qBD,statusCodes:TBD,afterStatusCodes:RBD,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},Nth=(e={})=>{if(typeof e=="number")return{...Rth,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{...Rth,...e}};async function y4c(e,t,r,i){return new Promise((n,a)=>{let o=setTimeout(()=>{r&&r.abort(),a(new ona(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function b4c(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 Fth=(e,t)=>{let r={};for(let i in t)!(i in Ith)&&!(i in Bth)&&!(i in e)&&(r[i]=t[i]);return r},Qth=e=>e===void 0?!1:Array.isArray(e)?e.length>0:e instanceof URLSearchParams?e.size>0:typeof e=="object"?Object.keys(e).length>0:typeof e=="string"?e.trim().length>0:!!e;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>Esu)throw new RangeError(`The \`timeout\` option cannot be greater than ${Esu}`);await Promise.resolve();let c=await i._fetch();for(let d of i._options.hooks.afterResponse){let s=await d(i.request,i._options,i._decorateResponse(c.clone()));s instanceof globalThis.Response&&(c=s)}if(i._decorateResponse(c),!c.ok&&i._options.throwHttpErrors){let d=new tHa(c,i.request,i._options);for(let s of i._options.hooks.beforeError)d=await s(d);throw d}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Eth)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return qth(c.clone(),i._options.onDownloadProgress)}return c},o=(i._options.retry.methods.includes(i.request.method.toLowerCase())?i._retry(n):n()).finally(async()=>{let c=i._originalRequest,d=[];c&&!c.bodyUsed&&d.push(c.body?.cancel()),i.request.bodyUsed||d.push(i.request.body?.cancel()),await Promise.all(d)});for(let[c,d]of Object.entries(Mth))c==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(o[c]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||d);let s=await o;if(c==="json"){if(s.status===204)return"";let u=await s.text();return u===""?"":r.parseJson?r.parseJson(u):JSON.parse(u)}return s[c]()});return o}static#e(t){return t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof URLSearchParams)?Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)):t}request;abortController;_retryCount=0;_input;_options;_originalRequest;constructor(t,r={}){if(this._input=t,this._options={...r,headers:p4c(this._input.headers,r.headers),hooks:_4c({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:zth(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:Nth(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(jth&&wth){let i=this._options.signal??this._input.signal;this.abortController=new globalThis.AbortController,this._options.signal=i?AbortSignal.any([i,this.abortController.signal]):this.abortController.signal}if(d4c&&(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),Qth(this._options.searchParams)){let n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(e.#e(this._options.searchParams)).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(Sth&&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)}if(this._options.onUploadProgress){if(typeof this._options.onUploadProgress!="function")throw new TypeError("The `onUploadProgress` option must be a function");if(!d4c)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=Tth(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof ona)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),Esu);if(this._retryCount<1)throw r;await b4c(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})===Ssu)return;return this._retry(t)}}async _fetch(){for(let r of this._options.hooks.beforeRequest){let i=await r(this.request,this._options);if(i instanceof Request){this.request=i;break}if(i instanceof Response)return i}let t=Fth(this.request,this._options);return this._originalRequest=this.request,this.request=this._originalRequest.clone(),this._options.timeout===!1?this._options.fetch(this._originalRequest,t):y4c(this._originalRequest,t,this.abortController,this._options)}};var v4c=e=>{let t=(r,i)=>iHa.create(r,rHa(e,i));for(let r of wsu)t[r]=(i,n)=>iHa.create(i,rHa(e,n,{method:r}));return t.create=r=>v4c(rHa(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),v4c(rHa(e,r))),t.stop=Ssu,t},zBD=v4c(),Uth=zBD;var crh=ce(srh(),1);function P4c(e){let t=(0,crh.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var iih=ce(rih(),1),nih=ce(pbe(),1),z4c=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},N4c=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function F4c(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??P4c(n),o=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,iih.default)(a.toString(),{recursive:!0}),d={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete d.accept,c&&(d.authorization=`${c.type} ${c.token}`);let s;try{s=await Uth(o,{headers:d,keepalive:!0}).json()}catch(f){throw f?.response?.status===404?new z4c(e):f}if(t.allVersions)return s;let u=new N4c(e,r);if(s["dist-tags"][r]){let{time:f}=s;s=s.versions[s["dist-tags"][r]],s.time=f}else if(r){let f=!!s.versions[r];if(i&&!f)for(let[_,h]of Object.entries(s.versions))h.deprecated&&delete s.versions[_];if(!f){let _=Object.keys(s.versions);if(r=nih.default.maxSatisfying(_,r),!r)throw u}let{time:p}=s;if(s=s.versions[r],s.time=p,!s)throw u}return s}async function cHa(e,t){let{version:r}=await F4c(e.toLowerCase(),t);return r}async function jKi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:cHa(e.packageName,{version:t?"prerelease":"latest"})}var aih=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],Usu=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=oc.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new Psu(t,r),this.isLocal=i??!1;let n=this.getPackageName(),a=this.getPackageVersion(),o=this.getCliName();(n==null||a==null||o==null)&&this.exitProgram(),this.environment={packageName:n,packageVersion:a,cliName:o}}getPackageName(){return"fern-api"}getPackageVersion(){return"3.37.5"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${Ct.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new US}failWithoutThrowing(t,r){this.didSucceed=!1,Osu({message:t,error:r,logger:this.logger})}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await rkn()).flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await Ath({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1395
1395
  `)||(r+=`
1396
1396
  `),this.stderr.info(r))}catch{}}async exitIfFailed(){this.didSucceed||await this.exit()}exitProgram({code:t}={}){process.exit(t??(this.didSucceed?0:1))}longestWorkspaceName;registerWorkspaces(t){let r=xZs(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 $Ga(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 US}finally{i.finish()}return n}async instrumentPostHogEvent(t){this.isLocal||(await rkn()).sendEvent(t)}logger=PHt((t,...r)=>this.log(t,...r));stderr=PHt((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=oih(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?oih(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=aih[this.numTasks++%aih.length],o=Ct.hex(a)(n);return{...this.constructTaskInit(),logPrefix:o}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===_w.Failure&&(this.didSucceed=!1)},instrumentPostHogEvent:async t=>{await this.instrumentPostHogEvent(t)},shouldBufferLogs:!1}}log(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}])}logStderr(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}],{stderr:!0})}logImmediately(t,{stderr:r=!1}={}){let i=t.filter(n=>tGi.indexOf(n.level)>=tGi.indexOf(this.logLevel));this.ttyAwareLogger.log(i,{includeDebugInfo:this.logLevel===oc.Debug,stderr:r})}_suppressUpgradeMessage=!1;suppressUpgradeMessage(){this._suppressUpgradeMessage=!0}_isUpgradeAvailable;async isUpgradeAvailable({includePreReleases:t=!1}={}){if(this._isUpgradeAvailable==null){this.logger.debug(`Checking if ${this.environment.packageName} upgrade is available...`);let r=await jKi({cliEnvironment:this.environment,includePreReleases:t}),i=S$(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await jsu({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){try{return await kUc({message:t,choices:[{name:"No",value:!1},{name:"Yes",value:!0}],default:r,theme:{prefix:Ct.yellow("?"),style:{answer:n=>Ct.cyan(n),message:n=>Ct.bold(n),highlight:n=>Ct.cyan(n)}}})}catch(i){throw i?.name==="ExitPromptError"?(this.logger.info(`
1397
1397
  Cancelled by user.`),new US):i}}async getInput(t){return await $Uc({message:t.message,default:t.default})}};function oih(e){return`[${e}]:`}var M3t=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}};function Lsu(e,t,r,i){if(typeof r!="function")throw new Error("method for before hook must be a function");return i||(i={}),Array.isArray(t)?t.reverse().reduce((n,a)=>Lsu.bind(null,e,a,n,i),r)():Promise.resolve().then(()=>e.registry[t]?e.registry[t].reduce((n,a)=>a.hook.bind(null,n,i),r)():r(i))}function uih(e,t,r,i){let n=i;e.registry[r]||(e.registry[r]=[]),t==="before"&&(i=(a,o)=>Promise.resolve().then(n.bind(null,o)).then(a.bind(null,o))),t==="after"&&(i=(a,o)=>{let c;return Promise.resolve().then(a.bind(null,o)).then(d=>(c=d,n(c,o))).then(()=>c)}),t==="error"&&(i=(a,o)=>Promise.resolve().then(a.bind(null,o)).catch(c=>n(c,o))),e.registry[r].push({hook:i,orig:n})}function sih(e,t,r){if(!e.registry[t])return;let i=e.registry[t].map(n=>n.orig).indexOf(r);i!==-1&&e.registry[t].splice(i,1)}var cih=Function.bind,lih=cih.bind(cih);function fih(e,t,r){let i=lih(sih,null).apply(null,r?[t,r]:[t]);e.api={remove:i},e.remove=i,["before","error","after","wrap"].forEach(n=>{let a=r?[t,n,r]:[t,n];e[n]=e.api[n]=lih(uih,null).apply(null,a)})}function VID(){let e=Symbol("Singular"),t={registry:{}},r=Lsu.bind(null,t,e);return fih(r,t,e),r}function WID(){let e={registry:{}},t=Lsu.bind(null,e);return fih(t,e),t}var dih={Singular:VID,Collection:WID};var GID="0.0.0-development",HID=`octokit-endpoint.js/${GID} ${lN()}`,xID={method:"GET",baseUrl:"https://api.github.com",headers:{accept:"application/vnd.github.v3+json","user-agent":HID},mediaType:{format:""}};function KID(e){return e?Object.keys(e).reduce((t,r)=>(t[r.toLowerCase()]=e[r],t),{}):{}}function JID(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);if(t===null)return!0;let r=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&Function.prototype.call(r)===Function.prototype.call(e)}function hih(e,t){let r=Object.assign({},e);return Object.keys(t).forEach(i=>{JID(t[i])?i in e?r[i]=hih(e[i],t[i]):Object.assign(r,{[i]:t[i]}):Object.assign(r,{[i]:t[i]})}),r}function pih(e){for(let t in e)e[t]===void 0&&delete e[t];return e}function U4c(e,t,r){if(typeof t=="string"){let[n,a]=t.split(" ");r=Object.assign(a?{method:n,url:a}:{url:n},r)}else r=Object.assign({},t);r.headers=KID(r.headers),pih(r),pih(r.headers);let i=hih(e||{},r);return r.url==="/graphql"&&(e&&e.mediaType.previews?.length&&(i.mediaType.previews=e.mediaType.previews.filter(n=>!i.mediaType.previews.includes(n)).concat(i.mediaType.previews)),i.mediaType.previews=(i.mediaType.previews||[]).map(n=>n.replace(/-preview/,""))),i}function $ID(e,t){let r=/\?/.test(e)?"&":"?",i=Object.keys(t);return i.length===0?e:e+r+i.map(n=>n==="q"?"q="+t.q.split("+").map(encodeURIComponent).join("+"):`${n}=${encodeURIComponent(t[n])}`).join("&")}var YID=/\{[^{}}]+\}/g;function XID(e){return e.replace(/(?:^\W+)|(?:(?<!\W)\W+$)/g,"").split(/,/)}function ZID(e){let t=e.match(YID);return t?t.map(XID).reduce((r,i)=>r.concat(i),[]):[]}function _ih(e,t){let r={__proto__:null};for(let i of Object.keys(e))t.indexOf(i)===-1&&(r[i]=e[i]);return r}function yih(e){return e.split(/(%[0-9A-Fa-f]{2})/g).map(function(t){return/%[0-9A-Fa-f]/.test(t)||(t=encodeURI(t).replace(/%5B/g,"[").replace(/%5D/g,"]")),t}).join("")}function hna(e){return encodeURIComponent(e).replace(/[!'()*]/g,function(t){return"%"+t.charCodeAt(0).toString(16).toUpperCase()})}function lHa(e,t,r){return t=e==="+"||e==="#"?yih(t):hna(t),r?hna(r)+"="+t:t}function _na(e){return e!=null}function Q4c(e){return e===";"||e==="&"||e==="?"}function kID(e,t,r,i){var n=e[r],a=[];if(_na(n)&&n!=="")if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")n=n.toString(),i&&i!=="*"&&(n=n.substring(0,parseInt(i,10))),a.push(lHa(t,n,Q4c(t)?r:""));else if(i==="*")Array.isArray(n)?n.filter(_na).forEach(function(o){a.push(lHa(t,o,Q4c(t)?r:""))}):Object.keys(n).forEach(function(o){_na(n[o])&&a.push(lHa(t,n[o],o))});else{let o=[];Array.isArray(n)?n.filter(_na).forEach(function(c){o.push(lHa(t,c))}):Object.keys(n).forEach(function(c){_na(n[c])&&(o.push(hna(c)),o.push(lHa(t,n[c].toString())))}),Q4c(t)?a.push(hna(r)+"="+o.join(",")):o.length!==0&&a.push(o.join(","))}else t===";"?_na(n)&&a.push(hna(r)):n===""&&(t==="&"||t==="?")?a.push(hna(r)+"="):n===""&&a.push("");return a}function eCD(e){return{expand:tCD.bind(null,e)}}function tCD(e,t){var r=["+","#",".","/",";","?","&"];return e=e.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g,function(i,n,a){if(n){let c="",d=[];if(r.indexOf(n.charAt(0))!==-1&&(c=n.charAt(0),n=n.substr(1)),n.split(/,/g).forEach(function(s){var u=/([^:\*]*)(?::(\d+)|(\*))?/.exec(s);d.push(kID(t,c,u[1],u[2]||u[3]))}),c&&c!=="+"){var o=",";return c==="?"?o="&":c!=="#"&&(o=c),(d.length!==0?c:"")+d.join(o)}else return d.join(",")}else return yih(a)}),e==="/"?e:e.replace(/\/$/,"")}function bih(e){let t=e.method.toUpperCase(),r=(e.url||"/").replace(/:([a-z]\w+)/g,"{$1}"),i=Object.assign({},e.headers),n,a=_ih(e,["method","baseUrl","url","headers","request","mediaType"]),o=ZID(r);r=eCD(r).expand(a),/^http/.test(r)||(r=e.baseUrl+r);let c=Object.keys(e).filter(u=>o.includes(u)).concat("baseUrl"),d=_ih(a,c);if(!/application\/octet-stream/i.test(i.accept)&&(e.mediaType.format&&(i.accept=i.accept.split(/,/).map(u=>u.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/,`application/vnd$1$2.${e.mediaType.format}`)).join(",")),r.endsWith("/graphql")&&e.mediaType.previews?.length)){let u=i.accept.match(/(?<![\w-])[\w-]+(?=-preview)/g)||[];i.accept=u.concat(e.mediaType.previews).map(f=>{let p=e.mediaType.format?`.${e.mediaType.format}`:"+json";return`application/vnd.github.${f}-preview${p}`}).join(",")}return["GET","HEAD"].includes(t)?r=$ID(r,d):"data"in d?n=d.data:Object.keys(d).length&&(n=d),!i["content-type"]&&typeof n<"u"&&(i["content-type"]="application/json; charset=utf-8"),["PATCH","PUT"].includes(t)&&typeof n>"u"&&(n=""),Object.assign({method:t,url:r,headers:i},typeof n<"u"?{body:n}:null,e.request?{request:e.request}:null)}function rCD(e,t,r){return bih(U4c(e,t,r))}function vih(e,t){let r=U4c(e,t),i=rCD.bind(null,r);return Object.assign(i,{DEFAULTS:r,defaults:vih.bind(null,r),merge:U4c.bind(null,r),parse:bih})}var gih=vih(null,xID);var wih=ce(Pih(),1);var D3t=class extends Error{name;status;request;response;constructor(t,r,i){super(t),this.name="HttpError",this.status=Number.parseInt(r),Number.isNaN(this.status)&&(this.status=0),"response"in i&&(this.response=i.response);let n=Object.assign({},i.request);i.request.headers.authorization&&(n.headers=Object.assign({},i.request.headers,{authorization:i.request.headers.authorization.replace(/(?<! ) .*$/," [REDACTED]")})),n.url=n.url.replace(/\bclient_secret=\w+/g,"client_secret=[REDACTED]").replace(/\baccess_token=\w+/g,"access_token=[REDACTED]"),this.request=n}};var iCD="10.0.6",nCD={headers:{"user-agent":`octokit-request.js/${iCD} ${lN()}`}};function aCD(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);if(t===null)return!0;let r=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&Function.prototype.call(r)===Function.prototype.call(e)}async function jih(e){let t=e.request?.fetch||globalThis.fetch;if(!t)throw new Error("fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing");let r=e.request?.log||console,i=e.request?.parseSuccessResponseBody!==!1,n=aCD(e.body)||Array.isArray(e.body)?JSON.stringify(e.body):e.body,a=Object.fromEntries(Object.entries(e.headers).map(([f,p])=>[f,String(p)])),o;try{o=await t(e.url,{method:e.method,body:n,redirect:e.request?.redirect,headers:a,signal:e.request?.signal,...e.body&&{duplex:"half"}})}catch(f){let p="Unknown Error";if(f instanceof Error){if(f.name==="AbortError")throw f.status=500,f;p=f.message,f.name==="TypeError"&&"cause"in f&&(f.cause instanceof Error?p=f.cause.message:typeof f.cause=="string"&&(p=f.cause))}let _=new D3t(p,500,{request:e});throw _.cause=f,_}let c=o.status,d=o.url,s={};for(let[f,p]of o.headers)s[f]=p;let u={url:d,status:c,headers:s,data:""};if("deprecation"in s){let f=s.link&&s.link.match(/<([^<>]+)>; rel="deprecation"/),p=f&&f.pop();r.warn(`[@octokit/request] "${e.method} ${e.url}" is deprecated. It is scheduled to be removed on ${s.sunset}${p?`. See ${p}`:""}`)}if(c===204||c===205)return u;if(e.method==="HEAD"){if(c<400)return u;throw new D3t(o.statusText,c,{response:u,request:e})}if(c===304)throw u.data=await L4c(o),new D3t("Not modified",c,{response:u,request:e});if(c>=400)throw u.data=await L4c(o),new D3t(uCD(u.data),c,{response:u,request:e});return u.data=i?await L4c(o):o.body,u}async function L4c(e){let t=e.headers.get("content-type");if(!t)return e.text().catch(()=>"");let r=(0,wih.safeParse)(t);if(oCD(r)){let i="";try{return i=await e.text(),JSON.parse(i)}catch{return i}}else return r.type.startsWith("text/")||r.parameters.charset?.toLowerCase()==="utf-8"?e.text().catch(()=>""):e.arrayBuffer().catch(()=>new ArrayBuffer(0))}function oCD(e){return e.type==="application/json"||e.type==="application/scim+json"}function uCD(e){if(typeof e=="string")return e;if(e instanceof ArrayBuffer)return"Unknown error";if("message"in e){let t="documentation_url"in e?` - ${e.documentation_url}`:"";return Array.isArray(e.errors)?`${e.message}: ${e.errors.map(r=>JSON.stringify(r)).join(", ")}${t}`:`${e.message}${t}`}return`Unknown error: ${JSON.stringify(e)}`}function V4c(e,t){let r=e.defaults(t);return Object.assign(function(n,a){let o=r.merge(n,a);if(!o.request||!o.request.hook)return jih(r.parse(o));let c=(d,s)=>jih(r.parse(r.merge(d,s)));return Object.assign(c,{endpoint:r,defaults:V4c.bind(null,r)}),o.request.hook(c,o)},{endpoint:r,defaults:V4c.bind(null,r)})}var vA=V4c(gih,nCD);var sCD="0.0.0-development";function cCD(e){return`Request failed due to following response errors:
@@ -1416,7 +1416,7 @@ Cancelled by user.`),new US):i}}async getInput(t){return await $Uc({message:t.me
1416
1416
  `+o.stack:"")}return i}function kRD({options:e,overrides:t}){return{naming:t?.naming??e?.asyncApiNaming??Kah.naming}}function Gfu(e){let t=String(e.description||e.name||e["x-fern-server-name"]||"default").trim(),r=t.toUpperCase();return r==="PRODUCTION"||r==="PRD"||r==="PROD"?"PRD":r==="SANDBOX"||r==="SBX"?"SBX":r==="STAGING"||r==="STG"?"STG":r==="PERFORMANCE"||r==="PRF"||r==="PERF"?"PRF":r==="E2E"||r==="E_2_E"?"E2E":r==="QAL"||r==="QUALITY"?"QAL":t}function ezD(e){try{let i=new URL(e).hostname.split("."),n=new Set(["api","www","service","services","example","com","org","net","io"]);for(let o of i){let c=o.split("-")[0];if(c&&!n.has(c.toLowerCase())&&c.length>2)return c.toLowerCase()}let a=i[0]?.split("-")[0];return a?a.toLowerCase():"api"}catch{let t=e.match(/https?:\/\/([^./-]+)/);return t&&t[1]?t[1].toLowerCase():"api"}}function XLc(e,t){let r=e??[],i=t??[];if(r.length===0&&i.length===0)return;let n=new Map;for(let a of[...r,...i]){let o=Object.keys(a).sort(),c={};for(let s of o)c[s]=a[s]??[];let d=JSON.stringify(c);n.has(d)||n.set(d,a)}return Array.from(n.values())}function tzD(e,t){if(e.length===0||t.length===0||e.length!==t.length)return!1;let r=new Map;for(let a of e){let o=Gfu(a);r.set(o,a.url)}let i=!0,n=!0;for(let a of t){let o=Gfu(a),c=r.get(o);c?c===a.url&&(n=!1):i=!1}return i&&n}function Iuh(e){if(e.length===0||!e[0])return"api";let t=e[0].url;return ezD(t)}function rzD(e,t,r){if(!(r?.groupMultiApiEnvironments===!0))return{apiVersion:e.apiVersion??t.apiVersion,title:e.title??t.title,description:e.description??t.description,basePath:e.basePath??t.basePath,servers:[...e.servers,...t.servers],websocketServers:[...e.websocketServers,...t.websocketServers],tags:{tagsById:{...e.tags.tagsById,...t.tags.tagsById},orderedTagIds:e.tags.orderedTagIds==null&&t.tags.orderedTagIds==null?void 0:[...e.tags.orderedTagIds??[],...t.tags.orderedTagIds??[]]},hasEndpointsMarkedInternal:e.hasEndpointsMarkedInternal||t.hasEndpointsMarkedInternal,endpoints:[...e.endpoints,...t.endpoints],webhooks:[...e.webhooks,...t.webhooks],channels:{...e.channels,...t.channels},groupedSchemas:Wfu(e.groupedSchemas,t.groupedSchemas),variables:{...e.variables,...t.variables},nonRequestReferencedSchemas:new Set([...e.nonRequestReferencedSchemas,...t.nonRequestReferencedSchemas]),securitySchemes:{...e.securitySchemes,...t.securitySchemes},security:XLc(e.security,t.security),globalHeaders:e.globalHeaders!=null?[...e.globalHeaders,...t.globalHeaders??[]]:void 0,idempotencyHeaders:e.idempotencyHeaders!=null?[...e.idempotencyHeaders,...t.idempotencyHeaders??[]]:void 0,groups:{...e.groups,...t.groups}};if(tzD(e.servers,t.servers)){let a=[],o=[],c=Iuh(e.servers),d=Iuh(t.servers),s=new Map;for(let p of e.servers){let _=Gfu(p);s.has(_)||s.set(_,{});let h=s.get(_);h&&(h[c]={url:p.url,audiences:p.audiences})}for(let p of t.servers){let _=Gfu(p);s.has(_)||s.set(_,{});let h=s.get(_);h&&(h[d]={url:p.url,audiences:p.audiences})}for(let[p,_]of s.entries()){let h={type:"grouped",name:p,description:`${p} environment`,urls:_};a.push(h)}let u=e.endpoints.map(p=>({...p,type:"multi-api",apiName:c,servers:[{name:c,url:void 0,audiences:void 0}]})),f=t.endpoints.map(p=>({...p,type:"multi-api",apiName:d,servers:[{name:d,url:void 0,audiences:void 0}]}));return o=[...u,...f],{apiVersion:e.apiVersion??t.apiVersion,title:e.title??t.title,description:e.description??t.description,basePath:e.basePath??t.basePath,servers:a.map(p=>(p.type==="single",p)),websocketServers:[...e.websocketServers,...t.websocketServers],tags:{tagsById:{...e.tags.tagsById,...t.tags.tagsById},orderedTagIds:e.tags.orderedTagIds==null&&t.tags.orderedTagIds==null?void 0:[...e.tags.orderedTagIds??[],...t.tags.orderedTagIds??[]]},hasEndpointsMarkedInternal:e.hasEndpointsMarkedInternal||t.hasEndpointsMarkedInternal,endpoints:o.map(p=>{if(p.type==="multi-api"){let{type:y,apiName:b,servers:v,...O}=p;return{...O,__apiName:b,servers:v}}let{type:_,...h}=p;return h}),webhooks:[...e.webhooks,...t.webhooks],channels:{...e.channels,...t.channels},groupedSchemas:Wfu(e.groupedSchemas,t.groupedSchemas),variables:{...e.variables,...t.variables},nonRequestReferencedSchemas:new Set([...e.nonRequestReferencedSchemas,...t.nonRequestReferencedSchemas]),securitySchemes:{...e.securitySchemes,...t.securitySchemes},security:XLc(e.security,t.security),globalHeaders:e.globalHeaders!=null?[...e.globalHeaders,...t.globalHeaders??[]]:void 0,idempotencyHeaders:e.idempotencyHeaders!=null?[...e.idempotencyHeaders,...t.idempotencyHeaders??[]]:void 0,groups:{...e.groups,...t.groups}}}return{apiVersion:e.apiVersion??t.apiVersion,title:e.title??t.title,description:e.description??t.description,basePath:e.basePath??t.basePath,servers:[...e.servers,...t.servers],websocketServers:[...e.websocketServers,...t.websocketServers],tags:{tagsById:{...e.tags.tagsById,...t.tags.tagsById},orderedTagIds:e.tags.orderedTagIds==null&&t.tags.orderedTagIds==null?void 0:[...e.tags.orderedTagIds??[],...t.tags.orderedTagIds??[]]},hasEndpointsMarkedInternal:e.hasEndpointsMarkedInternal||t.hasEndpointsMarkedInternal,endpoints:[...e.endpoints,...t.endpoints],webhooks:[...e.webhooks,...t.webhooks],channels:{...e.channels,...t.channels},groupedSchemas:Wfu(e.groupedSchemas,t.groupedSchemas),variables:{...e.variables,...t.variables},nonRequestReferencedSchemas:new Set([...e.nonRequestReferencedSchemas,...t.nonRequestReferencedSchemas]),securitySchemes:{...e.securitySchemes,...t.securitySchemes},security:XLc(e.security,t.security),globalHeaders:e.globalHeaders!=null?[...e.globalHeaders,...t.globalHeaders??[]]:void 0,idempotencyHeaders:e.idempotencyHeaders!=null?[...e.idempotencyHeaders,...t.idempotencyHeaders??[]]:void 0,groups:{...e.groups,...t.groups}}}function Wfu(e,t){e.rootSchemas={...e.rootSchemas,...t.rootSchemas};for(let[r,i]of Object.entries(t.namespacedSchemas))e.namespacedSchemas[r]!=null?e.namespacedSchemas[r]={...e.namespacedSchemas[r],...i}:e.namespacedSchemas[r]=i;return e}var Vyh=ce(Nhu(),1),Fhu={config:new Vyh.Config({apis:{},styleguide:{plugins:[zLc],rules:{struct:"warn"}}},void 0),dereference:!1,removeUnusedComponents:!1,keepUrlRefs:!1};function W3t({options:e,overrides:t}={}){return{...lEe({options:e,overrides:t}),...Kyn({options:e,overrides:t})}}var GZD={shouldUseTitleAsName:"useTitlesAsName",shouldUseUndiscriminatedUnionsWithLiterals:["shouldUseUndiscriminatedUnionsWithLiterals","discriminatedUnionV2"],shouldUseIdiomaticRequestNames:"shouldUseIdiomaticRequestNames",asyncApiMessageNaming:"asyncApiNaming",shouldUseOptionalAdditionalProperties:"optionalAdditionalProperties",coerceEnumsToLiterals:"coerceEnumsToLiterals",objectQueryParameters:"objectQueryParameters",respectReadonlySchemas:"respectReadonlySchemas",respectNullableSchemas:"respectNullableSchemas",onlyIncludeReferencedSchemas:"onlyIncludeReferencedSchemas",inlinePathParameters:"inlinePathParameters",useBytesForBinaryResponse:"useBytesForBinaryResponse",respectForwardCompatibleEnums:"respectForwardCompatibleEnums",filter:"filter",defaultFormParameterEncoding:"defaultFormParameterEncoding",exampleGeneration:"exampleGeneration",additionalPropertiesDefaultsTo:"additionalPropertiesDefaultsTo",typeDatesAsStrings:"typeDatesAsStrings",preserveSingleSchemaOneOf:"preserveSingleSchemaOneOf",inlineAllOfSchemas:"inlineAllOfSchemas",resolveAliases:"resolveAliases",groupMultiApiEnvironments:"groupMultiApiEnvironments",groupEnvironmentsByHost:"groupEnvironmentsByHost",wrapReferencesToNullableInOptional:"wrapReferencesToNullableInOptional",coerceOptionalSchemasToNullable:"coerceOptionalSchemasToNullable",removeDiscriminantsFromSchemas:"removeDiscriminantsFromSchemas",defaultIntegerFormat:"defaultIntegerFormat",pathParameterOrder:"pathParameterOrder"};function HZD(e,t,r){r!==void 0&&(e[t]=r)}function Qhu(e){let t={};if(e!=null)for(let[r,i]of Object.entries(GZD)){let n=e[r],a=Array.isArray(i)?i:[i];for(let o of a)HZD(t,o,n)}return W3t({options:t})}function ioa(e){if(e.settings==null&&e.apiOverride?.auth==null&&e.apiOverride?.["auth-schemes"]==null)return;let t={detectGlobalHeaders:!0};return e.settings?.unions==="v1"&&(t.discriminatedUnionV2=!0),e.apiOverride?.auth!=null&&(t.auth=e.apiOverride.auth),e.apiOverride?.["auth-schemes"]!=null&&(t.authSchemes=e.apiOverride["auth-schemes"]),t}function W7a(e){return e.swagger!=null}function c6c(e){return e.openapi!=null}function yJi(e,t={}){return{...Object.fromEntries(fI(e.namedDefinitionFiles).map(([r,i])=>[r,{...i,defaultUrl:t.defaultURL}])),...fI(e.importedDefinitions).reduce((r,[i,n])=>({...r,...wFa(yJi(n.definition,{defaultURL:n.url}),(a,o)=>_B(i,$u.of(o)))}),{})}}function G7a(e,t={}){return{...Object.fromEntries(fI(e.packageMarkers).map(([r,i])=>[r,{...i,defaultUrl:t.defaultURL}])),...fI(e.importedDefinitions).reduce((r,[i,n])=>({...r,...wFa(G7a(n.definition,{defaultURL:n.url}),(a,o)=>_B(i,$u.of(o)))}),{})}}function UQi(e){return{...G7a(e),...yJi(e)}}function gEe(e,t){return UQi(e.definition)[t]?.contents}function XI(e,t){for(let[r,i]of fI(UQi(e.definition)))t(r,i.contents,{isPackageMarker:Gln(r)===Db,defaultUrl:i.defaultUrl})}function Bbn(e,t){for(let[r,i]of fI(G7a(e.definition)))t(r,i.contents)}function OEe({breadcrumbs:e=[],title:t,subtitle:r}){let i=[];return e.length>0&&i.push(Ct.blue(e.join(" -> "))),i.push(t),r!=null&&i.push(Ct.dim(r)),i.join(`
1417
1417
  `)}var Wyh={None:"none",Header:"header"};var syu={};Zt(syu,{ConjureAliasDeclaration:()=>xhu,ConjureArgument:()=>ayu,ConjureArgumentWithParamType:()=>nyu,ConjureAuthDefinition:()=>uoa,ConjureAuthDefinitionType:()=>ryu,ConjureDefinitions:()=>eyu,ConjureEndpointDefinition:()=>oyu,ConjureEnumDeclaration:()=>Zhu,ConjureEnumVariant:()=>Xhu,ConjureEnumWithDocs:()=>Yhu,ConjureObjectDeclaration:()=>$hu,ConjureParamType:()=>iyu,ConjurePrimitive:()=>Hhu,ConjureService:()=>uyu,ConjureServiceName:()=>Ghu,ConjureType:()=>gJi,ConjureTypeDeclaration:()=>khu,ConjureTypeReference:()=>OJi,ConjureTypeWithDocs:()=>Khu,ConjureTypes:()=>tyu,ConjureUnionDeclaration:()=>Jhu,DefinitionFile:()=>bbh,WithDocs:()=>oYt,commons:()=>_6c,conjure:()=>h6c,services:()=>y6c,types:()=>b6c});var _6c={};Zt(_6c,{WithDocs:()=>oYt});var Kn={};Zt(Kn,{JsonError:()=>noa,ParseError:()=>aoa,any:()=>nbh,bigint:()=>Hyh,boolean:()=>abh,booleanLiteral:()=>ibh,date:()=>xyh,discriminant:()=>_bh,enum_:()=>Lhu,getObjectLikeUtils:()=>G3t,getObjectUtils:()=>Ibn,getSchemaUtils:()=>qP,isProperty:()=>vJi,lazy:()=>Kyh,lazyObject:()=>ebh,list:()=>Whu,number:()=>obh,object:()=>Vhu,objectWithoutOptionalProperties:()=>kyh,optional:()=>l6c,property:()=>$yh,record:()=>lbh,set:()=>fbh,string:()=>ubh,stringLiteral:()=>rbh,transform:()=>f6c,undiscriminatedUnion:()=>pbh,union:()=>ybh,unknown:()=>sbh,withParsedProperties:()=>p6c});var Sh={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 om(e,t){return`Expected ${t}. Received ${xZD(e)}.`}function xZD(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 YN(e){return{...e,json:Gyh(e.json),parse:Gyh(e.parse)}}function Gyh(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(`
1418
1418
  `)),{ok:!0,value:t}):i}}function Uhu(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var noa=class e extends Error{errors;constructor(t){super(t.map(Uhu).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var aoa=class e extends Error{errors;constructor(t){super(t.map(Uhu).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function qP(e){return{optional:()=>l6c(e),transform:t=>f6c(e,t),parseOrThrow:(t,r)=>{let i=e.parse(t,r);if(i.ok)return i.value;throw new aoa(i.errors)},jsonOrThrow:(t,r)=>{let i=e.json(t,r);if(i.ok)return i.value;throw new noa(i.errors)}}}function l6c(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:()=>Sh.OPTIONAL};return{...t,...qP(t)}}function f6c(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,...qP(r)}}function Hyh(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:om(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:om(t,"bigint")}]},getType:()=>Sh.BIGINT};return{...YN(e),...qP(e)}}var KZD=/^([+-]?\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 xyh(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:om(t,"string")}]}:KZD.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:om(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:om(t,"Date object")}]},getType:()=>Sh.DATE};return{...YN(e),...qP(e)}}function cW(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{...YN(r),...qP(r)}}}function Lhu(e){let t=new Set(e);return cW(Sh.ENUM,(i,{allowUnrecognizedEnumValues:n,breadcrumbsPrefix:a=[]}={})=>typeof i!="string"?{ok:!1,errors:[{path:a,message:om(i,"string")}]}:!t.has(i)&&!n?{ok:!1,errors:[{path:a,message:om(i,"enum")}]}:{ok:!0,value:i})()}function Kyh(e){let t=d6c(e);return{...t,...qP(t)}}function d6c(e){return{parse:(t,r)=>ooa(e).parse(t,r),json:(t,r)=>ooa(e).json(t,r),getType:()=>ooa(e).getType()}}function ooa(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function H7a(e){return Object.entries(e)}function x7a(e,t){let r=new Set(t);return Object.entries(e).reduce((i,[n,a])=>(r.has(n)&&(i[n]=a),i),{})}function bJi(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 K7a(e){return Object.keys(e)}function Jyh(e,t){let r=[],i=[];for(let n of e)t(n)?r.push(n):i.push(n);return[r,i]}function G3t(e){return{withParsedProperties:t=>p6c(e,t)}}function p6c(e,t){let r={parse:(i,n)=>{let a=e.parse(i,n);if(!a.ok)return a;let o=Object.entries(t).reduce((c,[d,s])=>({...c,[d]:typeof s=="function"?s(a.value):s}),{});return{ok:!0,value:{...a.value,...o}}},json:(i,n)=>{if(!bJi(i))return{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:om(i,"object")}]};let a=new Set(Object.keys(t)),o=x7a(i,Object.keys(i).filter(c=>!a.has(c)));return e.json(o,n)},getType:()=>e.getType()};return{...r,...qP(r),...G3t(r)}}function $yh(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function vJi(e){return e.isProperty}function Vhu(e){let t={_getRawProperties:()=>Object.entries(e).map(([r,i])=>vJi(i)?i.rawKey:r),_getParsedProperties:()=>K7a(e),parse:(r,i)=>{let n={},a=[];for(let[o,c]of H7a(e)){let d=vJi(c)?c.rawKey:o,s=vJi(c)?c.valueSchema:c,u={rawKey:d,parsedKey:o,valueSchema:s};n[d]=u,Zyh(s)&&a.push(d)}return Yyh({value:r,requiredKeys:a,getProperty:o=>{let c=n[o];if(c!=null)return{transformedKey:c.parsedKey,transform:d=>c.valueSchema.parse(d,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],o]})}},unrecognizedObjectKeys:i?.unrecognizedObjectKeys,skipValidation:i?.skipValidation,breadcrumbsPrefix:i?.breadcrumbsPrefix,omitUndefined:i?.omitUndefined})},json:(r,i)=>{let n=[];for(let[a,o]of H7a(e)){let c=vJi(o)?o.valueSchema:o;Zyh(c)&&n.push(a)}return Yyh({value:r,requiredKeys:n,getProperty:a=>{let o=e[a];if(o!=null)return vJi(o)?{transformedKey:o.rawKey,transform:c=>o.valueSchema.json(c,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],a]})}:{transformedKey:a,transform:c=>o.json(c,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],a]})}},unrecognizedObjectKeys:i?.unrecognizedObjectKeys,skipValidation:i?.skipValidation,breadcrumbsPrefix:i?.breadcrumbsPrefix,omitUndefined:i?.omitUndefined})},getType:()=>Sh.OBJECT};return{...YN(t),...qP(t),...G3t(t),...Ibn(t)}}function Yyh({value:e,requiredKeys:t,getProperty:r,unrecognizedObjectKeys:i="fail",skipValidation:n=!1,breadcrumbsPrefix:a=[]}){if(!bJi(e))return{ok:!1,errors:[{path:a,message:om(e,"object")}]};let o=new Set(t),c=[],d={};for(let[s,u]of Object.entries(e)){let f=r(s);if(f!=null){o.delete(s);let p=f.transform(u);p.ok?d[f.transformedKey]=p.value:(d[s]=u,c.push(...p.errors))}else switch(i){case"fail":c.push({path:[...a,s],message:`Unexpected key "${s}"`});break;case"strip":break;case"passthrough":d[s]=u;break}}return c.push(...t.filter(s=>o.has(s)).map(s=>({path:a,message:`Missing required key "${s}"`}))),c.length===0||n?{ok:!0,value:d}:{ok:!1,errors:c}}function Ibn(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(i,n)=>Xyh({extensionKeys:t._getRawProperties(),value:i,transformBase:a=>e.parse(a,n),transformExtension:a=>t.parse(a,n)}),json:(i,n)=>Xyh({extensionKeys:t._getParsedProperties(),value:i,transformBase:a=>e.json(a,n),transformExtension:a=>t.json(a,n)}),getType:()=>Sh.OBJECT};return{...r,...qP(r),...G3t(r),...Ibn(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:()=>Sh.OBJECT};return{...t,...qP(t),...G3t(t),...Ibn(t)}}}}function Xyh({extensionKeys:e,value:t,transformBase:r,transformExtension:i}){let n=new Set(e),[a,o]=Jyh(K7a(t),s=>n.has(s)),c=r(x7a(t,o)),d=i(x7a(t,a));return c.ok&&d.ok?{ok:!0,value:{...c.value,...d.value}}:{ok:!1,errors:[...c.ok?[]:c.errors,...d.ok?[]:d.errors]}}function Zyh(e){return!JZD(e)}function JZD(e){switch(e.getType()){case Sh.ANY:case Sh.UNKNOWN:case Sh.OPTIONAL:return!0;default:return!1}}function kyh(e){return Vhu(e)}function ebh(e){let t={...d6c(e),_getRawProperties:()=>ooa(e)._getRawProperties(),_getParsedProperties:()=>ooa(e)._getParsedProperties()};return{...t,...qP(t),...G3t(t),...Ibn(t)}}function Whu(e){let t={parse:(r,i)=>tbh(r,(n,a)=>e.parse(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),json:(r,i)=>tbh(r,(n,a)=>e.json(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),getType:()=>Sh.LIST};return{...YN(t),...qP(t)}}function tbh(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:om(e,"list"),path:[]}]}}function rbh(e){return cW(Sh.STRING_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:om(r,`"${e}"`)}]})()}function ibh(e){return cW(Sh.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:om(r,`${e.toString()}`)}]})()}var nbh=cW(Sh.ANY,e=>({ok:!0,value:e}));var abh=cW(Sh.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:om(e,"boolean")}]});var obh=cW(Sh.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:om(e,"number")}]});var ubh=cW(Sh.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:om(e,"string")}]});var sbh=cW(Sh.UNKNOWN,e=>({ok:!0,value:e}));function lbh(e,t){let r={parse:(i,n)=>cbh({value:i,isKeyNumeric:e.getType()===Sh.NUMBER,transformKey:a=>e.parse(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,o)=>t.parse(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${o}`]}),breadcrumbsPrefix:n?.breadcrumbsPrefix}),json:(i,n)=>cbh({value:i,isKeyNumeric:e.getType()===Sh.NUMBER,transformKey:a=>e.json(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,o)=>t.json(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${o}`]}),breadcrumbsPrefix:n?.breadcrumbsPrefix}),getType:()=>Sh.RECORD};return{...YN(r),...qP(r)}}function cbh({value:e,isKeyNumeric:t,transformKey:r,transformValue:i,breadcrumbsPrefix:n=[]}){return bJi(e)?H7a(e).reduce((a,[o,c])=>{if(c==null)return a;let d=a,s=o;if(t){let _=o.length>0?Number(o):NaN;isNaN(_)||(s=_)}let u=r(s),f=i(c,s);if(d.ok&&u.ok&&f.ok)return{ok:!0,value:{...d.value,[u.value]:f.value}};let p=[];return d.ok||p.push(...d.errors),u.ok||p.push(...u.errors),f.ok||p.push(...f.errors),{ok:!1,errors:p}},{ok:!0,value:{}}):{ok:!1,errors:[{path:n,message:om(e,"object")}]}}function fbh(e){let t=Whu(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:om(i,"Set")}]},getType:()=>Sh.SET};return{...YN(r),...qP(r)}}function pbh(e){let t={parse:(r,i)=>dbh((n,a)=>n.parse(r,a),e,i),json:(r,i)=>dbh((n,a)=>n.json(r,a),e,i),getType:()=>Sh.UNDISCRIMINATED_UNION};return{...YN(t),...qP(t)}}function dbh(e,t,r){let i=[];for(let[n,a]of t.entries()){let o=e(a,{...r,skipValidation:!1});if(o.ok)return o;for(let c of o.errors)i.push({path:c.path,message:`[Variant ${n}] ${c.message}`})}return{ok:!1,errors:i}}function _bh(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}function ybh(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,i=typeof e=="string"?e:e.parsedDiscriminant,n=Lhu(K7a(t)),a={parse:(o,c)=>hbh({value:o,discriminant:r,transformedDiscriminant:i,transformDiscriminantValue:d=>n.parse(d,{allowUnrecognizedEnumValues:c?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...c?.breadcrumbsPrefix??[],r]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:c?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,s)=>s.parse(d,c),breadcrumbsPrefix:c?.breadcrumbsPrefix}),json:(o,c)=>hbh({value:o,discriminant:i,transformedDiscriminant:r,transformDiscriminantValue:d=>n.json(d,{allowUnrecognizedEnumValues:c?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...c?.breadcrumbsPrefix??[],i]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:c?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,s)=>s.json(d,c),breadcrumbsPrefix:c?.breadcrumbsPrefix}),getType:()=>Sh.UNION};return{...YN(a),...qP(a),...G3t(a)}}function hbh({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:i,getAdditionalPropertiesSchema:n,allowUnrecognizedUnionMembers:a=!1,transformAdditionalProperties:o,breadcrumbsPrefix:c=[]}){if(!bJi(e))return{ok:!1,errors:[{path:c,message:om(e,"object")}]};let{[t]:d,...s}=e;if(d==null)return{ok:!1,errors:[{path:c,message:`Missing discriminant ("${t}")`}]};let u=i(d);if(!u.ok)return{ok:!1,errors:u.errors};let f=n(u.value);if(f==null)return a?{ok:!0,value:{[r]:u.value,...s}}:{ok:!1,errors:[{path:[...c,t],message:"Unexpected discriminant value"}]};let p=o(s,f);return p.ok?{ok:!0,value:{[r]:d,...p.value}}:p}var oYt=Kn.objectWithoutOptionalProperties({docs:Kn.string().optional()});var h6c={};Zt(h6c,{ConjureServiceName:()=>Ghu,DefinitionFile:()=>bbh});var Ghu=Kn.string();var Hhu=Kn.enum_(["rid","string","safelong","integer","double","boolean","binary"]);var gJi=Kn.undiscriminatedUnion([Hhu,Kn.string()]);var xhu=Kn.objectWithoutOptionalProperties({alias:gJi,docs:Kn.string().optional()});var Khu=Kn.objectWithoutOptionalProperties({type:gJi,docs:Kn.string().optional()});var OJi=Kn.undiscriminatedUnion([gJi,Khu]);var Jhu=Kn.objectWithoutOptionalProperties({union:Kn.record(Kn.string(),OJi)});var $hu=Kn.objectWithoutOptionalProperties({fields:Kn.record(Kn.string(),OJi)});var Yhu=Kn.objectWithoutOptionalProperties({value:Kn.string()}).extend(oYt);var Xhu=Kn.undiscriminatedUnion([Kn.string(),Yhu]);var Zhu=Kn.objectWithoutOptionalProperties({values:Kn.list(Xhu)});var khu=Kn.undiscriminatedUnion([xhu,Jhu,$hu,Zhu]);var eyu=Kn.objectWithoutOptionalProperties({objects:Kn.record(Kn.string(),khu).optional()});var tyu=Kn.objectWithoutOptionalProperties({conjureImports:Kn.property("conjure-imports",Kn.record(Kn.string(),Kn.string()).optional()),definitions:eyu.optional()});var ryu=Kn.enum_(["none","header"]);var uoa=Kn.undiscriminatedUnion([ryu,Kn.string()]);var iyu=Kn.enum_(["path","query","body"]);var nyu=Kn.objectWithoutOptionalProperties({paramType:Kn.property("param-type",iyu),type:Kn.string()}).extend(oYt);var ayu=Kn.undiscriminatedUnion([Kn.string(),nyu]);var oyu=Kn.objectWithoutOptionalProperties({http:Kn.string(),auth:uoa.optional(),args:Kn.record(Kn.string(),ayu).optional(),returns:OJi.optional()}).extend(oYt);var uyu=Kn.objectWithoutOptionalProperties({name:Kn.string().optional(),package:Kn.string().optional(),basePath:Kn.property("base-path",Kn.string().optional()),defaultAuth:Kn.property("default-auth",uoa.optional()),endpoints:Kn.record(Kn.string(),oyu).optional()}).extend(oYt);var bbh=Kn.objectWithoutOptionalProperties({types:tyu.optional(),services:Kn.record(Ghu,uyu).optional()});var y6c={};Zt(y6c,{ConjureArgument:()=>ayu,ConjureArgumentWithParamType:()=>nyu,ConjureAuthDefinition:()=>uoa,ConjureAuthDefinitionType:()=>ryu,ConjureEndpointDefinition:()=>oyu,ConjureParamType:()=>iyu,ConjureService:()=>uyu});var b6c={};Zt(b6c,{ConjureAliasDeclaration:()=>xhu,ConjureDefinitions:()=>eyu,ConjureEnumDeclaration:()=>Zhu,ConjureEnumVariant:()=>Xhu,ConjureEnumWithDocs:()=>Yhu,ConjureObjectDeclaration:()=>$hu,ConjurePrimitive:()=>Hhu,ConjureType:()=>gJi,ConjureTypeDeclaration:()=>khu,ConjureTypeReference:()=>OJi,ConjureTypeWithDocs:()=>Khu,ConjureTypes:()=>tyu,ConjureUnionDeclaration:()=>Jhu});var vbh=require("fs/promises");async function gbh(e,t){let r=[];for(let i of await xU(e,t))r.push(await $ZD({relativeFilepath:S_(e,i),absoluteFilepath:i}));return r}async function $ZD({relativeFilepath:e,absoluteFilepath:t}){let r=(await(0,vbh.readFile)(t)).toString().replaceAll(/: rid(?:$|\s)/g,`: string
1419
- `).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:syu.conjure.DefinitionFile.parseOrThrow(Di.load(r),{unrecognizedObjectKeys:"passthrough",allowUnrecognizedEnumValues:!0,allowUnrecognizedUnionMembers:!0})}}function Obh(e,t){if(YZD(e))return t.alias(e);if(XZD(e))return t.enum(e);if(ZZD(e))return t.object(e);if(kZD(e))return t.union(e);vt(e)}function YZD(e){return e?.alias!=null}function XZD(e){return e?.values!=null}function ZZD(e){return e?.fields!=null}function kZD(e){return e?.union!=null}var J7a=class extends DHa{fernDefinitionBuilder=new Zyn(!1);conjureFilepathToFernFilepath={};async import({absolutePathToConjureFolder:t,authOverrides:r,environmentOverrides:i,globalHeaderOverrides:n}){if(r!=null){for(let[a,o]of Object.entries(r["auth-schemes"]??{}))this.fernDefinitionBuilder.addAuthScheme({name:a,schema:o});r.auth!=null&&this.fernDefinitionBuilder.setAuth(r.auth)}if(i!=null){for(let[a,o]of Object.entries(i.environments??{}))this.fernDefinitionBuilder.addEnvironment({name:a,schema:o});i["default-environment"]!=null&&this.fernDefinitionBuilder.setDefaultEnvironment(i["default-environment"]),i["default-url"]!=null&&this.fernDefinitionBuilder.setDefaultUrl(i["default-url"])}return await Abh(t,(a,o,c)=>{for(let[u,f]of Object.entries(c.services??{})){let p=mCo({value:u,suffix:"Service"});this.conjureFilepathToFernFilepath[o]=Xe.of(`${p}/__package__.yml`);return}let s=rzi(o)?.split(".")[0];s!=null&&(this.conjureFilepathToFernFilepath[o]=Xe.of(`${s}/__package__.yml`))}),await Abh(t,(a,o,c)=>{if(c.services==null||Object.keys(c.services??{}).length===0){let d=this.conjureFilepathToFernFilepath[o];if(d==null)throw new Error(`Failed to find corresponding fern filepath for conjure file ${o}`);for(let[s,u]of Object.entries(c.types?.conjureImports??{})){let f=this.getFernFileToImport({absoluteFilePathToConjureFile:a,absoluteFilePathToConjureFolder:t,importFilePath:Xe.of(u)});this.fernDefinitionBuilder.addImport({file:d,fileToImport:Xe.of(f),alias:s})}this.importAllTypes({conjureFile:c,fernFilePath:d});return}for(let[d,s]of Object.entries(c.services)){let u=mCo({value:d,suffix:"Service"}),f=Xe.of(`${u}/__package__.yml`),p={};s.basePath!=null&&(p["base-path"]=s.basePath),s.docs!=null&&(p.docs=s.docs),this.fernDefinitionBuilder.setServiceInfo(f,p),this.importAllTypes({conjureFile:c,fernFilePath:f});for(let[_,h]of Object.entries(c.types?.conjureImports??{})){let y=this.getFernFileToImport({absoluteFilePathToConjureFile:a,absoluteFilePathToConjureFolder:t,importFilePath:Xe.of(h)});this.fernDefinitionBuilder.addImport({file:f,fileToImport:Xe.of(y),alias:_})}for(let[_,h]of Object.entries(s.endpoints??{})){let y=r2s(h.http);if(y.type==="failure"){this.context?.logger.error(`Failed to parse ${h.http}. Skipping.`);continue}let v={auth:(h.auth??s.defaultAuth)!==Wyh.None,path:y.path,method:y.method,response:h.returns==="binary"?"file":h.returns};h.docs!=null&&(v.docs=h.docs);let O={};if(h.args!=null)for(let A of y.pathParameters){let g=h.args[A];if(g==null)throw new Error(`Failed to find path parameter ${A} in ${h.http}`);O[A]=typeof g=="string"?g:{type:g.type}}Object.entries(O).length>0&&(v["path-parameters"]=O);for(let[A,g]of Object.entries(h.args??{}))if(O[A]==null)if(typeof g=="string")v.request?typeof v.request=="string"&&(v.request={body:v.request}):v.request={},v.request.body=g==="binary"?"bytes":g;else switch(g.paramType){case"body":v.request={body:g.type==="binary"?"bytes":g.type};break;case"query":v.request==null?v.request={"query-parameters":{[A]:g.type}}:typeof v.request!="string"&&v.request?.["query-parameters"]==null?v.request["query-parameters"]={[A]:g.type}:typeof v.request!="string"&&v.request?.["query-parameters"]!=null&&(v.request["query-parameters"][A]=g.type)}v.request!=null&&typeof v.request!="string"&&v.request?.["query-parameters"]!=null&&(v.request.name=`${_}Request`),this.fernDefinitionBuilder.addEndpoint(f,{name:_,schema:v,source:void 0})}}}),this.fernDefinitionBuilder.build()}convertBinaryType(t){return typeof t=="string"?t==="binary"?{type:"string",validation:{format:"binary"}}:t:t.type==="binary"?{...t,type:"string",validation:{format:"binary"}}:t}importAllTypes({conjureFile:t,fernFilePath:r}){for(let[i,n]of Object.entries(t.types?.definitions?.objects??{}))Obh(n,{alias:a=>{let o=a.alias==="binary"?{type:"string",validation:{format:"binary"}}:a.alias;this.fernDefinitionBuilder.addType(r,{name:i,schema:typeof o=="string"?{type:o,docs:a.docs}:{...o,docs:a.docs}})},object:a=>{this.fernDefinitionBuilder.addType(r,{name:i,schema:{properties:Object.fromEntries(Object.entries(a.fields).map(([o,c])=>[o,this.convertBinaryType(c)]))}})},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(([o,c])=>{let d=this.convertBinaryType(c);return[o,{type:typeof d=="string"?d:d.type,docs:typeof d=="string"?void 0:d.docs,key:o}]}))}})}})}getFernFileToImport({absoluteFilePathToConjureFile:t,importFilePath:r,absoluteFilePathToConjureFolder:i}){let n=It(en(t),Xe.of(r)),a=kK(i,n),o=this.conjureFilepathToFernFilepath[a];if(o==null)throw new Error(`Failed to find corresponding fern filepath for conjure file ${a}`);return o}};async function Abh(e,t){for(let r of await gbh(e,"{yml,yaml}"))await t(r.absoluteFilepath,r.relativeFilepath,r.fileContents)}function mbh(e,t){return bn(e,t)}var cyu=class extends M3t{type="conjure";absolutePathToConjureFolder;constructor({relativePathToConjureDirectory:t,...r}){super(r),this.absolutePathToConjureFolder=It(r.absoluteFilePath,t)}async toFernWorkspace({context:t},r){let i=await this.getDefinition({context:t},r);return new B$({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 J7a(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:Sr.of("/DUMMY_PATH"),rootApiFile:{defaultUrl:n.rootApiFile["default-url"],contents:n.rootApiFile,rawContents:Di.dump(n.rootApiFile)},namedDefinitionFiles:{...mbh(n.definitionFiles,a=>({absoluteFilepath:Sr.of("/DUMMY_PATH"),rawContents:Di.dump(a),contents:a})),[Xe.of(Db)]:{absoluteFilepath:Sr.of("/DUMMY_PATH"),rawContents:Di.dump(n.packageMarkerFile),contents:n.packageMarkerFile}},packageMarkers:{},importedDefinitions:{}}}getAbsoluteFilePaths(){return[this.absolutePathToConjureFolder]}};var VOh=ce(Mbh(),1);var R_;(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"})(R_||(R_={}));function Dbh(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function lyu(e,t){for(let[r,i]of fI(e))t2D({relativeFilepath:r,failure:i,logger:t})}function t2D({relativeFilepath:e,failure:t,logger:r}){switch(t.type){case R_.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 R_.FILE_READ:r.error("Failed to open file: "+e);break;case R_.FILE_MISSING:r.error("Missing file: "+e);break;case R_.FILE_PARSE:t.error instanceof dUa?r.error(OEe({title:`Failed to parse ${e}: ${t.error.reason}`,subtitle:t.error.mark.snippet})):r.error("Failed to parse file: "+e);break;case R_.STRUCTURE_VALIDATION:for(let i of t.error.issues)for(let{title:n,subtitle:a}of r2D(i))r.error(OEe({title:n,subtitle:a,breadcrumbs:[e,...i.path]}));break;case R_.FAILED_TO_LOAD_DEPENDENCY:r.error("Failed to load dependency: "+t.dependencyName);break;case R_.DEPENDENCY_NOT_LISTED:r.error(`Dependency is not listed in ${gqo}: `+t.dependencyName);break;case R_.EXPORT_PACKAGE_HAS_DEFINITIONS:r.error("Exported package contains API definitions: "+t.pathToPackage);break;case R_.EXPORTING_PACKAGE_MARKER_OTHER_KEYS:r.error(`${t.pathOfPackageMarker} has an export so it cannot define other keys.`);break;case R_.JSONSCHEMA_VALIDATION:if(t.error.error!=null){let i=t.error.error.instancePath.split("/").filter(n=>n!=="").map(Dbh);t.error.error.keyword==="required"&&t.error.error.params?.missingProperty?i.push(t.error.error.params.missingProperty):t.error.error.keyword==="additionalProperties"&&t.error.error.params?.additionalProperty&&i.push(t.error.error.params.additionalProperty),r.error(OEe({title:t.error.error.message??"Unknown error",breadcrumbs:[e,...i]}))}for(let i of t.error.allErrors)if(i!==t.error.error){let n=i.instancePath.split("/").filter(a=>a!=="").map(Dbh);i.keyword==="required"&&i.params?.missingProperty?n.push(i.params.missingProperty):i.keyword==="additionalProperties"&&i.params?.additionalProperty&&n.push(i.params.additionalProperty),r.debug(OEe({title:i.message??"Unknown error",breadcrumbs:[e,...n]}))}break;default:vt(t)}}function r2D(e){switch(e.code){case Ai.invalid_type:return[{title:"Incorrect type",subtitle:`Expected ${Ct.underline(e.expected)} but received ${Ct.underline(e.received)}`}];case Ai.unrecognized_keys:return e.keys.map(t=>({title:"Unexpected key",subtitle:`Encountered unexpected key ${Ct.underline(t)}`}));case Ai.invalid_enum_value:return[{title:"Unrecognized value",subtitle:`Allowed values: ${e.options.map(t=>Ct.underline(t)).join(", ")}`}];case Ai.invalid_union:case Ai.invalid_arguments:case Ai.invalid_return_type:case Ai.invalid_date:case Ai.invalid_string:case Ai.too_small:case Ai.too_big:case Ai.invalid_intersection_types:case Ai.not_multiple_of:case Ai.custom:default:return[{title:e.message}]}}var Bbh=require("fs/promises");async function Ibh(e,t){let r=[];for(let i of await xU(e,t))r.push(await i2D({relativeFilepath:S_(e,i),absoluteFilepath:i}));return r}async function i2D({relativeFilepath:e,absoluteFilepath:t}){return{relativeFilepath:e,absoluteFilepath:t,fileContents:(await(0,Bbh.readFile)(t)).toString()}}async function Cbh(e){let t={},r={};function i(n){try{t[n.relativeFilepath]={defaultUrl:void 0,contents:Di.load(n.fileContents,{schema:Di.CORE_SCHEMA}),rawContents:n.fileContents}}catch(a){r[n.relativeFilepath]={type:R_.FILE_PARSE,error:a}}}return await Promise.all(e.map(i)),Object.keys(r).length>0?{didSucceed:!1,failures:r}:{didSucceed:!0,files:t}}var sGc=ce(DHi(),1);var IOh=require("fs"),Coa=require("fs/promises");var COh=require("os"),qOh=ce(require("path"),1),TOh=require("stream/promises"),ROh=ce(uGc(),1),zOh=ce(Z9(),1);var qeB=ZNi();async function NOh({dependencyName:e,dependenciesConfiguration:t,context:r,rootApiFile:i,cliVersion:n,settings:a,loadAPIWorkspace:o}){let c,d={type:R_.FAILED_TO_LOAD_DEPENDENCY,dependencyName:e},s=t.dependencies[e];return s==null?d={type:R_.DEPENDENCY_NOT_LISTED,dependencyName:e}:await r.runInteractiveTask({name:`Download ${UeB(s)}`},async u=>{switch(s.type){case"version":c=await FeB({context:u,dependency:s,cliVersion:n,settings:a,loadAPIWorkspace:o});return;case"local":c=await NeB({context:u,dependency:s,cliVersion:n,settings:a,loadAPIWorkspace:o});return;default:vt(s)}}),c!=null?{didSucceed:!0,definition:c}:{didSucceed:!1,failure:d}}var FOh="dependencies";var TeB="metadata.json",ReB=".fern";function zeB(e){return It(Sr.of((0,COh.homedir)()),Xe.of(ReB),Xe.of(FOh),Xe.of(e.organization),Xe.of(e.apiName),Xe.of(e.version))}async function NeB({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 o=await a.workspace.getDefinition({context:t,relativePathToDependency:Xe.of(e.path)},i);return t.logger.info("Loaded..."),o}async function FeB({dependency:e,context:t,cliVersion:r,settings:i,loadAPIWorkspace:n}){let a=zeB(e),o=It(a,Xe.of(FOh)),c=It(a,Xe.of(TeB)),d;if(!await mi(o)||!await mi(c)){t.logger.info("Downloading manifest...");let f=await qeB.definitionRegistry.get(sGc.FernFiddle.OrganizationId(e.organization),sGc.FernFiddle.ApiId(e.apiName),e.version);if(!f.ok){f.error._visit({orgDoesNotExistError:()=>{t.failWithoutThrowing("Organization does not exist")},apiDoesNotExistError:()=>{t.failWithoutThrowing("API does not exist")},versionDoesNotExistError:()=>{t.failWithoutThrowing("Version does not exist")},_other:y=>{t.failWithoutThrowing("Failed to download API manifest",y)}});return}let p=f.body.yamlSchemaVersion!=null?parseInt(f.body.yamlSchemaVersion):void 0,_=Syn(r),h=Syn(f.body.cliVersion);if(p!=null){if(p>1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a higher version of fern. Upgrade this workspace to ${f.body.cliVersion}`);return}else if(p<1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a lower version of fern. Upgrade it to ${r}`);return}}else if(_.major!==h.major||_.minor!==h.minor){t.failWithoutThrowing(`CLI version is ${f.body.cliVersion}. Expected ${_.major}.${_.minor}.x (to match current workspace).`);return}t.logger.info("Downloading..."),t.logger.debug("Remote URL: "+f.body.definitionS3DownloadUrl),await(0,Coa.mkdir)(o,{recursive:!0});try{await QeB({s3PreSignedReadUrl:f.body.definitionS3DownloadUrl,absolutePathToLocalOutput:o})}catch(y){t.failWithoutThrowing("Failed to download API",y);return}d=f.body,await(0,Coa.writeFile)(c,JSON.stringify(d))}else d=JSON.parse((await(0,Coa.readFile)(c)).toString());if(t.logger.info("Parsing..."),n==null){t.failWithoutThrowing("Failed to load API");return}let s=await n({absolutePathToWorkspace:o,context:t,cliVersion:d.cliVersion,workspaceName:void 0});if(!s.didSucceed){t.failWithoutThrowing("Failed to parse dependency after downloading",s.failures);return}if(s.workspace.type==="oss"){t.failWithoutThrowing("Dependency must be a fern workspace.");return}return await s.workspace.getDefinition({context:t},i)}async function QeB({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t}){let r=await wB.get(e,{responseType:"stream"}),i=await zOh.default.dir(),n=qOh.default.join(i.path,"api.tgz");await(0,TOh.pipeline)(r.data,(0,IOh.createWriteStream)(n)),await(0,ROh.extract)({file:n,cwd:t})}function UeB(e){switch(e.type){case"version":return`@${e.organization}/${e.apiName}`;case"local":return`${e.path}`;default:vt(e)}}async function QOh({dependenciesConfiguration:e,structuralValidationResult:t,context:r,cliVersion:i,settings:n,loadAPIWorkspace:a}){let o={},c={},d={};return await Promise.all(fI(t.packageMarkers).map(async([s,u])=>{if(u.contents.export==null)o[s]=u;else{let{export:f,...p}=u.contents;if(gm(p)>0)d[s]={type:R_.EXPORTING_PACKAGE_MARKER_OTHER_KEYS,pathOfPackageMarker:s};else{let _=en(s);if(dLt(t.namedDefinitionFiles).some(y=>y!==s&&y.startsWith(_)))d[s]={type:R_.EXPORT_PACKAGE_HAS_DEFINITIONS,pathToPackage:_};else{let y=await NOh({dependencyName:typeof u.contents.export=="string"?u.contents.export:u.contents.export.dependency,dependenciesConfiguration:e,context:r,rootApiFile:t.rootApiFile.contents,cliVersion:i,settings:n,loadAPIWorkspace:a});y.didSucceed?c[en(s)]={definition:y.definition,url:typeof u.contents.export=="object"?u.contents.export.url:void 0}:d[s]=y.failure}}}})),gm(d)>0?{didSucceed:!1,failures:d}:{didSucceed:!0,packageMarkers:o,importedDefinitions:c}}var UOh=ce(require("path"),1);var cGc={};Zt(cGc,{additionalProperties:()=>GeB,default:()=>xeB,definitions:()=>HeB,properties:()=>VeB,required:()=>WeB,type:()=>LeB});var LeB="object",VeB={docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},"default-url":{oneOf:[{type:"string"},{type:"null"}]},"default-environment":{oneOf:[{type:"string"},{type:"null"}]},environments:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/environments.EnvironmentSchema"}},{type:"null"}]},auth:{oneOf:[{$ref:"#/definitions/auth.ApiAuthSchema"},{type:"null"}]},"auth-schemes":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/auth.AuthSchemeDeclarationSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},name:{type:"string"},imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},"error-discrimination":{oneOf:[{$ref:"#/definitions/file.ErrorDiscriminationSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},errors:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"idempotency-headers":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},variables:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/variables.VariableDeclarationSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"null"}]},product:{oneOf:[{$ref:"#/definitions/products.ProductDeclarationSchema"},{type:"null"}]},version:{oneOf:[{$ref:"#/definitions/versioning.VersionDeclarationSchema"},{type:"null"}]}},WeB=["name"],GeB=!1,HeB={"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.EndpointSecuritySchemaDetails":{type:"object",additionalProperties:!1},"auth.EndpointSecuritySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"endpoint-security":{$ref:"#/definitions/auth.EndpointSecuritySchemaDetails"}},required:["endpoint-security"],additionalProperties:!1},"auth.ApiAuthSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.AuthSchemeReferenceSchema"},{$ref:"#/definitions/auth.AnyAuthSchemesSchema"},{$ref:"#/definitions/auth.EndpointSecuritySchema"}]},"auth.AuthScope":{type:"string"},"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:{$ref:"#/definitions/auth.AuthScope"}},{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.TokenBearerAuthSchema":{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.InferredAuthenticatedRequestHeader":{type:"object",properties:{"response-property":{type:"string"},"header-name":{type:"string"},"value-prefix":{oneOf:[{type:"string"},{type:"null"}]}},required:["response-property","header-name"],additionalProperties:!1},"auth.InferredGetTokenEndpointSchemaObject":{type:"object",properties:{endpoint:{type:"string"},"expiry-response-property":{oneOf:[{type:"string"},{type:"null"}]},"authenticated-request-headers":{oneOf:[{type:"array",items:{$ref:"#/definitions/auth.InferredAuthenticatedRequestHeader"}},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.InferredGetTokenEndpointSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.InferredGetTokenEndpointSchemaObject"}]},"auth.InferredBearerAuthSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"bearer"},"get-token":{$ref:"#/definitions/auth.InferredGetTokenEndpointSchema"}},required:["scheme","get-token"],additionalProperties:!1},"auth.BearerAuthSchemeSchema":{anyOf:[{$ref:"#/definitions/auth.TokenBearerAuthSchema"},{$ref:"#/definitions/auth.InferredBearerAuthSchema"}]},"auth.AuthSchemeDeclarationSchema":{anyOf:[{$ref:"#/definitions/auth.OAuthSchemeSchema"},{$ref:"#/definitions/auth.HeaderAuthSchemeSchema"},{$ref:"#/definitions/auth.BasicAuthSchemeSchema"},{$ref:"#/definitions/auth.BearerAuthSchemeSchema"}]},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"file.PropertyBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"property"},"property-name":{type:"string"}},required:["strategy","property-name"],additionalProperties:!1},"file.StatusCodeBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"status-code"}},required:["strategy"],additionalProperties:!1},"file.ErrorDiscriminationSchema":{anyOf:[{$ref:"#/definitions/file.PropertyBasedErrorDiscrimination"},{$ref:"#/definitions/file.StatusCodeBasedErrorDiscrimination"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"variables.VariableDeclarationDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"variables.VariableDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/variables.VariableDeclarationDetailed"}]},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"}]},"versioning.VersionValueDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionValue":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionValueDetailed"}]},"versioning.VersionDeclarationHeaderObjectSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionDeclarationHeaderSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionDeclarationHeaderObjectSchema"}]},"versioning.VersionDeclarationSchema":{type:"object",properties:{default:{oneOf:[{type:"string"},{type:"null"}]},values:{type:"array",items:{$ref:"#/definitions/versioning.VersionValue"}},header:{$ref:"#/definitions/versioning.VersionDeclarationHeaderSchema"}},required:["values","header"],additionalProperties:!1},"products.ProductValueDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},versions:{oneOf:[{$ref:"#/definitions/versioning.VersionDeclarationSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"products.ProductValue":{anyOf:[{type:"string"},{$ref:"#/definitions/products.ProductValueDetailed"}]},"products.ProductDeclarationHeaderObjectSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"products.ProductDeclarationHeaderSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/products.ProductDeclarationHeaderObjectSchema"}]},"products.ProductDeclarationSchema":{type:"object",properties:{default:{oneOf:[{type:"string"},{type:"null"}]},values:{type:"array",items:{$ref:"#/definitions/products.ProductValue"}},header:{$ref:"#/definitions/products.ProductDeclarationHeaderSchema"}},required:["values","header"],additionalProperties:!1}},xeB={type:LeB,properties:VeB,required:WeB,additionalProperties:GeB,definitions:HeB};var lGc={};Zt(lGc,{additionalProperties:()=>$eB,default:()=>XeB,definitions:()=>YeB,properties:()=>JeB,type:()=>KeB});var KeB="object",JeB={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"}]}},$eB=!1,YeB={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"}]},"types.ObjectPropertyAccess":{type:"string",enum:["read-only","write-only"]},"types.ObjectPropertyWithAccessSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},access:{oneOf:[{$ref:"#/definitions/types.ObjectPropertyAccess"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.ObjectPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectPropertyWithAccessSchema"}]},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE","HEAD"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"auth.AuthScope":{type:"string"},"service.HttpEndpointSecurityItem":{type:"object",additionalProperties:{type:"array",items:{$ref:"#/definitions/auth.AuthScope"}}},"service.HttpEndpointSecurity":{type:"array",items:{$ref:"#/definitions/service.HttpEndpointSecurityItem"}},"service.HttpEndpointAuth":{anyOf:[{type:"boolean"},{$ref:"#/definitions/service.HttpEndpointSecurity"}]},"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.RetriesDisabledSchema":{type:"object",properties:{disabled:{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"service.RetriesConfiguration":{anyOf:[{$ref:"#/definitions/service.RetriesDisabledSchema"}]},"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:[{$ref:"#/definitions/service.HttpEndpointAuth"},{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"}]},retries:{oneOf:[{$ref:"#/definitions/service.RetriesConfiguration"},{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"},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},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"}]},"method-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}},XeB={type:KeB,properties:JeB,additionalProperties:$eB,definitions:YeB};var fGc={};Zt(fGc,{additionalProperties:()=>etB,default:()=>rtB,definitions:()=>ttB,properties:()=>keB,type:()=>ZeB});var ZeB="object",keB={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"}]}},etB=!1,ttB={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"}]},"types.ObjectPropertyAccess":{type:"string",enum:["read-only","write-only"]},"types.ObjectPropertyWithAccessSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},access:{oneOf:[{$ref:"#/definitions/types.ObjectPropertyAccess"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.ObjectPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectPropertyWithAccessSchema"}]},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE","HEAD"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"auth.AuthScope":{type:"string"},"service.HttpEndpointSecurityItem":{type:"object",additionalProperties:{type:"array",items:{$ref:"#/definitions/auth.AuthScope"}}},"service.HttpEndpointSecurity":{type:"array",items:{$ref:"#/definitions/service.HttpEndpointSecurityItem"}},"service.HttpEndpointAuth":{anyOf:[{type:"boolean"},{$ref:"#/definitions/service.HttpEndpointSecurity"}]},"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.RetriesDisabledSchema":{type:"object",properties:{disabled:{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"service.RetriesConfiguration":{anyOf:[{$ref:"#/definitions/service.RetriesDisabledSchema"}]},"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:[{$ref:"#/definitions/service.HttpEndpointAuth"},{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"}]},retries:{oneOf:[{$ref:"#/definitions/service.RetriesConfiguration"},{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"},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},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"}]},"method-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"}]}},rtB={type:ZeB,properties:keB,additionalProperties:etB,definitions:ttB};function LOh({files:e,absolutePathToDefinition:t}){let r,i={},n={},a={};for(let[o,c]of fI(e)){let d=c.contents,s=u=>{a[o]={type:R_.JSONSCHEMA_VALIDATION,error:u}};if(o===dB){let u=bLt(d,cGc);if(u.success){let f=TB.serialization.RootApiFileSchema.parseOrThrow(d);r={defaultUrl:f["default-url"],contents:f,rawContents:c.rawContents}}else s(u)}else if(UOh.default.basename(o)===Db){let u=bLt(d,fGc);if(u.success){let f=TB.serialization.PackageMarkerFileSchema.parseOrThrow(d);n[o]={defaultUrl:typeof f.export=="object"?f.export.url:void 0,contents:f,rawContents:c.rawContents}}else s(u)}else{let u=bLt(d,lGc);if(u.success){let f=TB.serialization.DefinitionFileSchema.parseOrThrow(d);i[o]={defaultUrl:void 0,contents:f,rawContents:c.rawContents,absoluteFilePath:It(t,o)}}else s(u)}}return r==null?{didSucceed:!1,failures:{[Xe.of(dB)]:{type:R_.FILE_MISSING},...a}}:Object.keys(a).length>0?{didSucceed:!1,failures:a}:{didSucceed:!0,namedDefinitionFiles:i,rootApiFile:r,packageMarkers:n}}var SEe=class extends M3t{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,VOh.default)(r??{}),n=this.fernWorkspaces[i];if(n==null){let a=t||this.context,o=It(this.absoluteFilePath,Xe.of(Pq)),c=await Jrc({absolutePathToWorkspace:this.absoluteFilePath,context:a}),d=await Ibh(o,"{yml,yaml}"),s=await Cbh(d);if(!s.didSucceed)return lyu(s.failures,a.logger),a.failAndThrow();let u=LOh({files:s.files,absolutePathToDefinition:o});if(!u.didSucceed)return lyu(u.failures,a.logger),a.failAndThrow();let f=await QOh({dependenciesConfiguration:c,structuralValidationResult:u,context:a,cliVersion:this.cliVersion,settings:r,loadAPIWorkspace:this.loadAPIWorkspace});if(!f.didSucceed)return lyu(f.failures,a.logger),a.failAndThrow();let p={absoluteFilePath:o,rootApiFile:u.rootApiFile,namedDefinitionFiles:u.namedDefinitionFiles,packageMarkers:f.packageMarkers,importedDefinitions:f.importedDefinitions};r?.auth!=null&&(p={...p,rootApiFile:{...p.rootApiFile,contents:{...p.rootApiFile.contents,auth:r?.auth}}}),n=new B$({absoluteFilePath:this.absoluteFilePath,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:c,workspaceName:this.workspaceName,definition:p,cliVersion:this.cliVersion,sources:[]}),this.fernWorkspaces[i]=n}return n}getAbsoluteFilePaths(){return[this.absoluteFilePath]}};var vmh=require("fs/promises");var pmh=ce(dmh(),1);async function qxa(e){return(await(0,pmh.convertObj)(e,{})).openapi}var hmh=require("fs/promises");var _mh=require("fs/promises");async function Uoa({absoluteFilePathToOverrides:e,data:t,context:r,allowNullKeys:i}){let n=null;try{let a=(await(0,_mh.readFile)(e,"utf8")).toString();try{n=JSON.parse(a)}catch{n=Di.load(a,{json:!0})}}catch{return r.failAndThrow(`Failed to read overrides from file ${e}`)}return ZZs({data:t,overrides:n,allowNullKeys:i})}async function TGc({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let i=(await(0,hmh.readFile)(t)).toString(),n=await Di.load(i);return r!=null?await Uoa({absoluteFilePathToOverrides:r,context:e,data:n}):n}var bmh=require("fs/promises");var Rxa=ce(Nhu(),1);var ymh=ce(Nhu(),1),RGc=ce(require("path"),1),Txa=class extends ymh.BaseResolver{absolutePathToOpenAPIOverrides;constructor(t){super(),this.absolutePathToOpenAPIOverrides=t}resolveExternalRef(t,r){let i=super.resolveExternalRef(t,r);return i.startsWith("http://")||i.startsWith("https://")||mLt(Sr.of(i))?i:this.absolutePathToOpenAPIOverrides!=null?RGc.default.resolve(RGc.default.dirname(this.absolutePathToOpenAPIOverrides),r):i}};async function zGc({absolutePathToOpenAPI:e,absolutePathToOpenAPIOverrides:t,parsed:r}){return(r!=null?await(0,Rxa.bundle)({...Fhu,doc:{source:new Rxa.Source(e,"<openapi>"),parsed:r},externalRefResolver:new Txa(t)}):await(0,Rxa.bundle)({...Fhu,ref:e,externalRefResolver:new Txa(t)})).bundle.parsed}function HrB(e,t){if(t.includes(e))return e;for(let r of t){let i=r.replace(/\{[^}]+\}/g,"([^/]+)");if(new RegExp(`^${i}$`).test(e))return r}}var xrB=["examples","example",Hi.EXAMPLES,G4.REDOCLY_CODE_SAMPLES_CAMEL,G4.REDOCLY_CODE_SAMPLES_KEBAB];async function zxa({context:e,absolutePathToOpenAPI:t,absolutePathToOpenAPIOverrides:r}){let i=await zGc({absolutePathToOpenAPI:t}),n;r!=null?n=r:typeof i=="object"&&i[Hi.OPENAPI_OVERIDES_FILEPATH]!=null&&(n=It(en(t),Xe.of(i[Hi.OPENAPI_OVERIDES_FILEPATH])));let a=i;n!=null&&(a=await Uoa({absoluteFilePathToOverrides:n,context:e,data:a,allowNullKeys:xrB}));let o=It(en(t),Xe.of("ai_examples_override.yml"));try{let c=await(0,bmh.readFile)(o,"utf-8"),d=Di.load(c);if(d?.paths&&a.paths){for(let[s,u]of Object.entries(d.paths))if(u&&typeof u=="object")for(let[f,p]of Object.entries(u)){let _=f.toLowerCase(),h=a.paths[s];if(!h&&a.paths){let y=HrB(s,Object.keys(a.paths));y&&(h=a.paths[y],e.logger.debug(`Matched override path "${s}" to OpenAPI path "${y}" using pattern matching`))}if(h&&typeof h=="object"){let b=h[_];if(b&&typeof b=="object"){let v=b;!v["x-fern-examples"]&&p["x-fern-examples"]&&(v["x-fern-examples"]=p["x-fern-examples"],e.logger.debug(`Added AI examples for ${f.toUpperCase()} ${s} from override file`))}}}}e.logger.debug(`Processed AI examples from ${o}`)}catch{}return n!=null||a!==i?await zGc({absolutePathToOpenAPI:t,absolutePathToOpenAPIOverrides:r,parsed:a}):a}var J3t=class{absoluteFilePath;constructor(t){this.absoluteFilePath=t}async loadDocuments({context:t,specs:r}){let i=[];for(let n of r)try{let a=(await(0,vmh.readFile)(n.absoluteFilepath)).toString(),o=S_(this.absoluteFilePath,n.source.file);n.source.relativePathToDependency!=null&&(o=It(n.source.relativePathToDependency,o));let c=n.source.type==="protobuf"?k8.protobuf({file:o}):k8.openapi({file:o});if(a.includes("openapi")||a.includes("swagger"))try{let d=await zxa({absolutePathToOpenAPI:n.absoluteFilepath,context:t,absolutePathToOpenAPIOverrides:n.absoluteFilepathToOverrides});if(c6c(d)){i.push({type:"openapi",value:d,source:c,namespace:n.namespace,settings:lEe({options:n.settings})});continue}else if(W7a(d)){(!d.schemes||d.schemes.length===0)&&(d.schemes=["https"]);let s=await qxa(d);i.push({type:"openapi",value:s,source:c,namespace:n.namespace,settings:lEe({options:n.settings})});continue}}catch(d){t.logger.debug(`Failed to parse OpenAPI document at ${n.absoluteFilepath}: ${d}. Skipping...`);continue}if(a.includes("asyncapi"))try{let d=await TGc({context:t,absoluteFilePath:n.absoluteFilepath,absoluteFilePathToOverrides:n.absoluteFilepathToOverrides});i.push({type:"asyncapi",value:d,source:c,namespace:n.namespace,settings:lEe({options:n.settings})});continue}catch(d){t.logger.error(`Failed to parse AsyncAPI document at ${n.absoluteFilepath}: ${d}. Skipping...`);continue}if(a.includes("openrpc"))try{let d=await TGc({context:t,absoluteFilePath:n.absoluteFilepath,absoluteFilePathToOverrides:n.absoluteFilepathToOverrides});i.push({type:"asyncapi",value:d,source:c,namespace:n.namespace,settings:lEe({options:n.settings})});continue}catch(d){t.logger.error(`Failed to parse OpenRPC document at ${n.absoluteFilepath}: ${d}. Skipping...`);continue}t.logger.warn(`${n.absoluteFilepath} is not a valid OpenAPI, AsyncAPI, or OpenRPC file. Skipping...`)}catch(a){t.logger.error(`Failed to read or process file ${n.absoluteFilepath}: ${a}. Skipping...`);continue}return i}};var KrB=zt.object({type:zt.string(),channelId:zt.string().optional(),messageId:zt.string(),value:zt.any()}),JrB=zt.object({summary:zt.string().optional(),description:zt.string().optional(),"query-parameters":zt.record(zt.string()).optional(),headers:zt.record(zt.string()).optional(),messages:zt.array(KrB)}),gmh=zt.array(JrB);var qbu=class extends el{channel;baseDir;key="x-fern-examples";constructor({breadcrumbs:t,channel:r,context:i,baseDir:n}){super({breadcrumbs:t??[],context:i}),this.channel=r,this.baseDir=n}convert(){let t=this.getExtensionValue(this.channel);if(t==null)return;let r=gmh.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-examples extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data.map(i=>({summary:i.summary,description:i.description,queryParameters:i["query-parameters"],headers:i.headers,messages:i.messages.map(n=>({type:n.type,channelId:n.channelId,messageId:n.messageId,value:n.value}))}))}};var Loa=class extends Ta{channel;channelPath;inlinedTypes={};websocketGroup;constructor({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a}){super({context:t,breadcrumbs:r}),this.websocketGroup=i,this.channel=n,this.channelPath=a}convertExamples({fullPath:t,baseUrl:r,asyncApiVersion:i}){let a=new qbu({context:this.context,breadcrumbs:this.breadcrumbs,channel:this.channel,baseDir:this.context.documentBaseDir}).convert();return a==null?{}:Object.fromEntries(a.map((o,c)=>[c.toString(),{channel:{method:"GET",path:t},baseUrl:t,environment:r,auth:void 0,pathParameters:{},queryParameters:o.queryParameters,headers:o.headers,messages:o.messages.map(d=>({type:i==="v2"?d.type:d.messageId,body:d.value}))}]))}transformToValidPath(t){return t.startsWith("/")?t:"/"+t}};var VJi=class extends bA.AbstractConverters.AbstractParameterConverter{parameterNamePrefix;constructor({context:t,breadcrumbs:r,parameter:i,parameterNamePrefix:n}){super({context:t,breadcrumbs:r,parameter:i}),this.parameterNamePrefix=n}convert(){let t,r={},n=new aR.FernOptionalExtension({breadcrumbs:this.breadcrumbs,parameter:this.parameter,context:this.context}).convert()??this.parameter.required===!1,a=this.parameter.schema??{...this.parameter,type:"string",enum:this.parameter.enum,default:this.parameter.default,example:this.parameter.example??this.parameter.name,examples:Object.values(this.parameter.examples??{}),deprecated:this.parameter.deprecated,required:void 0},c=new bA.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaIdOverride:this.parameterNamePrefix?`${this.parameterNamePrefix}_${this.parameter.name}`:this.parameter.name,schemaOrReference:a,wrapAsOptional:n}).convert();return c!=null&&(t=c.type,r=c.inlinedTypes??{}),this.convertToOutput({schema:a,typeReference:t,inlinedTypes:r})}};var Tbu=class extends el{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 Voa=class extends el{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 Rbu=class extends Loa{inlinedTypes={};constructor({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a}){super({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a})}convert(){let t=[],r=[],i=[],a=new Voa({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert()??this.websocketGroup?.join(".");this.channel.parameters&&this.convertPathParameters({context:this.context,pathParameters:t}),this.channel.bindings?.ws!=null&&(this.convertHeaders({context:this.context,headers:i}),this.convertBindingQueryParameters({context:this.context,queryParameters:r}));let o;this.channel.subscribe!=null&&(o=this.convertMessage({context:this.context,operation:this.channel.subscribe,origin:"server"}));let c;this.channel.publish!=null&&(c=this.convertMessage({context:this.context,operation:this.channel.publish,origin:"client"}));let d=[];o!=null&&d.push(o),c!=null&&d.push(c);let u=new Tbu({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert(),f=this.transformToValidPath(u??this.channelPath),p=this.channel.servers?.[0]??Object.keys(this.context.spec.servers??{})[0],_=iM(f),h=Xo(this.channelPath),y=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[];return{channel:{name:this.context.casingsGenerator.generateName(h),displayName:a,baseUrl:p,path:_,auth:!1,headers:i,queryParameters:r,pathParameters:t,messages:d,availability:this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({fullPath:f,baseUrl:p,asyncApiVersion:"v2"})}},audiences:y,inlinedTypes:this.inlinedTypes}}convertMessage({context:t,operation:r,origin:i}){let n,a=i==="server"?"subscribe":"publish",o=[...this.breadcrumbs,a],c=t.resolveMaybeReference({schemaOrReference:r.message,breadcrumbs:o});c!=null&&(r.message=c);let d=oln(Xo(`${this.channelPath}_${a}`)).replace(/ /g,"");if("oneOf"in r.message){let u=new bA.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:o,schemaOrReference:r.message,schemaIdOverride:d}).convert();u!=null&&u.schema!=null&&(n=u.schema,this.inlinedTypes={...this.inlinedTypes,...u.inlinedTypes})}else if(t.isMessageWithPayload(r.message)){let s=t.resolveMaybeReference({schemaOrReference:r.message.payload,breadcrumbs:o});if(s!=null){let f=new bA.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:o,schemaOrReference:s,schemaIdOverride:d}).convert();f!=null&&f.schema!=null&&(n=f.schema,this.inlinedTypes={...this.inlinedTypes,...f.inlinedTypes})}}if(n!=null){let s=n,u=ri.named({fernFilepath:t.createFernFilepath(),name:s.typeDeclaration.name.name,typeId:s.typeDeclaration.name.typeId,displayName:void 0,default:void 0,inline:!1}),f=N4.reference({bodyType:u,docs:r.description}),p=i==="server"?"subscribe":"publish";return{type:p,displayName:p,origin:i,body:f,availability:t.getAvailability({node:r,breadcrumbs:this.breadcrumbs}),docs:r.description,methodName:void 0}}}convertPathParameters({context:t,pathParameters:r}){for(let[i,n]of Object.entries(this.channel.parameters??{})){let a=t.resolveMaybeReference({schemaOrReference:n,breadcrumbs:this.breadcrumbs});if(a==null)continue;let c=new VJi({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...a,name:i,in:"path",description:a.description,required:a.required??!0}}).convert();c!=null&&(this.inlinedTypes={...this.inlinedTypes,...c.inlinedTypes},c.type==="path"&&r.push(c.parameter))}}convertHeaders({context:t,headers:r}){if(this.channel.bindings?.ws?.headers!=null){let i=this.channel.bindings.ws.headers.required??[];for(let[n,a]of Object.entries(this.channel.bindings.ws.headers.properties??{})){let o=t.resolveMaybeReference({schemaOrReference:a,breadcrumbs:[...this.breadcrumbs,n]});if(o==null)continue;let d=new VJi({context:this.context,breadcrumbs:[...this.breadcrumbs,n],parameter:{name:n,in:"header",required:i.includes(n),schema:o,description:"description"in o?o.description:void 0}}).convert();d!=null&&d.type==="header"&&(this.inlinedTypes={...this.inlinedTypes,...d.inlinedTypes},r.push(d.parameter))}}}convertBindingQueryParameters({context:t,queryParameters:r}){if(this.channel.bindings?.ws?.query!=null){let i=this.channel.bindings.ws.query.required??[];for(let[n,a]of Object.entries(this.channel.bindings.ws.query.properties??{})){let o=t.resolveMaybeReference({schemaOrReference:a,breadcrumbs:[...this.breadcrumbs,n]});if(o==null)continue;let d=new VJi({context:this.context,breadcrumbs:[...this.breadcrumbs,n],parameter:{name:n,in:"query",required:i.includes(n),schema:o,description:"description"in o?o.description:void 0,deprecated:o.deprecated??!1}}).convert();d!=null&&d.type==="query"&&(this.inlinedTypes={...this.inlinedTypes,...d.inlinedTypes},r.push(d.parameter))}}}};var Woa=class extends Ta{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:tM.singleBaseUrl({environments:t})}}constructServerUrl(t,r){return r.includes("://")?r:`${t}://${r}`}};var zbu=class extends Woa{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 NGc="$message.",Omh="#/channels/",Amh="#/servers/",Nbu=class extends Loa{operations;inlinedTypes={};constructor({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a,operations:o}){super({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a}),this.operations=o}convert(){let t=[],r=[],i=[],a=new Voa({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert()??this.websocketGroup?.join(".")??this.channelPath;this.channel.parameters&&this.convertChannelParameters({pathParameters:t,queryParameters:r,headers:i,channelPath:this.channelPath});let o=Object.entries(this.operations).reduce((p,[_,h])=>{try{this.getChannelPathFromOperation(h)===this.channelPath&&(p[_]=h)}catch{}return p},{}),c=[];for(let[p,_]of Object.entries(o))for(let h of _.messages){let y=this.context.convertReferenceToTypeReference({reference:h});if(y.ok){let b=N4.reference({bodyType:y.reference,docs:_.description});c.push({type:p,displayName:p,origin:_.action==="send"?"client":"server",body:b,availability:this.context.getAvailability({node:_,breadcrumbs:this.breadcrumbs}),docs:_.description,methodName:void 0})}}let d=this.resolveChannelServersFromReference(this.channel.servers??[])??Object.keys(this.context.spec.servers??{})[0],s=this.transformToValidPath(this.channel.address??this.channelPath),u=iM(s),f=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[];return{channel:{name:this.context.casingsGenerator.generateName(a),displayName:a,baseUrl:d,path:u,auth:!1,headers:i,queryParameters:r,pathParameters:t,messages:c,availability:this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({fullPath:s,baseUrl:d,asyncApiVersion:"v3"})}},audiences:f,inlinedTypes:this.inlinedTypes}}convertChannelParameters({pathParameters:t,queryParameters:r,headers:i,channelPath:n}){for(let a of Object.values(this.channel.parameters??{})){let o=this.context.resolveMaybeReference({schemaOrReference:a,breadcrumbs:[...this.breadcrumbs,"parameters"]});if(o==null)continue;let c=this.convertChannelParameterLocation(o.location);if(c==null)continue;let{type:d,parameterKey:s}=c,f=new VJi({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...o,name:s,in:d},parameterNamePrefix:this.channelPath}).convert();if(f!=null)switch(this.inlinedTypes={...this.inlinedTypes,...f.inlinedTypes},f.type){case"path":t.push(f.parameter);break;case"query":r.push(f.parameter);break;case"header":i.push(f.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(NGc)){this.context.errorCollector.collect({message:`Invalid location format: ${t}; expected ${NGc} prefix`,path:this.breadcrumbs});return}let n=r.substring(NGc.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(Amh)){this.context.errorCollector.collect({message:`Failed to resolve server name from server ref ${r.$ref}`,path:this.breadcrumbs});return}let i=r.$ref.substring(Amh.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(Omh))throw new Error(`Failed to resolve channel path from operation ${t.channel.$ref}`);return t.channel.$ref.substring(Omh.length)}};var Fbu=class extends Woa{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 Nxa=class extends O3t{constructor({context:t,breadcrumbs:r,audiences:i}){super({context:t,breadcrumbs:r,audiences:i})}async convert(){return this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.context.spec=await this.resolveAllExternalRefs({spec:this.context.spec}),this.isAsyncAPIV3(this.context)?this.convertChannelMessages():this.convertComponentMessages(),this.convertSchemas(),this.convertServers(),this.convertChannels(),this.finalizeIr()}isAsyncAPIV3(t){return parseFloat(t.spec.asyncapi)>=3}convertChannelMessages(){let t=this.context.spec;for(let[r,i]of Object.entries(t.channels??{}))for(let[n,a]of Object.entries(i.messages??{})){if(!this.context.isMessageWithPayload(a)&&!this.context.isReferenceObject(a))continue;let o=["channels",r,"messages",n],c=this.context.resolveMaybeReference({schemaOrReference:a,breadcrumbs:o});if(!this.context.isMessageWithPayload(c))continue;let d=this.context.resolveMaybeReference({schemaOrReference:c.payload,breadcrumbs:o});if(d==null)continue;let s=`${r}_${n}`;this.convertSchema({id:s,breadcrumbs:o,schema:d})}}convertComponentMessages(){for(let[t,r]of Object.entries(this.context.spec.components?.messages??{})){if(r.payload==null)continue;let i=["components","messages",t],n=this.context.resolveMaybeReference({schemaOrReference:r.payload,breadcrumbs:i});n!=null&&this.convertSchema({id:t,breadcrumbs:i,schema:n})}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{}))this.convertSchema({id:t,breadcrumbs:["components","schemas",t],schema:r})}convertSchema({id:t,breadcrumbs:r,schema:i}){let a=new bA.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:r,schema:i}).convert();a!=null&&this.addSchemaOutputToIr(t,a)}convertServers(){let t;if(this.isAsyncAPIV3(this.context)){let r=this.context.spec.servers;t=new Fbu({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}else{let r=this.context.spec.servers;t=new zbu({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}this.addEnvironmentsToIr({environmentConfig:t})}convertChannels(){for(let[t,r]of Object.entries(this.context.spec.channels??{})){let n=new aR.SdkGroupNameExtension({breadcrumbs:["channels",t],operation:r,context:this.context}).convert()?.groups,a;if(this.isAsyncAPIV3(this.context)){let c=this.context.spec.operations??{};a=new Nbu({context:this.context,breadcrumbs:["channels",t],websocketGroup:n,channel:r,channelPath:t,operations:c}).convert()}else a=new Rbu({context:this.context,breadcrumbs:["channels",t],websocketGroup:n,channel:r,channelPath:t}).convert();a!=null&&(this.addWebsocketChannelToIr({websocketChannel:a.channel,channelPath:t,audiences:a.audiences,websocketGroup:n}),this.addTypesToIr(a.inlinedTypes))}}};var Fxa=class extends VI{isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}isMessageWithPayload(t){return t!=null&&typeof t=="object"&&"payload"in t}getTypeIdFromMessageReference(t){let r=t.$ref.match(/\/messages\/(.+)$/);if(!(!r||!r[1]))return r[1]}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n}){let a,o=t.$ref.match(/^.*\/schemas\/(.+)$/),c=t.$ref.match(/^.*\/channels\/([^/]+)\/messages\/(.+)$/),d=t.$ref.match(/^.*\/messages\/(.+)$/);if(o&&o[1])return a=o[1],this.convertSchemaReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a});if(c&&c[2]){let s=c[1],u=c[2];return a=`${s}_${u}`,this.convertV3MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a})}else return d&&d[1]?(a=d[1],this.convertV2MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a})):{ok:!1}}convertSchemaReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a}){let o=this.resolveReference({reference:t,breadcrumbs:r});if(!o.resolved)return{ok:!1};let c;return n==="reference_identifier"?c=i??o.value.title:(n==="discriminator_key"||n==="schema_identifier")&&(c=o.value.title??i),{ok:!0,reference:ri.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(a),typeId:a,displayName:c,default:void 0,inline:!1})}}convertV3MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a}){let o=this.resolveReference({reference:t,breadcrumbs:r});if(!o.resolved)return{ok:!1};let c;return n==="reference_identifier"?c=i??o.value.name:(n==="discriminator_key"||n==="schema_identifier")&&(c=o.value.name??i),{ok:!0,reference:ri.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(a),typeId:a,displayName:c,default:void 0,inline:!1})}}convertV2MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a}){let o=this.resolveReference({reference:t,breadcrumbs:r});if(!o.resolved)return{ok:!1};let c;return n==="reference_identifier"?c=i??o.value.messageId??o.value.name:(n==="discriminator_key"||n==="schema_identifier")&&(c=o.value.messageId??o.value.name??i),{ok:!0,reference:ri.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(a),typeId:a,displayName:c,default:void 0,inline:!1})}}};var Mmh=ce(Qbu(),1);var Ubu=class extends el{document;key="x-fern-base-path";constructor({breadcrumbs:t,document:r,context:i}){super({breadcrumbs:t,context:i}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(typeof t!="string"){this.context.errorCollector.collect({message:"Received unexpected non-string value for x-fern-base-path",path:this.breadcrumbs});return}return t}}};var Lbu=class extends el{document;key="x-fern-global-headers";constructor({breadcrumbs:t,document:r,context:i}){super({breadcrumbs:t,context:i}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(!Array.isArray(t)){this.context.errorCollector.collect({message:"Received unexpected non-array value for x-fern-global-headers",path:this.breadcrumbs});return}return t}}};function mmh({globalHeaders:e,context:t}){return e.map(r=>({name:t.casingsGenerator.generateNameAndWireValue({name:r.name??"",wireValue:r.header}),valueType:r.optional?Ta.OPTIONAL_STRING:Ta.STRING,env:r.env,v2Examples:r.optional?void 0:XrB({header:r,context:t}),availability:void 0,docs:void 0}))}function XrB({header:e,context:t}){let r=new J8({breadcrumbs:[],context:t,schema:{type:"string"},example:e.header}),{validExample:i}=r.convert();return{userSpecifiedExamples:{},autogeneratedExamples:{globalHeaderExample:i}}}var Vbu=class extends bA.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r,parameter:i})}convert(){let t,r={};if(this.parameter.schema!=null){let i=this.context.convertBreadcrumbsToName([...this.breadcrumbs,this.parameter.name]),a=new bA.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,this.parameter.name,"schema"],schemaOrReference:this.parameter.schema,wrapAsOptional:this.parameter.required==null||!this.parameter.required,schemaIdOverride:i}).convert();a!=null&&(t=a.type,r=a.inlinedTypes??{})}return this.convertToOutput({schema:this.parameter.schema??{type:"string"},typeReference:t,inlinedTypes:r})}};var Wbu=class extends bA.AbstractConverters.AbstractMediaTypeObjectConverter{contentType;mediaType;description;required;schemaId;streamingExtension;queryParameters;constructor({context:t,breadcrumbs:r,contentType:i,mediaType:n,description:a,required:o,group:c,method:d,streamingExtension:s,queryParameters:u}){super({context:t,breadcrumbs:r,group:c,method:d}),this.contentType=i,this.mediaType=n,this.description=a,this.required=o,this.schemaId=[...this.group,this.method,"Request"].join("_"),this.streamingExtension=s,this.queryParameters=u??[]}convert(){return this.streamingExtension?.type=="streamCondition"?this.convertStreamConditionRequestBody():this.convertNonStreamConditionRequestBody()}convertStreamConditionRequestBody(){if(this.isOrderedJsonOrFormContentType())return this.handleStreamConditionJsonOrFormContent({contentType:this.contentType})}convertNonStreamConditionRequestBody(){if(this.isOrderedJsonOrFormContentType())return this.handleJsonOrFormContent({contentType:this.contentType});if(zO.parse(this.contentType)?.isMultipart())return this.handleMultipartContent({contentType:this.contentType});if(this.isBinaryContentType())return this.handleBinaryContent({contentType:this.contentType})}isOrderedJsonOrFormContentType(){let t=zO.parse(this.contentType);return t?t.isJSON()||t.isURLEncoded()||t.isPlainText()||t.isCSV()||t.isHTML()||t.isXML()||t.isDNS()||t.isApplicationText():!1}isBinaryContentType(){let t=zO.parse(this.contentType);return t?t.isBinary():!1}handleJsonOrFormContent({contentType:t}){let r=this.mediaType;if(r==null)return;let i=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,contentType:t});if(i==null)return;let n=i.schema?.typeDeclaration.shape;return n?.type==="object"?this.hasBodyQueryParameterOverlap(n.properties)?{requestBody:yA.reference({contentType:t,docs:this.description,requestBodyType:i.type,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:i.inlinedTypes??{}}:{requestBody:yA.inlinedRequestBody({contentType:t,docs:this.description,name:this.context.casingsGenerator.generateName(this.schemaId),extendedProperties:n.extendedProperties,extends:n.extends,properties:n.properties,extraProperties:n.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:i.inlinedTypes})}:{requestBody:yA.reference({contentType:t,docs:this.description,requestBodyType:i.type,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:i.inlinedTypes??{}}}handleMultipartContent({contentType:t}){let r=this.mediaType;if(r==null||r.schema==null)return;let i=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,resolveSchema:!0,contentType:t});if(i==null)return;let n=i.schema?.typeDeclaration.shape;if(n?.type==="object")return{requestBody:yA.fileUpload({contentType:t,docs:this.description,name:this.context.casingsGenerator.generateName(this.schemaId),properties:n.properties.map(a=>{let o=r.encoding?.[a.name.wireValue];return this.convertRequestBodyProperty({property:a,contentType:t,encoding:o})}),v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:i.inlinedTypes}),examples:i.examples}}handleBinaryContent({contentType:t}){let r=this.mediaType;if(r==null)return;let i=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,contentType:t});return{requestBody:yA.bytes({contentType:t,isOptional:this.required===!1,docs:this.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:i?.inlinedTypes??{}}}convertRequestBodyProperty({property:t,contentType:r,encoding:i}){let{isFile:n,isOptional:a,isArray:o}=this.recursivelyCheckTypeReferenceIsFile({typeReference:t.valueType});return n?o?kq.file(m$.fileArray({key:t.name,isOptional:a,contentType:r,docs:t.docs})):kq.file(m$.file({key:t.name,isOptional:a,contentType:r,docs:t.docs})):kq.bodyProperty({...t,contentType:i?.contentType??r,style:krB({encoding:i}),name:t.name})}handleStreamConditionJsonOrFormContent({contentType:t}){if(this.streamingExtension?.type!=="streamCondition")return;let r=this.mediaType;if(r==null||r.schema==null)return;let i=this.context.resolveMaybeReference({schemaOrReference:r.schema,breadcrumbs:[...this.breadcrumbs,"content",t,"schema"]});if(i==null)return;let n=i.properties?.[this.streamingExtension.streamConditionProperty];if(n==null||this.context.isReferenceObject(n))return;let a=this.buildStreamConditionInlinedRequestBody({streamConditionProperty:n,resolvedMediaTypeSchema:i,isStreaming:!0,contentType:t,mediaTypeObject:r}),o=this.buildStreamConditionInlinedRequestBody({streamConditionProperty:n,resolvedMediaTypeSchema:i,isStreaming:!1,contentType:t,mediaTypeObject:r});if(!(a==null||o==null))return{requestBody:o.requestBody,streamRequestBody:a.requestBody,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:{...a.inlinedTypes,...o.inlinedTypes}})}}buildStreamConditionInlinedRequestBody({streamConditionProperty:t,resolvedMediaTypeSchema:r,isStreaming:i,contentType:n,mediaTypeObject:a}){if(this.streamingExtension==null||this.streamingExtension.type!=="streamCondition")return;let o={...r,properties:{...r.properties,[this.streamingExtension.streamConditionProperty]:{type:"boolean",const:i,...t}},required:[...r.required??[],this.streamingExtension.streamConditionProperty]},c={...a,schema:o},d=this.parseMediaTypeObject({mediaTypeObject:c,schemaId:this.schemaId,contentType:n});if(d==null)return;let s=d.schema?.typeDeclaration.shape;if(s?.type==="object")return{requestBody:yA.inlinedRequestBody({contentType:n,docs:void 0,name:this.context.casingsGenerator.generateName(i?`${this.schemaId}_streaming`:this.schemaId),extendedProperties:s.extendedProperties,extends:s.extends,properties:s.properties,extraProperties:s.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:c,exampleGenerationStrategy:"request"})}),inlinedTypes:d.inlinedTypes}}recursivelyCheckTypeReferenceIsFile({typeReference:t,isOptional:r,isArray:i}){return this.context.isList(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.list,isOptional:r,isArray:!0}):this.context.isOptional(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.optional,isOptional:!0,isArray:i}):this.context.isNullable(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.nullable,isOptional:r,isArray:i}):{isFile:this.context.isFile(t),isOptional:r??!1,isArray:i??!1}}hasBodyQueryParameterOverlap(t){if(this.queryParameters.length===0)return!1;let r=new Set(this.queryParameters.map(i=>i.name.wireValue.toLowerCase()));return t.some(i=>r.has(i.name.wireValue.toLowerCase()))}},ZrB={"application/json":"json"};function krB({encoding:e}){if(e){if(e.explode)return"exploded";if(e.style==="form")return"form";if(e.contentType)return ZrB[e.contentType]}}var eiB=/{([^}]+)}/g,tiB=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]),Goa=class extends Ta{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 N0.Get;case"post":return N0.Post;case"put":return N0.Put;case"delete":return N0.Delete;case"patch":return N0.Patch;case"head":return N0.Head;default:return}}convertParameters({breadcrumbs:t}){let r=[],i=[],n=[];if(!this.operation.parameters)return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:i,headers:n};for(let a of this.operation.parameters){let o=this.context.resolveMaybeReference({schemaOrReference:a,breadcrumbs:t});if(o==null)continue;let d=new Vbu({context:this.context,breadcrumbs:t,parameter:o}).convert();if(d!=null)switch(this.inlinedTypes={...this.inlinedTypes,...d.inlinedTypes},d.type){case"path":r.push(d.parameter);break;case"query":i.push(d.parameter);break;case"header":{let s=d.parameter.name.name.originalName,u=d.parameter.name.wireValue,f=!1,p=this.context.authOverrides?.["auth-schemes"];if(p!=null){for(let h of Object.values(p))if(aiB(h)&&h.header.toLowerCase()===u.toLowerCase()){f=!0;break}}let _=this.context.globalHeaderNames;if(_!=null){for(let h of _)if(h.toLowerCase()===u.toLowerCase()){f=!0;break}}!tiB.has(s.toLowerCase())&&!f&&n.push(d.parameter);break}}}return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:i,headers:n}}checkMissingPathParameters(t){let i=[...this.path.matchAll(eiB)].map(n=>n[1]).filter(n=>!t.some(a=>a.name.originalName===n));for(let n of i){if(n==null)continue;let a=`${n}_example`;t.push({name:this.context.casingsGenerator.generateName(n),valueType:Ta.STRING,docs:void 0,location:"ENDPOINT",variable:void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{[a]:this.generateStringParameterExample({example:n})}},explode:void 0})}}convertRequestBody({breadcrumbs:t,group:r,method:i,streamingExtension:n,queryParameters:a}){if(this.operation.requestBody==null)return;let o=this.context.resolveMaybeReference({schemaOrReference:this.operation.requestBody,breadcrumbs:t});if(o==null)return null;let c=[];for(let[d,s]of Object.entries(o.content)){let f=new Wbu({context:this.context,breadcrumbs:t,contentType:d,mediaType:s,description:o.description,required:o.required,group:r??[],method:i,streamingExtension:n,queryParameters:a}).convert();f!=null&&(this.inlinedTypes={...this.inlinedTypes,...f.inlinedTypes},c.push({requestBody:f.requestBody,streamRequestBody:f.streamRequestBody,examples:f.examples}))}return c}computeGroupNameAndLocationFromExtensions(){let r=new aR.SdkMethodNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.methodName,n=new aR.SdkGroupNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.groups??[];if(r!=null)return{group:n,method:r}}evaluateMethodNameFromOperation(){let t=this.operation.operationId;return t??(this.operation.summary!=null?Xo(this.operation.summary):Xo(`${this.method}_${this.path.split("/").join("_")}`))}computeGroupNameFromTagAndOperationId(){let t=this.operation.tags?.[0],r=this.evaluateMethodNameFromOperation();if(t==null)return{method:r};let i=Pmh(t),n=Pmh(r);return ST(i,n)?{method:t}:this.computeGroupAndMethodFromTokens({tag:t,tagTokens:i,methodName:r,methodNameTokens:n})}computeGroupAndMethodFromTokens({tag:t,tagTokens:r,methodName:i,methodNameTokens:n}){if(r.some((c,d)=>c!==n[d]))return{group:[t],method:i};let o=n.slice(r.length);return{group:[t],method:Xo(o.join("_"))}}generateStringParameterExample({example:t}){let r=new bA.ExampleConverter({breadcrumbs:this.breadcrumbs,context:this.context,schema:{type:"string"},example:t}),{validExample:i}=r.convert();return i}};function Pmh(e){let t=riB(e)?iiB(e):niB(e);return t=t.map(r=>r.toLowerCase()),t=lje(t),t}function riB(e){return/^[a-z]+(?:[A-Z][a-z]+)*$/.test(e)}function iiB(e){return e.split(/(?=[A-Z])/)}function niB(e){return e.split(/[^a-zA-Z0-9]+/)}function aiB(e){return e?.header!=null}var Hoa=class extends Goa{constructor({context:t,breadcrumbs:r,operation:i,method:n,path:a}){super({context:t,breadcrumbs:r,operation:i,method:n,path:a})}convert(){if(this.operation.requestBody==null){this.context.errorCollector.collect({message:"Skipping webhook because no request body present",path:this.breadcrumbs});return}let t=this.convertHttpMethod();if(t==null)return;if(t!=="POST"&&t!=="GET"){this.context.errorCollector.collect({message:"Skipping webhook because non-POST or GET method",path:this.breadcrumbs});return}let{group:r,method:i}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),n=[...this.breadcrumbs,"Payload"],{headers:a,queryParameters:o}=this.convertParameters({breadcrumbs:n}),c=this.convertRequestBody({breadcrumbs:n,group:r,method:i,streamingExtension:void 0,queryParameters:o});if(c==null)return;let d=c[0]?.requestBody;if(d==null)return;let s;if(d.type==="inlinedRequestBody")s=z4.inlinedPayload({name:d.name,extends:d.extends,properties:d.properties});else if(d.type==="reference")s=z4.reference({payloadType:d.requestBodyType,docs:d.docs});else return;let u=this.convertWebhookResponses();return{audiences:this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],group:r,webhook:{id:`${r?.join(".")??""}.${i}`,name:this.context.casingsGenerator.generateName(i),displayName:this.operation.summary,method:t,headers:a,payload:s,responses:u.length>0?u:void 0,examples:[],availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),docs:this.operation.description,v2Examples:{autogeneratedExamples:this.getWebhookV2ExamplesFromRequestBodyV2Examples(d.v2Examples?.autogeneratedExamples??{}),userSpecifiedExamples:this.getWebhookV2ExamplesFromRequestBodyV2Examples(d.v2Examples?.userSpecifiedExamples??{})}},inlinedTypes:this.inlinedTypes}}convertWebhookResponses(){let t=[];if(this.operation.responses==null)return t;for(let[r,i]of Object.entries(this.operation.responses)){let n=/^\d[Xx]{2}$/.test(r),a;if(n)a=parseInt(r.charAt(0))*100;else if(a=parseInt(r),isNaN(a))continue;let c=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:[...this.breadcrumbs,"responses",r]})?.description;t.push({statusCode:a,isWildcardStatusCode:n?!0:void 0,body:void 0,docs:c})}return t}getWebhookV2ExamplesFromRequestBodyV2Examples(t){return Object.fromEntries(Object.entries(t).map(([r,i])=>[r,{name:r,payload:i}]))}};var UGc=ce(Qbu(),1);var jmh=["get","post","put","delete","patch","head"];var Gbu=class extends el{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 oiB=zt.object({cursor:zt.string(),next_cursor:zt.string(),results:zt.string()}),uiB=zt.object({offset:zt.string(),results:zt.string(),step:zt.string().optional(),"has-next-page":zt.string().optional()}),FGc=zt.union([zt.boolean(),oiB,uiB]);var QGc="$request.",Hbu="$response.",xbu=class extends el{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=FGc.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=FGc.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:VI.maybeTrimPrefix(r.cursor,QGc),nextCursor:VI.maybeTrimPrefix(r.next_cursor,Hbu),results:VI.maybeTrimPrefix(r.results,Hbu)};let i=t;return{type:"offset",offset:VI.maybeTrimPrefix(i.offset,QGc),results:VI.maybeTrimPrefix(i.results,Hbu),step:i.step!=null?VI.maybeTrimPrefix(i.step,QGc):void 0,hasNextPage:i["has-next-page"]!=null?VI.maybeTrimPrefix(i["has-next-page"],Hbu):void 0}}};var siB="$request.",ciB=zt.object({"stream-condition":zt.string().optional(),format:zt.enum(["sse","json"]).optional(),"stream-description":zt.string().optional(),"response-stream":zt.any(),response:zt.any()}),liB=zt.union([zt.boolean(),ciB]),Kbu=class extends el{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=liB.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-streaming extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean")return r.data?{type:"stream",format:"json"}:void 0;if(r.data["stream-condition"]==null&&r.data.format!=null)return{type:"stream",format:r.data.format};if(r.data["stream-condition"]==null){this.context.errorCollector.collect({message:"Missing stream-condition property without specified format.",path:this.breadcrumbs});return}return{type:"streamCondition",format:r.data.format??"json",streamDescription:r.data["stream-description"],streamConditionProperty:VI.maybeTrimPrefix(r.data["stream-condition"],siB),responseStream:r.data["response-stream"],response:r.data.response}}};var Jbu=class extends el{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 Ybu=require("fs"),wmh=require("path");function fiB(e){return ll(e)&&typeof e.$ref=="string"}function diB(e,t){if(e!=null){if(typeof e=="string")return e;if(fiB(e)){let r=(0,wmh.resolve)(t??process.cwd(),e.$ref);if((0,Ybu.existsSync)(r))try{return(0,Ybu.readFileSync)(r,"utf-8")}catch{return}}}}var $bu=class extends el{operation;baseDir;key="x-codeSamples";constructor({context:t,breadcrumbs:r,operation:i,baseDir:n}){super({breadcrumbs:r,context:t}),this.operation=i,this.baseDir=n}convert(){let t=ll(this.operation)?this.operation:{},r=t["x-codeSamples"],i=t["x-code-samples"],n=Array.isArray(r)?r:[],a=Array.isArray(i)?i:[],o=[...n,...a];if(o.length===0)return;let c=[];for(let d of o){if(!ll(d))continue;let s=d,u=s.lang,f=s.label,p=s.source;if(typeof u!="string")continue;let _=diB(p,this.baseDir);_!=null&&c.push({name:typeof f=="string"?f:u,language:u,code:_,install:void 0,docs:void 0})}if(c.length!==0)return[{"code-samples":c}]}};var Zbu=require("fs"),Emh=require("path");function piB(e){return ll(e)&&typeof e.$ref=="string"}function _iB(e,t){if(e!=null){if(typeof e=="string")return e;if(piB(e)){let r=(0,Emh.resolve)(t??process.cwd(),e.$ref);if((0,Zbu.existsSync)(r))try{return(0,Zbu.readFileSync)(r,"utf-8")}catch{return}}}}function hiB(e,t){if(!Array.isArray(e))return[];let r=[];for(let i of e){if(!ll(i))continue;let a=_iB(i.code,t);a!=null&&r.push({...i,code:a})}return r}var Xbu=class extends el{operation;baseDir;key="x-fern-examples";constructor({context:t,breadcrumbs:r,operation:i,baseDir:n}){super({breadcrumbs:r,context:t}),this.operation=i,this.baseDir=n}convert(){let t=this.getExtensionValue(this.operation);return t==null?void 0:(Array.isArray(t)?t:[]).map(a=>{if(!ll(a))return a;let c=a["code-samples"];if(c!=null){let d=hiB(c,this.baseDir);return{...a,"code-samples":d}}return a}).filter(a=>{let o=TB.serialization.ExampleEndpointCallSchema.parse(a);return o.ok||this.context.errorCollector.collect({message:`Failed to parse x-fern-example in ${this.breadcrumbs.join(".")}`,path:this.breadcrumbs}),o.ok})}};var Qxa=class extends el{document;key="x-fern-explorer";constructor({breadcrumbs:t,document:r,context:i}){super({breadcrumbs:t,context:i}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-explorer",path:this.breadcrumbs});return}return t}}};var Uxa=class extends bA.AbstractConverters.AbstractMediaTypeObjectConverter{responseBody;statusCode;streamingExtension;constructor({context:t,breadcrumbs:r,responseBody:i,group:n,method:a,statusCode:o,streamingExtension:c}){super({context:t,breadcrumbs:r,group:n,method:a}),this.responseBody=i,this.statusCode=o,this.streamingExtension=c}convert(){return this.shouldConvertAsStreaming()?this.convertStreamingResponseBody():this.convertNonStreamingResponseBody()}convertStreamingResponseBody(){if(this.streamingExtension!=null){if(this.streamingExtension.type=="streamCondition"){let t=this.streamingExtension.responseStream,r=this.streamingExtension.response,i=[...this.group,this.method,"Response",this.statusCode].join("_"),n=`${i}_streaming`,a=this.parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:n}),o=this.parseMediaTypeSchemaOrReference({schemaOrReference:r,schemaId:i});return this.convertStreamConditionResponse({convertedStreamingSchema:a,convertedNonStreamingSchema:o})}if(this.streamingExtension.type==="stream"){let t=[...this.group,this.method,"Response",this.statusCode].join("_"),r=Object.keys(this.responseBody.content??{});for(let i of r){let n=this.responseBody.content?.[i];if(n==null)continue;let a=this.parseMediaTypeObject({mediaTypeObject:n,schemaId:t,contentType:this.streamingExtension.format});if(a!=null)return this.convertStreamingResponse({mediaTypeObject:n,convertedSchema:a})}}}}convertNonStreamingResponseBody(){let t=[...this.group,this.method,"Response",this.statusCode].join("_"),r=Object.keys(this.responseBody.content??{}).filter(a=>a.includes("json"));for(let a of r){let o=this.responseBody.content?.[a];if(o==null)continue;let c=this.parseMediaTypeObject({mediaTypeObject:o,schemaId:t,contentType:a});if(c!=null&&this.shouldReturnJsonResponse(a))return this.returnJsonResponse({mediaTypeObject:o,convertedSchema:c})}let i=Object.keys(this.responseBody.content??{}).filter(a=>!a.includes("json"));for(let a of i){let o=this.responseBody.content?.[a];if(o==null)continue;let c=this.parseMediaTypeObject({mediaTypeObject:o,schemaId:t,contentType:a});if(c!=null){if(this.isBinarySchema(c))return this.shouldReturnBytesResponse()?this.returnBytesResponse({mediaTypeObject:o}):this.returnFileDownloadResponse({mediaTypeObject:o});if(this.shouldReturnTextResponse(a))return this.returnTextResponse({mediaTypeObject:o})}}let n=parseInt(this.statusCode);if(!isNaN(n)&&n>=200&&n<300){let a={schema:{type:"object",description:"Empty response body"}},o=this.parseMediaTypeObject({mediaTypeObject:a,schemaId:t,contentType:"application/json",resolveSchema:!0});if(o!=null)return this.returnJsonResponse({mediaTypeObject:a,convertedSchema:o})}}convertStreamConditionResponse({convertedStreamingSchema:t,convertedNonStreamingSchema:r}){if(t==null||r==null)return;let i=this.responseBody.description;return this.streamingExtension?.type==="streamCondition"&&this.streamingExtension.streamDescription!=null&&(i=this.streamingExtension.streamDescription),{responseBody:dd.json(NI.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:r.schema?.typeDeclaration.v2Examples})),streamResponseBody:dd.streaming(qB.json({docs:i,payload:t.type,terminator:void 0,v2Examples:t.schema?.typeDeclaration.v2Examples})),inlinedTypes:{...t.inlinedTypes,...r.inlinedTypes}}}convertStreamingResponse({mediaTypeObject:t,convertedSchema:r}){if(this.streamingExtension==null)return;switch(this.streamingExtension.format){case"json":return{responseBody:dd.streaming(qB.json({docs:this.responseBody.description,payload:r.type,terminator:void 0,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples};case"sse":return{responseBody:dd.streaming(qB.sse({docs:this.responseBody.description,payload:r.type,terminator:void 0,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples};default:return}}returnJsonResponse({mediaTypeObject:t,convertedSchema:r}){return{responseBody:dd.json(NI.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples}}returnBytesResponse({mediaTypeObject:t}){return{responseBody:dd.bytes({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{}}}returnFileDownloadResponse({mediaTypeObject:t}){return{responseBody:dd.fileDownload({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{}}}returnTextResponse({mediaTypeObject:t}){return{responseBody:dd.text({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{}}}isBinarySchema(t){let r=t.type;switch(r.type){case"container":case"named":case"unknown":return!1;case"primitive":return r.primitive.v2==null?!1:r.primitive.v2.type==="string"&&r.primitive.v2.validation?.format==="binary";default:return!1}}shouldConvertAsStreaming(){return this.streamingExtension!=null}shouldReturnJsonResponse(t){return t.includes("json")}shouldReturnBytesResponse(){return this.context.settings.useBytesForBinaryResponse&&this.streamingExtension==null}shouldReturnTextResponse(t){return zO.parse(t)?.isText()??!1}};var kbu=class extends bA.AbstractConverters.AbstractMediaTypeObjectConverter{responseError;statusCode;methodName;isWildcardStatusCode;constructor({context:t,breadcrumbs:r,responseError:i,group:n,method:a,methodName:o,statusCode:c,isWildcardStatusCode:d}){super({context:t,breadcrumbs:r,group:n,method:a}),this.responseError=i,this.statusCode=c,this.methodName=o,this.isWildcardStatusCode=d}convert(){if(!this.responseError.content){let i=this.getErrorNameForStatusCode(this.statusCode,this.isWildcardStatusCode);if(i==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}let n=this.getErrorIdFromErrorName(i);return{error:{error:{name:this.context.casingsGenerator.generateName(n),fernFilepath:{allParts:[],packagePath:[],file:void 0},errorId:n},docs:this.responseError.description},errorType:ri.unknown(),displayName:i,statusCode:this.statusCode,isWildcardStatusCode:this.isWildcardStatusCode,inlinedTypes:{},examples:{},headers:this.convertResponseHeaders()}}let t=Object.keys(this.responseError.content).filter(i=>i.includes("json")),r=this.getErrorNameForStatusCode(this.statusCode,this.isWildcardStatusCode);if(r==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}for(let i of[...t]){let n=this.responseError.content?.[i];if(n==null)continue;let a=this.parseMediaTypeObject({mediaTypeObject:n,schemaId:Smh(`${this.methodName}Request${r}`),contentType:i});if(a==null)continue;let o=this.getErrorIdFromErrorName(r);if(a.schema!=null)return this.constructErrorConverterOutput({errorName:r,errorId:o,fernFilepath:a.schema.typeDeclaration.name.fernFilepath,convertedSchema:a});if(a.type.type==="named")return this.constructErrorConverterOutput({errorName:r,errorId:o,fernFilepath:a.type.fernFilepath,convertedSchema:a})}}constructErrorConverterOutput({errorName:t,errorId:r,fernFilepath:i,convertedSchema:n}){return{error:{error:{name:this.context.casingsGenerator.generateName(r),fernFilepath:i,errorId:r},docs:this.responseError.description},errorType:n.type,displayName:t,statusCode:this.statusCode,isWildcardStatusCode:this.isWildcardStatusCode,inlinedTypes:n.inlinedTypes,examples:n.examples,headers:this.convertResponseHeaders()}}getErrorNameForStatusCode(t,r){if(r){if(t===400)return"ClientRequestError";if(t===500)return"ServerError"}return Duu[t]}getErrorIdFromErrorName(t){return this.context.enableUniqueErrorsPerEndpoint?Smh(`${this.methodName}Request${t}`):t}convertResponseHeaders(){let t=[],r=this.responseError.headers;if(r==null)return t;for(let[i,n]of Object.entries(r)){let a=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:[...this.breadcrumbs,"headers",i]});if(a==null)continue;let o=a.schema,c=Ta.OPTIONAL_STRING;if(o!=null){let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:[...this.breadcrumbs,"headers",i,"schema"]});s!=null&&(s.type==="number"||s.type==="integer"?c=ri.primitive({v1:s.type==="integer"?"INTEGER":"DOUBLE",v2:s.type==="integer"?gn.integer({default:void 0,validation:void 0}):gn.double({default:void 0,validation:void 0})}):s.type==="boolean"&&(c=ri.primitive({v1:"BOOLEAN",v2:gn.boolean({default:void 0})})))}let d=this.convertHeaderExamples({header:a,headerName:i,schema:o});t.push({name:this.context.casingsGenerator.generateNameAndWireValue({name:i,wireValue:i}),docs:a.description,valueType:c,env:void 0,v2Examples:d,availability:void 0})}return t}convertHeaderExamples({header:t,headerName:r,schema:i}){let n={userSpecifiedExamples:{},autogeneratedExamples:{}},a=t.example,o=t.examples;for(let[c,d]of Object.entries(o??{})){let s=this.context.resolveExampleWithValue(d);s!=null&&(n.userSpecifiedExamples[c]=this.generateHeaderExample({schema:i,example:s}))}if(a!=null){let c=this.context.generateUniqueName({prefix:`${r}_example`,existingNames:Object.keys(n.userSpecifiedExamples)});n.userSpecifiedExamples[c]=this.generateHeaderExample({schema:i,example:a})}if(Object.keys(n.userSpecifiedExamples).length===0&&i!=null){let c=`${r}_example`;n.autogeneratedExamples[c]=this.generateHeaderExample({schema:i,example:void 0,ignoreErrors:!0})}return n}generateHeaderExample({schema:t,example:r,ignoreErrors:i}){if(t==null)return r;let n=new J8({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:r}),{validExample:a,errors:o}=n.convert();return i||o.forEach(c=>{this.context.errorCollector.collect({message:c.message,path:c.path})}),a}};function Smh(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1)}var evu=class e extends Goa{idempotent;idToAuthScheme;topLevelServers;streamingExtension;static AUTHORIZATION_HEADER="Authorization";constructor({context:t,breadcrumbs:r,operation:i,method:n,path:a,idempotent:o,idToAuthScheme:c,topLevelServers:d,streamingExtension:s}){super({context:t,breadcrumbs:r,operation:i,method:n,path:a}),this.idempotent=o,this.idToAuthScheme=c,this.topLevelServers=d,this.streamingExtension=s}convert(){let t=this.convertHttpMethod();if(t==null)return;let{group:r,method:i}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),n=this.getGroupDisplayName(r),{headers:a,pathParameters:o,queryParameters:c}=this.convertParameters({breadcrumbs:[...this.breadcrumbs,"parameters"]}),d=this.convertRequestBody({breadcrumbs:[...this.breadcrumbs,"requestBody"],group:r,method:i,streamingExtension:this.streamingExtension,queryParameters:c}),s=d?.[0]?.requestBody,u=d?.[0]?.streamRequestBody,f={requestBodies:d?.map(ee=>ee.requestBody)},p=this.convertResponseBody({breadcrumbs:[...this.breadcrumbs,"responses"],group:r,method:i,streamingExtension:this.streamingExtension}),_=p?.response,h=p?.streamResponse,y=p!=null?p.errors:[],b={},v=y.map(ee=>ee.error),O=iM(this.path),A=this.getEndpointBaseUrl(),g=this.getEndpointBaseUrls(),m=this.convertExamples({httpPath:O,httpMethod:t,baseUrl:A}),j=new Set(this.operation.security?.flatMap(ee=>Object.keys(ee))??[]),S=this.authSchemeToHeaders(Array.from(j));S.length>0&&a.push(...S);for(let ee of y){let me=ee.error,ve=ee.errorType,H=me.error.errorId,G=ee.examples;b[H]={name:me.error,displayName:ee.displayName,discriminantValue:{name:me.error.name,wireValue:H},type:ve,statusCode:ee.statusCode,isWildcardStatusCode:ee.isWildcardStatusCode,docs:me.docs,examples:[],v2Examples:{userSpecifiedExamples:G??{},autogeneratedExamples:{}},headers:ee.headers}}let w=this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],B=new Qxa({context:this.context,breadcrumbs:this.breadcrumbs,document:this.context.spec}).convert(),R=new Qxa({context:this.context,breadcrumbs:this.breadcrumbs,document:this.operation}).convert()??B,N={displayName:this.operation.summary,method:t,baseUrl:A,v2BaseUrls:g,path:O,pathParameters:o,queryParameters:c,headers:a.filter((ee,me,ve)=>me===ve.findIndex(H=>H.name.wireValue===ee.name.wireValue)),sdkRequest:void 0,errors:v,auth:this.operation.security!=null||this.context.spec.security!=null||this.shouldApplyDefaultAuthOverrides(),security:this.operation.security??this.context.spec.security??this.getDefaultSecurityFromAuthOverrides(),availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),userSpecifiedExamples:[],autogeneratedExamples:[],idempotent:this.idempotent??!1,basePath:void 0,fullPath:O,allPathParameters:o,pagination:void 0,transport:void 0,source:U8.openapi(),audiences:w,retries:void 0,apiPlayground:R},F=this.context.namespace!=null?[this.context.namespace]:[],x=r?.map(ee=>Xo(ee));return F.push(...x??[]),{audiences:w,group:r,groupDisplayName:n,errors:b,endpoint:{...N,id:`endpoint_${F.join("/")}.${i}`,name:this.context.casingsGenerator.generateName(i),requestBody:s,v2RequestBodies:f,response:_,docs:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:m.examples},v2Responses:{responses:p?.v2Responses}},streamEndpoint:h!=null&&h.body!=null?{...N,id:`endpoint_${F.join("/")}.${i}_stream`,name:this.context.casingsGenerator.generateName(`${i}_stream`),requestBody:u,v2RequestBodies:void 0,response:h,docs:this.streamingExtension?.type==="streamCondition"?this.streamingExtension.streamDescription??this.operation.description:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:m.streamExamples},v2Responses:{responses:[{statusCode:200,isWildcardStatusCode:void 0,body:h.body,docs:h.docs}]}}:void 0,inlinedTypes:this.inlinedTypes,servers:this.filterOutTopLevelServers(this.operation.servers??[])}}convertResponseBody({breadcrumbs:t,group:r,method:i,streamingExtension:n}){if(this.operation.responses==null)return;let a,o=!1;for(let[c,d]of Object.entries(this.operation.responses)){let s=/^[45]XX$/i.test(c),u,f=!1;if(s)u=parseInt(c.charAt(0))*100,f=!0;else{if(u=parseInt(c),isNaN(u)||u<200||u>=300&&u<400)continue;f=u>=400&&u<600}if(a==null&&(a={response:void 0,v2Responses:void 0,streamResponse:void 0,errors:[],examples:{}}),u>=200&&u<300){let p=this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:[...t,c]});if(p==null)continue;let h=new Uxa({context:this.context,breadcrumbs:[...t,c],responseBody:p,group:r??[],method:i,statusCode:c,streamingExtension:n}).convert();h!=null&&(this.inlinedTypes={...this.inlinedTypes,...h.inlinedTypes},o||(o=!0,a.response={statusCode:u,isWildcardStatusCode:s?!0:void 0,body:h.responseBody,docs:p.description},a.streamResponse={statusCode:u,isWildcardStatusCode:s?!0:void 0,body:h.streamResponseBody,docs:p.description}),a.v2Responses=[...a.v2Responses??[],{statusCode:u,isWildcardStatusCode:s?!0:void 0,body:h.responseBody,docs:p.description}])}if(f){let p=this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:[...t,c]});if(p==null)continue;let h=new kbu({context:this.context,breadcrumbs:[...t,c],responseError:p,group:r??[],method:i,methodName:this.evaluateMethodNameFromOperation(),statusCode:u,isWildcardStatusCode:s?!0:void 0}).convert();h!=null&&(this.inlinedTypes={...this.inlinedTypes,...h.inlinedTypes},a.errors.push(h))}}if(this.streamingExtension!=null){a==null&&(a={response:void 0,v2Responses:void 0,streamResponse:void 0,errors:[],examples:{}});let d=new Uxa({context:this.context,breadcrumbs:[...t,"stream"],responseBody:{description:""},group:r??[],method:i,statusCode:"stream",streamingExtension:n}).convert();d!=null&&(this.inlinedTypes={...this.inlinedTypes,...d.inlinedTypes},a.response={statusCode:200,isWildcardStatusCode:void 0,body:d.responseBody,docs:void 0},a.streamResponse={statusCode:200,isWildcardStatusCode:void 0,body:d.streamResponseBody,docs:void 0},a.v2Responses=[{statusCode:200,isWildcardStatusCode:void 0,body:d.responseBody,docs:void 0}])}return a}shouldApplyDefaultAuthOverrides(){if(!this.context.authOverrides?.auth)return!1;let t=this.context.spec.security!=null&&this.context.spec.security.length>0,r=this.operation.security!=null;return!(t||r)}getDefaultSecurityFromAuthOverrides(){if(!this.context.authOverrides?.auth)return;let t=this.context.authOverrides.auth;if(typeof t!="string")return;let r={};return r[t]=[],[r]}authSchemeToHeaders(t){let r=[];for(let i of t){let n=this.idToAuthScheme?.[i];if(n==null)continue;let a={valueType:Ta.STRING,availability:void 0,docs:void 0,env:void 0,v2Examples:void 0};switch(n.type){case"bearer":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},...a});break;case"basic":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},...a});break;case"header":r.push({name:n.name,...a});break}}return r}convertExamples({httpPath:t,httpMethod:r,baseUrl:i}){let a=new Xbu({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],c=new $bu({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],s=a.some(u=>Array.isArray(u["code-samples"])&&u["code-samples"].length>0)?a:[...a,...c];return s.length===0?{examples:{},streamExamples:{}}:this.streamingExtension?.type==="streamCondition"?this.convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:s}):{examples:this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:s}),streamExamples:{}}}convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:n}){let a=n.filter(s=>!(s.response!=null&&"stream"in s.response)),o=n.filter(s=>s.response!=null&&"stream"in s.response),c=this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:a}),d=this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:o});return{examples:c,streamExamples:d}}convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:n}){return Object.fromEntries(n.map((a,o)=>[this.getExampleName({example:a,exampleIndex:o}),{displayName:void 0,request:a.request!=null||a["path-parameters"]!=null||a["query-parameters"]!=null||a.headers!=null?{docs:void 0,endpoint:{method:r,path:this.buildExamplePath(t,a["path-parameters"]??{})},baseUrl:void 0,environment:i,auth:void 0,pathParameters:a["path-parameters"]??{},queryParameters:a["query-parameters"]??{},headers:a.headers??{},requestBody:a.request??void 0}:void 0,response:a.response!=null?{docs:void 0,statusCode:void 0,body:this.getExampleResponseBody({example:a})}:void 0,codeSamples:a["code-samples"]?.map(c=>{let d=("language"in c?c.language:c.sdk)??void 0;return{name:c.name,docs:void 0,language:d,code:c.code}})}]))}getExampleName({example:t,exampleIndex:r}){return t.name??t["code-samples"]?.[0]?.name??`Example_${r}`}getExampleResponseBody({example:t}){if(t.response!=null){if("stream"in t.response)return gr.V2HttpEndpointResponseBody.stream(t.response.stream);if("body"in t.response)return gr.V2HttpEndpointResponseBody.json(t.response.body)}}getEndpointBaseUrl(){let r=new aR.ServerFromOperationNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert();if(r!=null)return this.context.logger.debug(`[getEndpointBaseUrl] Endpoint ${this.method.toUpperCase()} ${this.path} specifies a server with "${Hi.SERVER_NAME_V2}" extension. Returning server type: ${r}`),r;let i=this.operation.servers?.[0];if(i==null)return;let a=this.topLevelServers?.find(o=>o.url===i.url)??i;return dve.getServerName({server:a,context:this.context})}getEndpointBaseUrls(){let t=this.operation.servers;return t?.map(i=>{let a=this.topLevelServers?.find(o=>o.url===i.url)??i;return dve.getServerName({server:a,context:this.context})})}buildExamplePath(t,r){return t.head+t.parts.map(i=>`${r[i.pathParameter]?.toString()??i.pathParameter}${i.tail}`).join("")}filterOutTopLevelServers(t){return t.filter(r=>!this.topLevelServers?.some(i=>i.url===r.url))}getGroupDisplayName(t){let r=this.operation.tags?.[0];r!=null&&(r=this.context.getDisplayNameForTag(r));let i=t?.[t.length-1];if(i!=null&&r!=null)return r.toLowerCase().replaceAll(" ","")===i?r:void 0}};var tvu=class extends Ta{pathItem;path;idToAuthScheme;topLevelServers;constructor({context:t,breadcrumbs:r,pathItem:i,path:n,idToAuthScheme:a,topLevelServers:o}){super({context:t,breadcrumbs:r}),this.pathItem=i,this.path=n,this.idToAuthScheme=a,this.topLevelServers=o}convert(){let t=[],r=[],i={};for(let n of jmh){let a=this.pathItem[n];if(a==null)continue;let o=[...this.breadcrumbs,n],c=this.tryParseAsWebhook({operationBreadcrumbs:o,operation:a,method:n,context:this.context});if(c!=null){r.push(c),Object.assign(i,c.inlinedTypes);continue}let s=new Kbu({breadcrumbs:o,operation:a,context:this.context}).convert(),u=this.tryParseAsHttpEndpoint({operationBreadcrumbs:o,operation:a,method:n,streamingExtension:s});u!=null&&(t.push(u),Object.assign(i,u.inlinedTypes))}return{endpoints:t,webhooks:r,inlinedTypes:i}}tryParseAsWebhook({operation:t,method:r,operationBreadcrumbs:i,context:n}){return new Jbu({breadcrumbs:i,operation:t,context:n}).convert()?new Hoa({context:this.context,breadcrumbs:i,operation:t,method:UGc.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path}).convert():void 0}tryParseAsHttpEndpoint({operation:t,method:r,operationBreadcrumbs:i,streamingExtension:n}){new xbu({breadcrumbs:i,operation:t,document:this.context.spec,context:this.context}).convert()!=null;let d=new Gbu({breadcrumbs:i,operation:t,context:this.context}).convert();return new evu({context:this.context,breadcrumbs:i,operation:t,method:UGc.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path,idempotent:d,idToAuthScheme:this.idToAuthScheme,topLevelServers:this.topLevelServers,streamingExtension:n}).convert()}};var rvu=class extends Ta{securityScheme;schemeId;constructor({context:t,breadcrumbs:r,securityScheme:i,schemeId:n}){super({context:t,breadcrumbs:r}),this.securityScheme=i,this.schemeId=n}convert(){switch(this.securityScheme.type){case"http":{if(this.securityScheme.scheme==="bearer")return tm.bearer({key:this.schemeId,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,docs:this.securityScheme.description});if(this.securityScheme.scheme==="basic")return tm.basic({key:this.schemeId,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 tm.header({key:this.schemeId,name:{name:this.context.casingsGenerator.generateName("apiKey"),wireValue:this.securityScheme.name},valueType:Ta.OPTIONAL_STRING,prefix:void 0,headerEnvVar:void 0,docs:this.securityScheme.description});break}case"oauth2":return tm.bearer({key:this.schemeId,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,docs:this.securityScheme.description})}}};var Lxa=class extends O3t{constructor({breadcrumbs:t,context:r,audiences:i}){super({breadcrumbs:t,context:r,audiences:i})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.context.spec=await this.resolveAllExternalRefs({spec:this.context.spec}),this.overrideOpenApiAuthWithGeneratorsAuth(),this.convertSecuritySchemes(),this.convertGlobalHeaders(),this.convertBasePath(),this.convertSchemas(),this.convertWebhooks();let{endpointLevelServers:t,errors:r}=this.convertPaths();this.addErrorsToIr(r);let{defaultUrl:i}=this.convertServers({endpointLevelServers:t});this.updateEndpointsWithDefaultUrl(i);let n=this.context.spec.info?.title?.trim();return n&&n!=='""'&&(this.ir.apiDisplayName=n),this.finalizeIr()}convertGlobalHeaders(){this.context.globalHeaderOverrides;let r=new Lbu({breadcrumbs:["x-fern-global-headers"],document:this.context.spec,context:this.context}).convert();if(r!=null){let i=mmh({globalHeaders:r,context:this.context});this.addGlobalHeadersToIr(i),this.context.setGlobalHeaders(i)}}convertBasePath(){let r=new Ubu({breadcrumbs:["x-fern-base-path"],document:this.context.spec,context:this.context}).convert();r!=null&&(this.ir.basePath=iM(r))}convertSecuritySchemes(){if(this.context.authOverrides){let r=AQc({rawApiFileSchema:this.context.authOverrides,casingsGenerator:this.context.casingsGenerator});this.addAuthToIR({requirement:r.requirement,schemes:r.schemes,docs:r.docs});return}let t=this.convertOpenApiSecuritySchemes();t.length>0&&this.addAuthToIR({requirement:t.length===1?"ALL":"ANY",schemes:t,docs:void 0})}convertOpenApiSecuritySchemes(){let t=[];for(let[r,i]of Object.entries(this.context.spec.components?.securitySchemes??{})){let n=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:["components","securitySchemes",r]});if(n==null)continue;let o=new rvu({context:this.context,breadcrumbs:["components","securitySchemes",r],securityScheme:n,schemeId:r}).convert();o!=null&&t.push(o)}return t}convertServers({endpointLevelServers:t}){if(this.context.environmentOverrides){let n=EGa({rawApiFileSchema:this.context.environmentOverrides,casingsGenerator:this.context.casingsGenerator});return n!=null&&this.addEnvironmentsToIr({environmentConfig:n.environmentsConfig,audiences:n.audiences}),{defaultUrl:this.context.environmentOverrides["default-url"]}}let i=new dve({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t}).convert();return this.addEnvironmentsToIr({environmentConfig:i?.value}),{defaultUrl:i?.defaultUrl}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{})){let n=new bA.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:["components","schemas",t],schema:r}).convert();n!=null&&this.addSchemaOutputToIr(t,n)}}convertWebhooks(){for(let[,t]of Object.entries(this.context.spec.webhooks??{})){if(t==null){this.context.errorCollector.collect({message:"Skipping empty webhook",path:this.breadcrumbs});continue}if(!("post"in t)){this.context.errorCollector.collect({message:"Skipping webhook as it is not a POST method",path:this.breadcrumbs});continue}if(t.post?.operationId==null){this.context.errorCollector.collect({message:"Skipping webhook as no operationId is present",path:this.breadcrumbs});continue}let r=t.post.operationId,n=new Hoa({context:this.context,breadcrumbs:["webhooks",r],operation:t.post,method:Mmh.OpenAPIV3.HttpMethods.POST,path:r}).convert();n!=null&&(this.addWebhookToIr({webhook:n.webhook,operationId:r,audiences:n.audiences,group:n.group}),this.addTypesToIr(n.inlinedTypes))}}convertPaths(){let t=[],r={};for(let[i,n]of Object.entries(this.context.spec.paths??{})){if(n==null)continue;let o=new tvu({context:this.context,breadcrumbs:["paths",i],topLevelServers:this.context.spec.servers,pathItem:n,path:i}).convert();if(o!=null){for(let c of o.endpoints){if(c.streamEndpoint!=null&&this.addEndpointToIr({endpoint:c.streamEndpoint,audiences:c.audiences,endpointGroup:c.group,endpointGroupDisplayName:c.groupDisplayName}),this.addEndpointToIr({endpoint:c.endpoint,audiences:c.audiences,endpointGroup:c.group,endpointGroupDisplayName:c.groupDisplayName}),c.servers)for(let d of c.servers)this.shouldAddServerToCollectedServers({server:d,currentServers:t})&&t.push(d);if(c.errors)for(let[d,s]of Object.entries(c.errors))r[d]=s}for(let c of o.webhooks){let d=this.context.getGroup({groupParts:c.group,namespace:this.context.namespace});this.addWebhookToIr({webhook:c.webhook,operationId:d.join("."),group:d,audiences:c.audiences})}this.addTypesToIr(o.inlinedTypes)}}return{endpointLevelServers:t,errors:r}}overrideOpenApiAuthWithGeneratorsAuth(){if(!this.context.authOverrides?.["auth-schemes"])return;this.context.spec.components||(this.context.spec.components={}),this.context.spec.components.securitySchemes={};let t={};for(let r of Object.keys(this.context.authOverrides["auth-schemes"]))this.context.spec.components.securitySchemes[r]={type:"http",scheme:"bearer"},t[r]=[];this.context.spec.security=[t],this.removeEndpointSpecificAuth()}removeEndpointSpecificAuth(){if(this.context.spec.paths)for(let t of Object.values(this.context.spec.paths)){if(!t)continue;let r=["get","post","put","patch","delete","options","head","trace"];for(let i of r){let n=t[i];n?.security&&delete n.security}}}};var ivu=class extends el{tag;key="x-displayName";constructor({breadcrumbs:t,tag:r,context:i}){super({breadcrumbs:t,context:i}),this.tag=r}convert(){if(typeof this.tag!="object"||this.tag==null)return;let t=this.tag[this.key];if(t!=null){if(typeof t!="string"){this.context.errorCollector.collect({message:"x-displayName extension must be a string",path:this.breadcrumbs});return}if(t.trim().length!==0)return{displayName:t}}}};var nUi=class extends VI{globalHeaderNames;tagToDisplayName={};isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n}){let a=this.getTypeIdFromSchemaReference(t);if(a==null)return{ok:!1};let o=this.resolveReference({reference:t,breadcrumbs:r});if(!o.resolved)return{ok:!1};let c;n==="reference_identifier"?c=i??o.value.title:n==="discriminator_key"?c=o.value.title??i:n==="schema_identifier"&&(c=o.value.title);let d;if(a.includes("/")){let u=new bA.SchemaConverters.SchemaConverter({context:this,breadcrumbs:r??[],schema:o.value,id:a}).convert();u!=null&&(d={[a]:u.convertedSchema})}return{ok:!0,reference:ri.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(a),typeId:a,default:void 0,inline:!1,displayName:c}),inlinedTypes:d}}setGlobalHeaders(t){this.globalHeaderNames=t.map(r=>r.name.wireValue)}getDisplayNameForTag(t){if(Object.keys(this.tagToDisplayName).length===0)for(let r of this.spec.tags??[]){let n=new ivu({breadcrumbs:["tags",r.name],tag:r,context:this}).convert()?.displayName??r.name;this.tagToDisplayName[r.name]=n}return this.tagToDisplayName[t]??t}};var yiB=zt.object({description:zt.string().optional(),required:zt.boolean().optional(),deprecated:zt.boolean().optional(),allowEmptyValue:zt.boolean().optional(),style:zt.string().optional(),explode:zt.boolean().optional(),allowReserved:zt.boolean().optional(),schema:zt.any().optional(),example:zt.any().optional(),examples:zt.record(zt.string(),zt.any()).optional(),content:zt.record(zt.string(),zt.any()).optional()}),biB=yiB.extend({name:zt.string(),in:zt.string()}),viB=zt.array(biB),nvu=class extends el{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 viB.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 avu=class extends Ta{method;pathParameters;queryParameters;headers;topLevelServers;constructor({context:t,breadcrumbs:r,method:i,pathParameters:n=[],queryParameters:a=[],headers:o=[],topLevelServers:c=[]}){super({context:t,breadcrumbs:r}),this.method=i,this.pathParameters=n,this.queryParameters=a,this.headers=o,this.topLevelServers=c}convert(){let t={},r="";for(let s of this.pathParameters)r+=`/{${s.name.originalName}}`;let i=iM(r),n=[];for(let[s,u]of this.method.params.entries()){let f;if(this.context.isReferenceObject(u)){let y=this.context.resolveReference({reference:u});if(y.resolved)f=y.value;else continue}else f=u;let p=[this.method.name,"Param",f.name].join("_"),h=new bA.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"Param",f.name],schemaIdOverride:p,context:this.context,schemaOrReference:f.schema,wrapAsOptional:!f.required}).convert();h!=null&&(n.push({docs:f.description,availability:this.context.getAvailability({node:u,breadcrumbs:[...this.breadcrumbs,"parameters"]}),name:this.context.casingsGenerator.generateNameAndWireValue({name:f.name,wireValue:f.name}),valueType:h.type,v2Examples:h.schema?.typeDeclaration.v2Examples,propertyAccess:void 0}),t={...h.inlinedTypes,...t,...h.schema!=null?{[p]:h.schema}:{}})}let a;if(this.method.result!=null){let s=this.context.resolveMaybeReference({schemaOrReference:this.method.result,breadcrumbs:[...this.breadcrumbs,"result"]});if(s!=null){let u=new bA.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"result"],context:this.context,schemaOrReference:s.schema}),f=[this.method.name,"Result"].join("_"),p=u.convert();p!=null&&(a={docs:s.description,v2Examples:p.schema?.typeDeclaration.v2Examples,responseBodyType:p.type},t={...p.inlinedTypes,...t,...p.schema!=null?{[f]:p.schema}:{}})}}let o=this.getEndpointBaseUrls(),c=this.context.getAudiences({operation:this.method,breadcrumbs:this.breadcrumbs})??[];return{endpoint:{baseUrl:void 0,v2BaseUrls:o,basePath:void 0,auth:!1,security:void 0,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?yA.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,v2RequestBodies:void 0,sdkRequest:void 0,response:a!=null?{body:dd.json(NI.response(a)),statusCode:void 0,isWildcardStatusCode:void 0,docs:a.docs}:void 0,v2Responses:void 0,errors:[],idempotent:!1,pagination:void 0,userSpecifiedExamples:[],autogeneratedExamples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples()},transport:void 0,availability:void 0,source:U8.openrpc(),audiences:c,retries:void 0,apiPlayground:void 0},audiences:c,inlinedTypes:t,servers:this.filterOutTopLevelServers(this.method.servers??[])}}filterOutTopLevelServers(t){return t.filter(r=>!this.topLevelServers.some(i=>i.url===r.url))}getEndpointBaseUrls(){let t=this.method.servers;return t?.map(i=>{if(this.topLevelServers.find(c=>c.name===i.name&&c.url!==i.url)!=null)return i.url;let o=this.topLevelServers.find(c=>c.url===i.url)??i;return dve.getServerName({server:o,context:this.context})})}convertExamples(){let t={},r=0;if(this.method.examples&&this.method.examples.length>0){for(let i of this.method.examples??[]){let n;if(this.context.isReferenceObject(i)){let d=this.context.resolveReference({reference:i});if(d.resolved)n=d.value;else continue}else n=i;let a;if(n.result)if(this.context.isReferenceObject(n.result)){let d=this.context.resolveReference({reference:n.result});d.resolved&&(a=d.value)}else a=n.result;let o=n.name??`Example ${r+1}`,c=[];if(n.params&&Array.isArray(n.params)){c=[];for(let d of n.params)if(this.context.isReferenceObject(d)){let s=this.context.resolveReference({reference:d});if(s.resolved)c.push(s.value);else continue}else c.push(d)}t[o]={displayName:void 0,request:{docs:void 0,endpoint:{method:"POST",path:"/{apiKey}"},baseUrl:void 0,environment:void 0,auth:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:c.map(d=>d.value)??void 0},response:{docs:void 0,statusCode:void 0,body:a?.value?gr.V2HttpEndpointResponseBody.json({jsonrpc:"2.0",id:n.examplePairedRequest?.id||"1",result:a.value}):void 0},codeSamples:[]}}++r}return t}};var ovu=class extends bA.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r,parameter:i})}convert(){let t,r={};if(this.parameter.schema!=null){let n=new bA.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 Vxa=class extends O3t{constructor({context:t,breadcrumbs:r,audiences:i}){super({context:t,breadcrumbs:r,audiences:i})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.convertSchemas();let{endpointLevelServers:t}=this.convertMethods(),{defaultUrl:r}=this.convertServers({endpointLevelServers:t});return this.updateEndpointsWithDefaultUrl(r),this.finalizeIr()}convertServers({endpointLevelServers:t}){let i=new dve({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t}).convert();return this.addEnvironmentsToIr({environmentConfig:i?.value}),{defaultUrl:i?.defaultUrl}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{})){let n=new bA.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:["components","schemas",t],schema:r}).convert();n!=null&&this.addSchemaOutputToIr(t,n)}}convertMethods(){let t=[],i=new nvu({context:this.context,breadcrumbs:["methods"],operation:this.context.spec}).convert(),n=[],a=[],o=[];if(i&&i.length>0)for(let[d,s]of i.entries()){let f=new ovu({context:this.context,breadcrumbs:[...this.breadcrumbs,`x-fern-parameters[${d}]`],parameter:s}).convert();if(f!=null)switch(f.type){case"path":{n.push(f.parameter);break}case"query":{a.push(f.parameter);break}case"header":{o.push(f.parameter);break}}}let c=this.context.getGroup({groupParts:[],namespace:this.context.namespace});for(let d of this.context.spec.methods??[]){let s=this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:["methods"]});if(s==null)continue;let f=new avu({context:this.context,breadcrumbs:["methods"],method:s,pathParameters:n,queryParameters:a,headers:o,topLevelServers:this.context.spec.servers}).convert();if(f!=null&&(this.addEndpointToIr({endpoint:f.endpoint,audiences:f.audiences,endpointGroup:c,serviceName:"service_root"}),this.addTypesToIr(f.inlinedTypes),f.servers))for(let p of f.servers)this.shouldAddServerToCollectedServers({server:p,currentServers:t,specType:"openrpc"})&&t.push(this.maybeDeduplicateServerName(p))}return{endpointLevelServers:t}}maybeDeduplicateServerName(t){return this.context.spec.servers?.find(i=>i.name===t.name&&i.url!==t.url)?{...t,name:t.url}:t}};var Wxa=class extends VI{isReferenceObject(t){return t!=null&&"$ref"in t}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n}){let a=this.getTypeIdFromSchemaReference(t);if(a==null)return{ok:!1};let o=this.resolveReference({reference:t,breadcrumbs:r});if(!o.resolved)return{ok:!1};let c;return n==="reference_identifier"?c=i??o.value.title:(n==="discriminator_key"||n==="schema_identifier")&&(c=o.value.title??i),{ok:!0,reference:ri.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(a),typeId:a,displayName:c,default:void 0,inline:!1})}}};var bjh=require("fs/promises");var Dmh={[ki.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,M0(e)])),[ki.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"]),[ki.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"]),[ki.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","kwargs"]),[ki.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","vendor","any","bool","byte","complex64","complex128","error","float32","float64","int","int8","int16","int32","int64","make","new","rune","string","uint","uint8","uint16","uint32","uint64","uintptr"]),[ki.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","object_id","hash","eql?","equal?","method","send","respond_to?","respond_to_missing?","instance_of?","kind_of?","is_a?","extend","singleton_class","instance_variables","instance_variable_get","instance_variable_set","instance_variable_defined?","remove_instance_variable","public_methods","private_methods","protected_methods","singleton_methods"]),[ki.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"]),[ki.GenerationLanguage.RUST]:new Set(["as","async","await","break","const","continue","crate","dyn","else","enum","extern","false","fn","for","if","impl","in","let","loop","match","mod","move","mut","pub","ref","return","self","Self","static","struct","super","trait","true","type","union","unsafe","use","where","while","abstract","become","box","do","final","macro","override","priv","try","typeof","unsized","virtual","yield","bool","char","f32","f64","i8","i16","i32","i64","i128","isize","str","u8","u16","u32","u64","u128","usize","String","Vec","Option","Result","Box","Rc","Arc","Cell","RefCell","HashMap","HashSet","BTreeMap","BTreeSet"]),[ki.GenerationLanguage.SWIFT]:new Set([])};var giB=["go","ruby"];function cvu({generationLanguage:e,keywords:t,smartCasing:r}){let i={generateName:(n,a)=>{let o=MiB(n),c=p=>({unsafeName:p,safeName:OiB({name:p,keywords:AiB({generationLanguage:e,keywords:t})})}),d=Xo(o),s=M0(d),u=aln(o),f=tln(d);return r&&(!jiB(f)&&(e==null||giB.includes(e))&&(d=f.map((p,_)=>{if(_>0){let h=uvu(p);if(h!=null)return h;if(svu(p))return p.toUpperCase()}return p}).join(""),s=M0(f.map((p,_)=>{let h=uvu(p);return h??(svu(p)?p.toUpperCase():_===0?M0(p):p)}).join(""))),u=o.split(" ").map(p=>p.split(/(\d+)/).map(aln).join("")).join("_")),{originalName:n,camelCase:c(a?.casingOverrides?.camel??d),snakeCase:c(a?.casingOverrides?.snake??u),screamingSnakeCase:c(a?.casingOverrides?.["screaming-snake"]??u.toUpperCase()),pascalCase:c(a?.casingOverrides?.pascal??s)}},generateNameAndWireValue:({name:n,wireValue:a,opts:o})=>({name:i.generateName(n,o),wireValue:a})};return i}function OiB({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":PiB(e)?"_"+e:e}function AiB({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return Dmh[e]}var miB=/^[0-9]/;function PiB(e){return miB.test(e)}function jiB(e){return e.some((t,r)=>{if(r===0)return!1;let i=e[r-1];if(i==null)return!1;let n=uvu(i)!=null||svu(i),a=uvu(t)!=null||svu(t);return n&&a})}function uvu(e){return EiB.get(e.toUpperCase())}function svu(e){return wiB.has(e.toUpperCase())}var wiB=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"]),EiB=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]),SiB=[[/\[\]/g,"Array"]];function MiB(e){return SiB.reduce((t,[r,i])=>t.replace(r,i),e)}var Bmh=require("fs/promises");async function LGc({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let i=(await(0,Bmh.readFile)(t)).toString(),n;try{n=JSON.parse(i)}catch{n=Di.load(i)}return r!=null?await Uoa({absoluteFilePathToOverrides:r,context:e,data:n}):n}var njh=ce(ijh(),1);function GJi(e,t,r=[],{doNotPipeOutput:i=!1,secrets:n=[],substitutions:a={},...o}={}){let c=n.reduce((s,u)=>({...s,[u]:"<redacted>"}),a),d=[t,...r].join(" ");for(let[s,u]of Object.entries(c))d=d.replaceAll(s,u);return e?.debug(`+ ${d}`),(0,njh.default)(t,r,o)}async function Nb(e,t,r=[],{doNotPipeOutput:i=!1,secrets:n=[],substitutions:a={},...o}={}){let c=GJi(e,t,r,{doNotPipeOutput:i,secrets:n,substitutions:a,...o});i||(c.stdout?.pipe(process.stdout),c.stderr?.pipe(process.stderr));let d=await c;return d.stdout==null&&(d.stdout=""),d.stderr==null&&(d.stderr=""),d}function HJi(e,{logger:t,...r}={}){return(i,n)=>Nb(t,e,i,{...r,...n})}var Cve=require("fs/promises"),pjh=ce(require("path"),1),nHc=ce(Z9(),1);var ajh="buf.gen.yaml",AaB="output",ojh=`${AaB}/ir.json`,ujh="protoc-gen-fern",sjh=`version: v1
1419
+ `).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:syu.conjure.DefinitionFile.parseOrThrow(Di.load(r),{unrecognizedObjectKeys:"passthrough",allowUnrecognizedEnumValues:!0,allowUnrecognizedUnionMembers:!0})}}function Obh(e,t){if(YZD(e))return t.alias(e);if(XZD(e))return t.enum(e);if(ZZD(e))return t.object(e);if(kZD(e))return t.union(e);vt(e)}function YZD(e){return e?.alias!=null}function XZD(e){return e?.values!=null}function ZZD(e){return e?.fields!=null}function kZD(e){return e?.union!=null}var J7a=class extends DHa{fernDefinitionBuilder=new Zyn(!1);conjureFilepathToFernFilepath={};async import({absolutePathToConjureFolder:t,authOverrides:r,environmentOverrides:i,globalHeaderOverrides:n}){if(r!=null){for(let[a,o]of Object.entries(r["auth-schemes"]??{}))this.fernDefinitionBuilder.addAuthScheme({name:a,schema:o});r.auth!=null&&this.fernDefinitionBuilder.setAuth(r.auth)}if(i!=null){for(let[a,o]of Object.entries(i.environments??{}))this.fernDefinitionBuilder.addEnvironment({name:a,schema:o});i["default-environment"]!=null&&this.fernDefinitionBuilder.setDefaultEnvironment(i["default-environment"]),i["default-url"]!=null&&this.fernDefinitionBuilder.setDefaultUrl(i["default-url"])}return await Abh(t,(a,o,c)=>{for(let[u,f]of Object.entries(c.services??{})){let p=mCo({value:u,suffix:"Service"});this.conjureFilepathToFernFilepath[o]=Xe.of(`${p}/__package__.yml`);return}let s=rzi(o)?.split(".")[0];s!=null&&(this.conjureFilepathToFernFilepath[o]=Xe.of(`${s}/__package__.yml`))}),await Abh(t,(a,o,c)=>{if(c.services==null||Object.keys(c.services??{}).length===0){let d=this.conjureFilepathToFernFilepath[o];if(d==null)throw new Error(`Failed to find corresponding fern filepath for conjure file ${o}`);for(let[s,u]of Object.entries(c.types?.conjureImports??{})){let f=this.getFernFileToImport({absoluteFilePathToConjureFile:a,absoluteFilePathToConjureFolder:t,importFilePath:Xe.of(u)});this.fernDefinitionBuilder.addImport({file:d,fileToImport:Xe.of(f),alias:s})}this.importAllTypes({conjureFile:c,fernFilePath:d});return}for(let[d,s]of Object.entries(c.services)){let u=mCo({value:d,suffix:"Service"}),f=Xe.of(`${u}/__package__.yml`),p={};s.basePath!=null&&(p["base-path"]=s.basePath),s.docs!=null&&(p.docs=s.docs),this.fernDefinitionBuilder.setServiceInfo(f,p),this.importAllTypes({conjureFile:c,fernFilePath:f});for(let[_,h]of Object.entries(c.types?.conjureImports??{})){let y=this.getFernFileToImport({absoluteFilePathToConjureFile:a,absoluteFilePathToConjureFolder:t,importFilePath:Xe.of(h)});this.fernDefinitionBuilder.addImport({file:f,fileToImport:Xe.of(y),alias:_})}for(let[_,h]of Object.entries(s.endpoints??{})){let y=r2s(h.http);if(y.type==="failure"){this.context?.logger.error(`Failed to parse ${h.http}. Skipping.`);continue}let v={auth:(h.auth??s.defaultAuth)!==Wyh.None,path:y.path,method:y.method,response:h.returns==="binary"?"file":h.returns};h.docs!=null&&(v.docs=h.docs);let O={};if(h.args!=null)for(let A of y.pathParameters){let g=h.args[A];if(g==null)throw new Error(`Failed to find path parameter ${A} in ${h.http}`);O[A]=typeof g=="string"?g:{type:g.type}}Object.entries(O).length>0&&(v["path-parameters"]=O);for(let[A,g]of Object.entries(h.args??{}))if(O[A]==null)if(typeof g=="string")v.request?typeof v.request=="string"&&(v.request={body:v.request}):v.request={},v.request.body=g==="binary"?"bytes":g;else switch(g.paramType){case"body":v.request={body:g.type==="binary"?"bytes":g.type};break;case"query":v.request==null?v.request={"query-parameters":{[A]:g.type}}:typeof v.request!="string"&&v.request?.["query-parameters"]==null?v.request["query-parameters"]={[A]:g.type}:typeof v.request!="string"&&v.request?.["query-parameters"]!=null&&(v.request["query-parameters"][A]=g.type)}v.request!=null&&typeof v.request!="string"&&v.request?.["query-parameters"]!=null&&(v.request.name=`${_}Request`),this.fernDefinitionBuilder.addEndpoint(f,{name:_,schema:v,source:void 0})}}}),this.fernDefinitionBuilder.build()}convertBinaryType(t){return typeof t=="string"?t==="binary"?{type:"string",validation:{format:"binary"}}:t:t.type==="binary"?{...t,type:"string",validation:{format:"binary"}}:t}importAllTypes({conjureFile:t,fernFilePath:r}){for(let[i,n]of Object.entries(t.types?.definitions?.objects??{}))Obh(n,{alias:a=>{let o=a.alias==="binary"?{type:"string",validation:{format:"binary"}}:a.alias;this.fernDefinitionBuilder.addType(r,{name:i,schema:typeof o=="string"?{type:o,docs:a.docs}:{...o,docs:a.docs}})},object:a=>{this.fernDefinitionBuilder.addType(r,{name:i,schema:{properties:Object.fromEntries(Object.entries(a.fields).map(([o,c])=>[o,this.convertBinaryType(c)]))}})},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(([o,c])=>{let d=this.convertBinaryType(c);return[o,{type:typeof d=="string"?d:d.type,docs:typeof d=="string"?void 0:d.docs,key:o}]}))}})}})}getFernFileToImport({absoluteFilePathToConjureFile:t,importFilePath:r,absoluteFilePathToConjureFolder:i}){let n=It(en(t),Xe.of(r)),a=kK(i,n),o=this.conjureFilepathToFernFilepath[a];if(o==null)throw new Error(`Failed to find corresponding fern filepath for conjure file ${a}`);return o}};async function Abh(e,t){for(let r of await gbh(e,"{yml,yaml}"))await t(r.absoluteFilepath,r.relativeFilepath,r.fileContents)}function mbh(e,t){return bn(e,t)}var cyu=class extends M3t{type="conjure";absolutePathToConjureFolder;constructor({relativePathToConjureDirectory:t,...r}){super(r),this.absolutePathToConjureFolder=It(r.absoluteFilePath,t)}async toFernWorkspace({context:t},r){let i=await this.getDefinition({context:t},r);return new B$({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 J7a(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:Sr.of("/DUMMY_PATH"),rootApiFile:{defaultUrl:n.rootApiFile["default-url"],contents:n.rootApiFile,rawContents:Di.dump(n.rootApiFile)},namedDefinitionFiles:{...mbh(n.definitionFiles,a=>({absoluteFilepath:Sr.of("/DUMMY_PATH"),rawContents:Di.dump(a),contents:a})),[Xe.of(Db)]:{absoluteFilepath:Sr.of("/DUMMY_PATH"),rawContents:Di.dump(n.packageMarkerFile),contents:n.packageMarkerFile}},packageMarkers:{},importedDefinitions:{}}}getAbsoluteFilePaths(){return[this.absolutePathToConjureFolder]}};var VOh=ce(Mbh(),1);var R_;(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"})(R_||(R_={}));function Dbh(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function lyu(e,t){for(let[r,i]of fI(e))t2D({relativeFilepath:r,failure:i,logger:t})}function t2D({relativeFilepath:e,failure:t,logger:r}){switch(t.type){case R_.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 R_.FILE_READ:r.error("Failed to open file: "+e);break;case R_.FILE_MISSING:r.error("Missing file: "+e);break;case R_.FILE_PARSE:t.error instanceof dUa?r.error(OEe({title:`Failed to parse ${e}: ${t.error.reason}`,subtitle:t.error.mark.snippet})):r.error("Failed to parse file: "+e);break;case R_.STRUCTURE_VALIDATION:for(let i of t.error.issues)for(let{title:n,subtitle:a}of r2D(i))r.error(OEe({title:n,subtitle:a,breadcrumbs:[e,...i.path]}));break;case R_.FAILED_TO_LOAD_DEPENDENCY:r.error("Failed to load dependency: "+t.dependencyName);break;case R_.DEPENDENCY_NOT_LISTED:r.error(`Dependency is not listed in ${gqo}: `+t.dependencyName);break;case R_.EXPORT_PACKAGE_HAS_DEFINITIONS:r.error("Exported package contains API definitions: "+t.pathToPackage);break;case R_.EXPORTING_PACKAGE_MARKER_OTHER_KEYS:r.error(`${t.pathOfPackageMarker} has an export so it cannot define other keys.`);break;case R_.JSONSCHEMA_VALIDATION:if(t.error.error!=null){let i=t.error.error.instancePath.split("/").filter(n=>n!=="").map(Dbh);t.error.error.keyword==="required"&&t.error.error.params?.missingProperty?i.push(t.error.error.params.missingProperty):t.error.error.keyword==="additionalProperties"&&t.error.error.params?.additionalProperty&&i.push(t.error.error.params.additionalProperty),r.error(OEe({title:t.error.error.message??"Unknown error",breadcrumbs:[e,...i]}))}for(let i of t.error.allErrors)if(i!==t.error.error){let n=i.instancePath.split("/").filter(a=>a!=="").map(Dbh);i.keyword==="required"&&i.params?.missingProperty?n.push(i.params.missingProperty):i.keyword==="additionalProperties"&&i.params?.additionalProperty&&n.push(i.params.additionalProperty),r.debug(OEe({title:i.message??"Unknown error",breadcrumbs:[e,...n]}))}break;default:vt(t)}}function r2D(e){switch(e.code){case Ai.invalid_type:return[{title:"Incorrect type",subtitle:`Expected ${Ct.underline(e.expected)} but received ${Ct.underline(e.received)}`}];case Ai.unrecognized_keys:return e.keys.map(t=>({title:"Unexpected key",subtitle:`Encountered unexpected key ${Ct.underline(t)}`}));case Ai.invalid_enum_value:return[{title:"Unrecognized value",subtitle:`Allowed values: ${e.options.map(t=>Ct.underline(t)).join(", ")}`}];case Ai.invalid_union:case Ai.invalid_arguments:case Ai.invalid_return_type:case Ai.invalid_date:case Ai.invalid_string:case Ai.too_small:case Ai.too_big:case Ai.invalid_intersection_types:case Ai.not_multiple_of:case Ai.custom:default:return[{title:e.message}]}}var Bbh=require("fs/promises");async function Ibh(e,t){let r=[];for(let i of await xU(e,t))r.push(await i2D({relativeFilepath:S_(e,i),absoluteFilepath:i}));return r}async function i2D({relativeFilepath:e,absoluteFilepath:t}){return{relativeFilepath:e,absoluteFilepath:t,fileContents:(await(0,Bbh.readFile)(t)).toString()}}async function Cbh(e){let t={},r={};function i(n){try{t[n.relativeFilepath]={defaultUrl:void 0,contents:Di.load(n.fileContents,{schema:Di.CORE_SCHEMA}),rawContents:n.fileContents}}catch(a){r[n.relativeFilepath]={type:R_.FILE_PARSE,error:a}}}return await Promise.all(e.map(i)),Object.keys(r).length>0?{didSucceed:!1,failures:r}:{didSucceed:!0,files:t}}var sGc=ce(DHi(),1);var IOh=require("fs"),Coa=require("fs/promises");var COh=require("os"),qOh=ce(require("path"),1),TOh=require("stream/promises"),ROh=ce(uGc(),1),zOh=ce(Z9(),1);var qeB=ZNi();async function NOh({dependencyName:e,dependenciesConfiguration:t,context:r,rootApiFile:i,cliVersion:n,settings:a,loadAPIWorkspace:o}){let c,d={type:R_.FAILED_TO_LOAD_DEPENDENCY,dependencyName:e},s=t.dependencies[e];return s==null?d={type:R_.DEPENDENCY_NOT_LISTED,dependencyName:e}:await r.runInteractiveTask({name:`Download ${UeB(s)}`},async u=>{switch(s.type){case"version":c=await FeB({context:u,dependency:s,cliVersion:n,settings:a,loadAPIWorkspace:o});return;case"local":c=await NeB({context:u,dependency:s,cliVersion:n,settings:a,loadAPIWorkspace:o});return;default:vt(s)}}),c!=null?{didSucceed:!0,definition:c}:{didSucceed:!1,failure:d}}var FOh="dependencies";var TeB="metadata.json",ReB=".fern";function zeB(e){return It(Sr.of((0,COh.homedir)()),Xe.of(ReB),Xe.of(FOh),Xe.of(e.organization),Xe.of(e.apiName),Xe.of(e.version))}async function NeB({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 o=await a.workspace.getDefinition({context:t,relativePathToDependency:Xe.of(e.path)},i);return t.logger.info("Loaded..."),o}async function FeB({dependency:e,context:t,cliVersion:r,settings:i,loadAPIWorkspace:n}){let a=zeB(e),o=It(a,Xe.of(FOh)),c=It(a,Xe.of(TeB)),d;if(!await mi(o)||!await mi(c)){t.logger.info("Downloading manifest...");let f=await qeB.definitionRegistry.get(sGc.FernFiddle.OrganizationId(e.organization),sGc.FernFiddle.ApiId(e.apiName),e.version);if(!f.ok){f.error._visit({orgDoesNotExistError:()=>{t.failWithoutThrowing("Organization does not exist")},apiDoesNotExistError:()=>{t.failWithoutThrowing("API does not exist")},versionDoesNotExistError:()=>{t.failWithoutThrowing("Version does not exist")},_other:y=>{t.failWithoutThrowing("Failed to download API manifest",y)}});return}let p=f.body.yamlSchemaVersion!=null?parseInt(f.body.yamlSchemaVersion):void 0,_=Syn(r),h=Syn(f.body.cliVersion);if(p!=null){if(p>1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a higher version of fern. Upgrade this workspace to ${f.body.cliVersion}`);return}else if(p<1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a lower version of fern. Upgrade it to ${r}`);return}}else if(_.major!==h.major||_.minor!==h.minor){t.failWithoutThrowing(`CLI version is ${f.body.cliVersion}. Expected ${_.major}.${_.minor}.x (to match current workspace).`);return}t.logger.info("Downloading..."),t.logger.debug("Remote URL: "+f.body.definitionS3DownloadUrl),await(0,Coa.mkdir)(o,{recursive:!0});try{await QeB({s3PreSignedReadUrl:f.body.definitionS3DownloadUrl,absolutePathToLocalOutput:o})}catch(y){t.failWithoutThrowing("Failed to download API",y);return}d=f.body,await(0,Coa.writeFile)(c,JSON.stringify(d))}else d=JSON.parse((await(0,Coa.readFile)(c)).toString());if(t.logger.info("Parsing..."),n==null){t.failWithoutThrowing("Failed to load API");return}let s=await n({absolutePathToWorkspace:o,context:t,cliVersion:d.cliVersion,workspaceName:void 0});if(!s.didSucceed){t.failWithoutThrowing("Failed to parse dependency after downloading",s.failures);return}if(s.workspace.type==="oss"){t.failWithoutThrowing("Dependency must be a fern workspace.");return}return await s.workspace.getDefinition({context:t},i)}async function QeB({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t}){let r=await wB.get(e,{responseType:"stream"}),i=await zOh.default.dir(),n=qOh.default.join(i.path,"api.tgz");await(0,TOh.pipeline)(r.data,(0,IOh.createWriteStream)(n)),await(0,ROh.extract)({file:n,cwd:t})}function UeB(e){switch(e.type){case"version":return`@${e.organization}/${e.apiName}`;case"local":return`${e.path}`;default:vt(e)}}async function QOh({dependenciesConfiguration:e,structuralValidationResult:t,context:r,cliVersion:i,settings:n,loadAPIWorkspace:a}){let o={},c={},d={};return await Promise.all(fI(t.packageMarkers).map(async([s,u])=>{if(u.contents.export==null)o[s]=u;else{let{export:f,...p}=u.contents;if(gm(p)>0)d[s]={type:R_.EXPORTING_PACKAGE_MARKER_OTHER_KEYS,pathOfPackageMarker:s};else{let _=en(s);if(dLt(t.namedDefinitionFiles).some(y=>y!==s&&y.startsWith(_)))d[s]={type:R_.EXPORT_PACKAGE_HAS_DEFINITIONS,pathToPackage:_};else{let y=await NOh({dependencyName:typeof u.contents.export=="string"?u.contents.export:u.contents.export.dependency,dependenciesConfiguration:e,context:r,rootApiFile:t.rootApiFile.contents,cliVersion:i,settings:n,loadAPIWorkspace:a});y.didSucceed?c[en(s)]={definition:y.definition,url:typeof u.contents.export=="object"?u.contents.export.url:void 0}:d[s]=y.failure}}}})),gm(d)>0?{didSucceed:!1,failures:d}:{didSucceed:!0,packageMarkers:o,importedDefinitions:c}}var UOh=ce(require("path"),1);var cGc={};Zt(cGc,{additionalProperties:()=>GeB,default:()=>xeB,definitions:()=>HeB,properties:()=>VeB,required:()=>WeB,type:()=>LeB});var LeB="object",VeB={docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},"default-url":{oneOf:[{type:"string"},{type:"null"}]},"default-environment":{oneOf:[{type:"string"},{type:"null"}]},environments:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/environments.EnvironmentSchema"}},{type:"null"}]},auth:{oneOf:[{$ref:"#/definitions/auth.ApiAuthSchema"},{type:"null"}]},"auth-schemes":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/auth.AuthSchemeDeclarationSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},name:{type:"string"},imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},"error-discrimination":{oneOf:[{$ref:"#/definitions/file.ErrorDiscriminationSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},errors:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"idempotency-headers":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},variables:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/variables.VariableDeclarationSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"null"}]},product:{oneOf:[{$ref:"#/definitions/products.ProductDeclarationSchema"},{type:"null"}]},version:{oneOf:[{$ref:"#/definitions/versioning.VersionDeclarationSchema"},{type:"null"}]}},WeB=["name"],GeB=!1,HeB={"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.EndpointSecuritySchemaDetails":{type:"object",additionalProperties:!1},"auth.EndpointSecuritySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"endpoint-security":{$ref:"#/definitions/auth.EndpointSecuritySchemaDetails"}},required:["endpoint-security"],additionalProperties:!1},"auth.ApiAuthSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.AuthSchemeReferenceSchema"},{$ref:"#/definitions/auth.AnyAuthSchemesSchema"},{$ref:"#/definitions/auth.EndpointSecuritySchema"}]},"auth.AuthScope":{type:"string"},"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:{$ref:"#/definitions/auth.AuthScope"}},{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.TokenBearerAuthSchema":{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.InferredAuthenticatedRequestHeader":{type:"object",properties:{"response-property":{type:"string"},"header-name":{type:"string"},"value-prefix":{oneOf:[{type:"string"},{type:"null"}]}},required:["response-property","header-name"],additionalProperties:!1},"auth.InferredGetTokenEndpointSchemaObject":{type:"object",properties:{endpoint:{type:"string"},"expiry-response-property":{oneOf:[{type:"string"},{type:"null"}]},"authenticated-request-headers":{oneOf:[{type:"array",items:{$ref:"#/definitions/auth.InferredAuthenticatedRequestHeader"}},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.InferredGetTokenEndpointSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.InferredGetTokenEndpointSchemaObject"}]},"auth.InferredBearerAuthSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"bearer"},"get-token":{$ref:"#/definitions/auth.InferredGetTokenEndpointSchema"}},required:["scheme","get-token"],additionalProperties:!1},"auth.BearerAuthSchemeSchema":{anyOf:[{$ref:"#/definitions/auth.TokenBearerAuthSchema"},{$ref:"#/definitions/auth.InferredBearerAuthSchema"}]},"auth.AuthSchemeDeclarationSchema":{anyOf:[{$ref:"#/definitions/auth.OAuthSchemeSchema"},{$ref:"#/definitions/auth.HeaderAuthSchemeSchema"},{$ref:"#/definitions/auth.BasicAuthSchemeSchema"},{$ref:"#/definitions/auth.BearerAuthSchemeSchema"}]},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"file.PropertyBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"property"},"property-name":{type:"string"}},required:["strategy","property-name"],additionalProperties:!1},"file.StatusCodeBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"status-code"}},required:["strategy"],additionalProperties:!1},"file.ErrorDiscriminationSchema":{anyOf:[{$ref:"#/definitions/file.PropertyBasedErrorDiscrimination"},{$ref:"#/definitions/file.StatusCodeBasedErrorDiscrimination"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"variables.VariableDeclarationDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"variables.VariableDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/variables.VariableDeclarationDetailed"}]},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"}]},"versioning.VersionValueDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionValue":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionValueDetailed"}]},"versioning.VersionDeclarationHeaderObjectSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionDeclarationHeaderSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionDeclarationHeaderObjectSchema"}]},"versioning.VersionDeclarationSchema":{type:"object",properties:{default:{oneOf:[{type:"string"},{type:"null"}]},values:{type:"array",items:{$ref:"#/definitions/versioning.VersionValue"}},header:{$ref:"#/definitions/versioning.VersionDeclarationHeaderSchema"}},required:["values","header"],additionalProperties:!1},"products.ProductValueDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},versions:{oneOf:[{$ref:"#/definitions/versioning.VersionDeclarationSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"products.ProductValue":{anyOf:[{type:"string"},{$ref:"#/definitions/products.ProductValueDetailed"}]},"products.ProductDeclarationHeaderObjectSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"products.ProductDeclarationHeaderSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/products.ProductDeclarationHeaderObjectSchema"}]},"products.ProductDeclarationSchema":{type:"object",properties:{default:{oneOf:[{type:"string"},{type:"null"}]},values:{type:"array",items:{$ref:"#/definitions/products.ProductValue"}},header:{$ref:"#/definitions/products.ProductDeclarationHeaderSchema"}},required:["values","header"],additionalProperties:!1}},xeB={type:LeB,properties:VeB,required:WeB,additionalProperties:GeB,definitions:HeB};var lGc={};Zt(lGc,{additionalProperties:()=>$eB,default:()=>XeB,definitions:()=>YeB,properties:()=>JeB,type:()=>KeB});var KeB="object",JeB={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"}]}},$eB=!1,YeB={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"}]},"types.ObjectPropertyAccess":{type:"string",enum:["read-only","write-only"]},"types.ObjectPropertyWithAccessSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},access:{oneOf:[{$ref:"#/definitions/types.ObjectPropertyAccess"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.ObjectPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectPropertyWithAccessSchema"}]},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE","HEAD"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"auth.AuthScope":{type:"string"},"service.HttpEndpointSecurityItem":{type:"object",additionalProperties:{type:"array",items:{$ref:"#/definitions/auth.AuthScope"}}},"service.HttpEndpointSecurity":{type:"array",items:{$ref:"#/definitions/service.HttpEndpointSecurityItem"}},"service.HttpEndpointAuth":{anyOf:[{type:"boolean"},{$ref:"#/definitions/service.HttpEndpointSecurity"}]},"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.RetriesDisabledSchema":{type:"object",properties:{disabled:{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"service.RetriesConfiguration":{anyOf:[{$ref:"#/definitions/service.RetriesDisabledSchema"}]},"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:[{$ref:"#/definitions/service.HttpEndpointAuth"},{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"}]},retries:{oneOf:[{$ref:"#/definitions/service.RetriesConfiguration"},{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"},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},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"}]},"method-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}},XeB={type:KeB,properties:JeB,additionalProperties:$eB,definitions:YeB};var fGc={};Zt(fGc,{additionalProperties:()=>etB,default:()=>rtB,definitions:()=>ttB,properties:()=>keB,type:()=>ZeB});var ZeB="object",keB={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"}]}},etB=!1,ttB={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"}]},"types.ObjectPropertyAccess":{type:"string",enum:["read-only","write-only"]},"types.ObjectPropertyWithAccessSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},access:{oneOf:[{$ref:"#/definitions/types.ObjectPropertyAccess"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.ObjectPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectPropertyWithAccessSchema"}]},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE","HEAD"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"auth.AuthScope":{type:"string"},"service.HttpEndpointSecurityItem":{type:"object",additionalProperties:{type:"array",items:{$ref:"#/definitions/auth.AuthScope"}}},"service.HttpEndpointSecurity":{type:"array",items:{$ref:"#/definitions/service.HttpEndpointSecurityItem"}},"service.HttpEndpointAuth":{anyOf:[{type:"boolean"},{$ref:"#/definitions/service.HttpEndpointSecurity"}]},"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.RetriesDisabledSchema":{type:"object",properties:{disabled:{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"service.RetriesConfiguration":{anyOf:[{$ref:"#/definitions/service.RetriesDisabledSchema"}]},"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:[{$ref:"#/definitions/service.HttpEndpointAuth"},{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"}]},retries:{oneOf:[{$ref:"#/definitions/service.RetriesConfiguration"},{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"},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},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"}]},"method-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"}]}},rtB={type:ZeB,properties:keB,additionalProperties:etB,definitions:ttB};function LOh({files:e,absolutePathToDefinition:t}){let r,i={},n={},a={};for(let[o,c]of fI(e)){let d=c.contents,s=u=>{a[o]={type:R_.JSONSCHEMA_VALIDATION,error:u}};if(o===dB){let u=bLt(d,cGc);if(u.success){let f=TB.serialization.RootApiFileSchema.parseOrThrow(d);r={defaultUrl:f["default-url"],contents:f,rawContents:c.rawContents}}else s(u)}else if(UOh.default.basename(o)===Db){let u=bLt(d,fGc);if(u.success){let f=TB.serialization.PackageMarkerFileSchema.parseOrThrow(d);n[o]={defaultUrl:typeof f.export=="object"?f.export.url:void 0,contents:f,rawContents:c.rawContents}}else s(u)}else{let u=bLt(d,lGc);if(u.success){let f=TB.serialization.DefinitionFileSchema.parseOrThrow(d);i[o]={defaultUrl:void 0,contents:f,rawContents:c.rawContents,absoluteFilePath:It(t,o)}}else s(u)}}return r==null?{didSucceed:!1,failures:{[Xe.of(dB)]:{type:R_.FILE_MISSING},...a}}:Object.keys(a).length>0?{didSucceed:!1,failures:a}:{didSucceed:!0,namedDefinitionFiles:i,rootApiFile:r,packageMarkers:n}}var SEe=class extends M3t{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,VOh.default)(r??{}),n=this.fernWorkspaces[i];if(n==null){let a=t||this.context,o=It(this.absoluteFilePath,Xe.of(Pq)),c=await Jrc({absolutePathToWorkspace:this.absoluteFilePath,context:a}),d=await Ibh(o,"{yml,yaml}"),s=await Cbh(d);if(!s.didSucceed)return lyu(s.failures,a.logger),a.failAndThrow();let u=LOh({files:s.files,absolutePathToDefinition:o});if(!u.didSucceed)return lyu(u.failures,a.logger),a.failAndThrow();let f=await QOh({dependenciesConfiguration:c,structuralValidationResult:u,context:a,cliVersion:this.cliVersion,settings:r,loadAPIWorkspace:this.loadAPIWorkspace});if(!f.didSucceed)return lyu(f.failures,a.logger),a.failAndThrow();let p={absoluteFilePath:o,rootApiFile:u.rootApiFile,namedDefinitionFiles:u.namedDefinitionFiles,packageMarkers:f.packageMarkers,importedDefinitions:f.importedDefinitions};r?.auth!=null&&(p={...p,rootApiFile:{...p.rootApiFile,contents:{...p.rootApiFile.contents,auth:r?.auth}}}),n=new B$({absoluteFilePath:this.absoluteFilePath,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:c,workspaceName:this.workspaceName,definition:p,cliVersion:this.cliVersion,sources:[]}),this.fernWorkspaces[i]=n}return n}getAbsoluteFilePaths(){return[this.absoluteFilePath]}};var vmh=require("fs/promises");var pmh=ce(dmh(),1);async function qxa(e){return(await(0,pmh.convertObj)(e,{})).openapi}var hmh=require("fs/promises");var _mh=require("fs/promises");async function Uoa({absoluteFilePathToOverrides:e,data:t,context:r,allowNullKeys:i}){let n=null;try{let a=(await(0,_mh.readFile)(e,"utf8")).toString();try{n=JSON.parse(a)}catch{n=Di.load(a,{json:!0})}}catch{return r.failAndThrow(`Failed to read overrides from file ${e}`)}return ZZs({data:t,overrides:n,allowNullKeys:i})}async function TGc({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let i=(await(0,hmh.readFile)(t)).toString(),n=await Di.load(i);return r!=null?await Uoa({absoluteFilePathToOverrides:r,context:e,data:n}):n}var bmh=require("fs/promises");var Rxa=ce(Nhu(),1);var ymh=ce(Nhu(),1),RGc=ce(require("path"),1),Txa=class extends ymh.BaseResolver{absolutePathToOpenAPIOverrides;constructor(t){super(),this.absolutePathToOpenAPIOverrides=t}resolveExternalRef(t,r){let i=super.resolveExternalRef(t,r);return i.startsWith("http://")||i.startsWith("https://")||mLt(Sr.of(i))?i:this.absolutePathToOpenAPIOverrides!=null?RGc.default.resolve(RGc.default.dirname(this.absolutePathToOpenAPIOverrides),r):i}};async function zGc({absolutePathToOpenAPI:e,absolutePathToOpenAPIOverrides:t,parsed:r}){return(r!=null?await(0,Rxa.bundle)({...Fhu,doc:{source:new Rxa.Source(e,"<openapi>"),parsed:r},externalRefResolver:new Txa(t)}):await(0,Rxa.bundle)({...Fhu,ref:e,externalRefResolver:new Txa(t)})).bundle.parsed}function HrB(e,t){if(t.includes(e))return e;for(let r of t){let i=r.replace(/\{[^}]+\}/g,"([^/]+)");if(new RegExp(`^${i}$`).test(e))return r}}var xrB=["examples","example",Hi.EXAMPLES,G4.REDOCLY_CODE_SAMPLES_CAMEL,G4.REDOCLY_CODE_SAMPLES_KEBAB];async function zxa({context:e,absolutePathToOpenAPI:t,absolutePathToOpenAPIOverrides:r}){let i=await zGc({absolutePathToOpenAPI:t}),n;r!=null?n=r:typeof i=="object"&&i[Hi.OPENAPI_OVERIDES_FILEPATH]!=null&&(n=It(en(t),Xe.of(i[Hi.OPENAPI_OVERIDES_FILEPATH])));let a=i;n!=null&&(a=await Uoa({absoluteFilePathToOverrides:n,context:e,data:a,allowNullKeys:xrB}));let o=It(en(t),Xe.of("ai_examples_override.yml"));try{let c=await(0,bmh.readFile)(o,"utf-8"),d=Di.load(c);if(d?.paths&&a.paths){for(let[s,u]of Object.entries(d.paths))if(u&&typeof u=="object")for(let[f,p]of Object.entries(u)){let _=f.toLowerCase(),h=a.paths[s];if(!h&&a.paths){let y=HrB(s,Object.keys(a.paths));y&&(h=a.paths[y],e.logger.debug(`Matched override path "${s}" to OpenAPI path "${y}" using pattern matching`))}if(h&&typeof h=="object"){let b=h[_];if(b&&typeof b=="object"){let v=b;!v["x-fern-examples"]&&p["x-fern-examples"]&&(v["x-fern-examples"]=p["x-fern-examples"],e.logger.debug(`Added AI examples for ${f.toUpperCase()} ${s} from override file`))}}}}e.logger.debug(`Processed AI examples from ${o}`)}catch{}return n!=null||a!==i?await zGc({absolutePathToOpenAPI:t,absolutePathToOpenAPIOverrides:r,parsed:a}):a}var J3t=class{absoluteFilePath;constructor(t){this.absoluteFilePath=t}async loadDocuments({context:t,specs:r}){let i=[];for(let n of r)try{let a=(await(0,vmh.readFile)(n.absoluteFilepath)).toString(),o=S_(this.absoluteFilePath,n.source.file);n.source.relativePathToDependency!=null&&(o=It(n.source.relativePathToDependency,o));let c=n.source.type==="protobuf"?k8.protobuf({file:o}):k8.openapi({file:o});if(a.includes("openapi")||a.includes("swagger"))try{let d=await zxa({absolutePathToOpenAPI:n.absoluteFilepath,context:t,absolutePathToOpenAPIOverrides:n.absoluteFilepathToOverrides});if(c6c(d)){i.push({type:"openapi",value:d,source:c,namespace:n.namespace,settings:lEe({options:n.settings})});continue}else if(W7a(d)){(!d.schemes||d.schemes.length===0)&&(d.schemes=["https"]);let s=await qxa(d);i.push({type:"openapi",value:s,source:c,namespace:n.namespace,settings:lEe({options:n.settings})});continue}}catch(d){t.logger.debug(`Failed to parse OpenAPI document at ${n.absoluteFilepath}: ${d}. Skipping...`);continue}if(a.includes("asyncapi"))try{let d=await TGc({context:t,absoluteFilePath:n.absoluteFilepath,absoluteFilePathToOverrides:n.absoluteFilepathToOverrides});i.push({type:"asyncapi",value:d,source:c,namespace:n.namespace,settings:lEe({options:n.settings})});continue}catch(d){t.logger.error(`Failed to parse AsyncAPI document at ${n.absoluteFilepath}: ${d}. Skipping...`);continue}if(a.includes("openrpc"))try{let d=await TGc({context:t,absoluteFilePath:n.absoluteFilepath,absoluteFilePathToOverrides:n.absoluteFilepathToOverrides});i.push({type:"asyncapi",value:d,source:c,namespace:n.namespace,settings:lEe({options:n.settings})});continue}catch(d){t.logger.error(`Failed to parse OpenRPC document at ${n.absoluteFilepath}: ${d}. Skipping...`);continue}t.logger.warn(`${n.absoluteFilepath} is not a valid OpenAPI, AsyncAPI, or OpenRPC file. Skipping...`)}catch(a){t.logger.error(`Failed to read or process file ${n.absoluteFilepath}: ${a}. Skipping...`);continue}return i}};var KrB=zt.object({type:zt.string(),channelId:zt.string().optional(),messageId:zt.string(),value:zt.any()}),JrB=zt.object({summary:zt.string().optional(),description:zt.string().optional(),"query-parameters":zt.record(zt.string()).optional(),headers:zt.record(zt.string()).optional(),messages:zt.array(KrB)}),gmh=zt.array(JrB);var qbu=class extends el{channel;baseDir;key="x-fern-examples";constructor({breadcrumbs:t,channel:r,context:i,baseDir:n}){super({breadcrumbs:t??[],context:i}),this.channel=r,this.baseDir=n}convert(){let t=this.getExtensionValue(this.channel);if(t==null)return;let r=gmh.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-examples extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data.map(i=>({summary:i.summary,description:i.description,queryParameters:i["query-parameters"],headers:i.headers,messages:i.messages.map(n=>({type:n.type,channelId:n.channelId,messageId:n.messageId,value:n.value}))}))}};var Loa=class extends Ta{channel;channelPath;inlinedTypes={};websocketGroup;constructor({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a}){super({context:t,breadcrumbs:r}),this.websocketGroup=i,this.channel=n,this.channelPath=a}convertExamples({fullPath:t,baseUrl:r,asyncApiVersion:i}){let a=new qbu({context:this.context,breadcrumbs:this.breadcrumbs,channel:this.channel,baseDir:this.context.documentBaseDir}).convert();return a==null?{}:Object.fromEntries(a.map((o,c)=>[c.toString(),{channel:{method:"GET",path:t},baseUrl:t,environment:r,auth:void 0,pathParameters:{},queryParameters:o.queryParameters,headers:o.headers,messages:o.messages.map(d=>({type:i==="v2"?d.type:d.messageId,body:d.value}))}]))}transformToValidPath(t){return t.startsWith("/")?t:"/"+t}};var VJi=class extends bA.AbstractConverters.AbstractParameterConverter{parameterNamePrefix;constructor({context:t,breadcrumbs:r,parameter:i,parameterNamePrefix:n}){super({context:t,breadcrumbs:r,parameter:i}),this.parameterNamePrefix=n}convert(){let t,r={},n=new aR.FernOptionalExtension({breadcrumbs:this.breadcrumbs,parameter:this.parameter,context:this.context}).convert()??this.parameter.required===!1,a=this.parameter.schema??{...this.parameter,type:"string",enum:this.parameter.enum,default:this.parameter.default,example:this.parameter.example??this.parameter.name,examples:Object.values(this.parameter.examples??{}),deprecated:this.parameter.deprecated,required:void 0},c=new bA.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaIdOverride:this.parameterNamePrefix?`${this.parameterNamePrefix}_${this.parameter.name}`:this.parameter.name,schemaOrReference:a,wrapAsOptional:n}).convert();return c!=null&&(t=c.type,r=c.inlinedTypes??{}),this.convertToOutput({schema:a,typeReference:t,inlinedTypes:r})}};var Tbu=class extends el{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 Voa=class extends el{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 Rbu=class extends Loa{inlinedTypes={};constructor({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a}){super({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a})}convert(){let t=[],r=[],i=[],a=new Voa({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert()??this.websocketGroup?.join(".");this.channel.parameters&&this.convertPathParameters({context:this.context,pathParameters:t}),this.channel.bindings?.ws!=null&&(this.convertHeaders({context:this.context,headers:i}),this.convertBindingQueryParameters({context:this.context,queryParameters:r}));let o;this.channel.subscribe!=null&&(o=this.convertMessage({context:this.context,operation:this.channel.subscribe,origin:"server"}));let c;this.channel.publish!=null&&(c=this.convertMessage({context:this.context,operation:this.channel.publish,origin:"client"}));let d=[];o!=null&&d.push(o),c!=null&&d.push(c);let u=new Tbu({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert(),f=this.transformToValidPath(u??this.channelPath),p=this.channel.servers?.[0]??Object.keys(this.context.spec.servers??{})[0],_=iM(f),h=Xo(this.channelPath),y=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[];return{channel:{name:this.context.casingsGenerator.generateName(h),displayName:a,baseUrl:p,path:_,auth:!1,headers:i,queryParameters:r,pathParameters:t,messages:d,availability:this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({fullPath:f,baseUrl:p,asyncApiVersion:"v2"})}},audiences:y,inlinedTypes:this.inlinedTypes}}convertMessage({context:t,operation:r,origin:i}){let n,a=i==="server"?"subscribe":"publish",o=[...this.breadcrumbs,a],c=t.resolveMaybeReference({schemaOrReference:r.message,breadcrumbs:o});c!=null&&(r.message=c);let d=oln(Xo(`${this.channelPath}_${a}`)).replace(/ /g,"");if("oneOf"in r.message){let u=new bA.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:o,schemaOrReference:r.message,schemaIdOverride:d}).convert();u!=null&&u.schema!=null&&(n=u.schema,this.inlinedTypes={...this.inlinedTypes,...u.inlinedTypes})}else if(t.isMessageWithPayload(r.message)){let s=t.resolveMaybeReference({schemaOrReference:r.message.payload,breadcrumbs:o});if(s!=null){let f=new bA.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:o,schemaOrReference:s,schemaIdOverride:d}).convert();f!=null&&f.schema!=null&&(n=f.schema,this.inlinedTypes={...this.inlinedTypes,...f.inlinedTypes})}}if(n!=null){let s=n,u=ri.named({fernFilepath:t.createFernFilepath(),name:s.typeDeclaration.name.name,typeId:s.typeDeclaration.name.typeId,displayName:void 0,default:void 0,inline:!1}),f=N4.reference({bodyType:u,docs:r.description}),p=i==="server"?"subscribe":"publish";return{type:p,displayName:p,origin:i,body:f,availability:t.getAvailability({node:r,breadcrumbs:this.breadcrumbs}),docs:r.description,methodName:void 0}}}convertPathParameters({context:t,pathParameters:r}){for(let[i,n]of Object.entries(this.channel.parameters??{})){let a=t.resolveMaybeReference({schemaOrReference:n,breadcrumbs:this.breadcrumbs});if(a==null)continue;let c=new VJi({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...a,name:i,in:"path",description:a.description,required:a.required??!0}}).convert();c!=null&&(this.inlinedTypes={...this.inlinedTypes,...c.inlinedTypes},c.type==="path"&&r.push(c.parameter))}}convertHeaders({context:t,headers:r}){if(this.channel.bindings?.ws?.headers!=null){let i=this.channel.bindings.ws.headers.required??[];for(let[n,a]of Object.entries(this.channel.bindings.ws.headers.properties??{})){let o=t.resolveMaybeReference({schemaOrReference:a,breadcrumbs:[...this.breadcrumbs,n]});if(o==null)continue;let d=new VJi({context:this.context,breadcrumbs:[...this.breadcrumbs,n],parameter:{name:n,in:"header",required:i.includes(n),schema:o,description:"description"in o?o.description:void 0}}).convert();d!=null&&d.type==="header"&&(this.inlinedTypes={...this.inlinedTypes,...d.inlinedTypes},r.push(d.parameter))}}}convertBindingQueryParameters({context:t,queryParameters:r}){if(this.channel.bindings?.ws?.query!=null){let i=this.channel.bindings.ws.query.required??[];for(let[n,a]of Object.entries(this.channel.bindings.ws.query.properties??{})){let o=t.resolveMaybeReference({schemaOrReference:a,breadcrumbs:[...this.breadcrumbs,n]});if(o==null)continue;let d=new VJi({context:this.context,breadcrumbs:[...this.breadcrumbs,n],parameter:{name:n,in:"query",required:i.includes(n),schema:o,description:"description"in o?o.description:void 0,deprecated:o.deprecated??!1}}).convert();d!=null&&d.type==="query"&&(this.inlinedTypes={...this.inlinedTypes,...d.inlinedTypes},r.push(d.parameter))}}}};var Woa=class extends Ta{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:tM.singleBaseUrl({environments:t})}}constructServerUrl(t,r){return r.includes("://")?r:`${t}://${r}`}};var zbu=class extends Woa{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 NGc="$message.",Omh="#/channels/",Amh="#/servers/",Nbu=class extends Loa{operations;inlinedTypes={};constructor({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a,operations:o}){super({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a}),this.operations=o}convert(){let t=[],r=[],i=[],a=new Voa({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert()??this.websocketGroup?.join(".")??this.channelPath;this.channel.parameters&&this.convertChannelParameters({pathParameters:t,queryParameters:r,headers:i,channelPath:this.channelPath});let o=Object.entries(this.operations).reduce((p,[_,h])=>{try{this.getChannelPathFromOperation(h)===this.channelPath&&(p[_]=h)}catch{}return p},{}),c=[];for(let[p,_]of Object.entries(o))for(let h of _.messages){let y=this.context.convertReferenceToTypeReference({reference:h});if(y.ok){let b=N4.reference({bodyType:y.reference,docs:_.description});c.push({type:p,displayName:p,origin:_.action==="send"?"client":"server",body:b,availability:this.context.getAvailability({node:_,breadcrumbs:this.breadcrumbs}),docs:_.description,methodName:void 0})}}let d=this.resolveChannelServersFromReference(this.channel.servers??[])??Object.keys(this.context.spec.servers??{})[0],s=this.transformToValidPath(this.channel.address??this.channelPath),u=iM(s),f=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[];return{channel:{name:this.context.casingsGenerator.generateName(a),displayName:a,baseUrl:d,path:u,auth:!1,headers:i,queryParameters:r,pathParameters:t,messages:c,availability:this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({fullPath:s,baseUrl:d,asyncApiVersion:"v3"})}},audiences:f,inlinedTypes:this.inlinedTypes}}convertChannelParameters({pathParameters:t,queryParameters:r,headers:i,channelPath:n}){for(let a of Object.values(this.channel.parameters??{})){let o=this.context.resolveMaybeReference({schemaOrReference:a,breadcrumbs:[...this.breadcrumbs,"parameters"]});if(o==null)continue;let c=this.convertChannelParameterLocation(o.location);if(c==null)continue;let{type:d,parameterKey:s}=c,f=new VJi({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...o,name:s,in:d},parameterNamePrefix:this.channelPath}).convert();if(f!=null)switch(this.inlinedTypes={...this.inlinedTypes,...f.inlinedTypes},f.type){case"path":t.push(f.parameter);break;case"query":r.push(f.parameter);break;case"header":i.push(f.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(NGc)){this.context.errorCollector.collect({message:`Invalid location format: ${t}; expected ${NGc} prefix`,path:this.breadcrumbs});return}let n=r.substring(NGc.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(Amh)){this.context.errorCollector.collect({message:`Failed to resolve server name from server ref ${r.$ref}`,path:this.breadcrumbs});return}let i=r.$ref.substring(Amh.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(Omh))throw new Error(`Failed to resolve channel path from operation ${t.channel.$ref}`);return t.channel.$ref.substring(Omh.length)}};var Fbu=class extends Woa{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 Nxa=class extends O3t{constructor({context:t,breadcrumbs:r,audiences:i}){super({context:t,breadcrumbs:r,audiences:i})}async convert(){return this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.context.spec=await this.resolveAllExternalRefs({spec:this.context.spec}),this.isAsyncAPIV3(this.context)?this.convertChannelMessages():this.convertComponentMessages(),this.convertSchemas(),this.convertServers(),this.convertChannels(),this.finalizeIr()}isAsyncAPIV3(t){return parseFloat(t.spec.asyncapi)>=3}convertChannelMessages(){let t=this.context.spec;for(let[r,i]of Object.entries(t.channels??{}))for(let[n,a]of Object.entries(i.messages??{})){if(!this.context.isMessageWithPayload(a)&&!this.context.isReferenceObject(a))continue;let o=["channels",r,"messages",n],c=this.context.resolveMaybeReference({schemaOrReference:a,breadcrumbs:o});if(!this.context.isMessageWithPayload(c))continue;let d=this.context.resolveMaybeReference({schemaOrReference:c.payload,breadcrumbs:o});if(d==null)continue;let s=`${r}_${n}`;this.convertSchema({id:s,breadcrumbs:o,schema:d})}}convertComponentMessages(){for(let[t,r]of Object.entries(this.context.spec.components?.messages??{})){if(r.payload==null)continue;let i=["components","messages",t],n=this.context.resolveMaybeReference({schemaOrReference:r.payload,breadcrumbs:i});n!=null&&this.convertSchema({id:t,breadcrumbs:i,schema:n})}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{}))this.convertSchema({id:t,breadcrumbs:["components","schemas",t],schema:r})}convertSchema({id:t,breadcrumbs:r,schema:i}){let a=new bA.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:r,schema:i}).convert();a!=null&&this.addSchemaOutputToIr(t,a)}convertServers(){let t;if(this.isAsyncAPIV3(this.context)){let r=this.context.spec.servers;t=new Fbu({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}else{let r=this.context.spec.servers;t=new zbu({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}this.addEnvironmentsToIr({environmentConfig:t})}convertChannels(){for(let[t,r]of Object.entries(this.context.spec.channels??{})){let n=new aR.SdkGroupNameExtension({breadcrumbs:["channels",t],operation:r,context:this.context}).convert()?.groups,a;if(this.isAsyncAPIV3(this.context)){let c=this.context.spec.operations??{};a=new Nbu({context:this.context,breadcrumbs:["channels",t],websocketGroup:n,channel:r,channelPath:t,operations:c}).convert()}else a=new Rbu({context:this.context,breadcrumbs:["channels",t],websocketGroup:n,channel:r,channelPath:t}).convert();a!=null&&(this.addWebsocketChannelToIr({websocketChannel:a.channel,channelPath:t,audiences:a.audiences,websocketGroup:n}),this.addTypesToIr(a.inlinedTypes))}}};var Fxa=class extends VI{isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}isMessageWithPayload(t){return t!=null&&typeof t=="object"&&"payload"in t}getTypeIdFromMessageReference(t){let r=t.$ref.match(/\/messages\/(.+)$/);if(!(!r||!r[1]))return r[1]}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n}){let a,o=t.$ref.match(/^.*\/schemas\/(.+)$/),c=t.$ref.match(/^.*\/channels\/([^/]+)\/messages\/(.+)$/),d=t.$ref.match(/^.*\/messages\/(.+)$/);if(o&&o[1])return a=o[1],this.convertSchemaReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a});if(c&&c[2]){let s=c[1],u=c[2];return a=`${s}_${u}`,this.convertV3MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a})}else return d&&d[1]?(a=d[1],this.convertV2MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a})):{ok:!1}}convertSchemaReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a}){let o=this.resolveReference({reference:t,breadcrumbs:r});if(!o.resolved)return{ok:!1};let c;return n==="reference_identifier"?c=i??o.value.title:(n==="discriminator_key"||n==="schema_identifier")&&(c=o.value.title??i),{ok:!0,reference:ri.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(a),typeId:a,displayName:c,default:void 0,inline:!1})}}convertV3MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a}){let o=this.resolveReference({reference:t,breadcrumbs:r});if(!o.resolved)return{ok:!1};let c;return n==="reference_identifier"?c=i??o.value.name:(n==="discriminator_key"||n==="schema_identifier")&&(c=o.value.name??i),{ok:!0,reference:ri.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(a),typeId:a,displayName:c,default:void 0,inline:!1})}}convertV2MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a}){let o=this.resolveReference({reference:t,breadcrumbs:r});if(!o.resolved)return{ok:!1};let c;return n==="reference_identifier"?c=i??o.value.messageId??o.value.name:(n==="discriminator_key"||n==="schema_identifier")&&(c=o.value.messageId??o.value.name??i),{ok:!0,reference:ri.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(a),typeId:a,displayName:c,default:void 0,inline:!1})}}};var Mmh=ce(Qbu(),1);var Ubu=class extends el{document;key="x-fern-base-path";constructor({breadcrumbs:t,document:r,context:i}){super({breadcrumbs:t,context:i}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(typeof t!="string"){this.context.errorCollector.collect({message:"Received unexpected non-string value for x-fern-base-path",path:this.breadcrumbs});return}return t}}};var Lbu=class extends el{document;key="x-fern-global-headers";constructor({breadcrumbs:t,document:r,context:i}){super({breadcrumbs:t,context:i}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(!Array.isArray(t)){this.context.errorCollector.collect({message:"Received unexpected non-array value for x-fern-global-headers",path:this.breadcrumbs});return}return t}}};function mmh({globalHeaders:e,context:t}){return e.map(r=>({name:t.casingsGenerator.generateNameAndWireValue({name:r.name??"",wireValue:r.header}),valueType:r.optional?Ta.OPTIONAL_STRING:Ta.STRING,env:r.env,v2Examples:r.optional?void 0:XrB({header:r,context:t}),availability:void 0,docs:void 0}))}function XrB({header:e,context:t}){let r=new J8({breadcrumbs:[],context:t,schema:{type:"string"},example:e.header}),{validExample:i}=r.convert();return{userSpecifiedExamples:{},autogeneratedExamples:{globalHeaderExample:i}}}var Vbu=class extends bA.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r,parameter:i})}convert(){let t,r={};if(this.parameter.schema!=null){let i=this.context.convertBreadcrumbsToName([...this.breadcrumbs,this.parameter.name]),a=new bA.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,this.parameter.name,"schema"],schemaOrReference:this.parameter.schema,wrapAsOptional:this.parameter.required==null||!this.parameter.required,schemaIdOverride:i}).convert();a!=null&&(t=a.type,r=a.inlinedTypes??{})}return this.convertToOutput({schema:this.parameter.schema??{type:"string"},typeReference:t,inlinedTypes:r})}};var Wbu=class extends bA.AbstractConverters.AbstractMediaTypeObjectConverter{contentType;mediaType;description;required;schemaId;streamingExtension;queryParameters;constructor({context:t,breadcrumbs:r,contentType:i,mediaType:n,description:a,required:o,group:c,method:d,streamingExtension:s,queryParameters:u}){super({context:t,breadcrumbs:r,group:c,method:d}),this.contentType=i,this.mediaType=n,this.description=a,this.required=o,this.schemaId=[...this.group,this.method,"Request"].join("_"),this.streamingExtension=s,this.queryParameters=u??[]}convert(){return this.streamingExtension?.type=="streamCondition"?this.convertStreamConditionRequestBody():this.convertNonStreamConditionRequestBody()}convertStreamConditionRequestBody(){if(this.isOrderedJsonOrFormContentType())return this.handleStreamConditionJsonOrFormContent({contentType:this.contentType})}convertNonStreamConditionRequestBody(){if(this.isOrderedJsonOrFormContentType())return this.handleJsonOrFormContent({contentType:this.contentType});if(zO.parse(this.contentType)?.isMultipart())return this.handleMultipartContent({contentType:this.contentType});if(this.isBinaryContentType())return this.handleBinaryContent({contentType:this.contentType})}isOrderedJsonOrFormContentType(){let t=zO.parse(this.contentType);return t?t.isJSON()||t.isURLEncoded()||t.isPlainText()||t.isCSV()||t.isHTML()||t.isXML()||t.isDNS()||t.isApplicationText():!1}isBinaryContentType(){let t=zO.parse(this.contentType);return t?t.isBinary():!1}handleJsonOrFormContent({contentType:t}){let r=this.mediaType;if(r==null)return;let i=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,contentType:t});if(i==null)return;let n=i.schema?.typeDeclaration.shape;return n?.type==="object"?this.hasBodyQueryParameterOverlap(n.properties)?{requestBody:yA.reference({contentType:t,docs:this.description,requestBodyType:i.type,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:i.inlinedTypes??{}}:{requestBody:yA.inlinedRequestBody({contentType:t,docs:this.description,name:this.context.casingsGenerator.generateName(this.schemaId),extendedProperties:n.extendedProperties,extends:n.extends,properties:n.properties,extraProperties:n.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:i.inlinedTypes})}:{requestBody:yA.reference({contentType:t,docs:this.description,requestBodyType:i.type,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:i.inlinedTypes??{}}}handleMultipartContent({contentType:t}){let r=this.mediaType;if(r==null||r.schema==null)return;let i=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,resolveSchema:!0,contentType:t});if(i==null)return;let n=i.schema?.typeDeclaration.shape;if(n?.type==="object")return{requestBody:yA.fileUpload({contentType:t,docs:this.description,name:this.context.casingsGenerator.generateName(this.schemaId),properties:n.properties.map(a=>{let o=r.encoding?.[a.name.wireValue];return this.convertRequestBodyProperty({property:a,contentType:t,encoding:o})}),v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:i.inlinedTypes}),examples:i.examples}}handleBinaryContent({contentType:t}){let r=this.mediaType;if(r==null)return;let i=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,contentType:t});return{requestBody:yA.bytes({contentType:t,isOptional:this.required===!1,docs:this.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:i?.inlinedTypes??{}}}convertRequestBodyProperty({property:t,contentType:r,encoding:i}){let{isFile:n,isOptional:a,isArray:o}=this.recursivelyCheckTypeReferenceIsFile({typeReference:t.valueType});return n?o?kq.file(m$.fileArray({key:t.name,isOptional:a,contentType:r,docs:t.docs})):kq.file(m$.file({key:t.name,isOptional:a,contentType:r,docs:t.docs})):kq.bodyProperty({...t,contentType:i?.contentType??r,style:krB({encoding:i}),name:t.name})}handleStreamConditionJsonOrFormContent({contentType:t}){if(this.streamingExtension?.type!=="streamCondition")return;let r=this.mediaType;if(r==null||r.schema==null)return;let i=this.context.resolveMaybeReference({schemaOrReference:r.schema,breadcrumbs:[...this.breadcrumbs,"content",t,"schema"]});if(i==null)return;let n=i.properties?.[this.streamingExtension.streamConditionProperty];if(n==null||this.context.isReferenceObject(n))return;let a=this.buildStreamConditionInlinedRequestBody({streamConditionProperty:n,resolvedMediaTypeSchema:i,isStreaming:!0,contentType:t,mediaTypeObject:r}),o=this.buildStreamConditionInlinedRequestBody({streamConditionProperty:n,resolvedMediaTypeSchema:i,isStreaming:!1,contentType:t,mediaTypeObject:r});if(!(a==null||o==null))return{requestBody:o.requestBody,streamRequestBody:a.requestBody,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:{...a.inlinedTypes,...o.inlinedTypes}})}}buildStreamConditionInlinedRequestBody({streamConditionProperty:t,resolvedMediaTypeSchema:r,isStreaming:i,contentType:n,mediaTypeObject:a}){if(this.streamingExtension==null||this.streamingExtension.type!=="streamCondition")return;let o={...r,properties:{...r.properties,[this.streamingExtension.streamConditionProperty]:{type:"boolean",const:i,...t}},required:[...r.required??[],this.streamingExtension.streamConditionProperty]},c={...a,schema:o},d=this.parseMediaTypeObject({mediaTypeObject:c,schemaId:this.schemaId,contentType:n});if(d==null)return;let s=d.schema?.typeDeclaration.shape;if(s?.type==="object")return{requestBody:yA.inlinedRequestBody({contentType:n,docs:void 0,name:this.context.casingsGenerator.generateName(i?`${this.schemaId}_streaming`:this.schemaId),extendedProperties:s.extendedProperties,extends:s.extends,properties:s.properties,extraProperties:s.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:c,exampleGenerationStrategy:"request"})}),inlinedTypes:d.inlinedTypes}}recursivelyCheckTypeReferenceIsFile({typeReference:t,isOptional:r,isArray:i}){return this.context.isList(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.list,isOptional:r,isArray:!0}):this.context.isOptional(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.optional,isOptional:!0,isArray:i}):this.context.isNullable(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.nullable,isOptional:r,isArray:i}):{isFile:this.context.isFile(t),isOptional:r??!1,isArray:i??!1}}hasBodyQueryParameterOverlap(t){if(this.queryParameters.length===0)return!1;let r=new Set(this.queryParameters.map(i=>i.name.wireValue.toLowerCase()));return t.some(i=>r.has(i.name.wireValue.toLowerCase()))}},ZrB={"application/json":"json"};function krB({encoding:e}){if(e){if(e.explode)return"exploded";if(e.style==="form")return"form";if(e.contentType)return ZrB[e.contentType]}}var eiB=/{([^}]+)}/g,tiB=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]),Goa=class extends Ta{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 N0.Get;case"post":return N0.Post;case"put":return N0.Put;case"delete":return N0.Delete;case"patch":return N0.Patch;case"head":return N0.Head;default:return}}convertParameters({breadcrumbs:t}){let r=[],i=[],n=[];if(!this.operation.parameters)return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:i,headers:n};for(let a of this.operation.parameters){let o=this.context.resolveMaybeReference({schemaOrReference:a,breadcrumbs:t});if(o==null)continue;let d=new Vbu({context:this.context,breadcrumbs:t,parameter:o}).convert();if(d!=null)switch(this.inlinedTypes={...this.inlinedTypes,...d.inlinedTypes},d.type){case"path":r.push(d.parameter);break;case"query":i.push(d.parameter);break;case"header":{let s=d.parameter.name.name.originalName,u=d.parameter.name.wireValue,f=!1,p=this.context.authOverrides?.["auth-schemes"];if(p!=null){for(let h of Object.values(p))if(aiB(h)&&h.header.toLowerCase()===u.toLowerCase()){f=!0;break}}let _=this.context.globalHeaderNames;if(_!=null){for(let h of _)if(h.toLowerCase()===u.toLowerCase()){f=!0;break}}!tiB.has(s.toLowerCase())&&!f&&n.push(d.parameter);break}}}return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:i,headers:n}}checkMissingPathParameters(t){let i=[...this.path.matchAll(eiB)].map(n=>n[1]).filter(n=>!t.some(a=>a.name.originalName===n));for(let n of i){if(n==null)continue;let a=`${n}_example`;t.push({name:this.context.casingsGenerator.generateName(n),valueType:Ta.STRING,docs:void 0,location:"ENDPOINT",variable:void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{[a]:this.generateStringParameterExample({example:n})}},explode:void 0})}}convertRequestBody({breadcrumbs:t,group:r,method:i,streamingExtension:n,queryParameters:a}){if(this.operation.requestBody==null)return;let o=this.context.resolveMaybeReference({schemaOrReference:this.operation.requestBody,breadcrumbs:t});if(o==null)return null;let c=[];for(let[d,s]of Object.entries(o.content)){let f=new Wbu({context:this.context,breadcrumbs:t,contentType:d,mediaType:s,description:o.description,required:o.required,group:r??[],method:i,streamingExtension:n,queryParameters:a}).convert();f!=null&&(this.inlinedTypes={...this.inlinedTypes,...f.inlinedTypes},c.push({requestBody:f.requestBody,streamRequestBody:f.streamRequestBody,examples:f.examples}))}return c}computeGroupNameAndLocationFromExtensions(){let r=new aR.SdkMethodNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.methodName,n=new aR.SdkGroupNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.groups??[];if(r!=null)return{group:n,method:r}}evaluateMethodNameFromOperation(){let t=this.operation.operationId;return t??(this.operation.summary!=null?Xo(this.operation.summary):Xo(`${this.method}_${this.path.split("/").join("_")}`))}computeGroupNameFromTagAndOperationId(){let t=this.operation.tags?.[0],r=this.evaluateMethodNameFromOperation();if(t==null)return{method:r};let i=Pmh(t),n=Pmh(r);return ST(i,n)?{method:t}:this.computeGroupAndMethodFromTokens({tag:t,tagTokens:i,methodName:r,methodNameTokens:n})}computeGroupAndMethodFromTokens({tag:t,tagTokens:r,methodName:i,methodNameTokens:n}){if(r.some((c,d)=>c!==n[d]))return{group:[t],method:i};let o=n.slice(r.length);return{group:[t],method:Xo(o.join("_"))}}generateStringParameterExample({example:t}){let r=new bA.ExampleConverter({breadcrumbs:this.breadcrumbs,context:this.context,schema:{type:"string"},example:t}),{validExample:i}=r.convert();return i}};function Pmh(e){let t=riB(e)?iiB(e):niB(e);return t=t.map(r=>r.toLowerCase()),t=lje(t),t}function riB(e){return/^[a-z]+(?:[A-Z][a-z]+)*$/.test(e)}function iiB(e){return e.split(/(?=[A-Z])/)}function niB(e){return e.split(/[^a-zA-Z0-9]+/)}function aiB(e){return e?.header!=null}var Hoa=class extends Goa{constructor({context:t,breadcrumbs:r,operation:i,method:n,path:a}){super({context:t,breadcrumbs:r,operation:i,method:n,path:a})}convert(){if(this.operation.requestBody==null){this.context.errorCollector.collect({message:"Skipping webhook because no request body present",path:this.breadcrumbs});return}let t=this.convertHttpMethod();if(t==null)return;if(t!=="POST"&&t!=="GET"){this.context.errorCollector.collect({message:"Skipping webhook because non-POST or GET method",path:this.breadcrumbs});return}let{group:r,method:i}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),n=[...this.breadcrumbs,"Payload"],{headers:a,queryParameters:o}=this.convertParameters({breadcrumbs:n}),c=this.convertRequestBody({breadcrumbs:n,group:r,method:i,streamingExtension:void 0,queryParameters:o});if(c==null)return;let d=c[0]?.requestBody;if(d==null)return;let s;if(d.type==="inlinedRequestBody")s=z4.inlinedPayload({name:d.name,extends:d.extends,properties:d.properties});else if(d.type==="reference")s=z4.reference({payloadType:d.requestBodyType,docs:d.docs});else return;let u=this.convertWebhookResponses();return{audiences:this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],group:r,webhook:{id:`${r?.join(".")??""}.${i}`,name:this.context.casingsGenerator.generateName(i),displayName:this.operation.summary,method:t,headers:a,payload:s,responses:u.length>0?u:void 0,examples:[],availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),docs:this.operation.description,v2Examples:{autogeneratedExamples:this.getWebhookV2ExamplesFromRequestBodyV2Examples(d.v2Examples?.autogeneratedExamples??{}),userSpecifiedExamples:this.getWebhookV2ExamplesFromRequestBodyV2Examples(d.v2Examples?.userSpecifiedExamples??{})}},inlinedTypes:this.inlinedTypes}}convertWebhookResponses(){let t=[];if(this.operation.responses==null)return t;for(let[r,i]of Object.entries(this.operation.responses)){let n=/^\d[Xx]{2}$/.test(r),a;if(n)a=parseInt(r.charAt(0))*100;else if(a=parseInt(r),isNaN(a))continue;let c=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:[...this.breadcrumbs,"responses",r]})?.description;t.push({statusCode:a,isWildcardStatusCode:n?!0:void 0,body:void 0,docs:c})}return t}getWebhookV2ExamplesFromRequestBodyV2Examples(t){return Object.fromEntries(Object.entries(t).map(([r,i])=>[r,{name:r,payload:i}]))}};var UGc=ce(Qbu(),1);var jmh=["get","post","put","delete","patch","head"];var Gbu=class extends el{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 oiB=zt.object({cursor:zt.string(),next_cursor:zt.string(),results:zt.string()}),uiB=zt.object({offset:zt.string(),results:zt.string(),step:zt.string().optional(),"has-next-page":zt.string().optional()}),FGc=zt.union([zt.boolean(),oiB,uiB]);var QGc="$request.",Hbu="$response.",xbu=class extends el{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=FGc.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=FGc.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:VI.maybeTrimPrefix(r.cursor,QGc),nextCursor:VI.maybeTrimPrefix(r.next_cursor,Hbu),results:VI.maybeTrimPrefix(r.results,Hbu)};let i=t;return{type:"offset",offset:VI.maybeTrimPrefix(i.offset,QGc),results:VI.maybeTrimPrefix(i.results,Hbu),step:i.step!=null?VI.maybeTrimPrefix(i.step,QGc):void 0,hasNextPage:i["has-next-page"]!=null?VI.maybeTrimPrefix(i["has-next-page"],Hbu):void 0}}};var siB="$request.",ciB=zt.object({"stream-condition":zt.string().optional(),format:zt.enum(["sse","json"]).optional(),"stream-description":zt.string().optional(),"response-stream":zt.any(),response:zt.any()}),liB=zt.union([zt.boolean(),ciB]),Kbu=class extends el{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=liB.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-streaming extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean")return r.data?{type:"stream",format:"json"}:void 0;if(r.data["stream-condition"]==null&&r.data.format!=null)return{type:"stream",format:r.data.format};if(r.data["stream-condition"]==null){this.context.errorCollector.collect({message:"Missing stream-condition property without specified format.",path:this.breadcrumbs});return}return{type:"streamCondition",format:r.data.format??"json",streamDescription:r.data["stream-description"],streamConditionProperty:VI.maybeTrimPrefix(r.data["stream-condition"],siB),responseStream:r.data["response-stream"],response:r.data.response}}};var Jbu=class extends el{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 Ybu=require("fs"),wmh=require("path");function fiB(e){return ll(e)&&typeof e.$ref=="string"}function diB(e,t){if(e!=null){if(typeof e=="string")return e;if(fiB(e)){let r=(0,wmh.resolve)(t??process.cwd(),e.$ref);if((0,Ybu.existsSync)(r))try{return(0,Ybu.readFileSync)(r,"utf-8")}catch{return}}}}var $bu=class extends el{operation;baseDir;key="x-codeSamples";constructor({context:t,breadcrumbs:r,operation:i,baseDir:n}){super({breadcrumbs:r,context:t}),this.operation=i,this.baseDir=n}convert(){let t=ll(this.operation)?this.operation:{},r=t["x-codeSamples"],i=t["x-code-samples"],n=Array.isArray(r)?r:[],a=Array.isArray(i)?i:[],o=[...n,...a];if(o.length===0)return;let c=[];for(let d of o){if(!ll(d))continue;let s=d,u=s.lang,f=s.label,p=s.source;if(typeof u!="string")continue;let _=diB(p,this.baseDir);_!=null&&c.push({name:typeof f=="string"?f:u,language:u,code:_,install:void 0,docs:void 0})}if(c.length!==0)return[{"code-samples":c}]}};var Zbu=require("fs"),Emh=require("path");function piB(e){return ll(e)&&typeof e.$ref=="string"}function _iB(e,t){if(e!=null){if(typeof e=="string")return e;if(piB(e)){let r=(0,Emh.resolve)(t??process.cwd(),e.$ref);if((0,Zbu.existsSync)(r))try{return(0,Zbu.readFileSync)(r,"utf-8")}catch{return}}}}function hiB(e,t){if(!Array.isArray(e))return[];let r=[];for(let i of e){if(!ll(i))continue;let a=_iB(i.code,t);a!=null&&r.push({...i,code:a})}return r}var Xbu=class extends el{operation;baseDir;key="x-fern-examples";constructor({context:t,breadcrumbs:r,operation:i,baseDir:n}){super({breadcrumbs:r,context:t}),this.operation=i,this.baseDir=n}convert(){let t=this.getExtensionValue(this.operation);return t==null?void 0:(Array.isArray(t)?t:[]).map(a=>{if(!ll(a))return a;let c=a["code-samples"];if(c!=null){let d=hiB(c,this.baseDir);return{...a,"code-samples":d}}return a}).filter(a=>{let o=TB.serialization.ExampleEndpointCallSchema.parse(a);return o.ok||this.context.errorCollector.collect({message:`Failed to parse x-fern-example in ${this.breadcrumbs.join(".")}`,path:this.breadcrumbs}),o.ok})}};var Qxa=class extends el{document;key="x-fern-explorer";constructor({breadcrumbs:t,document:r,context:i}){super({breadcrumbs:t,context:i}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-explorer",path:this.breadcrumbs});return}return t}}};var Uxa=class extends bA.AbstractConverters.AbstractMediaTypeObjectConverter{responseBody;statusCode;streamingExtension;constructor({context:t,breadcrumbs:r,responseBody:i,group:n,method:a,statusCode:o,streamingExtension:c}){super({context:t,breadcrumbs:r,group:n,method:a}),this.responseBody=i,this.statusCode=o,this.streamingExtension=c}convert(){return this.shouldConvertAsStreaming()?this.convertStreamingResponseBody():this.convertNonStreamingResponseBody()}convertStreamingResponseBody(){if(this.streamingExtension!=null){if(this.streamingExtension.type=="streamCondition"){let t=this.streamingExtension.responseStream,r=this.streamingExtension.response,i=[...this.group,this.method,"Response",this.statusCode].join("_"),n=`${i}_streaming`,a=this.parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:n}),o=this.parseMediaTypeSchemaOrReference({schemaOrReference:r,schemaId:i});return this.convertStreamConditionResponse({convertedStreamingSchema:a,convertedNonStreamingSchema:o})}if(this.streamingExtension.type==="stream"){let t=[...this.group,this.method,"Response",this.statusCode].join("_"),r=Object.keys(this.responseBody.content??{});for(let i of r){let n=this.responseBody.content?.[i];if(n==null)continue;let a=this.parseMediaTypeObject({mediaTypeObject:n,schemaId:t,contentType:this.streamingExtension.format});if(a!=null)return this.convertStreamingResponse({mediaTypeObject:n,convertedSchema:a})}}}}convertNonStreamingResponseBody(){let t=[...this.group,this.method,"Response",this.statusCode].join("_"),r=Object.keys(this.responseBody.content??{}).filter(a=>a.includes("json"));for(let a of r){let o=this.responseBody.content?.[a];if(o==null)continue;let c=this.parseMediaTypeObject({mediaTypeObject:o,schemaId:t,contentType:a});if(c!=null&&this.shouldReturnJsonResponse(a))return this.returnJsonResponse({mediaTypeObject:o,convertedSchema:c})}let i=Object.keys(this.responseBody.content??{}).filter(a=>!a.includes("json"));for(let a of i){let o=this.responseBody.content?.[a];if(o==null)continue;let c=this.parseMediaTypeObject({mediaTypeObject:o,schemaId:t,contentType:a});if(c!=null){if(this.isBinarySchema(c))return this.shouldReturnBytesResponse()?this.returnBytesResponse({mediaTypeObject:o}):this.returnFileDownloadResponse({mediaTypeObject:o});if(this.shouldReturnTextResponse(a))return this.returnTextResponse({mediaTypeObject:o})}}let n=parseInt(this.statusCode);if(!isNaN(n)&&n>=200&&n<300){let a={schema:{type:"object",description:"Empty response body"}},o=this.parseMediaTypeObject({mediaTypeObject:a,schemaId:t,contentType:"application/json",resolveSchema:!0});if(o!=null)return this.returnJsonResponse({mediaTypeObject:a,convertedSchema:o})}}convertStreamConditionResponse({convertedStreamingSchema:t,convertedNonStreamingSchema:r}){if(t==null||r==null)return;let i=this.responseBody.description;return this.streamingExtension?.type==="streamCondition"&&this.streamingExtension.streamDescription!=null&&(i=this.streamingExtension.streamDescription),{responseBody:dd.json(NI.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:r.schema?.typeDeclaration.v2Examples})),streamResponseBody:dd.streaming(qB.json({docs:i,payload:t.type,terminator:void 0,v2Examples:t.schema?.typeDeclaration.v2Examples})),inlinedTypes:{...t.inlinedTypes,...r.inlinedTypes}}}convertStreamingResponse({mediaTypeObject:t,convertedSchema:r}){if(this.streamingExtension==null)return;switch(this.streamingExtension.format){case"json":return{responseBody:dd.streaming(qB.json({docs:this.responseBody.description,payload:r.type,terminator:void 0,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples};case"sse":return{responseBody:dd.streaming(qB.sse({docs:this.responseBody.description,payload:r.type,terminator:void 0,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples};default:return}}returnJsonResponse({mediaTypeObject:t,convertedSchema:r}){return{responseBody:dd.json(NI.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples}}returnBytesResponse({mediaTypeObject:t}){return{responseBody:dd.bytes({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{}}}returnFileDownloadResponse({mediaTypeObject:t}){return{responseBody:dd.fileDownload({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{}}}returnTextResponse({mediaTypeObject:t}){return{responseBody:dd.text({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{}}}isBinarySchema(t){let r=t.type;switch(r.type){case"container":case"named":case"unknown":return!1;case"primitive":return r.primitive.v2==null?!1:r.primitive.v2.type==="string"&&r.primitive.v2.validation?.format==="binary";default:return!1}}shouldConvertAsStreaming(){return this.streamingExtension!=null}shouldReturnJsonResponse(t){return t.includes("json")}shouldReturnBytesResponse(){return this.context.settings.useBytesForBinaryResponse&&this.streamingExtension==null}shouldReturnTextResponse(t){return zO.parse(t)?.isText()??!1}};var kbu=class extends bA.AbstractConverters.AbstractMediaTypeObjectConverter{responseError;statusCode;methodName;isWildcardStatusCode;constructor({context:t,breadcrumbs:r,responseError:i,group:n,method:a,methodName:o,statusCode:c,isWildcardStatusCode:d}){super({context:t,breadcrumbs:r,group:n,method:a}),this.responseError=i,this.statusCode=c,this.methodName=o,this.isWildcardStatusCode=d}convert(){if(!this.responseError.content){let i=this.getErrorNameForStatusCode(this.statusCode,this.isWildcardStatusCode);if(i==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}let n=this.getErrorIdFromErrorName(i);return{error:{error:{name:this.context.casingsGenerator.generateName(n),fernFilepath:{allParts:[],packagePath:[],file:void 0},errorId:n},docs:this.responseError.description},errorType:ri.unknown(),displayName:i,statusCode:this.statusCode,isWildcardStatusCode:this.isWildcardStatusCode,inlinedTypes:{},examples:{},headers:this.convertResponseHeaders()}}let t=Object.keys(this.responseError.content).filter(i=>i.includes("json")),r=this.getErrorNameForStatusCode(this.statusCode,this.isWildcardStatusCode);if(r==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}for(let i of[...t]){let n=this.responseError.content?.[i];if(n==null)continue;let a=this.parseMediaTypeObject({mediaTypeObject:n,schemaId:Smh(`${this.methodName}Request${r}`),contentType:i});if(a==null)continue;let o=this.getErrorIdFromErrorName(r);if(a.schema!=null)return this.constructErrorConverterOutput({errorName:r,errorId:o,fernFilepath:a.schema.typeDeclaration.name.fernFilepath,convertedSchema:a});if(a.type.type==="named")return this.constructErrorConverterOutput({errorName:r,errorId:o,fernFilepath:a.type.fernFilepath,convertedSchema:a})}}constructErrorConverterOutput({errorName:t,errorId:r,fernFilepath:i,convertedSchema:n}){return{error:{error:{name:this.context.casingsGenerator.generateName(r),fernFilepath:i,errorId:r},docs:this.responseError.description},errorType:n.type,displayName:t,statusCode:this.statusCode,isWildcardStatusCode:this.isWildcardStatusCode,inlinedTypes:n.inlinedTypes,examples:n.examples,headers:this.convertResponseHeaders()}}getErrorNameForStatusCode(t,r){if(r){if(t===400)return"ClientRequestError";if(t===500)return"ServerError"}return Duu[t]}getErrorIdFromErrorName(t){return this.context.enableUniqueErrorsPerEndpoint?Smh(`${this.methodName}Request${t}`):t}convertResponseHeaders(){let t=[],r=this.responseError.headers;if(r==null)return t;for(let[i,n]of Object.entries(r)){let a=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:[...this.breadcrumbs,"headers",i]});if(a==null)continue;let o=a.schema,c=Ta.OPTIONAL_STRING;if(o!=null){let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:[...this.breadcrumbs,"headers",i,"schema"]});s!=null&&(s.type==="number"||s.type==="integer"?c=ri.primitive({v1:s.type==="integer"?"INTEGER":"DOUBLE",v2:s.type==="integer"?gn.integer({default:void 0,validation:void 0}):gn.double({default:void 0,validation:void 0})}):s.type==="boolean"&&(c=ri.primitive({v1:"BOOLEAN",v2:gn.boolean({default:void 0})})))}let d=this.convertHeaderExamples({header:a,headerName:i,schema:o});t.push({name:this.context.casingsGenerator.generateNameAndWireValue({name:i,wireValue:i}),docs:a.description,valueType:c,env:void 0,v2Examples:d,availability:void 0})}return t}convertHeaderExamples({header:t,headerName:r,schema:i}){let n={userSpecifiedExamples:{},autogeneratedExamples:{}},a=t.example,o=t.examples;for(let[c,d]of Object.entries(o??{})){let s=this.context.resolveExampleWithValue(d);s!=null&&(n.userSpecifiedExamples[c]=this.generateHeaderExample({schema:i,example:s}))}if(a!=null){let c=this.context.generateUniqueName({prefix:`${r}_example`,existingNames:Object.keys(n.userSpecifiedExamples)});n.userSpecifiedExamples[c]=this.generateHeaderExample({schema:i,example:a})}if(Object.keys(n.userSpecifiedExamples).length===0&&i!=null){let c=`${r}_example`;n.autogeneratedExamples[c]=this.generateHeaderExample({schema:i,example:void 0,ignoreErrors:!0})}return n}generateHeaderExample({schema:t,example:r,ignoreErrors:i}){if(t==null)return r;let n=new J8({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:r}),{validExample:a,errors:o}=n.convert();return i||o.forEach(c=>{this.context.errorCollector.collect({message:c.message,path:c.path})}),a}};function Smh(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1)}var evu=class e extends Goa{idempotent;idToAuthScheme;topLevelServers;streamingExtension;static AUTHORIZATION_HEADER="Authorization";constructor({context:t,breadcrumbs:r,operation:i,method:n,path:a,idempotent:o,idToAuthScheme:c,topLevelServers:d,streamingExtension:s}){super({context:t,breadcrumbs:r,operation:i,method:n,path:a}),this.idempotent=o,this.idToAuthScheme=c,this.topLevelServers=d,this.streamingExtension=s}convert(){let t=this.convertHttpMethod();if(t==null)return;let{group:r,method:i}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),n=this.getGroupDisplayName(r),{headers:a,pathParameters:o,queryParameters:c}=this.convertParameters({breadcrumbs:[...this.breadcrumbs,"parameters"]}),d=this.convertRequestBody({breadcrumbs:[...this.breadcrumbs,"requestBody"],group:r,method:i,streamingExtension:this.streamingExtension,queryParameters:c}),s=d?.[0]?.requestBody,u=d?.[0]?.streamRequestBody,f={requestBodies:d?.map(ee=>ee.requestBody)},p=this.convertResponseBody({breadcrumbs:[...this.breadcrumbs,"responses"],group:r,method:i,streamingExtension:this.streamingExtension}),_=p?.response,h=p?.streamResponse,y=p!=null?p.errors:[],b={},v=y.map(ee=>ee.error),O=iM(this.path),A=this.getEndpointBaseUrl(),g=this.getEndpointBaseUrls(),m=this.convertExamples({httpPath:O,httpMethod:t,baseUrl:A}),j=new Set(this.operation.security?.flatMap(ee=>Object.keys(ee))??[]),S=this.authSchemeToHeaders(Array.from(j));S.length>0&&a.push(...S);for(let ee of y){let me=ee.error,ve=ee.errorType,H=me.error.errorId,G=ee.examples;b[H]={name:me.error,displayName:ee.displayName,discriminantValue:{name:me.error.name,wireValue:H},type:ve,statusCode:ee.statusCode,isWildcardStatusCode:ee.isWildcardStatusCode,docs:me.docs,examples:[],v2Examples:{userSpecifiedExamples:G??{},autogeneratedExamples:{}},headers:ee.headers}}let w=this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],B=new Qxa({context:this.context,breadcrumbs:this.breadcrumbs,document:this.context.spec}).convert(),R=new Qxa({context:this.context,breadcrumbs:this.breadcrumbs,document:this.operation}).convert()??B,N={displayName:this.operation.summary,method:t,baseUrl:A,v2BaseUrls:g,path:O,pathParameters:o,queryParameters:c,headers:a.filter((ee,me,ve)=>me===ve.findIndex(H=>H.name.wireValue===ee.name.wireValue)),sdkRequest:void 0,errors:v,auth:this.computeEndpointAuth(),security:this.operation.security??this.context.spec.security??this.getDefaultSecurityFromAuthOverrides(),availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),userSpecifiedExamples:[],autogeneratedExamples:[],idempotent:this.idempotent??!1,basePath:void 0,fullPath:O,allPathParameters:o,pagination:void 0,transport:void 0,source:U8.openapi(),audiences:w,retries:void 0,apiPlayground:R},F=this.context.namespace!=null?[this.context.namespace]:[],x=r?.map(ee=>Xo(ee));return F.push(...x??[]),{audiences:w,group:r,groupDisplayName:n,errors:b,endpoint:{...N,id:`endpoint_${F.join("/")}.${i}`,name:this.context.casingsGenerator.generateName(i),requestBody:s,v2RequestBodies:f,response:_,docs:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:m.examples},v2Responses:{responses:p?.v2Responses}},streamEndpoint:h!=null&&h.body!=null?{...N,id:`endpoint_${F.join("/")}.${i}_stream`,name:this.context.casingsGenerator.generateName(`${i}_stream`),requestBody:u,v2RequestBodies:void 0,response:h,docs:this.streamingExtension?.type==="streamCondition"?this.streamingExtension.streamDescription??this.operation.description:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:m.streamExamples},v2Responses:{responses:[{statusCode:200,isWildcardStatusCode:void 0,body:h.body,docs:h.docs}]}}:void 0,inlinedTypes:this.inlinedTypes,servers:this.filterOutTopLevelServers(this.operation.servers??[])}}convertResponseBody({breadcrumbs:t,group:r,method:i,streamingExtension:n}){if(this.operation.responses==null)return;let a,o=!1;for(let[c,d]of Object.entries(this.operation.responses)){let s=/^[45]XX$/i.test(c),u,f=!1;if(s)u=parseInt(c.charAt(0))*100,f=!0;else{if(u=parseInt(c),isNaN(u)||u<200||u>=300&&u<400)continue;f=u>=400&&u<600}if(a==null&&(a={response:void 0,v2Responses:void 0,streamResponse:void 0,errors:[],examples:{}}),u>=200&&u<300){let p=this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:[...t,c]});if(p==null)continue;let h=new Uxa({context:this.context,breadcrumbs:[...t,c],responseBody:p,group:r??[],method:i,statusCode:c,streamingExtension:n}).convert();h!=null&&(this.inlinedTypes={...this.inlinedTypes,...h.inlinedTypes},o||(o=!0,a.response={statusCode:u,isWildcardStatusCode:s?!0:void 0,body:h.responseBody,docs:p.description},a.streamResponse={statusCode:u,isWildcardStatusCode:s?!0:void 0,body:h.streamResponseBody,docs:p.description}),a.v2Responses=[...a.v2Responses??[],{statusCode:u,isWildcardStatusCode:s?!0:void 0,body:h.responseBody,docs:p.description}])}if(f){let p=this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:[...t,c]});if(p==null)continue;let h=new kbu({context:this.context,breadcrumbs:[...t,c],responseError:p,group:r??[],method:i,methodName:this.evaluateMethodNameFromOperation(),statusCode:u,isWildcardStatusCode:s?!0:void 0}).convert();h!=null&&(this.inlinedTypes={...this.inlinedTypes,...h.inlinedTypes},a.errors.push(h))}}if(this.streamingExtension!=null){a==null&&(a={response:void 0,v2Responses:void 0,streamResponse:void 0,errors:[],examples:{}});let d=new Uxa({context:this.context,breadcrumbs:[...t,"stream"],responseBody:{description:""},group:r??[],method:i,statusCode:"stream",streamingExtension:n}).convert();d!=null&&(this.inlinedTypes={...this.inlinedTypes,...d.inlinedTypes},a.response={statusCode:200,isWildcardStatusCode:void 0,body:d.responseBody,docs:void 0},a.streamResponse={statusCode:200,isWildcardStatusCode:void 0,body:d.streamResponseBody,docs:void 0},a.v2Responses=[{statusCode:200,isWildcardStatusCode:void 0,body:d.responseBody,docs:void 0}])}return a}computeEndpointAuth(){return this.operation.security!=null&&this.operation.security.length===0?!1:this.operation.security!=null&&this.operation.security.length>0?!0:this.context.spec.security!=null&&this.context.spec.security.length>0||this.shouldApplyDefaultAuthOverrides()}shouldApplyDefaultAuthOverrides(){if(!this.context.authOverrides?.auth)return!1;let t=this.context.spec.security!=null&&this.context.spec.security.length>0,r=this.operation.security!=null&&this.operation.security.length>0;return!(t||r)}getDefaultSecurityFromAuthOverrides(){if(!this.context.authOverrides?.auth)return;let t=this.context.authOverrides.auth;if(typeof t!="string")return;let r={};return r[t]=[],[r]}authSchemeToHeaders(t){let r=[];for(let i of t){let n=this.idToAuthScheme?.[i];if(n==null)continue;let a={valueType:Ta.STRING,availability:void 0,docs:void 0,env:void 0,v2Examples:void 0};switch(n.type){case"bearer":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},...a});break;case"basic":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},...a});break;case"header":r.push({name:n.name,...a});break}}return r}convertExamples({httpPath:t,httpMethod:r,baseUrl:i}){let a=new Xbu({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],c=new $bu({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],s=a.some(u=>Array.isArray(u["code-samples"])&&u["code-samples"].length>0)?a:[...a,...c];return s.length===0?{examples:{},streamExamples:{}}:this.streamingExtension?.type==="streamCondition"?this.convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:s}):{examples:this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:s}),streamExamples:{}}}convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:n}){let a=n.filter(s=>!(s.response!=null&&"stream"in s.response)),o=n.filter(s=>s.response!=null&&"stream"in s.response),c=this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:a}),d=this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:o});return{examples:c,streamExamples:d}}convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:n}){return Object.fromEntries(n.map((a,o)=>[this.getExampleName({example:a,exampleIndex:o}),{displayName:void 0,request:a.request!=null||a["path-parameters"]!=null||a["query-parameters"]!=null||a.headers!=null?{docs:void 0,endpoint:{method:r,path:this.buildExamplePath(t,a["path-parameters"]??{})},baseUrl:void 0,environment:i,auth:void 0,pathParameters:a["path-parameters"]??{},queryParameters:a["query-parameters"]??{},headers:a.headers??{},requestBody:a.request??void 0}:void 0,response:a.response!=null?{docs:void 0,statusCode:void 0,body:this.getExampleResponseBody({example:a})}:void 0,codeSamples:a["code-samples"]?.map(c=>{let d=("language"in c?c.language:c.sdk)??void 0;return{name:c.name,docs:void 0,language:d,code:c.code}})}]))}getExampleName({example:t,exampleIndex:r}){return t.name??t["code-samples"]?.[0]?.name??`Example_${r}`}getExampleResponseBody({example:t}){if(t.response!=null){if("stream"in t.response)return gr.V2HttpEndpointResponseBody.stream(t.response.stream);if("body"in t.response)return gr.V2HttpEndpointResponseBody.json(t.response.body)}}getEndpointBaseUrl(){let r=new aR.ServerFromOperationNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert();if(r!=null)return this.context.logger.debug(`[getEndpointBaseUrl] Endpoint ${this.method.toUpperCase()} ${this.path} specifies a server with "${Hi.SERVER_NAME_V2}" extension. Returning server type: ${r}`),r;let i=this.operation.servers?.[0];if(i==null)return;let a=this.topLevelServers?.find(o=>o.url===i.url)??i;return dve.getServerName({server:a,context:this.context})}getEndpointBaseUrls(){let t=this.operation.servers;return t?.map(i=>{let a=this.topLevelServers?.find(o=>o.url===i.url)??i;return dve.getServerName({server:a,context:this.context})})}buildExamplePath(t,r){return t.head+t.parts.map(i=>`${r[i.pathParameter]?.toString()??i.pathParameter}${i.tail}`).join("")}filterOutTopLevelServers(t){return t.filter(r=>!this.topLevelServers?.some(i=>i.url===r.url))}getGroupDisplayName(t){let r=this.operation.tags?.[0];r!=null&&(r=this.context.getDisplayNameForTag(r));let i=t?.[t.length-1];if(i!=null&&r!=null)return r.toLowerCase().replaceAll(" ","")===i?r:void 0}};var tvu=class extends Ta{pathItem;path;idToAuthScheme;topLevelServers;constructor({context:t,breadcrumbs:r,pathItem:i,path:n,idToAuthScheme:a,topLevelServers:o}){super({context:t,breadcrumbs:r}),this.pathItem=i,this.path=n,this.idToAuthScheme=a,this.topLevelServers=o}convert(){let t=[],r=[],i={};for(let n of jmh){let a=this.pathItem[n];if(a==null)continue;let o=[...this.breadcrumbs,n],c=this.tryParseAsWebhook({operationBreadcrumbs:o,operation:a,method:n,context:this.context});if(c!=null){r.push(c),Object.assign(i,c.inlinedTypes);continue}let s=new Kbu({breadcrumbs:o,operation:a,context:this.context}).convert(),u=this.tryParseAsHttpEndpoint({operationBreadcrumbs:o,operation:a,method:n,streamingExtension:s});u!=null&&(t.push(u),Object.assign(i,u.inlinedTypes))}return{endpoints:t,webhooks:r,inlinedTypes:i}}tryParseAsWebhook({operation:t,method:r,operationBreadcrumbs:i,context:n}){return new Jbu({breadcrumbs:i,operation:t,context:n}).convert()?new Hoa({context:this.context,breadcrumbs:i,operation:t,method:UGc.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path}).convert():void 0}tryParseAsHttpEndpoint({operation:t,method:r,operationBreadcrumbs:i,streamingExtension:n}){new xbu({breadcrumbs:i,operation:t,document:this.context.spec,context:this.context}).convert()!=null;let d=new Gbu({breadcrumbs:i,operation:t,context:this.context}).convert();return new evu({context:this.context,breadcrumbs:i,operation:t,method:UGc.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path,idempotent:d,idToAuthScheme:this.idToAuthScheme,topLevelServers:this.topLevelServers,streamingExtension:n}).convert()}};var rvu=class extends Ta{securityScheme;schemeId;constructor({context:t,breadcrumbs:r,securityScheme:i,schemeId:n}){super({context:t,breadcrumbs:r}),this.securityScheme=i,this.schemeId=n}convert(){switch(this.securityScheme.type){case"http":{if(this.securityScheme.scheme==="bearer")return tm.bearer({key:this.schemeId,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,docs:this.securityScheme.description});if(this.securityScheme.scheme==="basic")return tm.basic({key:this.schemeId,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 tm.header({key:this.schemeId,name:{name:this.context.casingsGenerator.generateName("apiKey"),wireValue:this.securityScheme.name},valueType:Ta.OPTIONAL_STRING,prefix:void 0,headerEnvVar:void 0,docs:this.securityScheme.description});break}case"oauth2":return tm.bearer({key:this.schemeId,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,docs:this.securityScheme.description})}}};var Lxa=class extends O3t{constructor({breadcrumbs:t,context:r,audiences:i}){super({breadcrumbs:t,context:r,audiences:i})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.context.spec=await this.resolveAllExternalRefs({spec:this.context.spec}),this.overrideOpenApiAuthWithGeneratorsAuth(),this.convertSecuritySchemes(),this.convertGlobalHeaders(),this.convertBasePath(),this.convertSchemas(),this.convertWebhooks();let{endpointLevelServers:t,errors:r}=this.convertPaths();this.addErrorsToIr(r);let{defaultUrl:i}=this.convertServers({endpointLevelServers:t});this.updateEndpointsWithDefaultUrl(i);let n=this.context.spec.info?.title?.trim();return n&&n!=='""'&&(this.ir.apiDisplayName=n),this.finalizeIr()}convertGlobalHeaders(){this.context.globalHeaderOverrides;let r=new Lbu({breadcrumbs:["x-fern-global-headers"],document:this.context.spec,context:this.context}).convert();if(r!=null){let i=mmh({globalHeaders:r,context:this.context});this.addGlobalHeadersToIr(i),this.context.setGlobalHeaders(i)}}convertBasePath(){let r=new Ubu({breadcrumbs:["x-fern-base-path"],document:this.context.spec,context:this.context}).convert();r!=null&&(this.ir.basePath=iM(r))}convertSecuritySchemes(){if(this.context.authOverrides){let r=AQc({rawApiFileSchema:this.context.authOverrides,casingsGenerator:this.context.casingsGenerator});this.addAuthToIR({requirement:r.requirement,schemes:r.schemes,docs:r.docs});return}let t=this.convertOpenApiSecuritySchemes();t.length>0&&this.addAuthToIR({requirement:t.length===1?"ALL":"ANY",schemes:t,docs:void 0})}convertOpenApiSecuritySchemes(){let t=[];for(let[r,i]of Object.entries(this.context.spec.components?.securitySchemes??{})){let n=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:["components","securitySchemes",r]});if(n==null)continue;let o=new rvu({context:this.context,breadcrumbs:["components","securitySchemes",r],securityScheme:n,schemeId:r}).convert();o!=null&&t.push(o)}return t}convertServers({endpointLevelServers:t}){if(this.context.environmentOverrides){let n=EGa({rawApiFileSchema:this.context.environmentOverrides,casingsGenerator:this.context.casingsGenerator});return n!=null&&this.addEnvironmentsToIr({environmentConfig:n.environmentsConfig,audiences:n.audiences}),{defaultUrl:this.context.environmentOverrides["default-url"]}}let i=new dve({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t}).convert();return this.addEnvironmentsToIr({environmentConfig:i?.value}),{defaultUrl:i?.defaultUrl}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{})){let n=new bA.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:["components","schemas",t],schema:r}).convert();n!=null&&this.addSchemaOutputToIr(t,n)}}convertWebhooks(){for(let[,t]of Object.entries(this.context.spec.webhooks??{})){if(t==null){this.context.errorCollector.collect({message:"Skipping empty webhook",path:this.breadcrumbs});continue}if(!("post"in t)){this.context.errorCollector.collect({message:"Skipping webhook as it is not a POST method",path:this.breadcrumbs});continue}if(t.post?.operationId==null){this.context.errorCollector.collect({message:"Skipping webhook as no operationId is present",path:this.breadcrumbs});continue}let r=t.post.operationId,n=new Hoa({context:this.context,breadcrumbs:["webhooks",r],operation:t.post,method:Mmh.OpenAPIV3.HttpMethods.POST,path:r}).convert();n!=null&&(this.addWebhookToIr({webhook:n.webhook,operationId:r,audiences:n.audiences,group:n.group}),this.addTypesToIr(n.inlinedTypes))}}convertPaths(){let t=[],r={};for(let[i,n]of Object.entries(this.context.spec.paths??{})){if(n==null)continue;let o=new tvu({context:this.context,breadcrumbs:["paths",i],topLevelServers:this.context.spec.servers,pathItem:n,path:i}).convert();if(o!=null){for(let c of o.endpoints){if(c.streamEndpoint!=null&&this.addEndpointToIr({endpoint:c.streamEndpoint,audiences:c.audiences,endpointGroup:c.group,endpointGroupDisplayName:c.groupDisplayName}),this.addEndpointToIr({endpoint:c.endpoint,audiences:c.audiences,endpointGroup:c.group,endpointGroupDisplayName:c.groupDisplayName}),c.servers)for(let d of c.servers)this.shouldAddServerToCollectedServers({server:d,currentServers:t})&&t.push(d);if(c.errors)for(let[d,s]of Object.entries(c.errors))r[d]=s}for(let c of o.webhooks){let d=this.context.getGroup({groupParts:c.group,namespace:this.context.namespace});this.addWebhookToIr({webhook:c.webhook,operationId:d.join("."),group:d,audiences:c.audiences})}this.addTypesToIr(o.inlinedTypes)}}return{endpointLevelServers:t,errors:r}}overrideOpenApiAuthWithGeneratorsAuth(){if(!this.context.authOverrides?.["auth-schemes"])return;this.context.spec.components||(this.context.spec.components={}),this.context.spec.components.securitySchemes={};let t={};for(let r of Object.keys(this.context.authOverrides["auth-schemes"]))this.context.spec.components.securitySchemes[r]={type:"http",scheme:"bearer"},t[r]=[];this.context.spec.security=[t],this.removeEndpointSpecificAuth()}removeEndpointSpecificAuth(){if(this.context.spec.paths)for(let t of Object.values(this.context.spec.paths)){if(!t)continue;let r=["get","post","put","patch","delete","options","head","trace"];for(let i of r){let n=t[i];n?.security&&delete n.security}}}};var ivu=class extends el{tag;key="x-displayName";constructor({breadcrumbs:t,tag:r,context:i}){super({breadcrumbs:t,context:i}),this.tag=r}convert(){if(typeof this.tag!="object"||this.tag==null)return;let t=this.tag[this.key];if(t!=null){if(typeof t!="string"){this.context.errorCollector.collect({message:"x-displayName extension must be a string",path:this.breadcrumbs});return}if(t.trim().length!==0)return{displayName:t}}}};var nUi=class extends VI{globalHeaderNames;tagToDisplayName={};isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n}){let a=this.getTypeIdFromSchemaReference(t);if(a==null)return{ok:!1};let o=this.resolveReference({reference:t,breadcrumbs:r});if(!o.resolved)return{ok:!1};let c;n==="reference_identifier"?c=i??o.value.title:n==="discriminator_key"?c=o.value.title??i:n==="schema_identifier"&&(c=o.value.title);let d;if(a.includes("/")){let u=new bA.SchemaConverters.SchemaConverter({context:this,breadcrumbs:r??[],schema:o.value,id:a}).convert();u!=null&&(d={[a]:u.convertedSchema})}return{ok:!0,reference:ri.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(a),typeId:a,default:void 0,inline:!1,displayName:c}),inlinedTypes:d}}setGlobalHeaders(t){this.globalHeaderNames=t.map(r=>r.name.wireValue)}getDisplayNameForTag(t){if(Object.keys(this.tagToDisplayName).length===0)for(let r of this.spec.tags??[]){let n=new ivu({breadcrumbs:["tags",r.name],tag:r,context:this}).convert()?.displayName??r.name;this.tagToDisplayName[r.name]=n}return this.tagToDisplayName[t]??t}};var yiB=zt.object({description:zt.string().optional(),required:zt.boolean().optional(),deprecated:zt.boolean().optional(),allowEmptyValue:zt.boolean().optional(),style:zt.string().optional(),explode:zt.boolean().optional(),allowReserved:zt.boolean().optional(),schema:zt.any().optional(),example:zt.any().optional(),examples:zt.record(zt.string(),zt.any()).optional(),content:zt.record(zt.string(),zt.any()).optional()}),biB=yiB.extend({name:zt.string(),in:zt.string()}),viB=zt.array(biB),nvu=class extends el{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 viB.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 avu=class extends Ta{method;pathParameters;queryParameters;headers;topLevelServers;constructor({context:t,breadcrumbs:r,method:i,pathParameters:n=[],queryParameters:a=[],headers:o=[],topLevelServers:c=[]}){super({context:t,breadcrumbs:r}),this.method=i,this.pathParameters=n,this.queryParameters=a,this.headers=o,this.topLevelServers=c}convert(){let t={},r="";for(let s of this.pathParameters)r+=`/{${s.name.originalName}}`;let i=iM(r),n=[];for(let[s,u]of this.method.params.entries()){let f;if(this.context.isReferenceObject(u)){let y=this.context.resolveReference({reference:u});if(y.resolved)f=y.value;else continue}else f=u;let p=[this.method.name,"Param",f.name].join("_"),h=new bA.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"Param",f.name],schemaIdOverride:p,context:this.context,schemaOrReference:f.schema,wrapAsOptional:!f.required}).convert();h!=null&&(n.push({docs:f.description,availability:this.context.getAvailability({node:u,breadcrumbs:[...this.breadcrumbs,"parameters"]}),name:this.context.casingsGenerator.generateNameAndWireValue({name:f.name,wireValue:f.name}),valueType:h.type,v2Examples:h.schema?.typeDeclaration.v2Examples,propertyAccess:void 0}),t={...h.inlinedTypes,...t,...h.schema!=null?{[p]:h.schema}:{}})}let a;if(this.method.result!=null){let s=this.context.resolveMaybeReference({schemaOrReference:this.method.result,breadcrumbs:[...this.breadcrumbs,"result"]});if(s!=null){let u=new bA.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"result"],context:this.context,schemaOrReference:s.schema}),f=[this.method.name,"Result"].join("_"),p=u.convert();p!=null&&(a={docs:s.description,v2Examples:p.schema?.typeDeclaration.v2Examples,responseBodyType:p.type},t={...p.inlinedTypes,...t,...p.schema!=null?{[f]:p.schema}:{}})}}let o=this.getEndpointBaseUrls(),c=this.context.getAudiences({operation:this.method,breadcrumbs:this.breadcrumbs})??[];return{endpoint:{baseUrl:void 0,v2BaseUrls:o,basePath:void 0,auth:!1,security:void 0,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?yA.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,v2RequestBodies:void 0,sdkRequest:void 0,response:a!=null?{body:dd.json(NI.response(a)),statusCode:void 0,isWildcardStatusCode:void 0,docs:a.docs}:void 0,v2Responses:void 0,errors:[],idempotent:!1,pagination:void 0,userSpecifiedExamples:[],autogeneratedExamples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples()},transport:void 0,availability:void 0,source:U8.openrpc(),audiences:c,retries:void 0,apiPlayground:void 0},audiences:c,inlinedTypes:t,servers:this.filterOutTopLevelServers(this.method.servers??[])}}filterOutTopLevelServers(t){return t.filter(r=>!this.topLevelServers.some(i=>i.url===r.url))}getEndpointBaseUrls(){let t=this.method.servers;return t?.map(i=>{if(this.topLevelServers.find(c=>c.name===i.name&&c.url!==i.url)!=null)return i.url;let o=this.topLevelServers.find(c=>c.url===i.url)??i;return dve.getServerName({server:o,context:this.context})})}convertExamples(){let t={},r=0;if(this.method.examples&&this.method.examples.length>0){for(let i of this.method.examples??[]){let n;if(this.context.isReferenceObject(i)){let d=this.context.resolveReference({reference:i});if(d.resolved)n=d.value;else continue}else n=i;let a;if(n.result)if(this.context.isReferenceObject(n.result)){let d=this.context.resolveReference({reference:n.result});d.resolved&&(a=d.value)}else a=n.result;let o=n.name??`Example ${r+1}`,c=[];if(n.params&&Array.isArray(n.params)){c=[];for(let d of n.params)if(this.context.isReferenceObject(d)){let s=this.context.resolveReference({reference:d});if(s.resolved)c.push(s.value);else continue}else c.push(d)}t[o]={displayName:void 0,request:{docs:void 0,endpoint:{method:"POST",path:"/{apiKey}"},baseUrl:void 0,environment:void 0,auth:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:c.map(d=>d.value)??void 0},response:{docs:void 0,statusCode:void 0,body:a?.value?gr.V2HttpEndpointResponseBody.json({jsonrpc:"2.0",id:n.examplePairedRequest?.id||"1",result:a.value}):void 0},codeSamples:[]}}++r}return t}};var ovu=class extends bA.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r,parameter:i})}convert(){let t,r={};if(this.parameter.schema!=null){let n=new bA.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 Vxa=class extends O3t{constructor({context:t,breadcrumbs:r,audiences:i}){super({context:t,breadcrumbs:r,audiences:i})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.convertSchemas();let{endpointLevelServers:t}=this.convertMethods(),{defaultUrl:r}=this.convertServers({endpointLevelServers:t});return this.updateEndpointsWithDefaultUrl(r),this.finalizeIr()}convertServers({endpointLevelServers:t}){let i=new dve({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t}).convert();return this.addEnvironmentsToIr({environmentConfig:i?.value}),{defaultUrl:i?.defaultUrl}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{})){let n=new bA.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:["components","schemas",t],schema:r}).convert();n!=null&&this.addSchemaOutputToIr(t,n)}}convertMethods(){let t=[],i=new nvu({context:this.context,breadcrumbs:["methods"],operation:this.context.spec}).convert(),n=[],a=[],o=[];if(i&&i.length>0)for(let[d,s]of i.entries()){let f=new ovu({context:this.context,breadcrumbs:[...this.breadcrumbs,`x-fern-parameters[${d}]`],parameter:s}).convert();if(f!=null)switch(f.type){case"path":{n.push(f.parameter);break}case"query":{a.push(f.parameter);break}case"header":{o.push(f.parameter);break}}}let c=this.context.getGroup({groupParts:[],namespace:this.context.namespace});for(let d of this.context.spec.methods??[]){let s=this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:["methods"]});if(s==null)continue;let f=new avu({context:this.context,breadcrumbs:["methods"],method:s,pathParameters:n,queryParameters:a,headers:o,topLevelServers:this.context.spec.servers}).convert();if(f!=null&&(this.addEndpointToIr({endpoint:f.endpoint,audiences:f.audiences,endpointGroup:c,serviceName:"service_root"}),this.addTypesToIr(f.inlinedTypes),f.servers))for(let p of f.servers)this.shouldAddServerToCollectedServers({server:p,currentServers:t,specType:"openrpc"})&&t.push(this.maybeDeduplicateServerName(p))}return{endpointLevelServers:t}}maybeDeduplicateServerName(t){return this.context.spec.servers?.find(i=>i.name===t.name&&i.url!==t.url)?{...t,name:t.url}:t}};var Wxa=class extends VI{isReferenceObject(t){return t!=null&&"$ref"in t}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n}){let a=this.getTypeIdFromSchemaReference(t);if(a==null)return{ok:!1};let o=this.resolveReference({reference:t,breadcrumbs:r});if(!o.resolved)return{ok:!1};let c;return n==="reference_identifier"?c=i??o.value.title:(n==="discriminator_key"||n==="schema_identifier")&&(c=o.value.title??i),{ok:!0,reference:ri.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(a),typeId:a,displayName:c,default:void 0,inline:!1})}}};var bjh=require("fs/promises");var Dmh={[ki.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,M0(e)])),[ki.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"]),[ki.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"]),[ki.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","kwargs"]),[ki.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","vendor","any","bool","byte","complex64","complex128","error","float32","float64","int","int8","int16","int32","int64","make","new","rune","string","uint","uint8","uint16","uint32","uint64","uintptr"]),[ki.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","object_id","hash","eql?","equal?","method","send","respond_to?","respond_to_missing?","instance_of?","kind_of?","is_a?","extend","singleton_class","instance_variables","instance_variable_get","instance_variable_set","instance_variable_defined?","remove_instance_variable","public_methods","private_methods","protected_methods","singleton_methods"]),[ki.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"]),[ki.GenerationLanguage.RUST]:new Set(["as","async","await","break","const","continue","crate","dyn","else","enum","extern","false","fn","for","if","impl","in","let","loop","match","mod","move","mut","pub","ref","return","self","Self","static","struct","super","trait","true","type","union","unsafe","use","where","while","abstract","become","box","do","final","macro","override","priv","try","typeof","unsized","virtual","yield","bool","char","f32","f64","i8","i16","i32","i64","i128","isize","str","u8","u16","u32","u64","u128","usize","String","Vec","Option","Result","Box","Rc","Arc","Cell","RefCell","HashMap","HashSet","BTreeMap","BTreeSet"]),[ki.GenerationLanguage.SWIFT]:new Set([])};var giB=["go","ruby"];function cvu({generationLanguage:e,keywords:t,smartCasing:r}){let i={generateName:(n,a)=>{let o=MiB(n),c=p=>({unsafeName:p,safeName:OiB({name:p,keywords:AiB({generationLanguage:e,keywords:t})})}),d=Xo(o),s=M0(d),u=aln(o),f=tln(d);return r&&(!jiB(f)&&(e==null||giB.includes(e))&&(d=f.map((p,_)=>{if(_>0){let h=uvu(p);if(h!=null)return h;if(svu(p))return p.toUpperCase()}return p}).join(""),s=M0(f.map((p,_)=>{let h=uvu(p);return h??(svu(p)?p.toUpperCase():_===0?M0(p):p)}).join(""))),u=o.split(" ").map(p=>p.split(/(\d+)/).map(aln).join("")).join("_")),{originalName:n,camelCase:c(a?.casingOverrides?.camel??d),snakeCase:c(a?.casingOverrides?.snake??u),screamingSnakeCase:c(a?.casingOverrides?.["screaming-snake"]??u.toUpperCase()),pascalCase:c(a?.casingOverrides?.pascal??s)}},generateNameAndWireValue:({name:n,wireValue:a,opts:o})=>({name:i.generateName(n,o),wireValue:a})};return i}function OiB({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":PiB(e)?"_"+e:e}function AiB({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return Dmh[e]}var miB=/^[0-9]/;function PiB(e){return miB.test(e)}function jiB(e){return e.some((t,r)=>{if(r===0)return!1;let i=e[r-1];if(i==null)return!1;let n=uvu(i)!=null||svu(i),a=uvu(t)!=null||svu(t);return n&&a})}function uvu(e){return EiB.get(e.toUpperCase())}function svu(e){return wiB.has(e.toUpperCase())}var wiB=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"]),EiB=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]),SiB=[[/\[\]/g,"Array"]];function MiB(e){return SiB.reduce((t,[r,i])=>t.replace(r,i),e)}var Bmh=require("fs/promises");async function LGc({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let i=(await(0,Bmh.readFile)(t)).toString(),n;try{n=JSON.parse(i)}catch{n=Di.load(i)}return r!=null?await Uoa({absoluteFilePathToOverrides:r,context:e,data:n}):n}var njh=ce(ijh(),1);function GJi(e,t,r=[],{doNotPipeOutput:i=!1,secrets:n=[],substitutions:a={},...o}={}){let c=n.reduce((s,u)=>({...s,[u]:"<redacted>"}),a),d=[t,...r].join(" ");for(let[s,u]of Object.entries(c))d=d.replaceAll(s,u);return e?.debug(`+ ${d}`),(0,njh.default)(t,r,o)}async function Nb(e,t,r=[],{doNotPipeOutput:i=!1,secrets:n=[],substitutions:a={},...o}={}){let c=GJi(e,t,r,{doNotPipeOutput:i,secrets:n,substitutions:a,...o});i||(c.stdout?.pipe(process.stdout),c.stderr?.pipe(process.stderr));let d=await c;return d.stdout==null&&(d.stdout=""),d.stderr==null&&(d.stderr=""),d}function HJi(e,{logger:t,...r}={}){return(i,n)=>Nb(t,e,i,{...r,...n})}var Cve=require("fs/promises"),pjh=ce(require("path"),1),nHc=ce(Z9(),1);var ajh="buf.gen.yaml",AaB="output",ojh=`${AaB}/ir.json`,ujh="protoc-gen-fern",sjh=`version: v1
1420
1420
  `,cjh=`version: v2
1421
1421
  `,bvu=e=>{let t=`version: v1
1422
1422
  `;if(e.length>0){t+=`deps:
@@ -1783,7 +1783,7 @@ A valid API configuration was not found at the path: fern/apis/${t.apiName}.
1783
1783
  Learn more about project structure:
1784
1784
  https://buildwithfern.com/learn/docs/getting-started/project-structure#api-definitions`:`Failed to load API Definition referenced in docs.
1785
1785
  Learn more about project structure:
1786
- https://buildwithfern.com/learn/docs/getting-started/project-structure#api-definitions`;throw new Error(r)}async toRootNode(){let t=Rt.V1.SlugGenerator.init(Rt.slugjoin(this.getDocsBasePath())),r=this.#e.get("root"),i=await this.toRootChild(t);return{type:"root",version:"v1",id:r,child:i,slug:t.get(),title:this.parsedDocsConfig.title??"Documentation",hidden:!1,icon:void 0,pointsTo:void 0,authed:void 0,viewers:void 0,orphaned:void 0,roles:this.parsedDocsConfig.roles?.map(n=>Rt.RoleId(n)),featureFlags:void 0}}async toRootChild(t){return vln(this.parsedDocsConfig.navigation)._visit({untabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),tabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),versioned:r=>this.toVersionedNode(r,t),productgroup:r=>this.toProductGroupNode({landingPageConfig:this.parsedDocsConfig.landingPage,productGroup:r,parentSlug:t})})}toLandingPageNode(t,r){let i=Rt.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??NE(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{type:"landingPage",id:this.#e.get(i),title:t.title,slug:n.get(),icon:this.resolveIconFileId(t.icon),hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toUnversionedNode({landingPage:t,navigationConfig:r,parentSlug:i}){let n=this.#e.get("unversioned"),a=t!=null?this.toLandingPageNode(t,i):void 0,o=r.type==="tabbed"?await this.convertTabbedNavigation(n,r.items,i):await this.toSidebarRootNode(n,r.items,i);return{type:"unversioned",id:n,landingPage:a,child:o}}async toVersionedNode(t,r){let i=this.#e.get("versioned"),n=t.versions[0];if(n?.hidden===!0)throw new Error(`The default version "${n.version}" cannot be hidden. Please set a non-hidden version as the first version in your versions list, or remove the hidden flag from the default version.`);return{id:i,type:"versioned",children:await Promise.all(t.versions.map((a,o)=>this.toVersionNode(a,r,o===0)))}}async toProductGroupNode({productGroup:t,landingPageConfig:r,parentSlug:i}){let n=this.#e.get("productgroup"),a=r!=null?this.toLandingPageNode(r,i):void 0;return{id:n,type:"productgroup",landingPage:a,children:await Promise.all(t.products.map(o=>this.toProductNode(o,i)))}}async toProductNode(t,r){if(t.type==="internal"){let i=r.setProductSlug(t.slug??NE(t.product)),n;switch(t.navigation.type){case"tabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.convertTabbedNavigation(this.#e.get(t.product),t.navigation.items,i)};break;case"untabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.toSidebarRootNode(this.#e.get(t.product),t.navigation.items,i)};break;case"versioned":n=await this.toVersionedNode(t.navigation,i);break;default:vt(t.navigation)}return{type:"product",id:this.#e.get(t.product),productId:Rt.V1.ProductId(t.product),title:t.product,subtitle:t.subtitle??"",slug:i.get(),child:n,default:!1,hidden:void 0,authed:void 0,icon:this.resolveIconFileId(t.icon),image:t.image!=null?this.getFileId(t.image):void 0,pointsTo:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,announcement:t.announcement!=null?{text:t.announcement.message}:void 0}}else return{type:"productLink",id:this.#e.get(t.product),productId:Rt.V1.ProductId(t.product),title:t.product,subtitle:t.subtitle??"",href:iG.Url(t.href??""),target:t.target,default:!1,hidden:void 0,authed:void 0,icon:this.resolveIconFileId(t.icon),image:t.image!=null?this.getFileId(t.image):void 0,viewers:t.viewers,orphaned:t.orphaned}}async toVersionNode(t,r,i){let n=this.#e.get(t.version),a=r.setVersionSlug(t.slug??NE(t.version)),o=t.navigation.type==="tabbed"?await this.convertTabbedNavigation(n,t.navigation.items,a):await this.toSidebarRootNode(n,t.navigation.items,a);return{type:"version",id:n,versionId:Rt.VersionId(t.version),title:t.version,slug:a.get(),child:o,default:i,availability:t.availability!=null?ZlB(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,a):void 0,hidden:t.hidden,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,icon:void 0,pointsTo:void 0,featureFlags:t.featureFlags,announcement:t.announcement!=null?{text:t.announcement.message}:void 0}}async toSidebarRootNode(t,r,i){let n=this.#e.get(`${t}/root`),a=await Promise.all(r.map(c=>this.toNavigationChild({prefix:n,item:c,parentSlug:i}))),o=[];return a.forEach(c=>{if(c.type==="apiReference"){o.push(c);return}if(c.type==="section"&&!c.collapsed){o.push(c);return}let d=o.length>0?o[o.length-1]:void 0,s;d?.type==="sidebarGroup"?s=d:(s={id:this.#e.get(`${n}/group`),type:"sidebarGroup",children:[]},o.push(s)),s.children.push(c)}),{type:"sidebarRoot",id:n,children:o}}async toSidebarRootNodeWithVariants(t,r,i){let n=this.#e.get(`${t}/root`);return{type:"sidebarRoot",id:n,children:[{type:"varianted",id:n,children:await Promise.all(r.map(a=>this.toVariantNode(a,n,i)))}]}}async toVariantNode(t,r,i){let n=this.#e.get(`${r}/variant/${t.slug??NE(t.title)}`),a=i.apply({urlSlug:t.slug??NE(t.title),skipUrlSlug:t.skipUrlSlug}),o=await Promise.all(t.layout.map(c=>this.toVariantChild(c,n,a)));return{type:"variant",id:n,variantId:Rt.V1.VariantId(t.title),subtitle:t.subtitle??"",default:t.default??!1,image:void 0,children:o,title:t.title,slug:a.get(),icon:this.resolveIconFileId(t.icon),hidden:t.hidden,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,pointsTo:void 0}}async toVariantChild(t,r,i){return vln(t)._visit({page:async n=>this.toPageNode({item:n,parentSlug:i}),apiSection:async n=>this.toApiSectionNode({item:n,parentSlug:i}),section:async n=>this.toSectionNode({prefix:r,item:n,parentSlug:i}),link:async n=>this.toLinkNode(n),changelog:async n=>this.toChangelogNode(n,i)})}async toNavigationChild({prefix:t,item:r,parentSlug:i,hideChildren:n,parentAvailability:a}){return vln(r)._visit({page:async o=>this.toPageNode({item:o,parentSlug:i,hideChildren:n,parentAvailability:a}),apiSection:async o=>this.toApiSectionNode({item:o,parentSlug:i,hideChildren:n,parentAvailability:a}),section:async o=>this.toSectionNode({prefix:t,item:o,parentSlug:i,hideChildren:n,parentAvailability:a}),link:async o=>this.toLinkNode(o),changelog:async o=>this.toChangelogNode(o,i,n)})}async toApiSectionNode({item:t,parentSlug:r,hideChildren:i,parentAvailability:n}){let a=USh(t.snippetsConfiguration),o,c=await this.getFernWorkspaceForApiSection(t).toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,objectQueryParameters:!0,preserveSchemaIds:!0}),d=this.parsedDocsConfig.experimental?.openapiParserV3,s=d==null||d;if(s)try{o=await this.getOpenApiWorkspaceForApiSection(t).getIntermediateRepresentation({context:this.taskContext,audiences:t.audiences,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1,logWarnings:!1})}catch{}let u;if(t.tagDescriptionPages&&s)try{let b=await this.getOpenApiWorkspaceForApiSection(t).getOpenAPIIr({context:this.taskContext});b.tags.tagsById&&(u=Object.fromEntries(Object.entries(b.tags.tagsById).filter(([v,O])=>O.description&&O.description.trim().length>0).map(([v,O])=>[v,{id:String(O.id),description:O.description}])))}catch(y){this.taskContext.logger.warn("Failed to extract OpenAPI tags for tag description pages",String(y))}o==null&&(o=eS({workspace:c,audiences:t.audiences,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!0},readme:void 0,version:void 0,packageName:void 0,context:this.taskContext,sourceResolver:new kE(this.taskContext,c)})),this.docsWorkspace.config.settings?.substituteEnvVars&&(o=MT(o,{onError:y=>this.taskContext.failAndThrow(`Error substituting environment variables in API spec: ${y}`)},{substituteAsEmpty:!1}));let f=await this.registerApi({ir:o,snippetsConfig:a,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName,workspace:c}),p=AKa({ir:o,apiDefinitionId:f,playgroundConfig:{oauth:t.playground?.oauth},context:this.taskContext}),_=new Sgu(t,p,r,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,this.#e,this.collectedFileIds,c,i,n??t.availability,u),h=_.getTagDescriptionContent();for(let[y,b]of h.entries()){let v=y.split("/").pop()||y,O=Xe.of(v),A=b;this.docsWorkspace.config.settings?.substituteEnvVars&&(A=MT(b,{onError:g=>this.taskContext.logger.error(`Error in tag description environment variable substitution: ${g}`)},{substituteAsEmpty:!1})),this.rawMarkdownFiles[O]=A,this.parsedDocsConfig.pages[O]=A}return _.get()}async toChangelogNode(t,r,i){return new pvn(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:this.resolveIconFileId(t.icon),viewers:t.viewers,hidden:i||t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:Rt.V1.Url(t.url),icon:this.resolveIconFileId(t.icon),target:t.target}}async toPageNode({item:t,parentSlug:r,hideChildren:i,parentAvailability:n}){let a=Rt.PageId(this.toRelativeFilepath(t.absolutePath)),o=r.apply({urlSlug:t.slug??NE(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(a),type:"page",slug:o.get(),title:this.markdownFilesToSidebarTitle.get(t.absolutePath)??t.title,icon:this.resolveIconFileId(t.icon),hidden:i||t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:a,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags,availability:t.availability??n}}async toSectionNode({prefix:t,item:r,parentSlug:i,hideChildren:n,parentAvailability:a}){let o=this.toRelativeFilepath(r.overviewAbsolutePath),c=o?Rt.PageId(o):void 0,d=this.#e.get(c??`${t}/section`),s=i.apply({urlSlug:r.slug??NE(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug}),u=r.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(r.overviewAbsolutePath):void 0,f=n||r.hidden;return{id:d,type:"section",overviewPageId:c,slug:s.get(),title:r.overviewAbsolutePath!=null?this.markdownFilesToSidebarTitle.get(r.overviewAbsolutePath)??r.title:r.title,icon:this.resolveIconFileId(r.icon),collapsed:r.collapsed,hidden:f,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(p=>this.toNavigationChild({prefix:d,item:p,parentSlug:s,hideChildren:f,parentAvailability:r.availability??a}))),authed:void 0,pointsTo:void 0,noindex:u,featureFlags:r.featureFlags,availability:r.availability??a}}async convertTabbedNavigation(t,r,i){let n=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:n,children:await Promise.all(r.map(a=>this.toTabChild(n,a,i)))}}async toTabChild(t,r,i){return vln(r.child)._visit({link:({href:n,target:a})=>this.toTabLinkNode(r,n,a),layout:({layout:n})=>this.toTabNode(t,r,n,i),changelog:({changelog:n})=>this.toTabChangelogNode(r,n,i),variants:({variants:n})=>this.toTabNodeWithVariants(t,r,n,i)})}async toTabChangelogNode(t,r,i){return new pvn(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:i,title:t.title,icon:this.resolveIconFileId(t.icon),viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r,i){return{type:"link",id:this.#e.get(r),title:t.title,url:Rt.V1.Url(r),target:i,icon:this.resolveIconFileId(t.icon)}}async toTabNode(t,r,i,n){let a=this.#e.get(`${t}/tab`),o=n.apply({urlSlug:r.slug??NE(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:this.resolveIconFileId(r.icon),hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNode(a,i,o),featureFlags:r.featureFlags}}async toTabNodeWithVariants(t,r,i,n){let a=this.#e.get(`${t}/tab`),o=n.apply({urlSlug:r.slug??NE(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:this.resolveIconFileId(r.icon),hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNodeWithVariants(a,i,o),featureFlags:r.featureFlags}}getFileId(t){if(t==null)return;let r=this.collectedFileIds.get(t);return r==null?this.taskContext.failAndThrow("Failed to locate file after uploading: "+t):iG.FileId(r)}resolveIconFileId(t){if(t!=null)return this.collectedFileIds.has(t)?`file:${this.getFileId(t)}`:t}convertPageActions(){if(this.parsedDocsConfig.pageActions!=null)return{default:this.parsedDocsConfig.pageActions.default,options:{askAi:this.parsedDocsConfig.pageActions.options.askAi,copyPage:this.parsedDocsConfig.pageActions.options.copyPage,viewAsMarkdown:this.parsedDocsConfig.pageActions.options.viewAsMarkdown,openAi:this.parsedDocsConfig.pageActions.options.openAi,claude:this.parsedDocsConfig.pageActions.options.claude,cursor:this.parsedDocsConfig.pageActions.options.cursor,vscode:this.parsedDocsConfig.pageActions.options.vscode,custom:this.parsedDocsConfig.pageActions.options.custom.map(t=>({title:t.title,subtitle:t.subtitle,url:t.url,icon:this.resolveIconFileId(t.icon),default:t.default}))}}}convertColorConfigImageReferences(){let{colors:t}=this.parsedDocsConfig;if(t!=null)return t.type==="dark"?{...t,...this.convertLogoAndBackgroundImage({theme:"dark"})}:t.type==="light"?{...t,...this.convertLogoAndBackgroundImage({theme:"light"}),type:"light"}:{...t,dark:{...t.dark,...this.convertLogoAndBackgroundImage({theme:"dark"})},light:{...t.light,...this.convertLogoAndBackgroundImage({theme:"light"})}}}convertLogoAndBackgroundImage({theme:t}){let{logo:r,backgroundImage:i}=this.parsedDocsConfig,n=r?.[t],a=i?.[t];return{logo:this.getFileId(n),backgroundImage:this.getFileId(a)}}convertDocsTypographyConfiguration(){if(this.parsedDocsConfig.typography!=null)return{headingsFont:this.convertFont(this.parsedDocsConfig.typography.headingsFont,"headings"),bodyFont:this.convertFont(this.parsedDocsConfig.typography.bodyFont,"body"),codeFont:this.convertFont(this.parsedDocsConfig.typography.codeFont,"code")}}convertFont(t,r){if(t==null||t.variants[0]==null)return;let i=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${i}`,variants:t.variants.map(n=>({fontFile:this.getFileId(n.absolutePath),weight:n.weight,style:n.style!=null?[n.style]:void 0})),display:t.display,fallback:t.fallback,fontVariationSettings:t.fontVariationSettings}}convertJavascriptConfiguration(){if(this.parsedDocsConfig.js!=null)return{files:this.parsedDocsConfig.js.files.map(({absolutePath:t,strategy:r})=>({fileId:this.getFileId(t),strategy:r})).filter(ds),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:iG.Url(t.url)})),inline:void 0}}convertMetadata(){if(this.parsedDocsConfig.metadata==null)return;let{"og:image":t,"og:logo":r,"twitter:image":i,...n}=this.parsedDocsConfig.metadata;return{...n,"og:image":this.convertFileIdOrUrl(t),"og:logo":this.convertFileIdOrUrl(r),"twitter:image":this.convertFileIdOrUrl(i)}}convertFileIdOrUrl(t){if(t!=null)return vln(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:iG.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function XlB(e,t){if(e?.github==null)return;let{owner:r,repo:i,branch:n="main",host:a="https://github.com"}=e.github;return`${tH(a)}/${r}/${i}/blob/${n}/fern/${t}?plain=1`}function ZlB(e){switch(e){case"beta":return Rt.V1.NavigationV1Availability.Beta;case"deprecated":return Rt.V1.NavigationV1Availability.Deprecated;case"ga":return Rt.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return Rt.V1.NavigationV1Availability.Stable;default:vt(e)}}async function rL(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof ZE?t:null))).filter(ds)}async function U7c(e,t,r){if(e instanceof SEe){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof ZE))return;let i=await e.getIntermediateRepresentation({context:t,audiences:r,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1,logWarnings:!1});return eH({ir:i,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0,phpSdk:void 0,swiftSdk:void 0,rustSdk:void 0},playgroundConfig:{oauth:!0},context:t})}var Ys={};Zt(Ys,{AlgoliaSearchIndex:()=>oMh,ApiDefinitionId:()=>SMh,ApiId:()=>IMh,Availability:()=>xMh,DocsConfigId:()=>CMh,EndpointId:()=>TMh,EndpointPathLiteral:()=>GMh,EnvironmentId:()=>qMh,FileId:()=>QMh,HttpMethod:()=>HMh,IndexSegmentId:()=>uMh,JqString:()=>LMh,OrgId:()=>DMh,PageId:()=>FMh,PayloadLocation:()=>gDh,PropertyKey:()=>VMh,PullRequestState:()=>_Dh,RoleId:()=>WMh,TokenId:()=>BMh,TypeId:()=>NMh,Url:()=>UMh,VersionId:()=>MMh,WebSocketId:()=>RMh,WebhookId:()=>zMh,algolia:()=>L7c,api:()=>X7c,commons:()=>Z7c,diff:()=>KMh,docs:()=>uxc,generators:()=>cxc,git:()=>lxc,navigation:()=>pxc,sdks:()=>hxc,snippets:()=>bDh,snippetsFactory:()=>vDh,templates:()=>yxc,tokens:()=>ODh});var L7c={};Zt(L7c,{AlgoliaSearchIndex:()=>oMh,IndexSegmentId:()=>uMh});function oMh(e){return e}function uMh(e){return e}var X7c={};Zt(X7c,{latest:()=>G7c,v1:()=>Y7c});var G7c={};Zt(G7c,{AuthSchemeId:()=>sMh,WebhookHttpMethod:()=>dMh,auth:()=>V7c,commons:()=>cMh,endpoint:()=>lMh,type_:()=>fMh,webhook:()=>W7c,websocket:()=>pMh});var V7c={};Zt(V7c,{AuthSchemeId:()=>sMh});function sMh(e){return e}var cMh={};var lMh={};var fMh={};var W7c={};Zt(W7c,{WebhookHttpMethod:()=>dMh});var dMh={Get:"GET",Post:"POST"};var pMh={};var Y7c={};Zt(Y7c,{SubpackageId:()=>PMh,WebSocketMessageId:()=>jMh,WebSocketMessageOrigin:()=>wMh,WebhookHttpMethod:()=>EMh,commons:()=>$7c,db:()=>H7c,read:()=>K7c,register:()=>J7c});var H7c={};Zt(H7c,{endpoint:()=>_Mh});var _Mh={};var K7c={};Zt(K7c,{SupportedLanguage:()=>hMh,endpoint:()=>x7c,type_:()=>yMh,webhook:()=>bMh,websocket:()=>vMh});var x7c={};Zt(x7c,{SupportedLanguage:()=>hMh});var hMh={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby",Csharp:"csharp"};var yMh={};var bMh={};var vMh={};var J7c={};Zt(J7c,{SourceId:()=>klB,endpoint:()=>gMh,type_:()=>OMh,webhook:()=>AMh,websocket:()=>mMh});var gMh={};var OMh={};var AMh={};var mMh={};function klB(e){return e}var $7c={};Zt($7c,{SubpackageId:()=>PMh,WebSocketMessageId:()=>jMh,WebSocketMessageOrigin:()=>wMh,WebhookHttpMethod:()=>EMh});function PMh(e){return e}function jMh(e){return e}var wMh={Client:"client",Server:"server"};var EMh={Get:"GET",Post:"POST"};var Z7c={};Zt(Z7c,{ApiDefinitionId:()=>SMh,ApiId:()=>IMh,Availability:()=>xMh,DocsConfigId:()=>CMh,EndpointId:()=>TMh,EndpointPathLiteral:()=>GMh,EnvironmentId:()=>qMh,FileId:()=>QMh,HttpMethod:()=>HMh,JqString:()=>LMh,OrgId:()=>DMh,PageId:()=>FMh,PropertyKey:()=>VMh,RoleId:()=>WMh,TokenId:()=>BMh,TypeId:()=>NMh,Url:()=>UMh,VersionId:()=>MMh,WebSocketId:()=>RMh,WebhookId:()=>zMh});function SMh(e){return e}function MMh(e){return e}function DMh(e){return e}function BMh(e){return e}function IMh(e){return e}function CMh(e){return e}function qMh(e){return e}function TMh(e){return e}function RMh(e){return e}function zMh(e){return e}function NMh(e){return e}function FMh(e){return e}function QMh(e){return e}function UMh(e){return e}function LMh(e){return e}function VMh(e){return e}function WMh(e){return e}function GMh(e){return e}var HMh={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var xMh={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var KMh={};var uxc={};Zt(uxc,{latest:()=>txc,v1:()=>axc,v2:()=>oxc});var txc={};Zt(txc,{Layout:()=>$Mh,MdxEngine:()=>efB,TwitterCardSetting:()=>YMh,commons:()=>JMh,frontmatter:()=>k7c,seo:()=>exc});var efB={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var JMh={};var k7c={};Zt(k7c,{Layout:()=>$Mh});var $Mh={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var exc={};Zt(exc,{TwitterCardSetting:()=>YMh});var YMh={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var axc={};Zt(axc,{commons:()=>nxc,db:()=>XMh,read:()=>ZMh,write:()=>rxc});var XMh={};var ZMh={};var rxc={};Zt(rxc,{DocsRegistrationId:()=>rfB,FilePath:()=>tfB});function tfB(e){return e}function rfB(e){return e}var nxc={};Zt(nxc,{ContentAlignment:()=>rDh,FontDisplay:()=>uDh,FontStyle:()=>oDh,HeaderPosition:()=>iDh,JsScriptStrategy:()=>aDh,ProgrammingLanguage:()=>kMh,SearchbarPlacement:()=>eDh,TabsPlacement:()=>tDh,TwitterCardSetting:()=>nDh,commons:()=>ixc});var ixc={};Zt(ixc,{ContentAlignment:()=>rDh,FontDisplay:()=>uDh,FontStyle:()=>oDh,HeaderPosition:()=>iDh,JsScriptStrategy:()=>aDh,ProgrammingLanguage:()=>kMh,SearchbarPlacement:()=>eDh,TabsPlacement:()=>tDh,TwitterCardSetting:()=>nDh});var kMh={Typescript:"typescript",Javascript:"javascript",Python:"python",Java:"java",Go:"go",Ruby:"ruby",Csharp:"csharp",Nodets:"nodets",Nodejs:"nodejs",Dotnet:"dotnet",Curl:"curl",Jvm:"jvm",Ts:"ts",Js:"js"};var eDh={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var tDh={Header:"HEADER",Sidebar:"SIDEBAR"};var rDh={Center:"CENTER",Left:"LEFT"};var iDh={Fixed:"FIXED",Absolute:"ABSOLUTE"};var nDh={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var aDh={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var oDh={Normal:"normal",Italic:"italic"};var uDh={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var oxc={};Zt(oxc,{read:()=>sDh,write:()=>cDh});var sDh={};var cDh={};var cxc={};Zt(cxc,{ChangelogEntryType:()=>fDh,GeneratorId:()=>ifB,GeneratorLanguage:()=>nfB,ReleaseType:()=>dDh,cli:()=>lDh,commons:()=>sxc,versions:()=>pDh});var lDh={};var sxc={};Zt(sxc,{ChangelogEntryType:()=>fDh,ReleaseType:()=>dDh});var fDh={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var dDh={Ga:"GA",Rc:"RC"};var pDh={};function ifB(e){return e}var nfB={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var lxc={};Zt(lxc,{PullRequestState:()=>_Dh});var _Dh={Open:"open",Closed:"closed",Merged:"merged"};var pxc={};Zt(pxc,{latest:()=>fxc,v1:()=>dxc});var fxc={};Zt(fxc,{NodeId:()=>ufB,ProductId:()=>sfB,Slug:()=>afB,TabId:()=>ofB});function afB(e){return e}function ofB(e){return e}function ufB(e){return e}function sfB(e){return e}var dxc={};Zt(dxc,{NavigationV1Availability:()=>pfB,NodeId:()=>ffB,ProductId:()=>dfB,Slug:()=>cfB,TabId:()=>lfB});function cfB(e){return e}function lfB(e){return e}function ffB(e){return e}function dfB(e){return e}var pfB={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var hxc={};Zt(hxc,{Language:()=>hDh,VersionBump:()=>yDh,versions:()=>_xc});var _xc={};Zt(_xc,{Language:()=>hDh,VersionBump:()=>yDh});var hDh={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var yDh={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var bDh={};var vDh={};var yxc={};Zt(yxc,{PayloadLocation:()=>gDh});var gDh={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var ODh={};var zgu=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};function No(e){return e!=null}var mDh=ce(TFa(),1);var ADh=["PII","PHI","PCI","GDPR","CCPA","HIPAA","COPPA","FERPA","GLBA","SOX","FISMA","NIST","CIS","ISO","IEC","ITAR","EAR","CMMC","CUI","CDI","FTC","FCC","SEC","FINRA","XSS","CSRF","SSRF","XSRF","TLS","SSL","SSH","API","OAuth","OAuth1","OAuth1.0","OAuth2","OAuth2.0","SAML","OpenID","OpenID Connect","CAPTCHA","reCAPTCHA","2FA","MFA","OTP","TOTP","HOTP","U2F","FIDO","FIDO2","PKI","HMAC","AES","RSA","SHA","MD5","BCrypt","PBKDF2","Argon2","SCrypt","JWT","JWE","JWS","JWK","JWA","JOSE","SKU","SKUs","UPC","EAN","ISBN","ASIN","MPN","MSRP","MAP","RRP","MSRP","AM","PM","UTC","GMT","PST","PDT","EST","EDT","CST","CDT","MST","MDT","USA","UK","EU","UAE","APAC","EMEA","LATAM","ANZ","SEA","MEA","MENA","NATO","NA","SA","CA","EU","AU","NZ","JP","KR","CN","HK","TW","SG","MY","TH","ID","PH","VN","IN","PK","BD","LK","NP","MM","KH","LA","MM","BT","MV","USD","EUR","GBP","JPY","CNY","RUB","INR","AUD","CAD","CHF","SGD","MYR","THB","IDR","KRW","PHP","VND","HKD","TWD","MXN","BRL","ARS","CLP","COP","PEN","ZAR","NGN","EGP","AED","SAR","ILS","TRY","SEK","NOK","DKK","ISK","HUF","PLN","CZK","RON","BGN","API","APIs","SDK","SDKs","AI","OCR","REST","SOAP","JSON","XML","HTTP","HTTPS","URI","URL","CRUD","RESTful","KYB","KYC","AML","HTML","CSS","JS","SQL","DB","UI","UX","SaaS","PaaS","IaaS","IP","TCP","UDP","DNS","FTP","SMTP","IMAP","POP3","CSV","MVC","MVP","MVVM","DOM","SPA","SSR","CSR","DDoS","CDN","IoT","ML","DL","NLP","CLI","GUI","BI","ETL","RDBMS","NoSQL","IDE","CMS","CCPA","POSIX","ABI","API","AST","COBOL","DDL","DML","NN","CNN","RNN","LSTM","GRU","ANN","GAN","RL","DL","ML","NLP","NLG","NLU","BERT","GPT","SVM","PCA","AI","CV","TF","TTS","ASR","HMM","DNN","MLP","RBM","CRF","PDF","PDFs","RTF","TXT","XLS","XLSX","PPT","JPG","JPEG","PNG","GIF","GIFs","SVG","TIFF","BMP","ICO","PSD","WebP","AVIF","HEIF","HEIC","EPS","MP3","WAV","AIFF","FLAC","WMA","AAC","OGG","AVI","WMV","MOV","M4V","MP4","MPG","MPEG","FLV","SWF","MKV","WebM","GCP","AWS","VM","VPC","S3","EC2","DynamoDB","CosmosDB","BigQuery","CI/CD","SOC1","SOC2","SOC3","PCI DSS","WAF","IAM","SDN","MPLS","BGP","Vue.js","Node.js",".NET"];function SYt(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,mDh.default)(e,{special:ADh}).replace(/V\s(\d)/g,"V$1")}function PDh({endpoints:e,webhookEndpoints:t}){let r={};return Object.values({...e,...t}).forEach(i=>{let n=[];i.namespace?.forEach(a=>{let o=[...n,a],c=Ys.api.v1.SubpackageId(o.join("."));r[c]={id:c,name:a,displayName:SYt(a)},n.push(a)})}),r}var Ngu=class{input;context;constructor(t,r){this.input=t,this.context=r}errors(){return this.context.errors.errors}warnings(){return this.context.errors.warnings}};function jDh(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var po=class extends Ngu{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){if(super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,n!=null){let a=Array.isArray(this.pathId)?this.pathId:[this.pathId];a.every((o,c)=>o===this.accessPath[this.accessPath.length-a.length+c])||this.accessPath.push(...a)}r.logger.debug(`Processing ${jDh(this.accessPath)}`)}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}},iC=class extends po{},K$=class extends iC{seenSchemas;constructor(t){super(t),this.seenSchemas=new Set(t.seenSchemas)}};var wDh="x-fern-base-path",EDh="x-fern-availability",Fgu="x-fern-sdk-group-name",SDh="x-fern-global-headers",MDh="x-fern-sdk-method-name";var DDh="x-fern-webhook",BDh="x-fern-access-token-locator",IDh="x-fern-basic",CDh="x-fern-username-variable-name",qDh="x-fern-password-variable-name",TDh="x-fern-bearer",RDh="x-fern-token-variable-name",zDh="x-fern-header",NDh="x-fern-header-variable-name",FDh="x-fern-server-name",QDh="x-fern-examples";var Qgu=class extends po{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[FDh]}convert(){if(this.serverName!=null)return this.serverName}};var Ugu=class extends po{url;serverName;constructor(t){super(t),this.safeParse()}parse(){this.url=Object.entries(this.input.variables??{}).reduce((t,[r,i])=>t.replace(`{${r}}`,i.default),this.input.url)??this.input.url,this.serverName=new Qgu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.serverName?.convert()??this.url;if(!(this.url==null||t==null))return{id:Ys.EnvironmentId(t),baseUrl:this.url}}};function i$i(e,t,r,i){let n=e??[],a=new Set(n.map(c=>c.url)),o=(t??[]).filter(c=>!a.has(c.url)).map((c,d)=>new Ugu({input:c,context:r,accessPath:i,pathId:["servers",`${d}`]}));return[...n,...o]}function zv(e){return typeof e=="object"&&No(e)&&"$ref"in e&&typeof e.$ref=="string"}function iL(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(zv(n)&&(n=iL(n,t,r)),n)}function Lgu(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return zv(r)?iL(r,t,void 0):r}var BBh=ce(VS());var Vgu=class extends po{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[IDh];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var Wgu=class extends po{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[qDh]}convert(){return this.passwordVariableName}};var Ggu=class extends po{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[CDh]}convert(){return this.usernameVariableName}};var Hgu=class extends po{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[TDh];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var xgu=class extends po{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[RDh]}convert(){return this.tokenVariableName}};function UDh(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var LDh="x-bearer-format",VDh="x-code-samples",WDh="x-codeSamples";var Kgu=class extends po{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[LDh]}convert(){return this.bearerFormat}};var Jgu=class extends po{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[zDh];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var $gu=class extends po{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[NDh]}convert(){return this.headerVariableName}};function GDh(e){return e.type==="apiKey"}var mua=class extends po{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){GDh(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new Jgu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new $gu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new Kgu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.headerAuthNode?.convert();if(t!=null)return{type:"header",nameOverride:t?.name,headerWireValue:this.headerName??"Authorization",prefix:t?.prefix??this.headerBearerFormatNode?.convert()}}};function Ygu(e){return e}function Xgu(e){return e==="__proto__"}function Zgu(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function Pua(e){return typeof e=="string"||typeof e=="symbol"?e:Object.is(e?.valueOf?.(),-0)?"-0":String(e)}function mKa(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e))return e.map(mKa).join(",");let t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function kgu(e){if(Array.isArray(e))return e.map(Pua);if(typeof e=="symbol")return[e];e=mKa(e);let t=[],r=e.length;if(r===0)return t;let i=0,n="",a="",o=!1;for(e.charCodeAt(0)===46&&(t.push(""),i++);i<r;){let c=e[i];a?c==="\\"&&i+1<r?(i++,n+=e[i]):c===a?a="":n+=c:o?c==='"'||c==="'"?a=c:c==="]"?(o=!1,t.push(n),n=""):n+=c:c==="["?(o=!0,n&&(t.push(n),n="")):c==="."?n&&(t.push(n),n=""):n+=c,i++}return n&&t.push(n),t}function PKa(e,t,r){if(e==null)return r;switch(typeof t){case"string":{if(Xgu(t))return r;let i=e[t];return i===void 0?Zgu(t)?PKa(e,kgu(t),r):r:i}case"number":case"symbol":{typeof t=="number"&&(t=Pua(t));let i=e[t];return i===void 0?r:i}default:{if(Array.isArray(t))return _fB(e,t,r);if(Object.is(t?.valueOf(),-0)?t="-0":t=String(t),Xgu(t))return r;let i=e[t];return i===void 0?r:i}}}function _fB(e,t,r){if(t.length===0)return r;let i=e;for(let n=0;n<t.length;n++){if(i==null||Xgu(t[n]))return r;i=i[t[n]]}return i===void 0?r:i}function HDh(e){return function(t){return PKa(t,e)}}function xDh(e){return e!==null&&(typeof e=="object"||typeof e=="function")}function eOu(e){return e==null||typeof e!="object"&&typeof e!="function"}function bxc(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function gxc(e,t,r){return typeof r!="function"?gxc(e,t,()=>{}):vxc(e,t,function i(n,a,o,c,d,s){let u=r(n,a,o,c,d,s);return u!==void 0?!!u:vxc(n,a,i,s)},new Map)}function vxc(e,t,r,i){if(t===e)return!0;switch(typeof t){case"object":return hfB(e,t,r,i);case"function":return Object.keys(t).length>0?vxc(e,{...t},r,i):bxc(e,t);default:return xDh(e)?typeof t=="string"?t==="":!0:bxc(e,t)}}function hfB(e,t,r,i){if(t==null)return!0;if(Array.isArray(t))return KDh(e,t,r,i);if(t instanceof Map)return yfB(e,t,r,i);if(t instanceof Set)return bfB(e,t,r,i);let n=Object.keys(t);if(e==null)return n.length===0;if(n.length===0)return!0;if(i?.has(t))return i.get(t)===e;i?.set(t,e);try{for(let a=0;a<n.length;a++){let o=n[a];if(!eOu(e)&&!(o in e)||t[o]===void 0&&e[o]!==void 0||t[o]===null&&e[o]!==null||!r(e[o],t[o],o,e,t,i))return!1}return!0}finally{i?.delete(t)}}function yfB(e,t,r,i){if(t.size===0)return!0;if(!(e instanceof Map))return!1;for(let[n,a]of t.entries()){let o=e.get(n);if(r(o,a,n,e,t,i)===!1)return!1}return!0}function KDh(e,t,r,i){if(t.length===0)return!0;if(!Array.isArray(e))return!1;let n=new Set;for(let a=0;a<t.length;a++){let o=t[a],c=!1;for(let d=0;d<e.length;d++){if(n.has(d))continue;let s=e[d],u=!1;if(r(s,o,a,e,t,i)&&(u=!0),u){n.add(d),c=!0;break}}if(!c)return!1}return!0}function bfB(e,t,r,i){return t.size===0?!0:e instanceof Set?KDh([...e],[...t],r,i):!1}function tOu(e,t){return gxc(e,t,()=>{})}function JDh(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function rOu(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}var $Dh="[object RegExp]",iOu="[object String]",nOu="[object Number]",aOu="[object Boolean]",oOu="[object Arguments]",YDh="[object Symbol]",XDh="[object Date]",ZDh="[object Map]",kDh="[object Set]",eBh="[object Array]";var tBh="[object ArrayBuffer]",rBh="[object Object]";var iBh="[object DataView]",nBh="[object Uint8Array]",aBh="[object Uint8ClampedArray]",oBh="[object Uint16Array]",uBh="[object Uint32Array]";var sBh="[object Int8Array]",cBh="[object Int16Array]",lBh="[object Int32Array]";var fBh="[object Float32Array]",dBh="[object Float64Array]";function pBh(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function _Bh(e,t){return n$i(e,void 0,e,new Map,t)}function n$i(e,t,r,i=new Map,n=void 0){let a=n?.(e,t,r,i);if(a!==void 0)return a;if(eOu(e))return e;if(i.has(e))return i.get(e);if(Array.isArray(e)){let o=new Array(e.length);i.set(e,o);for(let c=0;c<e.length;c++)o[c]=n$i(e[c],c,r,i,n);return Object.hasOwn(e,"index")&&(o.index=e.index),Object.hasOwn(e,"input")&&(o.input=e.input),o}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp){let o=new RegExp(e.source,e.flags);return o.lastIndex=e.lastIndex,o}if(e instanceof Map){let o=new Map;i.set(e,o);for(let[c,d]of e)o.set(c,n$i(d,c,r,i,n));return o}if(e instanceof Set){let o=new Set;i.set(e,o);for(let c of e)o.add(n$i(c,void 0,r,i,n));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(e))return e.subarray();if(pBh(e)){let o=new(Object.getPrototypeOf(e)).constructor(e.length);i.set(e,o);for(let c=0;c<e.length;c++)o[c]=n$i(e[c],c,r,i,n);return o}if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)return e.slice(0);if(e instanceof DataView){let o=new DataView(e.buffer.slice(0),e.byteOffset,e.byteLength);return i.set(e,o),a8t(o,e,r,i,n),o}if(typeof File<"u"&&e instanceof File){let o=new File([e],e.name,{type:e.type});return i.set(e,o),a8t(o,e,r,i,n),o}if(typeof Blob<"u"&&e instanceof Blob){let o=new Blob([e],{type:e.type});return i.set(e,o),a8t(o,e,r,i,n),o}if(e instanceof Error){let o=new e.constructor;return i.set(e,o),o.message=e.message,o.name=e.name,o.stack=e.stack,o.cause=e.cause,a8t(o,e,r,i,n),o}if(e instanceof Boolean){let o=new Boolean(e.valueOf());return i.set(e,o),a8t(o,e,r,i,n),o}if(e instanceof Number){let o=new Number(e.valueOf());return i.set(e,o),a8t(o,e,r,i,n),o}if(e instanceof String){let o=new String(e.valueOf());return i.set(e,o),a8t(o,e,r,i,n),o}if(typeof e=="object"&&vfB(e)){let o=Object.create(Object.getPrototypeOf(e));return i.set(e,o),a8t(o,e,r,i,n),o}return e}function a8t(e,t,r=e,i,n){let a=[...Object.keys(t),...JDh(t)];for(let o=0;o<a.length;o++){let c=a[o],d=Object.getOwnPropertyDescriptor(e,c);(d==null||d.writable)&&(e[c]=n$i(t[c],c,r,i,n))}}function vfB(e){switch(rOu(e)){case oOu:case eBh:case tBh:case iBh:case aOu:case XDh:case fBh:case dBh:case sBh:case cBh:case lBh:case ZDh:case nOu:case rBh:case $Dh:case kDh:case iOu:case YDh:case nBh:case aBh:case oBh:case uBh:return!0;default:return!1}}function hBh(e){return n$i(e,void 0,e,new Map,void 0)}function yBh(e){return e=hBh(e),t=>tOu(t,e)}function bBh(e,t){return _Bh(e,(r,i,n,a)=>{let o=t?.(r,i,n,a);if(o!==void 0)return o;if(typeof e=="object")switch(Object.prototype.toString.call(e)){case nOu:case iOu:case aOu:{let c=new e.constructor(e?.valueOf());return a8t(c,e),c}case oOu:{let c={};return a8t(c,e),c.length=e.length,c[Symbol.iterator]=e[Symbol.iterator],c}default:return}})}function vBh(e){return bBh(e)}var gfB=/^(?:0|[1-9]\d*)$/;function gBh(e,t=Number.MAX_SAFE_INTEGER){switch(typeof e){case"number":return Number.isInteger(e)&&e>=0&&e<t;case"symbol":return!1;case"string":return gfB.test(e)}}function OBh(e){return e!==null&&typeof e=="object"&&rOu(e)==="[object Arguments]"}function ABh(e,t){let r;if(Array.isArray(t)?r=t:typeof t=="string"&&Zgu(t)&&e?.[t]==null?r=kgu(t):r=[t],r.length===0)return!1;let i=e;for(let n=0;n<r.length;n++){let a=r[n];if((i==null||!Object.hasOwn(i,a))&&!((Array.isArray(i)||OBh(i))&&gBh(a)&&a<i.length))return!1;i=i[a]}return!0}function mBh(e,t){switch(typeof e){case"object":{Object.is(e?.valueOf(),-0)&&(e="-0");break}case"number":{e=Pua(e);break}}return t=vBh(t),function(r){let i=PKa(r,e);return i===void 0?ABh(r,e):t===void 0?i===void 0:tOu(i,t)}}function PBh(e){if(e==null)return Ygu;switch(typeof e){case"function":return e;case"object":return Array.isArray(e)&&e.length===2?mBh(e[0],e[1]):yBh(e);case"string":case"symbol":case"number":return HDh(e)}}function jBh(e,t){let r={},i=Object.keys(e);for(let n=0;n<i.length;n++){let a=i[n],o=e[a];r[a]=t(o,a,e)}return r}function uOu(e,t=Ygu){return e==null?{}:jBh(e,PBh(t))}function wBh(e){return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}var OfB=new RegExp("\\p{Lu}?\\p{Ll}+|[0-9]+|\\p{Lu}+(?!\\p{Ll})|\\p{Emoji_Presentation}|\\p{Extended_Pictographic}|\\p{L}+","gu");function EBh(e){return Array.from(e.match(OfB)??[])}function SBh(e){let t=EBh(e);if(t.length===0)return"";let[r,...i]=t;return`${r.toLowerCase()}${i.map(n=>wBh(n)).join("")}`}function MBh(e){return typeof e!="string"&&(e=mKa(e)),e.replace(/['\u2019]/g,"")}function o8t(e){return SBh(MBh(e))}function RP(e){if(e!=null)return Array.isArray(e)?e:[e]}function sOu({namespace:e,path:t,method:r,sdkMethodName:i,operationId:n,displayName:a,isWebhook:o}){if(t==null)return;let c=r!=null&&t!=null?`${r}_${t.split("/").join("_")}`:r??t.split("/").join("_");if(!(i==null&&n==null&&a==null&&c==null))return`${AfB(o)}${mfB(e)}.${PfB(i,n,a,c)}`}function AfB(e){return e?"webhook_":"endpoint_"}function mfB(e){return e!=null?RP(e)?.map(t=>o8t(t)).join("/"):""}function PfB(e,t,r,i){return e||t||o8t(r??"")||o8t(i??"")}function DBh(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var cOu=class extends po{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[BDh],this.accessTokenLocator!=null&&(DBh(this.accessTokenLocator)||(this.context.errors.error({message:"Invalid access token locator, must be a valid jq path",path:this.accessPath}),this.accessTokenLocator=void 0))}convert(){return this.accessTokenLocator}};var lOu=class extends po{authorizationUrl;headerAuthNode;accessTokenLocatorNode;constructor(t){super(t),this.safeParse()}parse(){if(this.input.flows.clientCredentials!=null){let t=this.input.flows.clientCredentials;this.authorizationUrl=t.tokenUrl,this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.headerAuthNode=new mua({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new cOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.accessTokenLocatorNode?.accessTokenLocator==null&&this.context.errors.error({message:"Expected 'x-fern-access-token-locator' property to be specified",path:this.accessPath})}}convert(){let t=this.accessTokenLocatorNode?.convert();if(t==null||this.authorizationUrl==null)return{type:"bearerAuth",tokenName:void 0};let r=sOu({namespace:void 0,path:this.authorizationUrl,method:"POST",sdkMethodName:void 0,operationId:void 0,displayName:void 0,isWebhook:void 0});if(r!=null)return{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:Ys.EndpointId(r),accessTokenLocator:Ys.JqString(t),headerName:this.headerAuthNode?.convert()?.headerWireValue,tokenPrefix:this.headerAuthNode?.convert()?.prefix}}}}};var jua=class extends po{authScheme;headerAuthNode;bearerTokenNode;bearerTokenVariableNameNode;basicAuthNode;basicUsernameVariableNameNode;basicPasswordVariableNameNode;oauth2Node;constructor(t){super(t),this.safeParse()}parse(){switch(this.input.type){case"http":switch(this.input.scheme){case"basic":{this.authScheme="basic",this.basicAuthNode=new Vgu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicUsernameVariableNameNode=new Ggu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new Wgu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),(this.basicAuthNode==null||this.basicAuthNode.username==null&&this.basicUsernameVariableNameNode?.usernameVariableName==null||this.basicAuthNode.password==null&&this.basicPasswordVariableNameNode?.passwordVariableName==null)&&this.context.errors.warning({message:"Basic auth should specify either a username or a username variable name",path:this.accessPath});break}case"bearer":{this.authScheme="bearer",this.bearerTokenNode=new Hgu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new xgu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}default:{this.context.errors.warning({message:`Unsupported HTTP auth scheme: ${this.input.scheme}`,path:this.accessPath});break}}break;case"apiKey":{UDh(this.input)?(this.authScheme="header",this.headerAuthNode=new mua({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})):this.context.errors.error({message:`Unsupported API key location: ${this.input.in}`,path:this.accessPath});break}case"oauth2":{this.authScheme="oauth",this.oauth2Node=new lOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}case"openIdConnect":{this.authScheme="bearer";break}}}convert(){switch(this.authScheme){case"basic":{let t=this.basicAuthNode?.convert();return{type:"basicAuth",usernameName:t?.username?.name??this.basicUsernameVariableNameNode?.convert(),passwordName:t?.password?.name??this.basicPasswordVariableNameNode?.convert()}}case"bearer":return{type:"bearerAuth",tokenName:this.bearerTokenNode?.convert()?.tokenVariableName??this.bearerTokenVariableNameNode?.convert()};case"header":return this.headerAuthNode?.convert();case"oauth":return this.oauth2Node?.convert();case void 0:return;default:new BBh.UnreachableCaseError(this.authScheme);return}}};var wua=class extends po{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(i=>{let n=Lgu(i,this.context.document);if(n==null){this.context.errors.warning({message:`No auth scheme found for ${i}. Inline security schemes are not supported.`,path:this.accessPath});return}let a=new jua({input:n,context:this.context,accessPath:this.accessPath,pathId:["security",`${r}`]});a.convert()!=null?(this.authNodesMap??={},this.authNodesMap[i]=a):this.context.errors.warning({message:`No auth scheme found for ${i}`,path:this.accessPath})}))}convert(){return Object.fromEntries(Object.entries(this.authNodesMap??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[t,i]}).filter(No))}};var fOu=class extends po{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[wDh],this.basePath!=null?(this.basePath.startsWith("/")&&(this.basePath=this.basePath.slice(1)),this.basePath.endsWith("/")&&(this.basePath=this.basePath.slice(0,-1))):this.basePath=void 0}convert(){return this.basePath}};function IBh(e){return"required"in e&&typeof e.required=="boolean"?e.required:!1}function CBh(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function Eua(e,t){return e==null?void 0:Object.entries(e).map(([i,n])=>RP(n.convert())?.map(o=>((t!=null&&!t.includes(i)||t==null&&!IBh(n))&&(o=CBh(o,o.type==="enum"?o.default:void 0)),{key:Ys.PropertyKey(i),valueShape:o,description:n.description,availability:n.availability?.convert()})).filter(No)).filter(No).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(o=>[...a,o]):[[...a]]),[[]])}function dOu(e,t){return zv(e)?iL(e,t,void 0):e}function a$i(e,t){return e!=null&&e!==""?e:t!=null&&t!==""?t:void 0}function qBh(e,t){let r={...e};for(let[i,n]of Object.entries(t??{}))r[i]=[...r[i]??[],...n];return Object.keys(r).length>0?r:void 0}function TBh(e,t){if(e==null)return t;if(t==null)return e;let r=[];for(let i of e)for(let n of t)r.push({path:i.path??n.path,responseStatusCode:i.responseStatusCode??n.responseStatusCode,name:i.name??n.name,description:i.description??n.description,pathParameters:i.pathParameters??n.pathParameters,queryParameters:i.queryParameters??n.queryParameters,headers:i.headers??n.headers,requestBody:i.requestBody??n.requestBody,responseBody:i.responseBody??n.responseBody,snippets:{...n.snippets,...i.snippets}});return r}var RBh=ce(VS());var Oxc=["decimal","decimal128","double-int","double","float","sf-decimal"],Axc=["int16","int32","int64","int8","sf-integer","uint8"],mxc=["base64url","binary","byte","char","commonmark","date-time","date","decimal","decimal128","duration","email","hostname","html","http-date","idn-email","idn-hostname","int64","ipv4","ipv6","iri-reference","iri","json-pointer","media-range","password","regex","relative-json-pointer","sf-binary","sf-boolean","sf-string","sf-token","time","uri-reference","uri-template","uri","uuid"],Pxc=["beta","pre-release","in-development","generally-available","deprecated"];function nC(e,t){return zv(e)?iL(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var FEe=class extends po{availability;constructor(t){super(t),this.safeParse()}parse(){if(nC(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[EDh];r!=null&&(Pxc.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${Pxc.join(", ")}. Received: ${r}`,path:this.accessPath}),this.availability=void 0))}}convert(){switch(this.availability){case"beta":case"pre-release":return Ys.Availability.Beta;case"in-development":return Ys.Availability.InDevelopment;case"generally-available":return Ys.Availability.GenerallyAvailable;case"deprecated":return Ys.Availability.Deprecated;case void 0:return;default:new RBh.UnreachableCaseError(this.availability);return}}};var _Ou=ce(VS());function zBh(e){return typeof e=="object"&&e!=null&&"language"in e}function NBh(e){return typeof e=="object"&&e!=null&&"sdk"in e}function FBh(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function QBh(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function pOu(e){return typeof e=="object"&&e!=null&&"event"in e}function jxc(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(pOu)}function o$i(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function UBh(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var hOu=class extends po{path;successResponseStatusCode;requestBodyByContentType;responseBodies;examples;constructor(t,r,i,n,a){super(t),this.path=r,this.successResponseStatusCode=i,this.requestBodyByContentType=n,this.responseBodies=a,this.safeParse()}parse(){this.examples=this.input[QDh]}convertFormDataExampleRequest(t,r){if(t.fields!=null)switch(t.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(t.fields).map(([n,a])=>{let o=typeof r=="object"?r[n]:void 0;switch(a.multipartType){case"file":return o$i(o)?[n,{type:"filenameWithData",filename:o.filename,data:Ys.FileId(o.data)}]:o!=null?[n,{type:"filename",value:o}]:void 0;case"files":{if(Array.isArray(o)){if(o.every(c=>o$i(c)))return[n,{type:"filenamesWithData",value:o.map(c=>({filename:c.filename,data:Ys.FileId(c.data)}))}];if(o.every(c=>typeof c=="string"))return[n,{type:"filenames",value:o}]}return}case"property":return[n,{type:"json",value:o}];case void 0:return;default:new _Ou.UnreachableCaseError(a.multipartType);return}}).filter(No))};case"json":return{type:"json",value:r};case"bytes":return typeof r=="string"?{type:"bytes",value:{type:"base64",value:r}}:void 0;default:return}}convert(){if(this.examples==null)return;this.requestBodyByContentType!=null&&Object.keys(this.requestBodyByContentType).length>1&&this.context.logger.warn(`Multiple request bodies found for #/${[this.accessPath,this.pathId,"x-fern-examples"].join("/")}. Coercing to first request body until supported.`);let t=Object.keys(this.requestBodyByContentType??{})[0];return this.examples.flatMap(r=>(this.responseBodies??[]).map(i=>{let n=t!=null?this.requestBodyByContentType?.[t]:void 0,a;if(n!=null)switch(n.contentType){case"form-data":a=UBh(r.request)?this.convertFormDataExampleRequest(n,r.request):void 0;break;case"json":a=r.request!=null?{type:"json",value:r.request}:void 0;break;case"bytes":a=typeof r.request=="string"&&r.request!=null?{type:"bytes",value:{type:"base64",value:r.request}}:void 0;break;case void 0:break;default:new _Ou.UnreachableCaseError(n.contentType);break}let o;switch(i.contentType){case"application/json":{FBh(r.response)&&(o={type:"json",value:r.response.body});break}case"text/event-stream":{jxc(r.response)&&(o={type:"sse",value:r.response.stream.map(f=>({event:f.event,data:f.data}))});break}case"application/octet-stream":!jxc(r.response)&&QBh(r.response)&&(o={type:"stream",value:r.response.stream});break;case void 0:break;default:new _Ou.UnreachableCaseError(i.contentType);break}let c={};r["code-samples"]?.forEach(f=>{zBh(f)?f.language!=null&&(c[f.language]??=[],c[f.language]?.push({name:f.name,language:f.language,install:f.install,code:f.code,generated:!1,description:f.docs})):NBh(f)&&f.sdk!=null&&(c[f.sdk]??=[],c[f.sdk]?.push({name:f.name,language:f.sdk,install:void 0,code:f.code,generated:!1,description:f.docs}))});let d=Object.fromEntries(Object.entries(r["path-parameters"]??{}).map(([f,p])=>[Ys.PropertyKey(f),p])),s=Object.fromEntries(Object.entries(r["query-parameters"]??{}).map(([f,p])=>[Ys.PropertyKey(f),p])),u=Object.fromEntries(Object.entries(r.headers??{}).map(([f,p])=>[Ys.PropertyKey(f),p]));return{path:this.path,responseStatusCode:this.successResponseStatusCode,name:r.name,description:r.docs,pathParameters:Object.keys(d).length>0?d:void 0,queryParameters:Object.keys(s).length>0?s:void 0,headers:Object.keys(u).length>0?u:void 0,requestBody:a,responseBody:o,snippets:c}}))}};var jKa=class extends po{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[Fgu]}convert(){if(this.groupName==null)return;let t;return Array.isArray(this.groupName)?t=this.groupName:t=[this.groupName],t.map(r=>Ys.api.v1.SubpackageId(o8t(r)))}};var yOu=class extends po{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[MDh]}convert(){return this.sdkMethodName}};var bOu=class extends po{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[DDh]}convert(){return this.isWebhook}};var vOu=class extends po{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[VDh]??[],...this.input[WDh]??[]],this.codeSamples.forEach(t=>{[...Object.values(Ys.api.v1.read.SupportedLanguage),"Kotlin","Swift","PHP"].map(r=>r.toLowerCase()).includes(t.lang.toLowerCase())||this.context.errors.warning({message:`Unsupported language: ${t.lang}. This may not render correctly.`,path:this.accessPath})})}convert(){let t={};if(this.codeSamples?.forEach(r=>{t[r.lang.toLowerCase()]??=[],t[r.lang.toLowerCase()]?.push({name:r.label,language:r.lang,code:r.source,install:void 0,generated:!1,description:void 0})}),Object.keys(t).length!==0)return t}};var _vn=ce(VS());function wxc(e,t){return zv(e)?iL(e,t,void 0):e}function LBh(e,t){return e.replace(/{(\w+)}/g,(r,i)=>t[i]!=null&&typeof t[i]=="string"||typeof t[i]=="number"||typeof t[i]=="boolean"?`${t[i]}`:r)}var nF="",MYt=class extends po{path;responseStatusCode;name;shapes;resolvedRequestInput;resolvedResponseInput;summary;constructor(t,r,i,n,a){super(t),this.path=r,this.responseStatusCode=i,this.name=n,this.shapes=a,this.safeParse()}validateFormDataRequestExample(){return typeof this.resolvedRequestInput?.value!="object"?!1:Object.entries(this.shapes.requestBody?.fields??{}).reduce((t,[r,i])=>{let n=this.resolvedRequestInput?.value[r];switch(i.multipartType){case"file":return t&&(o$i(n)||typeof n=="string");case"files":return t&&Array.isArray(n)&&n.every(a=>o$i(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new _vn.UnreachableCaseError(i.multipartType),t}},!0)}parse(){let t=this.shapes.requestBody?.schema?.example({includeOptionals:!1,override:void 0});this.resolvedRequestInput=wxc(this.input?.requestExample,this.context.document)??(t!=null?{value:t}:void 0);let r=this.shapes.responseBody?.schema?.example({includeOptionals:!1,override:void 0});if(this.resolvedResponseInput=wxc(this.input?.responseExample,this.context.document)??(r!=null?{value:r}:void 0),this.summary=this.input?.requestExample?.summary??this.input?.responseExample?.summary,this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody?.contentType){case"json":{if(typeof this.resolvedRequestInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break}case"bytes":{if(typeof this.resolvedRequestInput.value!="string"){this.context.errors.error({message:"Invalid example, expected string for bytes",path:this.accessPath});return}break}case"form-data":{if(!this.validateFormDataRequestExample()){this.context.errors.error({message:"Invalid example, expected valid form-data",path:this.accessPath});return}break}case void 0:break;default:new _vn.UnreachableCaseError(this.shapes.requestBody?.contentType),this.context.errors.error({message:"Invalid example, unsupported content type",path:this.accessPath});return}if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody?.contentType){case"application/json":if(this.resolvedResponseInput!=null&&typeof this.resolvedResponseInput!="object"||this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break;case"text/event-stream":if(this.resolvedResponseInput.value!=null&&!Array.isArray(this.resolvedResponseInput.value)&&!this.resolvedResponseInput.value.every(pOu)){this.context.errors.error({message:"Invalid example, expected array of SSE events for event-stream",path:this.accessPath});return}break;case"application/octet-stream":if(this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="string"&&!Array.isArray(this.resolvedResponseInput.value)){this.context.errors.error({message:"Invalid example, expected string or array for octet-stream",path:this.accessPath});return}break;case void 0:break;default:new _vn.UnreachableCaseError(this.shapes.responseBody?.contentType);return}}convertFormDataExampleRequest(){if(!(this.resolvedRequestInput==null||this.shapes.requestBody?.fields==null))switch(this.shapes.requestBody?.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(this.shapes.requestBody.fields).map(([r,i])=>{let n=this.resolvedRequestInput?.value?.[r];switch(i.multipartType){case"file":return o$i(n)?[r,{type:"filenameWithData",filename:n.filename,data:Ys.FileId(n.data)}]:[r,{type:"filename",value:n}];case"files":{if(Array.isArray(n)){if(n.every(a=>o$i(a)))return[r,{type:"filenamesWithData",value:n.map(a=>({filename:a.filename,data:Ys.FileId(a.data)}))}];if(n.every(a=>typeof a=="string"))return[r,{type:"filenames",value:n}]}return}case"property":return[r,{type:"json",value:n}];case void 0:return;default:new _vn.UnreachableCaseError(i.multipartType);return}}).filter(No))};case"json":return{type:"json",value:this.resolvedRequestInput.value};case"bytes":return typeof this.resolvedRequestInput.value=="string"?{type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}}:void 0;default:return}}convertDescription(){if(this.resolvedRequestInput!=null&&this.resolvedResponseInput!=null)return this.resolvedResponseInput.description;if(this.resolvedRequestInput!=null)return this.resolvedRequestInput.description;if(this.resolvedResponseInput!=null)return this.resolvedResponseInput.description}convert(){let t;if(this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody.contentType){case"form-data":t=this.convertFormDataExampleRequest();break;case"json":t={type:"json",value:this.resolvedRequestInput.value};break;case"bytes":t={type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}};break;case void 0:break;default:new _vn.UnreachableCaseError(this.shapes.requestBody?.contentType);break}let r;if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody.contentType){case"application/json":{r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break}case"text/event-stream":r={type:"sse",value:this.resolvedResponseInput?.value};break;case"application/octet-stream":r={type:typeof this.resolvedResponseInput?.value=="string"?"filename":"stream",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;case void 0:r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;default:new _vn.UnreachableCaseError(this.shapes.responseBody?.contentType);break}let i=Object.fromEntries(Object.entries(this.shapes.pathParameters??{}).map(([o,c])=>[o,c.example({includeOptionals:!1,override:o})]));i=Object.keys(i).length>0?i:void 0;let n=Object.fromEntries(Object.entries(this.shapes.queryParameters??{}).map(([o,c])=>c.required||c.inputExample!=null?[o,c.example({includeOptionals:!1,override:o})]:void 0).filter(No));n=Object.keys(n).length>0?n:void 0;let a=Object.fromEntries(Object.entries(this.shapes.requestHeaders??{}).map(([o,c])=>c.required||c.inputExample!=null?[o,c.example({includeOptionals:!1,override:o})]:void 0).filter(No));if(a=Object.keys(a).length>0?a:void 0,!(this.path==null&&t==null&&r==null&&a==null&&n==null&&i==null))return{path:LBh(this.path,i??{}),responseStatusCode:this.responseStatusCode,name:this.name!=null?SYt(this.name):this.summary!=null?SYt(this.summary):void 0,description:this.convertDescription(),pathParameters:i,queryParameters:n,headers:a,requestBody:t,responseBody:r,snippets:void 0}}};function VBh(e,t){return zv(e)?iL(e,t,void 0):e}var tIh=ce(VS());var WBh="#/components/schemas/";function Sua(e){if(e.$ref.startsWith(WBh))return e.$ref.replace(WBh,"")}function bUi(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}function u$i(e){return typeof e.type=="string"&&e.type==="array"}function GBh(e){return e.type==="boolean"}function HBh(e){return e.type==="integer"}function s$i(e){return!Array.isArray(e.type)&&!u$i(e)}function xBh(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||s$i(t)||u$i(t))}function KBh(e){return"nullable"in e&&typeof e.nullable=="boolean"}function JBh(e){return e.type==="null"}function $Bh(e){return e.type==="number"}function Exc(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function YBh(e){return e.type==="string"}var gOu=class extends K${item;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.item=new G0({input:this.input.items,context:this.context,accessPath:this.accessPath,pathId:"items",seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}),this.input.items==null&&this.context.errors.error({message:"Expected 'items' property to be specified",path:this.accessPath})}convert(){return RP(this.item?.convert())?.map(r=>({type:"alias",value:{type:"list",itemShape:r}}))}example(t){return this.input.example??this.input.examples?.[0]??[this.item?.example(t)]}};var OOu=class extends iC{constValue;description;availability;constructor(t){super(t),this.safeParse()}parse(){this.input.const!=null&&(typeof this.input.const=="string"||typeof this.input.const=="number"||typeof this.input.const=="boolean")?this.constValue=this.input.const.toString():this.context.errors.warning({message:`Unsupported const type: ${typeof this.input}`,path:this.accessPath}),this.description=this.input.description,this.availability=new FEe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"})}convert(){if(this.constValue!=null)return{type:"enum",default:this.constValue,values:[{value:this.constValue,description:this.description,availability:this.availability?.convert()}]}}example(){return this.input.example??this.input.examples?.[0]??this.constValue}};var AOu=class extends K${typeNodes;nullable;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.parse()}parse(){this.typeNodes=this.input.map(t=>{if(t.type==="null")this.nullable=!0;else return new G0({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName})}).filter(No)}convert(){if(this.typeNodes==null)return;let i=this.typeNodes.map(n=>RP(n.convert())?.map(o=>({displayName:n.name,shape:o,description:n.description,availability:n.availability?.convert()}))).filter(No).reduce((n,a)=>n.flatMap(o=>a.length>0?a.map(c=>[...o,c]):[[...o]]),[[]]).map(n=>({type:"undiscriminatedUnion",variants:n}));return this.nullable?i.map(bUi).filter(No):i}example(t){return this.nullable?null:this.typeNodes?.[0]?.example(t)}};function mOu(e){return e!=null&&e.length>0?e:[void 0]}var Mua=class extends K${description;extends=[];properties;extraProperties;requiredProperties;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.extends=[],this.requiredProperties=this.input.required,this.properties=Object.fromEntries(Object.entries(this.input.properties??{}).map(([t,r])=>[t,new G0({input:r,context:this.context,accessPath:this.accessPath,pathId:["properties",t],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})])),this.extraProperties=this.input.additionalProperties!=null?typeof this.input.additionalProperties=="boolean"?this.input.additionalProperties?this.input.title:void 0:new G0({input:this.input.additionalProperties,context:this.context,accessPath:this.accessPath,pathId:["additionalProperties"],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0,this.input.allOf!=null&&(this.extends=this.extends.concat(this.input.allOf.map((t,r)=>{if(zv(t))return Sua(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([i,n])=>[i,new G0({input:n,context:this.context,accessPath:this.accessPath,pathId:["allOf",r.toString(),"properties",i],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))}}).filter(No))),this.description=this.input.description}convertProperties(){if(this.properties!=null)return Eua(this.properties,this.requiredProperties)}convertExtraProperties(){return this.extraProperties==null?void 0:typeof this.extraProperties=="string"?[{type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:{type:"alias",value:{type:"unknown",displayName:this.extraProperties}}}]:RP(this.extraProperties.convert())?.map(r=>({type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:r})).filter(No)}convert(){let t=this.convertProperties();if(t==null)return;let r=this.convertExtraProperties();return t.flatMap(i=>mOu(r).map(n=>(this.extends==null||this.extends.length===0)&&i.length===0&&n!=null?{type:"alias",value:n}:{type:"object",extends:this.extends.map(a=>Ys.TypeId(a)),properties:i,extraProperties:n}))}example({includeOptionals:t}){let r={...this.properties};return this.input.allOf?.forEach(i=>{let n=nC(i,this.context.document);n!=null&&(r={...r,...Object.fromEntries(Object.entries(n.properties??{}).map(([a,o])=>[a,new G0({input:o,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))})}),this.input.example??this.input.examples?.[0]??(!t&&this.requiredProperties!=null&&this.requiredProperties.length>0?this.requiredProperties?.reduce((i,n)=>{let a=r?.[n];return i[n]=a?.example({includeOptionals:t,override:n}),i},{}):Object.entries(r).reduce((i,[n,a])=>(i[n]=a?.example({includeOptionals:t,override:n}),i),{}))}};var POu=class extends K${isNullable;discriminated;discriminant;discriminatedMapping;undiscriminatedMapping;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.input.oneOf!=null||this.input.anyOf!=null)if(this.isNullable=(this.input.oneOf??this.input.anyOf)?.some(t=>nC(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>nC(t,this.context.document)?.type!=="null"?new G0({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0).filter(No);else{let t=this.input.discriminator.mapping;if(t!=null){this.discriminated=!0,this.discriminant=this.input.discriminator.propertyName,this.discriminatedMapping={};let r=this.discriminatedMapping;Object.entries(t).map(([i,n])=>{let a=nC({$ref:n},this.context.document);if(a==null){this.context.errors.warning({message:`Expected schema reference. Received undefined reference: ${n}`,path:[...this.accessPath,"discriminator","mapping",i]});return}r[i]=new G0({input:a,context:this.context,accessPath:[...this.accessPath,"discriminator","mapping",i],pathId:i,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})})}}}convert(){if(!this.discriminated&&this.undiscriminatedMapping?.length===1){let n=this.undiscriminatedMapping?.flatMap(a=>a.convert()).filter(No);return this.isNullable&&n!=null?n.map(bUi).filter(No):n}let t=0,r=this.discriminated&&this.discriminant!=null&&this.discriminatedMapping!=null?{type:"discriminatedUnion",discriminant:Ys.PropertyKey(this.discriminant),variants:Object.entries(this.discriminatedMapping).flatMap(([n,a])=>RP(a.convert())?.map(c=>{if(!(c==null||c.type!=="object"))return{discriminantValue:n,displayName:a.name??SYt(n),availability:a.availability?.convert(),description:a.description,...c}}).filter(No)).filter(No)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(n=>RP(n.convert())?.map(o=>{if(o==null)return;t+=1;let c=o.type==="object"?SYt(`${this.schemaName??"Variant"} ${t}`):void 0;return{displayName:n.name??(o.type==="alias"&&o.value.type==="id"?SYt(o.value.id):c),shape:o,description:n.description,availability:n.availability?.convert()}}).filter(No)).filter(No)}:void 0,i=this.isNullable?bUi(r):r;return i!=null?[i]:void 0}example(t){return this.input.example??this.input.examples?.[0]??this.undiscriminatedMapping?.[0]?.example(t)??Object.values(this.discriminatedMapping??{})[0]?.example(t)}};var jOu=class extends iC{default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.input.default!=null&&typeof this.input.default!="boolean"&&this.context.errors.warning({message:`Expected default value to be a boolean. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default}convert(){return{type:"alias",value:{type:"primitive",value:{type:"boolean",default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:!1)}};var c$i=class extends iC{default;values=[];nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){if(this.input.enum!=null){let t=!0;this.values=this.input.enum.map((r,i)=>{if(t){if(zv(r)){let n=nC(r,this.context.document);r=typeof n=="string"?n:typeof n?.default=="string"?n?.default:typeof n?.example=="string"?n.example:void 0}if(typeof r!="string"){this.context.errors.error({message:`Expected enum values to be strings. Received ${r}`,path:[...this.accessPath,`enum[${i}]`]}),t=!1;return}return r}}).filter(No),this.values=Array.from(new Set(this.values))}this.default=this.input.default}convert(){return{type:"enum",values:this.values.map(t=>({value:t,description:void 0,availability:void 0})),default:this.default}}example(){return this.input.example??this.input.examples?.[0]??this.default??this.values[0]??(this.nullable?null:void 0)}};var XBh=ce(VS());function jfB(e){return Axc.includes(e)}var wOu=class extends iC{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be an integer. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(jfB(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${Axc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="integer";if(this.format!=null)switch(this.format){case"int64":t="long";break;case"int8":case"int16":case"int32":case"uint8":case"sf-integer":case void 0:t="integer";break;default:new XBh.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var EOu=class extends iC{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return bUi({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var ZBh=ce(VS());function wfB(e){return Oxc.includes(e)}var SOu=class extends iC{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be a number. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(wfB(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${Oxc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="double";if(this.format!=null)switch(this.format){case"decimal":case"decimal128":case"double-int":case"double":case"float":case"sf-decimal":case void 0:t="double";break;default:new ZBh.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var kBh=ce(VS());function EfB(e){return mxc.includes(e)}var MOu=class extends iC{format;regex;default;minLength;maxLength;enum;mimeType;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}mapToFdrType(t){switch(t){case"base64url":case"binary":case"byte":case"sf-binary":return"base64";case"date-time":return"datetime";case"int64":return"bigInteger";case"date":return"date";case"uuid":return"uuid";case"char":case"commonmark":case"decimal":case"decimal128":case"duration":case"email":case"hostname":case"html":case"http-date":case"idn-email":case"idn-hostname":case"ipv4":case"ipv6":case"iri-reference":case"iri":case"json-pointer":case"media-range":case"password":case"regex":case"relative-json-pointer":case"sf-boolean":case"sf-string":case"sf-token":case"time":case"uri-reference":case"uri-template":case"uri":case void 0:return"string";default:return new kBh.UnreachableCaseError(t),"string"}}parse(){this.regex=this.input.pattern,this.minLength=this.input.minLength,this.maxLength=this.input.maxLength,this.mimeType=this.input.contentMediaType,this.input.default!=null&&typeof this.input.default!="string"&&this.context.errors.warning({message:`Expected default value to be a string. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(EfB(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${mxc.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new c$i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"enum",nullable:this.nullable}))}convert(){if(this.enum!=null)return this.enum.convert();let t="string";return this.format!=null&&(t=this.mapToFdrType(this.format)),{type:"alias",value:{type:"primitive",value:t==="base64"?{type:t,mimeType:this.mimeType,default:this.default}:{type:t,format:t==="string"?this.format:void 0,regex:this.regex,minLength:this.minLength,maxLength:this.maxLength,default:this.default}}}}example({override:t}){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:t??"string")}};var eIh=ce(VS());var DOu=class extends iC{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,eIh.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var hvn=class extends K${description;availability;schemaId;maybeEnumConverterNode;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.description=t.description,this.availability=t.availability,this.safeParse()}parse(){this.schemaId=Sua(this.input);let t=nC(this.input,this.context.document);t?.enum!=null&&s$i(t)&&(this.maybeEnumConverterNode=new c$i({input:t,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",nullable:this.nullable})),this.schemaId==null&&this.context.errors.error({message:`Unprocessable reference: ${this.input.$ref}`,path:this.accessPath})}convert(){if(this.schemaId!=null)return{type:"alias",value:{type:"id",id:Ys.TypeId(this.schemaId),default:this.maybeEnumConverterNode?.default!=null?{type:"enum",value:this.maybeEnumConverterNode.default}:void 0}}}example(t){let r=nC(this.input,this.context.document);if(r!=null)return new G0({input:r,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName}).example(t)}};var G0=class e extends K${typeShapeNode;description;name;examples;availability;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.description=this.input.description,this.availability=new FEe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),s$i(this.input)&&KBh(this.input)&&(this.nullable=this.input.nullable!=null?this.input.nullable:this.nullable),zv(this.input)){let t=Sua(this.input);if(t==null){this.context.errors.error({message:"Reference object does not have a valid schema ID",path:this.accessPath});return}if(this.seenSchemas.has(t)){this.context.errors.warning({message:"Circular or deeply nested schema found, terminating",path:this.accessPath});return}this.seenSchemas.add(t),this.typeShapeNode=new hvn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName,description:this.description,availability:this.availability})}else if(this.name=this.input.title,this.examples=this.input.example,this.input.const!=null)this.typeShapeNode=new OOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(xBh(this.input))this.typeShapeNode=new AOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(s$i(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new POu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(Exc(this.input)&&this.input.allOf!=null)this.typeShapeNode=new Mua({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(s$i(this.input)&&this.input.enum!=null)this.typeShapeNode=new c$i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable});else if(typeof this.input.type=="string"||Array.isArray(this.input.type)&&this.input.type.length===1){if(this.input.type=Array.isArray(this.input.type)?this.input.type[0]:this.input.type,!Array.isArray(this.input.type))switch(this.input.type){case"object":Exc(this.input)&&(this.typeShapeNode=new Mua({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"array":u$i(this.input)&&(this.typeShapeNode=new gOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"boolean":GBh(this.input)&&(this.typeShapeNode=new jOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"integer":HBh(this.input)&&(this.typeShapeNode=new wOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"number":$Bh(this.input)&&(this.typeShapeNode=new SOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"string":YBh(this.input)&&(this.typeShapeNode=new MOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"null":JBh(this.input)&&(this.typeShapeNode=new EOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case void 0:break;default:new tIh.UnreachableCaseError(this.input.type);break}}else if(Array.isArray(this.input.type)&&this.input.type.includes("null")&&this.input.type.length===2){let t=this.input.type.filter(r=>r!=="null")[0];t!=="array"&&(this.typeShapeNode=new e({input:{...this.input,type:t},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:!0,schemaName:this.schemaName}))}else this.input.properties!=null&&(this.typeShapeNode=new Mua({input:{...this.input,type:"object"},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));this.typeShapeNode==null&&(this.typeShapeNode=new DOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),!zv(this.input)&&(!u$i(this.input)&&this.input==null||u$i(this.input)&&this.input.items==null)&&this.context.errors.error({message:"Expected type declaration. Received: null",path:this.accessPath}))}convert(){let t=this.typeShapeNode?.convert();if(t==null)return;let r=RP(t)?.map(i=>this.nullable?bUi(i):i).filter(No);return Array.isArray(t)&&t.length>1?r:r?.[0]}example(t){return this.availability?.availability!=="deprecated"?this.typeShapeNode?.example(t):void 0}};function l$i(e){if(e!=null)return Eua(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(No))}var DYt=class extends iC{availability;required;schema;description;inputExample;constructor(t){super(t),this.safeParse(t.parameterName)}parse(t){this.description=this.input.description;let r;zv(this.input)?r=this.input:this.input.schema!=null?(r=this.input.schema,this.required=this.input.required):(r={type:"string"},this.required=!1),this.availability=new FEe({input:r,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new G0({input:r,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:t});let i=VBh(this.input,this.context.document);this.inputExample=i?.example??Object.values(i?.examples??{})[0]}convert(){return this.schema?.convert()}example(t){return this.inputExample??this.schema?.example(t)}};function rIh(e,t){return zv(e)?iL(e,t,void 0):e}var Sxc=ce(VS());function BOu(e){let{uniqueId:t,type:r,contextTypes:i,description:n,availability:a}=e;i[Ys.TypeId(t)]={name:t,shape:r,description:n,availability:a}}var iIh=ce(IZs(),1),Dua=class e{type;subtype;essence;parameters;mimeType;input;constructor(t,r,i,n,a,o){this.type=t,this.subtype=r,this.essence=i,this.parameters=n,this.mimeType=a,this.input=o}static APPLICATION_JSON="application/json";static APPLICATION_OCTET_STREAM="application/octet-stream";static MULTIPART_FORM_DATA="multipart/form-data";static parse(t){if(t==null)return null;let r=iIh.default.parse(t);return r==null?null:new e(r.type,r.subtype,r.essence,r.parameters,r,t)}toString(){return this.input}isText(){return this.type==="text"}isImage(){return this.type==="image"}isAudio(){return this.type==="audio"}isVideo(){return this.type==="video"}isFont(){return this.type==="font"}isMultipart(){return this.type==="multipart"}isApplication(){return this.type==="application"}isMessage(){return this.type==="message"}isModel(){return this.type==="model"}isCSS(){return this.isText()&&this.subtype==="css"}isCSV(){return this.isText()&&this.subtype==="csv"}isMarkdown(){return this.isText()&&this.subtype==="markdown"}isPlainText(){return this.isText()&&this.subtype==="plain"}isEventStream(){return this.isText()&&this.subtype==="event-stream"}isMultiPartFormData(){return this.isMultipart()&&this.subtype==="form-data"}isJSON(){return this.isApplication()&&this.subtype==="json"}containsJSON(){return this.isApplication()&&this.subtype.includes("json")}isURLEncoded(){return this.isApplication()&&this.subtype==="x-www-form-urlencoded"}isOctetStream(){return this.isApplication()&&this.subtype==="octet-stream"}isPDF(){return this.isApplication()&&this.subtype==="pdf"}isZip(){return this.isApplication()&&this.subtype==="zip"}isGzip(){return this.isApplication()&&this.subtype==="gzip"}isTar(){return this.isApplication()&&this.subtype==="tar"}isBrotli(){return this.isApplication()&&this.subtype==="br"}isDeflate(){return this.isApplication()&&this.subtype==="deflate"}isProtobuf(){return this.isApplication()&&this.subtype==="protobuf"}isAvif(){return this.isImage()&&this.subtype==="avif"}isWebP(){return this.isImage()&&this.subtype==="webp"}isSVG(){return this.isImage()&&this.subtype==="svg+xml"}isPNG(){return this.isImage()&&this.subtype==="png"}isJPEG(){return this.isImage()&&this.subtype==="jpeg"}isGIF(){return this.isImage()&&this.subtype==="gif"}isMPEG(){return this.isAudio()&&this.subtype==="mpeg"}isWAV(){return this.isAudio()&&this.subtype==="wav"}isHTML(){return this.mimeType.isHTML()}isXML(){return this.mimeType.isXML()}isJavaScript(){return this.mimeType.isJavaScript()}};function SfB(e){return typeof e.securitySchemes=="object"&&e.securitySchemes!=null}var IOu=class extends po{typeSchemas;securitySchemes;constructor(t){super(t),this.safeParse()}parse(){this.input.schemas!=null&&(this.typeSchemas=Object.fromEntries(Object.entries(this.input.schemas).map(([t,r])=>[t,new G0({input:r,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:new Set,nullable:void 0,schemaName:t})]))),SfB(this.input)&&this.input.securitySchemes!=null&&(this.securitySchemes=Object.fromEntries(Object.entries(this.input.securitySchemes??{}).map(([t,r],i)=>{let n;if(zv(r)?n=Lgu(r.$ref,this.context.document):n=r,n!=null)return[t,new jua({input:n,context:this.context,accessPath:this.accessPath,pathId:["securitySchemes",`${i}`]})]}).filter(No)))}convert(){return{auths:this.securitySchemes!=null?Object.fromEntries(Object.entries(this.securitySchemes??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[Ys.api.latest.AuthSchemeId(t),i]}).filter(No)):void 0,types:this.typeSchemas!=null?Object.fromEntries(Object.entries(this.typeSchemas).map(([t,r])=>{let i=r.name??t,n=RP(r.convert());return n==null?[t,void 0]:[Ys.TypeId(t),{name:i,shape:n[0],description:r.description,availability:void 0}]}).filter(([t,r])=>No(r))):void 0}}};var COu=class extends G0{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=nC(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${zv(this.input)?`Received undefined reference: ${this.input.$ref}`:""}`,path:this.accessPath});return}if(t.type==="string"&&t.format==="binary")this.multipartType="file",this.contentType=t.contentMediaType;else if(t.type==="array"){let r=nC(t.items,this.context.document);r?.type==="string"&&r?.format==="binary"?(this.multipartType="files",this.contentType=r?.contentMediaType):(this.context.errors.warning({message:"Expected multipart form data files definition with array type with internal string type and binary format.",path:this.accessPath}),this.multipartType=void 0,this.contentType=void 0)}else this.multipartType="property",this.contentType=t.contentMediaType}};var qOu=class extends po{description;method;path;schema;isOptional;contentType;availability;requiredFields;fields;examples;constructor(t){super(t),this.method=t.method,this.path=t.path,this.safeParse(t)}parse({contentType:t}){if(this.input.schema!=null){let i=nC(this.input.schema,this.context.document);this.availability=new FEe({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=zv(this.input.schema)?new hvn({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:!1,schemaName:"Request Body",description:this.input.schema.description,availability:this.availability}):void 0;let n=Dua.parse(t);n?.containsJSON()?(this.contentType="json",this.schema=this.schema??new G0({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:"Request Body"})):n?.isOctetStream()?(this.contentType="bytes",this.isOptional=i?.required==null):n?.isMultiPartFormData()?(this.contentType="form-data",this.requiredFields=i?.required,this.fields=Object.fromEntries(Object.entries(i?.properties??{}).map(([a,o])=>{if(o!=null)return[a,new COu({input:o,context:this.context,accessPath:this.accessPath,pathId:`schema.${a}`,seenSchemas:new Set,nullable:void 0,schemaName:a})]}).filter(No))):this.context.errors.warning({message:`Expected request body of reference or object with json, streaming or form-data content types. Received: ${t}`,path:this.accessPath})}let r=this.schema?.example({includeOptionals:!0,override:void 0});this.examples={...this.input.example!=null?{[nF]:{value:this.input.example}}:{},...this.input.examples},r!=null&&Object.keys(this.examples).length===0&&(this.examples={[nF]:{value:r}})}convertJsonLike(){let t=this.schema?.convert();return t==null?void 0:RP(t)?.map(i=>{let n=i.type;switch(n){case"object":case"alias":return i;case"enum":case"undiscriminatedUnion":case"discriminatedUnion":{let a=o8t([this.method,this.path,this.contentType,"request"].join("_"));return BOu({uniqueId:a,type:i,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:Ys.TypeId(a),default:i.type==="enum"&&i.default!=null?{type:"enum",value:i.default}:void 0}}}case void 0:return;default:new Sxc.UnreachableCaseError(n);return}}).filter(No)}convert(){if(this.schema instanceof hvn)return this.schema.convert();switch(this.contentType){case"json":return this.convertJsonLike();case"bytes":return{type:"bytes",isOptional:this.isOptional??!1,contentType:this.contentType};case"form-data":return Object.entries(this.fields??{}).map(([i,n])=>{switch(n.multipartType){case"file":return[{type:n.multipartType,key:Ys.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"files":return[{type:n.multipartType,key:Ys.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"property":{let a=RP(n.convert()),o=n.multipartType;return a?.map(c=>({type:o,key:Ys.PropertyKey(i),contentType:n.contentType,exploded:void 0,valueShape:c,description:n.description,availability:n.availability?.convert()}))}case void 0:return[];default:return new Sxc.UnreachableCaseError(n.multipartType),[]}}).filter(No).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(o=>[...a,o]):[[...a]]),[[]]).map(i=>({type:"formData",fields:i,availability:this.availability?.convert(),description:this.description}));case void 0:return this.convertJsonLike();default:return}}};var TOu=class extends po{description;requestBodiesByContentType;constructor(t){super(t),this.safeParse(t)}parse({method:t,path:r}){let i=rIh(this.input,this.context.document);if(i==null){this.context.errors.error({message:"Expected request body. Received: null",path:this.accessPath});return}Object.entries(i.content).forEach(([n,a])=>{this.requestBodiesByContentType??={},this.requestBodiesByContentType[n]=new qOu({input:a,context:this.context,accessPath:this.accessPath,pathId:"content",contentType:n,method:t,path:r})})}convert(){return Object.entries(this.requestBodiesByContentType??{}).flatMap(([t,r])=>RP(r.convert())?.map(n=>({description:this.description,contentType:t,body:n}))).filter(No)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>RP(t.convert())?.map(i=>{if(!(i.type!=="alias"&&i.type!=="object"))return{description:this.description,shape:i}})).filter(No)}webhookExample(){return{payload:this.requestBodiesByContentType?.["application/json"]?.schema?.example({includeOptionals:!0,override:void 0})}}};var nIh={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};function aIh(e,t){if(zv(e)){let r=iL(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var ROu=ce(VS());var oIh="application/json";var uIh="application/octet-stream";function sIh(e,t){return e===t||t===nF||e===nF}var wKa=class extends po{streamingFormat;path;method;statusCode;requests;shapes;schema;contentType;unsupportedContentType;contentSubtype;examples;empty;constructor(t,r,i,n,a,o,c,d){super(t),this.streamingFormat=i,this.path=n,this.method=a,this.statusCode=o,this.requests=c,this.shapes=d,this.safeParse(r)}matchRequestResponseExamplesByName(t,r,i){for(let n of t)for(let[a,o]of Object.entries(n?.examples??{}))for(let[c,d]of Object.entries(r))for(let s of d)sIh(c,a)&&(i.add(c),this.examples?.push(new MYt({input:{requestExample:o,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,a$i(a,c),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}matchExamplesByIndex(t,r){let i=0;for(let n of t){let a=0;for(let[o,c]of r){if(a===i){let[d,s,u]=n??[void 0,void 0,void 0];this.examples?.push(...c.map(f=>new MYt({input:{requestExample:u,responseExample:f},context:this.context,accessPath:this.accessPath,pathId:s!=null&&s!==""?["examples",s]:"examples"},this.path,this.statusCode,a$i(s,o),{requestBody:d,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}a++}i++}if(t.length>r.length)for(let n of t.slice(r.length)){let[a,o]=r[r.length-1]??[void 0,void 0],[c,d,s]=n??[void 0,void 0,void 0];this.examples?.push(...(o??[void 0]).map(u=>new MYt({input:{requestExample:s,responseExample:u},context:this.context,accessPath:this.accessPath,pathId:d!=null&&d!==""?["examples",d]:"examples"},this.path,this.statusCode,a$i(d,a),{requestBody:c,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}if(r.length>t.length){let[n,a,o]=t[t.length-1]??[void 0,void 0,void 0];for(let[c,d]of r.slice(t.length))this.examples?.push(...d.map(s=>new MYt({input:{requestExample:o,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,a$i(a,c),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}}pushResponseExample(t,r,i,n){let a=t[nF];if(a!=null)for(let o of a)this.examples?.push(new MYt({input:{requestExample:n,responseExample:o},context:this.context,accessPath:this.accessPath,pathId:i!=null&&i!==""?["examples",i]:"examples"},this.path,this.statusCode,a$i(i,void 0),{requestBody:r,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders}))}addGlobalFallbackExample(t,r){if(t==null||t.length===0)this.pushResponseExample(r,void 0,void 0,void 0);else for(let i of t)if(Object.keys(i.examples??{}).length===0)this.pushResponseExample(r,i,void 0,void 0);else for(let[n,a]of Object.entries(i.examples??{}))this.pushResponseExample(r,i,n,a)}parse(t){if(t==="empty")this.empty=!0;else{let c=Dua.parse(t);if(c?.isJSON()||c?.isEventStream())this.contentType=oIh,this.input.schema==null?(this.streamingFormat==null||this.streamingFormat==="json")&&this.context.errors.error({message:"Expected schema for JSON response body. Received null",path:this.accessPath}):this.schema=new G0({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"type",seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"});else if(c?.isOctetStream())this.contentType=uIh,this.contentSubtype=nC(this.input.schema,this.context.document)?.contentMediaType;else if(this.unsupportedContentType=t,this.input.schema==null){this.context.errors.error({message:"Expected schema for plain text response body. Received null",path:this.accessPath});return}else this.schema=new G0({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"})}let r={};this.input.examples!=null&&(r=uOu(this.input.examples,c=>[c])),this.input.example!=null&&Object.keys(r).length===0&&(r[nF]??=[],r[nF]=[{value:this.input.example}]);let i=nC(this.input.schema,this.context.document);if(i!=null&&(i.examples!=null&&Object.keys(r).length===0&&(r=uOu(i.examples,c=>[c])),i.example!=null&&Object.keys(r).length===0&&(r[nF]??=[],r[nF]?.push({value:i.example}))),Object.keys(r).length===0){let c=this.schema?.example({includeOptionals:!0,override:void 0});r[nF]??=[],r[nF]?.push(c!=null?{value:c}:void 0)}this.examples??=[];let n=new Set;this.matchRequestResponseExamplesByName(this.requests,r,n);let a=[];for(let c of this.requests)a.push(...Object.entries(c.examples??{}).filter(([d])=>!n.has(d)&&d!==nF).map(([d,s])=>[c,d,s]));let o=Object.entries(r).filter(([c,d])=>!n.has(c)&&No(d)&&c!==nF);Object.keys(r).every(c=>c===nF)||this.matchExamplesByIndex(a,o),!n.has(nF)&&this.examples.length===0&&this.addGlobalFallbackExample(this.requests,r),this.examples.length===0&&(this.examples=void 0)}convertStreamingFormat(){switch(this.streamingFormat){case"json":return RP(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new ROu.UnreachableCaseError(this.streamingFormat);return}}convertJsonLike(){return RP(this.schema?.convert())?.map(r=>{let i=r.type;switch(i){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":{let n=o8t([this.method,this.path,this.statusCode,"response"].join("_"));return BOu({uniqueId:n,type:r,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:Ys.TypeId(n),default:r.type==="enum"&&r.default!=null?{type:"enum",value:r.default}:void 0}}}case"object":return r;default:new ROu.UnreachableCaseError(i);return}}).filter(No)}convert(){if(this.empty)return{type:"empty"};if(this.contentType!=null)switch(this.contentType){case"application/json":return this.streamingFormat==null?this.convertJsonLike():this.convertStreamingFormat();case"application/octet-stream":return{type:"fileDownload",contentType:this.contentSubtype};case"text/event-stream":return this.convertStreamingFormat();case void 0:return;default:new ROu.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?this.convertJsonLike():void 0}};var EKa=class extends po{path;method;statusCode;requests;shapes;headers;responses;description;constructor(t,r,i,n,a,o){super(t),this.path=r,this.method=i,this.statusCode=n,this.requests=a,this.shapes=o,this.safeParse()}parse(t){this.description=this.input.description;let r=aIh(this.input,this.context.document);if(r==null){this.context.errors.error({message:zv(this.input)?`Undefined reference: ${this.input.$ref}`:"Expected response, received null",path:this.accessPath});return}Object.entries(r.headers??{}).forEach(([i,n])=>{this.headers??={},this.headers[i]=new DYt({input:n,context:this.context,accessPath:this.accessPath,pathId:"headers",parameterName:i})}),r.content==null?(this.responses??=[],this.responses.push(new wKa({input:{},context:this.context,accessPath:this.accessPath,pathId:["content"]},"empty",t,this.path,this.method,this.statusCode,this.requests,this.shapes))):Object.entries(r.content??{}).forEach(([i,n])=>{this.responses??=[],this.responses.push(new wKa({input:n,context:this.context,accessPath:this.accessPath,pathId:["content",i]},i,t,this.path,this.method,this.statusCode,this.requests,this.shapes))})}convert(){return this.responses?.flatMap(t=>t.convert()).filter(No)}};var zOu=class extends po{path;method;requests;shapes;responsesByStatusCode;errorsByStatusCode;constructor(t,r,i,n,a){super(t),this.path=r,this.method=i,this.requests=n,this.shapes=a,this.safeParse()}parse(){let t=this.input.default;Object.entries(this.input).forEach(([r,i])=>{r!=="default"&&(parseInt(r)>=400?(this.errorsByStatusCode??={},this.errorsByStatusCode[r]=new EKa({input:{...t,...i},context:this.context,accessPath:this.accessPath,pathId:"errors"},this.path,this.method,parseInt(r),[],this.shapes)):(this.responsesByStatusCode??={},this.responsesByStatusCode[r]=new EKa({input:i,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,parseInt(r),this.requests,this.shapes)))})}convertResponseObjectToHttpResponses(){return Object.entries(this.responsesByStatusCode??{}).flatMap(([t,r])=>{let i=r.convert();if(i!=null)return mOu(l$i(r.headers)).flatMap(n=>i?.map(a=>({headers:n,response:{statusCode:parseInt(t),body:a,description:r.description},examples:(r.responses??[]).flatMap(o=>(o.examples??[]).map(c=>c.convert()).filter(No))})))}).filter(No)}convertResponseObjectToErrors(){return Object.entries(this.errorsByStatusCode??{}).flatMap(([t,r])=>r.responses?.flatMap(i=>{let n=i.schema,a=RP(n?.convert());if(n!=null)return a?.map(o=>({statusCode:parseInt(t),shape:o,description:r.description??n.description,availability:n.availability?.convert(),name:n.name??nIh[parseInt(t)]??"UNKNOWN ERROR",examples:i.examples?.map(c=>{let d=c.convert();if(d!=null&&d.responseBody?.type==="json")return{name:d.name,description:d.description,responseBody:d.responseBody}}).filter(No)})).filter(No)})).filter(No)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var f$i=class extends po{servers;globalAuth;path;method;basePath;isWebhook;endpointIds;description;displayName;operationId;pathParameters;queryParameters;requestHeaders;requests;responses;availability;auth;namespaces;xFernExamplesNode;redocExamplesNode;emptyResponseExamples;constructor(t){super(t),this.servers=t.servers,this.globalAuth=t.globalAuth,this.path=t.path,this.method=t.method,this.basePath=t.basePath,this.isWebhook=t.isWebhook,this.safeParse()}pushEmptyResponseExample(t,r,i){this.emptyResponseExamples??=[],this.emptyResponseExamples.push(new MYt({input:{requestExample:t,responseExample:void 0},context:this.context,accessPath:this.accessPath,pathId:"examples"},this.path,200,a$i(i,void 0),{requestBody:r,pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}))}parse(){if(this.isWebhook&&this.method!=="POST"&&this.method!=="GET"){this.context.errors.error({message:`Webhook method must be POST or GET. Received: ${this.method}`,path:this.accessPath});return}this.description=this.input.description,this.displayName=this.input.summary,this.operationId=this.input.operationId,this.availability=new FEe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=i$i(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new bOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((i,n)=>{if(zv(i)){let a=dOu(i,this.context.document);if(a!=null)i=a;else{this.context.errors.warning({message:`Expected parameter reference to resolve to an object. Received undefined reference: ${i.$ref}`,path:[...this.accessPath,`parameters[${n}]`]});return}}i.in==="path"?i.schema!=null&&(this.pathParameters??={},this.pathParameters[i.name]=new DYt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="query"?i.schema!=null&&(this.queryParameters??={},this.queryParameters[i.name]=new DYt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="header"&&i.schema!=null&&(this.requestHeaders??={},this.requestHeaders[i.name]=new DYt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name}))});for(let i of this.extractPathParameterIds()??[])this.pathParameters?.[i]==null&&this.context.errors.warning({message:`Path parameter not defined: ${i}`,path:[...this.accessPath,"parameters"]});if(this.redocExamplesNode=new vOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new TOu({input:this.input.requestBody,context:this.context,accessPath:this.accessPath,pathId:"requestBody",method:this.method,path:this.path}):void 0,this.responses=this.input.responses!=null?new zOu({input:this.input.responses,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,Object.values(this.requests?.requestBodiesByContentType??{}),{pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}):void 0,this.responses==null){let i=this.requests?.requestBodiesByContentType;i==null||Object.keys(i).length===0?this.pushEmptyResponseExample(void 0,void 0,void 0):Object.values(i).forEach(n=>{if(Object.keys(n.examples??{}).length===0){let a=n.schema?.example({includeOptionals:!1,override:void 0});a!=null&&this.pushEmptyResponseExample({value:a},n,void 0)}else Object.entries(n.examples??{}).forEach(([a,o])=>{this.pushEmptyResponseExample(o,n,a)})})}let t=200;this.responses?.responsesByStatusCode!=null&&(t=Number(Object.keys(this.responses.responsesByStatusCode)?.filter(i=>Number(i)>=200&&Number(i)<300)[0])),this.globalAuth!=null&&(this.auth=this.globalAuth),this.input.security!=null&&(this.auth=new wua({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespaces=[new jKa({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-group-name"})],this.namespaces?.every(i=>i.groupName==null)&&this.input.tags!=null&&(this.namespaces=this.input.tags.slice(0,1).map((i,n)=>new jKa({input:{[Fgu]:i},context:this.context,accessPath:this.accessPath,pathId:["tags",`${n}`]})));let r=new yOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointIds=this.namespaces.map(i=>sOu({namespace:RP(i?.groupName),path:this.path,method:this.method,sdkMethodName:r.sdkMethodName,operationId:this.input.operationId,displayName:this.displayName,isWebhook:this.isWebhook})).filter(No),this.xFernExamplesNode=new hOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-examples"},this.path,t,this.requests?.requestBodiesByContentType,this.responses?.responsesByStatusCode?.[t]?.responses)}extractPathParameterIds(){if(this.path!=null)return this.path.split("/").map(t=>{if(t.startsWith("{")&&t.endsWith("}"))return t.slice(1,-1).trim()}).filter(No)}convertPathToPathParts(){if(this.path===void 0)return;let t=this.path.startsWith("/")?this.path.slice(1):this.path,r=this.basePath?.convert();return(r?[r,...t.split("/")]:t.split("/")).reduce((n,a)=>(n.push({type:"literal",value:"/"}),a.startsWith("{")&&a.endsWith("}")?n.push({type:"pathParameter",value:Ys.PropertyKey(a.slice(1,-1).trim())}):n.push({type:"literal",value:a}),n),[])}convert(){if(this.path==null||this.endpointIds==null)return;let{responses:t,errors:r}=this.responses?.convert()??{responses:void 0,errors:void 0},i=this.emptyResponseExamples?.map(u=>u.convert()).filter(No),n=TBh(this.xFernExamplesNode?.convert(),[...i??[],...t?.flatMap(u=>u.examples)??[]])?.map(u=>({...u,snippets:qBh(u.snippets,this.redocExamplesNode?.convert())}));if(this.isWebhook)return this.endpointIds.map((u,f)=>{if(!(this.method!=="POST"&&this.method!=="GET"))return{id:Ys.WebhookId(u),description:this.description,availability:this.availability?.convert(),displayName:this.displayName,operationId:this.operationId,namespace:this.namespaces?.[f]?.convert(),method:this.method,path:this.convertPathToPathParts()?.map(p=>p.value.toString())??[],queryParameters:l$i(this.queryParameters)?.flat(),headers:l$i(this.requestHeaders)?.flat(),payloads:this.requests?.convertToWebhookPayload(),examples:[this.requests?.webhookExample()].filter(No)}}).filter(No);let a=this.servers?.map(u=>u.convert()).filter(No),o=this.convertPathToPathParts();if(o==null)return;let c,d=this.auth?.convert();d!=null&&(c=Object.keys(d));let s=t?.flatMap(u=>u.headers).filter(No);return this.endpointIds.map((u,f)=>({id:Ys.EndpointId(u),description:this.description,availability:this.availability?.convert(),namespace:this.namespaces?.[f]?.convert()?.map(p=>Ys.api.v1.SubpackageId(p)),displayName:this.displayName,operationId:this.operationId,method:this.method,path:o,auth:c?.map(p=>Ys.api.latest.AuthSchemeId(p)),defaultEnvironment:a?.[0]?.id,environments:a,pathParameters:l$i(this.pathParameters)?.flat(),queryParameters:l$i(this.queryParameters)?.flat(),requestHeaders:l$i(this.requestHeaders)?.flat(),responseHeaders:s!=null&&s.length>0?s:void 0,requests:this.requests?.convert(),responses:t?.map(p=>p.response),errors:r,examples:n,snippetTemplates:void 0,protocol:{type:"rest"}}))}};var Bua=class extends po{description;get;post;put;patch;delete;path;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i,isWebhook:n}){this.description=this.input.description;let a=i$i(t,this.input.servers,this.context,this.accessPath),o=Array.isArray(this.pathId)?this.pathId.join("/"):this.pathId;this.input.get!=null&&(this.get=new f$i({input:this.input.get,context:this.context,accessPath:this.accessPath,pathId:"get",servers:a,globalAuth:r,path:o,method:"GET",basePath:i,isWebhook:n})),this.input.post!=null&&(this.post=new f$i({input:this.input.post,context:this.context,accessPath:this.accessPath,pathId:"post",servers:a,globalAuth:r,path:o,method:"POST",basePath:i,isWebhook:n})),this.input.put!=null&&(this.put=new f$i({input:this.input.put,context:this.context,accessPath:this.accessPath,pathId:"put",servers:a,globalAuth:r,path:o,method:"PUT",basePath:i,isWebhook:!1})),this.input.patch!=null&&(this.patch=new f$i({input:this.input.patch,context:this.context,accessPath:this.accessPath,pathId:"patch",servers:a,globalAuth:r,path:o,method:"PATCH",basePath:i,isWebhook:!1})),this.input.delete!=null&&(this.delete=new f$i({input:this.input.delete,context:this.context,accessPath:this.accessPath,pathId:"delete",servers:a,globalAuth:r,path:o,method:"DELETE",basePath:i,isWebhook:!1}))}convert(){return[...this.get?.convert()??[],...this.post?.convert()??[],...this.put?.convert()??[],...this.patch?.convert()??[],...this.delete?.convert()??[]].filter(No)}};function NOu(e){return"payloads"in e}var FOu=class extends po{paths;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.paths=Object.entries(this.input).map(([n,a])=>{if(a!=null)return new Bua({input:a,context:this.context,accessPath:this.accessPath,pathId:n,servers:i$i(t,a.servers,this.context,this.accessPath),globalAuth:r,basePath:i,isWebhook:void 0})}).filter(No)}convert(){if(this.paths==null)return;let t={},r={};return this.paths.forEach(i=>{let n=i.convert();n?.forEach(a=>{NOu(a)?r[Ys.WebhookId(a.id)]=a:t[Ys.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var QOu=class extends po{globalHeaders;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[SDh]?.map(r=>{let{header:i,...n}=r;return(n.optional!=null&&!n.optional||dOu(n,this.context.document)?.required)&&(this.requiredProperties??=[],this.requiredProperties?.push(i)),[i,new DYt({input:n,context:this.context,accessPath:this.accessPath,pathId:this.pathId,parameterName:i})]});t!=null&&(this.globalHeaders=Object.fromEntries(t))}convert(){return Eua(this.globalHeaders,this.requiredProperties)?.flat()}};function cIh(e,t){if(zv(e)){let r=iL(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var UOu=class extends po{webhooks;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.webhooks=Object.entries(this.input??{}).map(([n,a])=>{let o=cIh(a,this.context.document);if(o!=null)return new Bua({input:o,context:this.context,accessPath:this.accessPath,pathId:n,servers:t,globalAuth:r,basePath:i,isWebhook:!0})}).filter(No)}convert(){return this.webhooks?.reduce((t,r)=>(r.convert()?.forEach(i=>{NOu(i)&&(t[Ys.WebhookId(i.id)]=i)}),t),{})}};var LOu=class extends po{paths;webhooks;components;auth;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){let t=i$i(void 0,this.input.servers,this.context,this.accessPath);this.input.security!=null&&(this.auth=new wua({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"}));let r=new fOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});this.input.paths==null&&this.input.webhooks==null&&this.context.errors.warning({message:"Expected 'paths' or 'webhooks' property to be specified",path:this.accessPath}),this.input.paths!=null&&(this.paths=new FOu({input:this.input.paths,context:this.context,accessPath:this.accessPath,pathId:"paths",basePath:r,servers:t,globalAuth:this.auth})),this.input.webhooks!=null&&(this.webhooks=new UOu({input:this.input.webhooks,context:this.context,accessPath:this.accessPath,pathId:"webhooks",basePath:r,servers:t,globalAuth:this.auth})),this.input.components!=null&&(this.components=new IOu({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"})),this.globalHeaders=new QOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=Hbe(),{webhookEndpoints:r,endpoints:i}=this.paths?.convert()??{},n={...this.webhooks?.convert()??{},...r??{}},a=PDh({endpoints:i,webhookEndpoints:n}),{types:o,auths:c}=this.components?.convert()??{};return{id:Ys.ApiDefinitionId(t),endpoints:i??{},websockets:{},webhooks:n,types:{...o,...this.context.generatedTypes},subpackages:a,auths:{...c,...this.auth?.convert()??{}},globalHeaders:this.globalHeaders?.convert(),snippetsConfiguration:void 0}}};async function Mxc(e,t){if(e instanceof SEe){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof ZE))return;let r=new J3t(e.absoluteFilePath),i=await DEe({context:t,specs:e.specs}),n=await r.loadDocuments({context:t,specs:i}),a;for(let o of n){if(o.type!=="openapi")continue;let c={document:o.value,logger:t.logger,errors:new zgu,generatedTypes:{}},d=new LOu({input:o.value,context:c,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=KZs(a,d.convert())}return a}var S4h=ce(Ixc(),1),M4h=ce(DAu(),1),kmu=require("fs/promises"),D4h=ce(require("http"),1),B4h=ce(require("path"),1);var pRh=require("events"),TAu=ce(require("fs"),1),wvn=ce(require("path"),1);var $Th=ce(require("os"),1),YTh=300,v$i=20,$Ka=1e7,XTh=$Th.default.platform();var $vB=XTh==="darwin",XKc=XTh==="win32",g$i=$vB||XKc,ZTh=3e3,kTh=2e4,ZKc=1250;var qYt;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(qYt||(qYt={}));var jvn;(function(e){e.CHANGE="change",e.RENAME="rename"})(jvn||(jvn={}));var YKa;(function(e){e.CHANGE="change",e.ERROR="error"})(YKa||(YKa={}));var Hl;(function(e){e.ADD="add",e.ADD_DIR="addDir",e.CHANGE="change",e.RENAME="rename",e.RENAME_DIR="renameDir",e.UNLINK="unlink",e.UNLINK_DIR="unlinkDir"})(Hl||(Hl={}));var nH;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(nH||(nH={}));var YvB=(e,t=1,r)=>{t=Math.max(1,t);let i=r?.leading??!1,n=r?.trailing??!0,a=Math.max(r?.maxWait??1/0,t),o,c,d=0,s=0,u=()=>{let g=Date.now(),m=g-d,j=g-s,S=m>=t||j>=a;return[g,S]},f=g=>{if(s=g,!o)return;let m=o;o=void 0,e.apply(void 0,m)},p=()=>{O(0)},_=()=>{c&&(p(),f(Date.now()))},h=g=>{if(s=g,i)return f(g)},y=g=>{if(n&&o)return f(g);o=void 0},b=()=>{c=void 0;let[g,m]=u();return m?y(g):v(g)},v=g=>{let m=g-d,j=g-s,S=t-m,w=a-j,D=Math.min(S,w);return O(D)},O=g=>{c&&clearTimeout(c),!(g<=0)&&(c=setTimeout(b,g))},A=(...g)=>{let[m,j]=u(),S=!!c;if(o=g,d=m,(j||!c)&&O(t),j)return S?f(m):h(m)};return A.cancel=p,A.flush=_,A},BAu=YvB;var rJc=ce(require("fs"),1),CAu=ce(require("path"),1);var KO=ce(require("fs"),1),nL=require("util");var gUi=(e,t)=>function(...i){return e.apply(void 0,i).catch(t)},TYt=(e,t)=>function(...i){try{return e.apply(void 0,i)}catch(n){return t(n)}};var kKc=ce(require("process"),1),eRh=kKc.default.getuid?!kKc.default.getuid():!1,tRh=1e4,X$=()=>{};var XKa={isChangeErrorOk:e=>{if(!XKa.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!eRh&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!XKa.isNodeError(e))return!1;let{code:t}=e;return t==="EMFILE"||t==="ENFILE"||t==="EAGAIN"||t==="EBUSY"||t==="EACCESS"||t==="EACCES"||t==="EACCS"||t==="EPERM"},onChangeError:e=>{if(!XKa.isNodeError(e))throw e;if(!XKa.isChangeErrorOk(e))throw e}},aC=XKa;var eJc=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=tRh,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(i),i=()=>t(r);this.add(i)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},rRh=new eJc;var OUi=(e,t)=>function(i){return function n(...a){return rRh.schedule().then(o=>{let c=s=>(o(),s),d=s=>{if(o(),Date.now()>=i)throw s;if(t(s)){let u=Math.round(100*Math.random());return new Promise(p=>setTimeout(p,u)).then(()=>n.apply(void 0,a))}throw s};return e.apply(void 0,a).then(c,d)})}},AUi=(e,t)=>function(i){return function n(...a){try{return e.apply(void 0,a)}catch(o){if(Date.now()>i)throw o;if(t(o))return n.apply(void 0,a);throw o}}};var XvB={attempt:{chmod:gUi((0,nL.promisify)(KO.default.chmod),aC.onChangeError),chown:gUi((0,nL.promisify)(KO.default.chown),aC.onChangeError),close:gUi((0,nL.promisify)(KO.default.close),X$),fsync:gUi((0,nL.promisify)(KO.default.fsync),X$),mkdir:gUi((0,nL.promisify)(KO.default.mkdir),X$),realpath:gUi((0,nL.promisify)(KO.default.realpath),X$),stat:gUi((0,nL.promisify)(KO.default.stat),X$),unlink:gUi((0,nL.promisify)(KO.default.unlink),X$),chmodSync:TYt(KO.default.chmodSync,aC.onChangeError),chownSync:TYt(KO.default.chownSync,aC.onChangeError),closeSync:TYt(KO.default.closeSync,X$),existsSync:TYt(KO.default.existsSync,X$),fsyncSync:TYt(KO.default.fsync,X$),mkdirSync:TYt(KO.default.mkdirSync,X$),realpathSync:TYt(KO.default.realpathSync,X$),statSync:TYt(KO.default.statSync,X$),unlinkSync:TYt(KO.default.unlinkSync,X$)},retry:{close:OUi((0,nL.promisify)(KO.default.close),aC.isRetriableError),fsync:OUi((0,nL.promisify)(KO.default.fsync),aC.isRetriableError),open:OUi((0,nL.promisify)(KO.default.open),aC.isRetriableError),readFile:OUi((0,nL.promisify)(KO.default.readFile),aC.isRetriableError),rename:OUi((0,nL.promisify)(KO.default.rename),aC.isRetriableError),stat:OUi((0,nL.promisify)(KO.default.stat),aC.isRetriableError),write:OUi((0,nL.promisify)(KO.default.write),aC.isRetriableError),writeFile:OUi((0,nL.promisify)(KO.default.writeFile),aC.isRetriableError),closeSync:AUi(KO.default.closeSync,aC.isRetriableError),fsyncSync:AUi(KO.default.fsyncSync,aC.isRetriableError),openSync:AUi(KO.default.openSync,aC.isRetriableError),readFileSync:AUi(KO.default.readFileSync,aC.isRetriableError),renameSync:AUi(KO.default.renameSync,aC.isRetriableError),statSync:AUi(KO.default.statSync,aC.isRetriableError),writeSync:AUi(KO.default.writeSync,aC.isRetriableError),writeFileSync:AUi(KO.default.writeFileSync,aC.isRetriableError)}},iRh=XvB;var IAu=ce(require("fs"),1),ZKa=ce(require("path"),1);var tJc=()=>{};var ZvB=()=>{let e=tJc,t=tJc,r=!1,i=!1;return{promise:new Promise((d,s)=>{e=u=>(r=!0,d(u)),t=u=>(i=!0,s(u))}),resolve:e,reject:t,isPending:()=>!r&&!i,isResolved:()=>r,isRejected:()=>i}},nRh=ZvB;var kvB=()=>{let{promise:e,resolve:t,isPending:r}=nRh(),i=0,n=()=>{i+=1},a=()=>{i-=1,!i&&t()};return(()=>{n(),queueMicrotask(a)})(),{promise:e,isPending:r,increment:n,decrement:a}},aRh=kvB;var oRh={then:e=>{e()}};var uRh=e=>Array.isArray(e)?e:[e],sRh=e=>typeof e=="function";var egB=(e,t)=>{let r=t?.followSymlinks??!1,i=t?.depth??1/0,n=t?.limit??1/0,a=t?.ignore??[],o=uRh(a).map(H=>sRh(H)?H:G=>H.test(G)),c=H=>o.some(G=>G(H)),d=t?.signal??{aborted:!1},s=t?.onDirents||(()=>{}),u=[],f=new Set,p={},_=[],h=new Set,y={},b=[],v=new Set,O={},A={},g=new Set,m={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},j={directories:u,directoriesNames:f,directoriesNamesToPaths:p,files:_,filesNames:h,filesNamesToPaths:y,symlinks:b,symlinksNames:v,symlinksNamesToPaths:O,map:A},{promise:S,increment:w,decrement:D}=aRh(),B=0,q=(H,G,Ee,ue)=>{g.has(G)||B>=n||(B+=1,H.directories.push(G),H.directoriesNames.add(Ee),u.push(G),f.add(Ee),p.propertyIsEnumerable(Ee)||(p[Ee]=[]),p[Ee].push(G),g.add(G),!(ue>=i)&&(B>=n||ee(G,ue+1)))},U=(H,G,Ee)=>{g.has(G)||B>=n||(B+=1,H.files.push(G),H.filesNames.add(Ee),_.push(G),h.add(Ee),y.propertyIsEnumerable(Ee)||(y[Ee]=[]),y[Ee].push(G),g.add(G))},R=(H,G,Ee,ue)=>{g.has(G)||B>=n||(B+=1,H.symlinks.push(G),H.symlinksNames.add(Ee),b.push(G),v.add(Ee),O.propertyIsEnumerable(Ee)||(O[Ee]=[]),O[Ee].push(G),g.add(G),r&&(ue>=i||B>=n||me(G,ue+1)))},N=(H,G,Ee,ue,ge)=>{d.aborted||c(G)||(ue.isDirectory()?q(H,G,Ee,ge):ue.isFile()?U(H,G,Ee):ue.isSymbolicLink()&&R(H,G,Ee,ge))},F=(H,G,Ee,ue)=>{if(d.aborted)return;let ge=G===ZKa.default.sep?"":ZKa.default.sep,We=Ee.name,se=`${G}${ge}${We}`;c(se)||(Ee.isDirectory()?q(H,se,We,ue):Ee.isFile()?U(H,se,We):Ee.isSymbolicLink()&&R(H,se,We,ue))},x=(H,G,Ee,ue)=>{for(let ge=0,We=Ee.length;ge<We;ge++)F(H,G,Ee[ge],ue)},ee=(H,G)=>{d.aborted||G>i||B>=n||(w(),IAu.default.readdir(H,{withFileTypes:!0},(Ee,ue)=>{if(Ee||d.aborted||!ue.length)return D();(s(ue)||oRh).then(()=>{let We=A[H]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};x(We,H,ue,G),D()})}))},me=(H,G)=>{w(),IAu.default.realpath(H,(Ee,ue)=>{if(Ee||d.aborted)return D();IAu.default.stat(ue,(ge,We)=>{if(ge||d.aborted)return D();let se=ZKa.default.basename(ue),ne=A[H]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};N(ne,ue,se,We,G),D()})})};return(async(H,G=1)=>(H=ZKa.default.normalize(H),g.add(H),ee(H,G),await S,d.aborted?m:j))(e)},cRh=egB;var RYt={lang:{debounce:BAu,attempt:e=>{try{return e()}catch(t){return RYt.lang.castError(t)}},castArray:e=>RYt.lang.isArray(e)?e:[e],castError:e=>RYt.lang.isError(e)?e:RYt.lang.isString(e)?new Error(e):new Error("Unknown error"),defer:e=>setTimeout(e,0),isArray:e=>Array.isArray(e),isError:e=>e instanceof Error,isFunction:e=>typeof e=="function",isNaN:e=>Number.isNaN(e),isNumber:e=>typeof e=="number",isPrimitive:e=>{if(e===null)return!0;let t=typeof e;return t!=="object"&&t!=="function"},isShallowEqual:(e,t)=>{if(e===t)return!0;if(RYt.lang.isNaN(e))return RYt.lang.isNaN(t);if(RYt.lang.isPrimitive(e)||RYt.lang.isPrimitive(t))return e===t;for(let r in e)if(!(r in t))return!1;for(let r in t)if(e[r]!==t[r])return!1;return!0},isSet:e=>e instanceof Set,isString:e=>typeof e=="string",isUndefined:e=>e===void 0,noop:()=>{},uniq:e=>e.length<2?e:Array.from(new Set(e))},fs:{getDepth:e=>Math.max(0,e.split(CAu.default.sep).length-1),getRealPath:(e,t)=>{try{return t?rJc.default.realpathSync.native(e):rJc.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===CAu.default.sep&&t.length-e.length>CAu.default.sep.length,poll:(e,t=kTh)=>iRh.retry.stat(t)(e,{bigint:!0}).catch(RYt.lang.noop),readdir:async(e,t,r=1/0,i=1/0,n,a)=>{if(a&&r===1&&e in a){let o=a[e];return[o.directories,o.files]}else{let o=await cRh(e,{depth:r,limit:i,ignore:t,signal:n});return[o.directories,o.files]}}}},Mp=RYt;var qAu=ce(require("path"),1);var iJc=class{constructor(t,r,i){this.base=i,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||Mp.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=YTh){return(()=>{let r=this.watcher._readyWait,i=[],n=new Set,a=async(c,d)=>{let s=this.options.ignoreInitial?[]:c,u=await this.eventsPopulate([...d]),f=this.eventsDeduplicate([...s,...u]);this.onTargetEvents(f)},o=Mp.lang.debounce(()=>{this.watcher.isClosed()||(r=a(i,n),i=[],n=new Set)},t);return async(c,d="",s=!1)=>{s?await this.eventsPopulate([d],i,!0):n.add(d),r.then(o)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((i,n)=>{let[a,o]=n,c=r[o];return a===c||a===Hl.CHANGE&&c===Hl.ADD||(r[o]=a,i.push(n)),i},[])}async eventsPopulate(t,r=[],i=!1){return await Promise.all(t.map(async n=>{let a=await this.watcher._poller.update(n,this.options.pollingTimeout);await Promise.all(a.map(async o=>{r.push([o,n]),o===Hl.ADD_DIR?await this.eventsPopulateAddDir(t,n,r,i):o===Hl.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,n,r,i)}))})),r}async eventsPopulateAddDir(t,r,i=[],n=!1){if(n)return i;let a=this.options.recursive?this.options.depth??v$i:Math.min(1,this.options.depth??v$i),o=this.options.limit??$Ka,[c,d]=await Mp.fs.readdir(r,this.options.ignore,a,o,this.watcher._closeSignal),s=[...c,...d];return await Promise.all(s.map(u=>{if(!this.watcher.isIgnored(u,this.options.ignore)&&!t.includes(u))return this.eventsPopulate([u],i,!0)})),i}async eventsPopulateUnlinkDir(t,r,i=[],n=!1){if(n)return i;for(let a of this.watcher._poller.stats.keys())Mp.fs.isSubPath(r,a)&&(t.includes(a)||await this.eventsPopulate([a],i,!0));return i}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(Hl.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!g$i&&this.options.native!==!1&&this.watcher.watchDirectory(t,this.options,this.handler,void 0,this.base||this),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAddDir(t,this.options.renameTimeout):this.watcher.event(Hl.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(Hl.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(qAu.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(Hl.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(qAu.default.dirname(t),t,!1),this.watcher.watchersClose(t),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlinkDir(t,this.options.renameTimeout):this.watcher.event(Hl.UNLINK_DIR,t))}onTargetEvent(t){let[r,i]=t;r===Hl.ADD?this.onTargetAdd(i):r===Hl.ADD_DIR?this.onTargetAddDir(i):r===Hl.CHANGE?this.onTargetChange(i):r===Hl.UNLINK?this.onTargetUnlink(i):r===Hl.UNLINK_DIR&&this.onTargetUnlinkDir(i)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,i=!1){return this.handlerBatched(t,r,i)}onWatcherChange(t=jvn.CHANGE,r){if(this.watcher.isClosed())return;let i=qAu.default.resolve(this.folderPath,r||"");this.filePath&&i!==this.folderPath&&i!==this.filePath||this.watcher.isIgnored(i,this.options.ignore)||this.onWatcherEvent(t,i)}onWatcherError(t){XKc&&t.code==="EPERM"?this.onWatcherChange(jvn.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(YKa.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(YKa.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(jvn.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&g$i&&this.options.native!==!1?this.options.depth??v$i:Math.min(1,this.options.depth??v$i),i=this.options.limit??$Ka,[n,a]=await Mp.fs.readdir(this.folderPath,this.options.ignore,r,i,this.watcher._closeSignal,this.options.readdirMap),o=[this.folderPath,...n,...a];await Promise.all(o.map(c=>{if(!this.watcher._poller.stats.has(c)&&!this.watcher.isIgnored(c,this.options.ignore))return this.onWatcherEvent(jvn.CHANGE,c,t)}))}}},lRh=iJc;var aH={interval:100,intervalId:void 0,fns:new Map,init:()=>{aH.intervalId||(aH.intervalId=setInterval(aH.resolve,aH.interval))},reset:()=>{aH.intervalId&&(clearInterval(aH.intervalId),delete aH.intervalId)},add:(e,t)=>{aH.fns.set(e,Date.now()+t),aH.init()},remove:e=>{aH.fns.delete(e)},resolve:()=>{if(!aH.fns.size)return aH.reset();let e=Date.now();for(let[t,r]of aH.fns)r>=e||(aH.remove(t),t())}},kKa=aH;var eJa=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=ZKc){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{let f=this._watcher._poller.paths.find(i||-1,p=>p!==n);if(f&&f!==n){if(Mp.fs.getRealPath(n,!0)===f)return;this._watcher.event(a.rename,f,n)}else this._watcher.event(a.add,n)};if(!i)return c();let d=()=>{o.add.delete(i),kKa.remove(s)},s=()=>{d(),c()};kKa.add(s,r);let u=()=>{let f=o.unlink.get(i);if(!f)return;d();let p=f();n===p?a.change&&this._watcher._poller.stats.has(n)&&this._watcher.event(a.change,n):this._watcher.event(a.rename,p,n)};o.add.set(i,u),u()}getLockUnlink(t,r=ZKc){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{this._watcher.event(a.unlink,n)};if(!i)return c();let d=()=>{o.unlink.delete(i),kKa.remove(s)},s=()=>{d(),c()};kKa.add(s,r);let u=()=>(d(),n);o.unlink.set(i,u),o.add.get(i)?.()}getLockTargetAdd(t,r){let i=this._watcher._poller.getIno(t,Hl.ADD,qYt.FILE);return this.getLockAdd({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let i=this._watcher._poller.getIno(t,Hl.ADD_DIR,qYt.DIR);return this.getLockAdd({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let i=this._watcher._poller.getIno(t,Hl.UNLINK,qYt.FILE);return this.getLockUnlink({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let i=this._watcher._poller.getIno(t,Hl.UNLINK_DIR,qYt.DIR);return this.getLockUnlink({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};eJa.DIR_EVENTS={add:Hl.ADD_DIR,rename:Hl.RENAME_DIR,unlink:Hl.UNLINK_DIR};eJa.FILE_EVENTS={add:Hl.ADD,change:Hl.CHANGE,rename:Hl.RENAME,unlink:Hl.UNLINK};var fRh=eJa;var nJc=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(Mp.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let i=this.map.get(t);if(Mp.lang.isSet(i)){let n=i.delete(r);return i.size||this.map.delete(t),n}else if(i===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let i=this.map.get(t);if(Mp.lang.isSet(i))return Array.from(i).find(r);if(r(i))return i}}get(t){return this.map.get(t)}has(t,r){if(Mp.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let i=this.map.get(t);return Mp.lang.isSet(i)?i.has(r):i===r}return!1}set(t,r){if(this.map.has(t)){let i=this.map.get(t);Mp.lang.isSet(i)?i.add(r):i!==r&&this.map.set(t,new Set([i,r]))}else this.map.set(t,r);return this}},aJc=nJc;var oJc=class{constructor(t){this.ino=t.ino<=Number.MAX_SAFE_INTEGER?Number(t.ino):t.ino,this.size=Number(t.size),this.atimeMs=Number(t.atimeMs),this.mtimeMs=Number(t.mtimeMs),this.ctimeMs=Number(t.ctimeMs),this.birthtimeMs=Number(t.birthtimeMs),this._isFile=t.isFile(),this._isDirectory=t.isDirectory(),this._isSymbolicLink=t.isSymbolicLink()}isFile(){return this._isFile}isDirectory(){return this._isDirectory}isSymbolicLink(){return this._isSymbolicLink}},dRh=oJc;var uJc=class{constructor(){this.inos={},this.paths=new aJc,this.stats=new Map}getIno(t,r,i){let n=this.inos[r];if(!n)return;let a=n[t];if(a&&!(i&&a[1]!==i))return a[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let i=await Mp.fs.poll(t,r);if(!(!i||!(i.isFile()||i.isDirectory())))return new dRh(i)}reset(){this.inos={},this.paths=new aJc,this.stats=new Map}async update(t,r){let i=this.getStats(t),n=await this.poll(t,r);if(this.updateStats(t,n),!i&&n){if(n.isFile())return this.updateIno(t,Hl.ADD,n),[Hl.ADD];if(n.isDirectory())return this.updateIno(t,Hl.ADD_DIR,n),[Hl.ADD_DIR]}else if(i&&!n){if(i.isFile())return this.updateIno(t,Hl.UNLINK,i),[Hl.UNLINK];if(i.isDirectory())return this.updateIno(t,Hl.UNLINK_DIR,i),[Hl.UNLINK_DIR]}else if(i&&n){if(i.isFile()){if(n.isFile())return i.ino===n.ino&&!i.size&&!n.size?[]:(this.updateIno(t,Hl.CHANGE,n),[Hl.CHANGE]);if(n.isDirectory())return this.updateIno(t,Hl.UNLINK,i),this.updateIno(t,Hl.ADD_DIR,n),[Hl.UNLINK,Hl.ADD_DIR]}else if(i.isDirectory()){if(n.isFile())return this.updateIno(t,Hl.UNLINK_DIR,i),this.updateIno(t,Hl.ADD,n),[Hl.UNLINK_DIR,Hl.ADD];if(n.isDirectory())return i.ino===n.ino?[]:(this.updateIno(t,Hl.UNLINK_DIR,i),this.updateIno(t,Hl.ADD_DIR,n),[Hl.UNLINK_DIR,Hl.ADD_DIR])}}return[]}updateIno(t,r,i){let n=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=i.isFile()?qYt.FILE:qYt.DIR;n[t]=[i.ino,a]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let i=this.stats.get(t)?.ino||-1;this.paths.delete(i,t),this.stats.delete(t)}}},sJc=uJc;var cJc=class e extends pRh.EventEmitter{constructor(t,r,i){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(nH.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(n=>this.on(nH.CLOSE,n)),this._readyWait=new Promise(n=>this.on(nH.READY,n)),this._locker=new fRh(this),this._roots=new Set,this._poller=new sJc,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,i)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(Mp.lang.isFunction(r)?!!r(t):r.test(t))}isReady(){return this._ready}close(){return this._locker.reset(),this._poller.reset(),this._roots.clear(),this.watchersClose(),this.isClosed()?!1:(this._closed=!0,this.emit(nH.CLOSE))}error(t){if(this.isClosed())return!1;let r=Mp.lang.castError(t);return this.emit(nH.ERROR,r)}event(t,r,i){return this.isClosed()?!1:(this.emit(nH.ALL,t,r,i),this.emit(t,r,i))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(nH.READY))}pollerExists(t,r){for(let i of this._pollers)if(i.targetPath===t&&Mp.lang.isShallowEqual(i.options,r))return!0;return!1}subwatcherExists(t,r){for(let i of this._subwatchers)if(i.targetPath===t&&Mp.lang.isShallowEqual(i.options,r))return!0;return!1}watchersClose(t,r,i=!0){if(t){let n=this._watchers[t];if(n)for(let a of[...n])r&&a.filePath!==r||this.watcherClose(a);if(i)for(let a in this._watchers)Mp.fs.isSubPath(t,a)&&this.watchersClose(a,r,!1)}else for(let n in this._watchers)this.watchersClose(n,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,i]of t)this.watchPath(r,i.options,i.handler)}async watcherAdd(t,r){let{folderPath:i}=t;(this._watchers[i]=this._watchers[i]||[]).push(t);let a=new lRh(this,t,r);return await a.init(),a}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let a=r.indexOf(t);r.splice(a,1),r.length||delete this._watchers[t.folderPath]}let i=t.filePath||t.folderPath;this._roots.has(i)&&(this._watchersRestorable[i]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=Mp.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,i,n){if(this._watchers[t]?.find(c=>c.handler===i&&(!c.filePath||c.filePath===n)&&c.options.ignore===r.ignore&&!!c.options.native==!!r.native&&(!r.recursive||c.options.recursive)))return!0;let o=wvn.default.dirname(t);for(let c=1;c<1/0;c++){if(this._watchers[o]?.find(u=>(c===1||u.options.recursive&&c<=(u.options.depth??v$i))&&u.handler===i&&(!u.filePath||u.filePath===n)&&u.options.ignore===r.ignore&&!!u.options.native==!!r.native&&(!r.recursive||u.options.recursive&&g$i&&u.options.native!==!1)))return!0;if(!g$i)break;let s=wvn.default.dirname(t);if(o===s)break;o=s}return!1}async watchDirectories(t,r,i,n,a){if(this.isClosed())return;t=Mp.lang.uniq(t).sort();let o;for(let c of t)if(!this.isIgnored(c,r.ignore)&&!this.watcherExists(c,r,i,n))try{let d=!r.recursive||g$i&&r.native!==!1?r:{...r,recursive:!1},u={watcher:TAu.default.watch(c,d),handler:i,options:r,folderPath:c,filePath:n},f=o=await this.watcherAdd(u,a);if(this._roots.has(n||c)){let _={...r,ignoreInitial:!0,recursive:!1},h=wvn.default.dirname(c),y=c;await this.watchDirectories([h],_,i,y,f)}}catch(d){this.error(d)}return o}async watchDirectory(t,r,i,n,a){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||g$i&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,i,n,a));{r={...r,recursive:!0};let o=r.depth??v$i,c=r.limit??$Ka,[d]=await Mp.fs.readdir(t,r.ignore,o,c,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let s=await this.watchDirectories([t],r,i,n,a);if(d.length){let u=Mp.fs.getDepth(t);for(let f of d){let p=Mp.fs.getDepth(f),_=Math.max(0,o-(p-u)),h={...r,depth:_};await this.watchDirectories([f],h,i,n,a||s)}}})}}}async watchFileOnce(t,r,i){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let n={targetPath:t,options:r},a=(s,u)=>{u===t&&(d(),i())},o=new e(a),c=()=>{this._subwatchers.add(n),this.on(nH.CLOSE,d),o.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(n),this.removeListener(nH.CLOSE,d),o.close()};return c()}async watchFile(t,r,i){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let n=wvn.default.dirname(t);return this.watchDirectory(n,r,i,t)}async watchPollingOnce(t,r,i){if(this.isClosed())return;let n=!1,a=new sJc,o=await this.watchPolling(t,r,async()=>{n||!(await a.update(t,r.pollingTimeout)).length||n||(n=!0,o(),i())})}async watchPolling(t,r,i){if(this.isClosed())return Mp.lang.noop;if(this.pollerExists(t,r))return Mp.lang.noop;let n={...r,interval:r.pollingInterval??ZTh},a={targetPath:t,options:r},o=()=>{this._pollers.add(a),this.on(nH.CLOSE,c),TAu.default.watchFile(t,n,i)},c=()=>{this._pollers.delete(a),this.removeListener(nH.CLOSE,c),TAu.default.unwatchFile(t,i)};return Mp.lang.attempt(o),()=>Mp.lang.attempt(c)}async watchUnknownChild(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchFileOnce(t,r,n)}async watchUnknownTarget(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchPollingOnce(t,r,n)}async watchPaths(t,r,i){if(this.isClosed())return;if(t=Mp.lang.uniq(t).sort(),t.every((a,o)=>t.every((c,d)=>d===o||!Mp.fs.isSubPath(a,c))))await Promise.all(t.map(a=>this.watchPath(a,r,i)));else for(let a of t)await this.watchPath(a,r,i)}async watchPath(t,r,i){if(this.isClosed()||(t=wvn.default.resolve(t),this.isIgnored(t,r.ignore)))return;let n=await Mp.fs.poll(t,r.pollingTimeout);if(n){if(n.isFile())return this.watchFile(t,r,i);if(n.isDirectory())return this.watchDirectory(t,r,i);this.error(`"${t}" is not supported`)}else{let a=wvn.default.dirname(t);return(await Mp.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,i):this.watchUnknownTarget(t,r,i)}}async watch(t,r,i=Mp.lang.noop){if(Mp.lang.isFunction(t))return this.watch([],{},t);if(Mp.lang.isUndefined(t))return this.watch([],r,i);if(Mp.lang.isFunction(r))return this.watch(t,{},r);if(Mp.lang.isUndefined(r))return this.watch(t,{},i);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let n=Mp.lang.castArray(t);n.forEach(a=>this._roots.add(a)),await this.watchPaths(n,r,i),!this.isClosed()&&(i!==Mp.lang.noop&&this.on(nH.ALL,i),r.readdirMap=void 0,this.ready())}},RAu=cJc;bXo();var xua=require("fs/promises"),_Rh=require("os"),hRh=ce(require("path"),1),tgB=".fern",rgB="logs";function igB(){return"cli@3.37.3"}var tJa=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=It(Sr.of((0,_Rh.homedir)()),Xe.of(tgB)),r=It(t,Xe.of(rgB));await mi(r)||await(0,xua.mkdir)(r,{recursive:!0});let n=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=It(r,Xe.of(n));let a=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${hRh.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
1786
+ https://buildwithfern.com/learn/docs/getting-started/project-structure#api-definitions`;throw new Error(r)}async toRootNode(){let t=Rt.V1.SlugGenerator.init(Rt.slugjoin(this.getDocsBasePath())),r=this.#e.get("root"),i=await this.toRootChild(t);return{type:"root",version:"v1",id:r,child:i,slug:t.get(),title:this.parsedDocsConfig.title??"Documentation",hidden:!1,icon:void 0,pointsTo:void 0,authed:void 0,viewers:void 0,orphaned:void 0,roles:this.parsedDocsConfig.roles?.map(n=>Rt.RoleId(n)),featureFlags:void 0}}async toRootChild(t){return vln(this.parsedDocsConfig.navigation)._visit({untabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),tabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),versioned:r=>this.toVersionedNode(r,t),productgroup:r=>this.toProductGroupNode({landingPageConfig:this.parsedDocsConfig.landingPage,productGroup:r,parentSlug:t})})}toLandingPageNode(t,r){let i=Rt.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??NE(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{type:"landingPage",id:this.#e.get(i),title:t.title,slug:n.get(),icon:this.resolveIconFileId(t.icon),hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toUnversionedNode({landingPage:t,navigationConfig:r,parentSlug:i}){let n=this.#e.get("unversioned"),a=t!=null?this.toLandingPageNode(t,i):void 0,o=r.type==="tabbed"?await this.convertTabbedNavigation(n,r.items,i):await this.toSidebarRootNode(n,r.items,i);return{type:"unversioned",id:n,landingPage:a,child:o}}async toVersionedNode(t,r){let i=this.#e.get("versioned"),n=t.versions[0];if(n?.hidden===!0)throw new Error(`The default version "${n.version}" cannot be hidden. Please set a non-hidden version as the first version in your versions list, or remove the hidden flag from the default version.`);return{id:i,type:"versioned",children:await Promise.all(t.versions.map((a,o)=>this.toVersionNode(a,r,o===0)))}}async toProductGroupNode({productGroup:t,landingPageConfig:r,parentSlug:i}){let n=this.#e.get("productgroup"),a=r!=null?this.toLandingPageNode(r,i):void 0;return{id:n,type:"productgroup",landingPage:a,children:await Promise.all(t.products.map(o=>this.toProductNode(o,i)))}}async toProductNode(t,r){if(t.type==="internal"){let i=r.setProductSlug(t.slug??NE(t.product)),n;switch(t.navigation.type){case"tabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.convertTabbedNavigation(this.#e.get(t.product),t.navigation.items,i)};break;case"untabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.toSidebarRootNode(this.#e.get(t.product),t.navigation.items,i)};break;case"versioned":n=await this.toVersionedNode(t.navigation,i);break;default:vt(t.navigation)}return{type:"product",id:this.#e.get(t.product),productId:Rt.V1.ProductId(t.product),title:t.product,subtitle:t.subtitle??"",slug:i.get(),child:n,default:!1,hidden:void 0,authed:void 0,icon:this.resolveIconFileId(t.icon),image:t.image!=null?this.getFileId(t.image):void 0,pointsTo:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,announcement:t.announcement!=null?{text:t.announcement.message}:void 0}}else return{type:"productLink",id:this.#e.get(t.product),productId:Rt.V1.ProductId(t.product),title:t.product,subtitle:t.subtitle??"",href:iG.Url(t.href??""),target:t.target,default:!1,hidden:void 0,authed:void 0,icon:this.resolveIconFileId(t.icon),image:t.image!=null?this.getFileId(t.image):void 0,viewers:t.viewers,orphaned:t.orphaned}}async toVersionNode(t,r,i){let n=this.#e.get(t.version),a=r.setVersionSlug(t.slug??NE(t.version)),o=t.navigation.type==="tabbed"?await this.convertTabbedNavigation(n,t.navigation.items,a):await this.toSidebarRootNode(n,t.navigation.items,a);return{type:"version",id:n,versionId:Rt.VersionId(t.version),title:t.version,slug:a.get(),child:o,default:i,availability:t.availability!=null?ZlB(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,a):void 0,hidden:t.hidden,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,icon:void 0,pointsTo:void 0,featureFlags:t.featureFlags,announcement:t.announcement!=null?{text:t.announcement.message}:void 0}}async toSidebarRootNode(t,r,i){let n=this.#e.get(`${t}/root`),a=await Promise.all(r.map(c=>this.toNavigationChild({prefix:n,item:c,parentSlug:i}))),o=[];return a.forEach(c=>{if(c.type==="apiReference"){o.push(c);return}if(c.type==="section"&&!c.collapsed){o.push(c);return}let d=o.length>0?o[o.length-1]:void 0,s;d?.type==="sidebarGroup"?s=d:(s={id:this.#e.get(`${n}/group`),type:"sidebarGroup",children:[]},o.push(s)),s.children.push(c)}),{type:"sidebarRoot",id:n,children:o}}async toSidebarRootNodeWithVariants(t,r,i){let n=this.#e.get(`${t}/root`);return{type:"sidebarRoot",id:n,children:[{type:"varianted",id:n,children:await Promise.all(r.map(a=>this.toVariantNode(a,n,i)))}]}}async toVariantNode(t,r,i){let n=this.#e.get(`${r}/variant/${t.slug??NE(t.title)}`),a=i.apply({urlSlug:t.slug??NE(t.title),skipUrlSlug:t.skipUrlSlug}),o=await Promise.all(t.layout.map(c=>this.toVariantChild(c,n,a)));return{type:"variant",id:n,variantId:Rt.V1.VariantId(t.title),subtitle:t.subtitle??"",default:t.default??!1,image:void 0,children:o,title:t.title,slug:a.get(),icon:this.resolveIconFileId(t.icon),hidden:t.hidden,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,pointsTo:void 0}}async toVariantChild(t,r,i){return vln(t)._visit({page:async n=>this.toPageNode({item:n,parentSlug:i}),apiSection:async n=>this.toApiSectionNode({item:n,parentSlug:i}),section:async n=>this.toSectionNode({prefix:r,item:n,parentSlug:i}),link:async n=>this.toLinkNode(n),changelog:async n=>this.toChangelogNode(n,i)})}async toNavigationChild({prefix:t,item:r,parentSlug:i,hideChildren:n,parentAvailability:a}){return vln(r)._visit({page:async o=>this.toPageNode({item:o,parentSlug:i,hideChildren:n,parentAvailability:a}),apiSection:async o=>this.toApiSectionNode({item:o,parentSlug:i,hideChildren:n,parentAvailability:a}),section:async o=>this.toSectionNode({prefix:t,item:o,parentSlug:i,hideChildren:n,parentAvailability:a}),link:async o=>this.toLinkNode(o),changelog:async o=>this.toChangelogNode(o,i,n)})}async toApiSectionNode({item:t,parentSlug:r,hideChildren:i,parentAvailability:n}){let a=USh(t.snippetsConfiguration),o,c=await this.getFernWorkspaceForApiSection(t).toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,objectQueryParameters:!0,preserveSchemaIds:!0}),d=this.parsedDocsConfig.experimental?.openapiParserV3,s=d==null||d;if(s)try{o=await this.getOpenApiWorkspaceForApiSection(t).getIntermediateRepresentation({context:this.taskContext,audiences:t.audiences,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1,logWarnings:!1})}catch{}let u;if(t.tagDescriptionPages&&s)try{let b=await this.getOpenApiWorkspaceForApiSection(t).getOpenAPIIr({context:this.taskContext});b.tags.tagsById&&(u=Object.fromEntries(Object.entries(b.tags.tagsById).filter(([v,O])=>O.description&&O.description.trim().length>0).map(([v,O])=>[v,{id:String(O.id),description:O.description}])))}catch(y){this.taskContext.logger.warn("Failed to extract OpenAPI tags for tag description pages",String(y))}o==null&&(o=eS({workspace:c,audiences:t.audiences,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!0},readme:void 0,version:void 0,packageName:void 0,context:this.taskContext,sourceResolver:new kE(this.taskContext,c)})),this.docsWorkspace.config.settings?.substituteEnvVars&&(o=MT(o,{onError:y=>this.taskContext.failAndThrow(`Error substituting environment variables in API spec: ${y}`)},{substituteAsEmpty:!1}));let f=await this.registerApi({ir:o,snippetsConfig:a,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName,workspace:c}),p=AKa({ir:o,apiDefinitionId:f,playgroundConfig:{oauth:t.playground?.oauth},context:this.taskContext}),_=new Sgu(t,p,r,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,this.#e,this.collectedFileIds,c,i,n??t.availability,u),h=_.getTagDescriptionContent();for(let[y,b]of h.entries()){let v=y.split("/").pop()||y,O=Xe.of(v),A=b;this.docsWorkspace.config.settings?.substituteEnvVars&&(A=MT(b,{onError:g=>this.taskContext.logger.error(`Error in tag description environment variable substitution: ${g}`)},{substituteAsEmpty:!1})),this.rawMarkdownFiles[O]=A,this.parsedDocsConfig.pages[O]=A}return _.get()}async toChangelogNode(t,r,i){return new pvn(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:this.resolveIconFileId(t.icon),viewers:t.viewers,hidden:i||t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:Rt.V1.Url(t.url),icon:this.resolveIconFileId(t.icon),target:t.target}}async toPageNode({item:t,parentSlug:r,hideChildren:i,parentAvailability:n}){let a=Rt.PageId(this.toRelativeFilepath(t.absolutePath)),o=r.apply({urlSlug:t.slug??NE(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(a),type:"page",slug:o.get(),title:this.markdownFilesToSidebarTitle.get(t.absolutePath)??t.title,icon:this.resolveIconFileId(t.icon),hidden:i||t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:a,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags,availability:t.availability??n}}async toSectionNode({prefix:t,item:r,parentSlug:i,hideChildren:n,parentAvailability:a}){let o=this.toRelativeFilepath(r.overviewAbsolutePath),c=o?Rt.PageId(o):void 0,d=this.#e.get(c??`${t}/section`),s=i.apply({urlSlug:r.slug??NE(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug}),u=r.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(r.overviewAbsolutePath):void 0,f=n||r.hidden;return{id:d,type:"section",overviewPageId:c,slug:s.get(),title:r.overviewAbsolutePath!=null?this.markdownFilesToSidebarTitle.get(r.overviewAbsolutePath)??r.title:r.title,icon:this.resolveIconFileId(r.icon),collapsed:r.collapsed,hidden:f,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(p=>this.toNavigationChild({prefix:d,item:p,parentSlug:s,hideChildren:f,parentAvailability:r.availability??a}))),authed:void 0,pointsTo:void 0,noindex:u,featureFlags:r.featureFlags,availability:r.availability??a}}async convertTabbedNavigation(t,r,i){let n=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:n,children:await Promise.all(r.map(a=>this.toTabChild(n,a,i)))}}async toTabChild(t,r,i){return vln(r.child)._visit({link:({href:n,target:a})=>this.toTabLinkNode(r,n,a),layout:({layout:n})=>this.toTabNode(t,r,n,i),changelog:({changelog:n})=>this.toTabChangelogNode(r,n,i),variants:({variants:n})=>this.toTabNodeWithVariants(t,r,n,i)})}async toTabChangelogNode(t,r,i){return new pvn(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:i,title:t.title,icon:this.resolveIconFileId(t.icon),viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r,i){return{type:"link",id:this.#e.get(r),title:t.title,url:Rt.V1.Url(r),target:i,icon:this.resolveIconFileId(t.icon)}}async toTabNode(t,r,i,n){let a=this.#e.get(`${t}/tab`),o=n.apply({urlSlug:r.slug??NE(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:this.resolveIconFileId(r.icon),hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNode(a,i,o),featureFlags:r.featureFlags}}async toTabNodeWithVariants(t,r,i,n){let a=this.#e.get(`${t}/tab`),o=n.apply({urlSlug:r.slug??NE(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:this.resolveIconFileId(r.icon),hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNodeWithVariants(a,i,o),featureFlags:r.featureFlags}}getFileId(t){if(t==null)return;let r=this.collectedFileIds.get(t);return r==null?this.taskContext.failAndThrow("Failed to locate file after uploading: "+t):iG.FileId(r)}resolveIconFileId(t){if(t!=null)return this.collectedFileIds.has(t)?`file:${this.getFileId(t)}`:t}convertPageActions(){if(this.parsedDocsConfig.pageActions!=null)return{default:this.parsedDocsConfig.pageActions.default,options:{askAi:this.parsedDocsConfig.pageActions.options.askAi,copyPage:this.parsedDocsConfig.pageActions.options.copyPage,viewAsMarkdown:this.parsedDocsConfig.pageActions.options.viewAsMarkdown,openAi:this.parsedDocsConfig.pageActions.options.openAi,claude:this.parsedDocsConfig.pageActions.options.claude,cursor:this.parsedDocsConfig.pageActions.options.cursor,vscode:this.parsedDocsConfig.pageActions.options.vscode,custom:this.parsedDocsConfig.pageActions.options.custom.map(t=>({title:t.title,subtitle:t.subtitle,url:t.url,icon:this.resolveIconFileId(t.icon),default:t.default}))}}}convertColorConfigImageReferences(){let{colors:t}=this.parsedDocsConfig;if(t!=null)return t.type==="dark"?{...t,...this.convertLogoAndBackgroundImage({theme:"dark"})}:t.type==="light"?{...t,...this.convertLogoAndBackgroundImage({theme:"light"}),type:"light"}:{...t,dark:{...t.dark,...this.convertLogoAndBackgroundImage({theme:"dark"})},light:{...t.light,...this.convertLogoAndBackgroundImage({theme:"light"})}}}convertLogoAndBackgroundImage({theme:t}){let{logo:r,backgroundImage:i}=this.parsedDocsConfig,n=r?.[t],a=i?.[t];return{logo:this.getFileId(n),backgroundImage:this.getFileId(a)}}convertDocsTypographyConfiguration(){if(this.parsedDocsConfig.typography!=null)return{headingsFont:this.convertFont(this.parsedDocsConfig.typography.headingsFont,"headings"),bodyFont:this.convertFont(this.parsedDocsConfig.typography.bodyFont,"body"),codeFont:this.convertFont(this.parsedDocsConfig.typography.codeFont,"code")}}convertFont(t,r){if(t==null||t.variants[0]==null)return;let i=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${i}`,variants:t.variants.map(n=>({fontFile:this.getFileId(n.absolutePath),weight:n.weight,style:n.style!=null?[n.style]:void 0})),display:t.display,fallback:t.fallback,fontVariationSettings:t.fontVariationSettings}}convertJavascriptConfiguration(){if(this.parsedDocsConfig.js!=null)return{files:this.parsedDocsConfig.js.files.map(({absolutePath:t,strategy:r})=>({fileId:this.getFileId(t),strategy:r})).filter(ds),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:iG.Url(t.url)})),inline:void 0}}convertMetadata(){if(this.parsedDocsConfig.metadata==null)return;let{"og:image":t,"og:logo":r,"twitter:image":i,...n}=this.parsedDocsConfig.metadata;return{...n,"og:image":this.convertFileIdOrUrl(t),"og:logo":this.convertFileIdOrUrl(r),"twitter:image":this.convertFileIdOrUrl(i)}}convertFileIdOrUrl(t){if(t!=null)return vln(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:iG.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function XlB(e,t){if(e?.github==null)return;let{owner:r,repo:i,branch:n="main",host:a="https://github.com"}=e.github;return`${tH(a)}/${r}/${i}/blob/${n}/fern/${t}?plain=1`}function ZlB(e){switch(e){case"beta":return Rt.V1.NavigationV1Availability.Beta;case"deprecated":return Rt.V1.NavigationV1Availability.Deprecated;case"ga":return Rt.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return Rt.V1.NavigationV1Availability.Stable;default:vt(e)}}async function rL(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof ZE?t:null))).filter(ds)}async function U7c(e,t,r){if(e instanceof SEe){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof ZE))return;let i=await e.getIntermediateRepresentation({context:t,audiences:r,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1,logWarnings:!1});return eH({ir:i,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0,phpSdk:void 0,swiftSdk:void 0,rustSdk:void 0},playgroundConfig:{oauth:!0},context:t})}var Ys={};Zt(Ys,{AlgoliaSearchIndex:()=>oMh,ApiDefinitionId:()=>SMh,ApiId:()=>IMh,Availability:()=>xMh,DocsConfigId:()=>CMh,EndpointId:()=>TMh,EndpointPathLiteral:()=>GMh,EnvironmentId:()=>qMh,FileId:()=>QMh,HttpMethod:()=>HMh,IndexSegmentId:()=>uMh,JqString:()=>LMh,OrgId:()=>DMh,PageId:()=>FMh,PayloadLocation:()=>gDh,PropertyKey:()=>VMh,PullRequestState:()=>_Dh,RoleId:()=>WMh,TokenId:()=>BMh,TypeId:()=>NMh,Url:()=>UMh,VersionId:()=>MMh,WebSocketId:()=>RMh,WebhookId:()=>zMh,algolia:()=>L7c,api:()=>X7c,commons:()=>Z7c,diff:()=>KMh,docs:()=>uxc,generators:()=>cxc,git:()=>lxc,navigation:()=>pxc,sdks:()=>hxc,snippets:()=>bDh,snippetsFactory:()=>vDh,templates:()=>yxc,tokens:()=>ODh});var L7c={};Zt(L7c,{AlgoliaSearchIndex:()=>oMh,IndexSegmentId:()=>uMh});function oMh(e){return e}function uMh(e){return e}var X7c={};Zt(X7c,{latest:()=>G7c,v1:()=>Y7c});var G7c={};Zt(G7c,{AuthSchemeId:()=>sMh,WebhookHttpMethod:()=>dMh,auth:()=>V7c,commons:()=>cMh,endpoint:()=>lMh,type_:()=>fMh,webhook:()=>W7c,websocket:()=>pMh});var V7c={};Zt(V7c,{AuthSchemeId:()=>sMh});function sMh(e){return e}var cMh={};var lMh={};var fMh={};var W7c={};Zt(W7c,{WebhookHttpMethod:()=>dMh});var dMh={Get:"GET",Post:"POST"};var pMh={};var Y7c={};Zt(Y7c,{SubpackageId:()=>PMh,WebSocketMessageId:()=>jMh,WebSocketMessageOrigin:()=>wMh,WebhookHttpMethod:()=>EMh,commons:()=>$7c,db:()=>H7c,read:()=>K7c,register:()=>J7c});var H7c={};Zt(H7c,{endpoint:()=>_Mh});var _Mh={};var K7c={};Zt(K7c,{SupportedLanguage:()=>hMh,endpoint:()=>x7c,type_:()=>yMh,webhook:()=>bMh,websocket:()=>vMh});var x7c={};Zt(x7c,{SupportedLanguage:()=>hMh});var hMh={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby",Csharp:"csharp"};var yMh={};var bMh={};var vMh={};var J7c={};Zt(J7c,{SourceId:()=>klB,endpoint:()=>gMh,type_:()=>OMh,webhook:()=>AMh,websocket:()=>mMh});var gMh={};var OMh={};var AMh={};var mMh={};function klB(e){return e}var $7c={};Zt($7c,{SubpackageId:()=>PMh,WebSocketMessageId:()=>jMh,WebSocketMessageOrigin:()=>wMh,WebhookHttpMethod:()=>EMh});function PMh(e){return e}function jMh(e){return e}var wMh={Client:"client",Server:"server"};var EMh={Get:"GET",Post:"POST"};var Z7c={};Zt(Z7c,{ApiDefinitionId:()=>SMh,ApiId:()=>IMh,Availability:()=>xMh,DocsConfigId:()=>CMh,EndpointId:()=>TMh,EndpointPathLiteral:()=>GMh,EnvironmentId:()=>qMh,FileId:()=>QMh,HttpMethod:()=>HMh,JqString:()=>LMh,OrgId:()=>DMh,PageId:()=>FMh,PropertyKey:()=>VMh,RoleId:()=>WMh,TokenId:()=>BMh,TypeId:()=>NMh,Url:()=>UMh,VersionId:()=>MMh,WebSocketId:()=>RMh,WebhookId:()=>zMh});function SMh(e){return e}function MMh(e){return e}function DMh(e){return e}function BMh(e){return e}function IMh(e){return e}function CMh(e){return e}function qMh(e){return e}function TMh(e){return e}function RMh(e){return e}function zMh(e){return e}function NMh(e){return e}function FMh(e){return e}function QMh(e){return e}function UMh(e){return e}function LMh(e){return e}function VMh(e){return e}function WMh(e){return e}function GMh(e){return e}var HMh={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var xMh={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var KMh={};var uxc={};Zt(uxc,{latest:()=>txc,v1:()=>axc,v2:()=>oxc});var txc={};Zt(txc,{Layout:()=>$Mh,MdxEngine:()=>efB,TwitterCardSetting:()=>YMh,commons:()=>JMh,frontmatter:()=>k7c,seo:()=>exc});var efB={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var JMh={};var k7c={};Zt(k7c,{Layout:()=>$Mh});var $Mh={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var exc={};Zt(exc,{TwitterCardSetting:()=>YMh});var YMh={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var axc={};Zt(axc,{commons:()=>nxc,db:()=>XMh,read:()=>ZMh,write:()=>rxc});var XMh={};var ZMh={};var rxc={};Zt(rxc,{DocsRegistrationId:()=>rfB,FilePath:()=>tfB});function tfB(e){return e}function rfB(e){return e}var nxc={};Zt(nxc,{ContentAlignment:()=>rDh,FontDisplay:()=>uDh,FontStyle:()=>oDh,HeaderPosition:()=>iDh,JsScriptStrategy:()=>aDh,ProgrammingLanguage:()=>kMh,SearchbarPlacement:()=>eDh,TabsPlacement:()=>tDh,TwitterCardSetting:()=>nDh,commons:()=>ixc});var ixc={};Zt(ixc,{ContentAlignment:()=>rDh,FontDisplay:()=>uDh,FontStyle:()=>oDh,HeaderPosition:()=>iDh,JsScriptStrategy:()=>aDh,ProgrammingLanguage:()=>kMh,SearchbarPlacement:()=>eDh,TabsPlacement:()=>tDh,TwitterCardSetting:()=>nDh});var kMh={Typescript:"typescript",Javascript:"javascript",Python:"python",Java:"java",Go:"go",Ruby:"ruby",Csharp:"csharp",Nodets:"nodets",Nodejs:"nodejs",Dotnet:"dotnet",Curl:"curl",Jvm:"jvm",Ts:"ts",Js:"js"};var eDh={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var tDh={Header:"HEADER",Sidebar:"SIDEBAR"};var rDh={Center:"CENTER",Left:"LEFT"};var iDh={Fixed:"FIXED",Absolute:"ABSOLUTE"};var nDh={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var aDh={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var oDh={Normal:"normal",Italic:"italic"};var uDh={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var oxc={};Zt(oxc,{read:()=>sDh,write:()=>cDh});var sDh={};var cDh={};var cxc={};Zt(cxc,{ChangelogEntryType:()=>fDh,GeneratorId:()=>ifB,GeneratorLanguage:()=>nfB,ReleaseType:()=>dDh,cli:()=>lDh,commons:()=>sxc,versions:()=>pDh});var lDh={};var sxc={};Zt(sxc,{ChangelogEntryType:()=>fDh,ReleaseType:()=>dDh});var fDh={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var dDh={Ga:"GA",Rc:"RC"};var pDh={};function ifB(e){return e}var nfB={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var lxc={};Zt(lxc,{PullRequestState:()=>_Dh});var _Dh={Open:"open",Closed:"closed",Merged:"merged"};var pxc={};Zt(pxc,{latest:()=>fxc,v1:()=>dxc});var fxc={};Zt(fxc,{NodeId:()=>ufB,ProductId:()=>sfB,Slug:()=>afB,TabId:()=>ofB});function afB(e){return e}function ofB(e){return e}function ufB(e){return e}function sfB(e){return e}var dxc={};Zt(dxc,{NavigationV1Availability:()=>pfB,NodeId:()=>ffB,ProductId:()=>dfB,Slug:()=>cfB,TabId:()=>lfB});function cfB(e){return e}function lfB(e){return e}function ffB(e){return e}function dfB(e){return e}var pfB={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var hxc={};Zt(hxc,{Language:()=>hDh,VersionBump:()=>yDh,versions:()=>_xc});var _xc={};Zt(_xc,{Language:()=>hDh,VersionBump:()=>yDh});var hDh={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var yDh={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var bDh={};var vDh={};var yxc={};Zt(yxc,{PayloadLocation:()=>gDh});var gDh={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var ODh={};var zgu=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};function No(e){return e!=null}var mDh=ce(TFa(),1);var ADh=["PII","PHI","PCI","GDPR","CCPA","HIPAA","COPPA","FERPA","GLBA","SOX","FISMA","NIST","CIS","ISO","IEC","ITAR","EAR","CMMC","CUI","CDI","FTC","FCC","SEC","FINRA","XSS","CSRF","SSRF","XSRF","TLS","SSL","SSH","API","OAuth","OAuth1","OAuth1.0","OAuth2","OAuth2.0","SAML","OpenID","OpenID Connect","CAPTCHA","reCAPTCHA","2FA","MFA","OTP","TOTP","HOTP","U2F","FIDO","FIDO2","PKI","HMAC","AES","RSA","SHA","MD5","BCrypt","PBKDF2","Argon2","SCrypt","JWT","JWE","JWS","JWK","JWA","JOSE","SKU","SKUs","UPC","EAN","ISBN","ASIN","MPN","MSRP","MAP","RRP","MSRP","AM","PM","UTC","GMT","PST","PDT","EST","EDT","CST","CDT","MST","MDT","USA","UK","EU","UAE","APAC","EMEA","LATAM","ANZ","SEA","MEA","MENA","NATO","NA","SA","CA","EU","AU","NZ","JP","KR","CN","HK","TW","SG","MY","TH","ID","PH","VN","IN","PK","BD","LK","NP","MM","KH","LA","MM","BT","MV","USD","EUR","GBP","JPY","CNY","RUB","INR","AUD","CAD","CHF","SGD","MYR","THB","IDR","KRW","PHP","VND","HKD","TWD","MXN","BRL","ARS","CLP","COP","PEN","ZAR","NGN","EGP","AED","SAR","ILS","TRY","SEK","NOK","DKK","ISK","HUF","PLN","CZK","RON","BGN","API","APIs","SDK","SDKs","AI","OCR","REST","SOAP","JSON","XML","HTTP","HTTPS","URI","URL","CRUD","RESTful","KYB","KYC","AML","HTML","CSS","JS","SQL","DB","UI","UX","SaaS","PaaS","IaaS","IP","TCP","UDP","DNS","FTP","SMTP","IMAP","POP3","CSV","MVC","MVP","MVVM","DOM","SPA","SSR","CSR","DDoS","CDN","IoT","ML","DL","NLP","CLI","GUI","BI","ETL","RDBMS","NoSQL","IDE","CMS","CCPA","POSIX","ABI","API","AST","COBOL","DDL","DML","NN","CNN","RNN","LSTM","GRU","ANN","GAN","RL","DL","ML","NLP","NLG","NLU","BERT","GPT","SVM","PCA","AI","CV","TF","TTS","ASR","HMM","DNN","MLP","RBM","CRF","PDF","PDFs","RTF","TXT","XLS","XLSX","PPT","JPG","JPEG","PNG","GIF","GIFs","SVG","TIFF","BMP","ICO","PSD","WebP","AVIF","HEIF","HEIC","EPS","MP3","WAV","AIFF","FLAC","WMA","AAC","OGG","AVI","WMV","MOV","M4V","MP4","MPG","MPEG","FLV","SWF","MKV","WebM","GCP","AWS","VM","VPC","S3","EC2","DynamoDB","CosmosDB","BigQuery","CI/CD","SOC1","SOC2","SOC3","PCI DSS","WAF","IAM","SDN","MPLS","BGP","Vue.js","Node.js",".NET"];function SYt(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,mDh.default)(e,{special:ADh}).replace(/V\s(\d)/g,"V$1")}function PDh({endpoints:e,webhookEndpoints:t}){let r={};return Object.values({...e,...t}).forEach(i=>{let n=[];i.namespace?.forEach(a=>{let o=[...n,a],c=Ys.api.v1.SubpackageId(o.join("."));r[c]={id:c,name:a,displayName:SYt(a)},n.push(a)})}),r}var Ngu=class{input;context;constructor(t,r){this.input=t,this.context=r}errors(){return this.context.errors.errors}warnings(){return this.context.errors.warnings}};function jDh(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var po=class extends Ngu{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){if(super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,n!=null){let a=Array.isArray(this.pathId)?this.pathId:[this.pathId];a.every((o,c)=>o===this.accessPath[this.accessPath.length-a.length+c])||this.accessPath.push(...a)}r.logger.debug(`Processing ${jDh(this.accessPath)}`)}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}},iC=class extends po{},K$=class extends iC{seenSchemas;constructor(t){super(t),this.seenSchemas=new Set(t.seenSchemas)}};var wDh="x-fern-base-path",EDh="x-fern-availability",Fgu="x-fern-sdk-group-name",SDh="x-fern-global-headers",MDh="x-fern-sdk-method-name";var DDh="x-fern-webhook",BDh="x-fern-access-token-locator",IDh="x-fern-basic",CDh="x-fern-username-variable-name",qDh="x-fern-password-variable-name",TDh="x-fern-bearer",RDh="x-fern-token-variable-name",zDh="x-fern-header",NDh="x-fern-header-variable-name",FDh="x-fern-server-name",QDh="x-fern-examples";var Qgu=class extends po{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[FDh]}convert(){if(this.serverName!=null)return this.serverName}};var Ugu=class extends po{url;serverName;constructor(t){super(t),this.safeParse()}parse(){this.url=Object.entries(this.input.variables??{}).reduce((t,[r,i])=>t.replace(`{${r}}`,i.default),this.input.url)??this.input.url,this.serverName=new Qgu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.serverName?.convert()??this.url;if(!(this.url==null||t==null))return{id:Ys.EnvironmentId(t),baseUrl:this.url}}};function i$i(e,t,r,i){let n=e??[],a=new Set(n.map(c=>c.url)),o=(t??[]).filter(c=>!a.has(c.url)).map((c,d)=>new Ugu({input:c,context:r,accessPath:i,pathId:["servers",`${d}`]}));return[...n,...o]}function zv(e){return typeof e=="object"&&No(e)&&"$ref"in e&&typeof e.$ref=="string"}function iL(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(zv(n)&&(n=iL(n,t,r)),n)}function Lgu(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return zv(r)?iL(r,t,void 0):r}var BBh=ce(VS());var Vgu=class extends po{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[IDh];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var Wgu=class extends po{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[qDh]}convert(){return this.passwordVariableName}};var Ggu=class extends po{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[CDh]}convert(){return this.usernameVariableName}};var Hgu=class extends po{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[TDh];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var xgu=class extends po{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[RDh]}convert(){return this.tokenVariableName}};function UDh(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var LDh="x-bearer-format",VDh="x-code-samples",WDh="x-codeSamples";var Kgu=class extends po{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[LDh]}convert(){return this.bearerFormat}};var Jgu=class extends po{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[zDh];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var $gu=class extends po{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[NDh]}convert(){return this.headerVariableName}};function GDh(e){return e.type==="apiKey"}var mua=class extends po{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){GDh(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new Jgu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new $gu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new Kgu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.headerAuthNode?.convert();if(t!=null)return{type:"header",nameOverride:t?.name,headerWireValue:this.headerName??"Authorization",prefix:t?.prefix??this.headerBearerFormatNode?.convert()}}};function Ygu(e){return e}function Xgu(e){return e==="__proto__"}function Zgu(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function Pua(e){return typeof e=="string"||typeof e=="symbol"?e:Object.is(e?.valueOf?.(),-0)?"-0":String(e)}function mKa(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e))return e.map(mKa).join(",");let t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function kgu(e){if(Array.isArray(e))return e.map(Pua);if(typeof e=="symbol")return[e];e=mKa(e);let t=[],r=e.length;if(r===0)return t;let i=0,n="",a="",o=!1;for(e.charCodeAt(0)===46&&(t.push(""),i++);i<r;){let c=e[i];a?c==="\\"&&i+1<r?(i++,n+=e[i]):c===a?a="":n+=c:o?c==='"'||c==="'"?a=c:c==="]"?(o=!1,t.push(n),n=""):n+=c:c==="["?(o=!0,n&&(t.push(n),n="")):c==="."?n&&(t.push(n),n=""):n+=c,i++}return n&&t.push(n),t}function PKa(e,t,r){if(e==null)return r;switch(typeof t){case"string":{if(Xgu(t))return r;let i=e[t];return i===void 0?Zgu(t)?PKa(e,kgu(t),r):r:i}case"number":case"symbol":{typeof t=="number"&&(t=Pua(t));let i=e[t];return i===void 0?r:i}default:{if(Array.isArray(t))return _fB(e,t,r);if(Object.is(t?.valueOf(),-0)?t="-0":t=String(t),Xgu(t))return r;let i=e[t];return i===void 0?r:i}}}function _fB(e,t,r){if(t.length===0)return r;let i=e;for(let n=0;n<t.length;n++){if(i==null||Xgu(t[n]))return r;i=i[t[n]]}return i===void 0?r:i}function HDh(e){return function(t){return PKa(t,e)}}function xDh(e){return e!==null&&(typeof e=="object"||typeof e=="function")}function eOu(e){return e==null||typeof e!="object"&&typeof e!="function"}function bxc(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function gxc(e,t,r){return typeof r!="function"?gxc(e,t,()=>{}):vxc(e,t,function i(n,a,o,c,d,s){let u=r(n,a,o,c,d,s);return u!==void 0?!!u:vxc(n,a,i,s)},new Map)}function vxc(e,t,r,i){if(t===e)return!0;switch(typeof t){case"object":return hfB(e,t,r,i);case"function":return Object.keys(t).length>0?vxc(e,{...t},r,i):bxc(e,t);default:return xDh(e)?typeof t=="string"?t==="":!0:bxc(e,t)}}function hfB(e,t,r,i){if(t==null)return!0;if(Array.isArray(t))return KDh(e,t,r,i);if(t instanceof Map)return yfB(e,t,r,i);if(t instanceof Set)return bfB(e,t,r,i);let n=Object.keys(t);if(e==null)return n.length===0;if(n.length===0)return!0;if(i?.has(t))return i.get(t)===e;i?.set(t,e);try{for(let a=0;a<n.length;a++){let o=n[a];if(!eOu(e)&&!(o in e)||t[o]===void 0&&e[o]!==void 0||t[o]===null&&e[o]!==null||!r(e[o],t[o],o,e,t,i))return!1}return!0}finally{i?.delete(t)}}function yfB(e,t,r,i){if(t.size===0)return!0;if(!(e instanceof Map))return!1;for(let[n,a]of t.entries()){let o=e.get(n);if(r(o,a,n,e,t,i)===!1)return!1}return!0}function KDh(e,t,r,i){if(t.length===0)return!0;if(!Array.isArray(e))return!1;let n=new Set;for(let a=0;a<t.length;a++){let o=t[a],c=!1;for(let d=0;d<e.length;d++){if(n.has(d))continue;let s=e[d],u=!1;if(r(s,o,a,e,t,i)&&(u=!0),u){n.add(d),c=!0;break}}if(!c)return!1}return!0}function bfB(e,t,r,i){return t.size===0?!0:e instanceof Set?KDh([...e],[...t],r,i):!1}function tOu(e,t){return gxc(e,t,()=>{})}function JDh(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function rOu(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}var $Dh="[object RegExp]",iOu="[object String]",nOu="[object Number]",aOu="[object Boolean]",oOu="[object Arguments]",YDh="[object Symbol]",XDh="[object Date]",ZDh="[object Map]",kDh="[object Set]",eBh="[object Array]";var tBh="[object ArrayBuffer]",rBh="[object Object]";var iBh="[object DataView]",nBh="[object Uint8Array]",aBh="[object Uint8ClampedArray]",oBh="[object Uint16Array]",uBh="[object Uint32Array]";var sBh="[object Int8Array]",cBh="[object Int16Array]",lBh="[object Int32Array]";var fBh="[object Float32Array]",dBh="[object Float64Array]";function pBh(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function _Bh(e,t){return n$i(e,void 0,e,new Map,t)}function n$i(e,t,r,i=new Map,n=void 0){let a=n?.(e,t,r,i);if(a!==void 0)return a;if(eOu(e))return e;if(i.has(e))return i.get(e);if(Array.isArray(e)){let o=new Array(e.length);i.set(e,o);for(let c=0;c<e.length;c++)o[c]=n$i(e[c],c,r,i,n);return Object.hasOwn(e,"index")&&(o.index=e.index),Object.hasOwn(e,"input")&&(o.input=e.input),o}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp){let o=new RegExp(e.source,e.flags);return o.lastIndex=e.lastIndex,o}if(e instanceof Map){let o=new Map;i.set(e,o);for(let[c,d]of e)o.set(c,n$i(d,c,r,i,n));return o}if(e instanceof Set){let o=new Set;i.set(e,o);for(let c of e)o.add(n$i(c,void 0,r,i,n));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(e))return e.subarray();if(pBh(e)){let o=new(Object.getPrototypeOf(e)).constructor(e.length);i.set(e,o);for(let c=0;c<e.length;c++)o[c]=n$i(e[c],c,r,i,n);return o}if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)return e.slice(0);if(e instanceof DataView){let o=new DataView(e.buffer.slice(0),e.byteOffset,e.byteLength);return i.set(e,o),a8t(o,e,r,i,n),o}if(typeof File<"u"&&e instanceof File){let o=new File([e],e.name,{type:e.type});return i.set(e,o),a8t(o,e,r,i,n),o}if(typeof Blob<"u"&&e instanceof Blob){let o=new Blob([e],{type:e.type});return i.set(e,o),a8t(o,e,r,i,n),o}if(e instanceof Error){let o=new e.constructor;return i.set(e,o),o.message=e.message,o.name=e.name,o.stack=e.stack,o.cause=e.cause,a8t(o,e,r,i,n),o}if(e instanceof Boolean){let o=new Boolean(e.valueOf());return i.set(e,o),a8t(o,e,r,i,n),o}if(e instanceof Number){let o=new Number(e.valueOf());return i.set(e,o),a8t(o,e,r,i,n),o}if(e instanceof String){let o=new String(e.valueOf());return i.set(e,o),a8t(o,e,r,i,n),o}if(typeof e=="object"&&vfB(e)){let o=Object.create(Object.getPrototypeOf(e));return i.set(e,o),a8t(o,e,r,i,n),o}return e}function a8t(e,t,r=e,i,n){let a=[...Object.keys(t),...JDh(t)];for(let o=0;o<a.length;o++){let c=a[o],d=Object.getOwnPropertyDescriptor(e,c);(d==null||d.writable)&&(e[c]=n$i(t[c],c,r,i,n))}}function vfB(e){switch(rOu(e)){case oOu:case eBh:case tBh:case iBh:case aOu:case XDh:case fBh:case dBh:case sBh:case cBh:case lBh:case ZDh:case nOu:case rBh:case $Dh:case kDh:case iOu:case YDh:case nBh:case aBh:case oBh:case uBh:return!0;default:return!1}}function hBh(e){return n$i(e,void 0,e,new Map,void 0)}function yBh(e){return e=hBh(e),t=>tOu(t,e)}function bBh(e,t){return _Bh(e,(r,i,n,a)=>{let o=t?.(r,i,n,a);if(o!==void 0)return o;if(typeof e=="object")switch(Object.prototype.toString.call(e)){case nOu:case iOu:case aOu:{let c=new e.constructor(e?.valueOf());return a8t(c,e),c}case oOu:{let c={};return a8t(c,e),c.length=e.length,c[Symbol.iterator]=e[Symbol.iterator],c}default:return}})}function vBh(e){return bBh(e)}var gfB=/^(?:0|[1-9]\d*)$/;function gBh(e,t=Number.MAX_SAFE_INTEGER){switch(typeof e){case"number":return Number.isInteger(e)&&e>=0&&e<t;case"symbol":return!1;case"string":return gfB.test(e)}}function OBh(e){return e!==null&&typeof e=="object"&&rOu(e)==="[object Arguments]"}function ABh(e,t){let r;if(Array.isArray(t)?r=t:typeof t=="string"&&Zgu(t)&&e?.[t]==null?r=kgu(t):r=[t],r.length===0)return!1;let i=e;for(let n=0;n<r.length;n++){let a=r[n];if((i==null||!Object.hasOwn(i,a))&&!((Array.isArray(i)||OBh(i))&&gBh(a)&&a<i.length))return!1;i=i[a]}return!0}function mBh(e,t){switch(typeof e){case"object":{Object.is(e?.valueOf(),-0)&&(e="-0");break}case"number":{e=Pua(e);break}}return t=vBh(t),function(r){let i=PKa(r,e);return i===void 0?ABh(r,e):t===void 0?i===void 0:tOu(i,t)}}function PBh(e){if(e==null)return Ygu;switch(typeof e){case"function":return e;case"object":return Array.isArray(e)&&e.length===2?mBh(e[0],e[1]):yBh(e);case"string":case"symbol":case"number":return HDh(e)}}function jBh(e,t){let r={},i=Object.keys(e);for(let n=0;n<i.length;n++){let a=i[n],o=e[a];r[a]=t(o,a,e)}return r}function uOu(e,t=Ygu){return e==null?{}:jBh(e,PBh(t))}function wBh(e){return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}var OfB=new RegExp("\\p{Lu}?\\p{Ll}+|[0-9]+|\\p{Lu}+(?!\\p{Ll})|\\p{Emoji_Presentation}|\\p{Extended_Pictographic}|\\p{L}+","gu");function EBh(e){return Array.from(e.match(OfB)??[])}function SBh(e){let t=EBh(e);if(t.length===0)return"";let[r,...i]=t;return`${r.toLowerCase()}${i.map(n=>wBh(n)).join("")}`}function MBh(e){return typeof e!="string"&&(e=mKa(e)),e.replace(/['\u2019]/g,"")}function o8t(e){return SBh(MBh(e))}function RP(e){if(e!=null)return Array.isArray(e)?e:[e]}function sOu({namespace:e,path:t,method:r,sdkMethodName:i,operationId:n,displayName:a,isWebhook:o}){if(t==null)return;let c=r!=null&&t!=null?`${r}_${t.split("/").join("_")}`:r??t.split("/").join("_");if(!(i==null&&n==null&&a==null&&c==null))return`${AfB(o)}${mfB(e)}.${PfB(i,n,a,c)}`}function AfB(e){return e?"webhook_":"endpoint_"}function mfB(e){return e!=null?RP(e)?.map(t=>o8t(t)).join("/"):""}function PfB(e,t,r,i){return e||t||o8t(r??"")||o8t(i??"")}function DBh(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var cOu=class extends po{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[BDh],this.accessTokenLocator!=null&&(DBh(this.accessTokenLocator)||(this.context.errors.error({message:"Invalid access token locator, must be a valid jq path",path:this.accessPath}),this.accessTokenLocator=void 0))}convert(){return this.accessTokenLocator}};var lOu=class extends po{authorizationUrl;headerAuthNode;accessTokenLocatorNode;constructor(t){super(t),this.safeParse()}parse(){if(this.input.flows.clientCredentials!=null){let t=this.input.flows.clientCredentials;this.authorizationUrl=t.tokenUrl,this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.headerAuthNode=new mua({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new cOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.accessTokenLocatorNode?.accessTokenLocator==null&&this.context.errors.error({message:"Expected 'x-fern-access-token-locator' property to be specified",path:this.accessPath})}}convert(){let t=this.accessTokenLocatorNode?.convert();if(t==null||this.authorizationUrl==null)return{type:"bearerAuth",tokenName:void 0};let r=sOu({namespace:void 0,path:this.authorizationUrl,method:"POST",sdkMethodName:void 0,operationId:void 0,displayName:void 0,isWebhook:void 0});if(r!=null)return{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:Ys.EndpointId(r),accessTokenLocator:Ys.JqString(t),headerName:this.headerAuthNode?.convert()?.headerWireValue,tokenPrefix:this.headerAuthNode?.convert()?.prefix}}}}};var jua=class extends po{authScheme;headerAuthNode;bearerTokenNode;bearerTokenVariableNameNode;basicAuthNode;basicUsernameVariableNameNode;basicPasswordVariableNameNode;oauth2Node;constructor(t){super(t),this.safeParse()}parse(){switch(this.input.type){case"http":switch(this.input.scheme){case"basic":{this.authScheme="basic",this.basicAuthNode=new Vgu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicUsernameVariableNameNode=new Ggu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new Wgu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),(this.basicAuthNode==null||this.basicAuthNode.username==null&&this.basicUsernameVariableNameNode?.usernameVariableName==null||this.basicAuthNode.password==null&&this.basicPasswordVariableNameNode?.passwordVariableName==null)&&this.context.errors.warning({message:"Basic auth should specify either a username or a username variable name",path:this.accessPath});break}case"bearer":{this.authScheme="bearer",this.bearerTokenNode=new Hgu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new xgu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}default:{this.context.errors.warning({message:`Unsupported HTTP auth scheme: ${this.input.scheme}`,path:this.accessPath});break}}break;case"apiKey":{UDh(this.input)?(this.authScheme="header",this.headerAuthNode=new mua({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})):this.context.errors.error({message:`Unsupported API key location: ${this.input.in}`,path:this.accessPath});break}case"oauth2":{this.authScheme="oauth",this.oauth2Node=new lOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}case"openIdConnect":{this.authScheme="bearer";break}}}convert(){switch(this.authScheme){case"basic":{let t=this.basicAuthNode?.convert();return{type:"basicAuth",usernameName:t?.username?.name??this.basicUsernameVariableNameNode?.convert(),passwordName:t?.password?.name??this.basicPasswordVariableNameNode?.convert()}}case"bearer":return{type:"bearerAuth",tokenName:this.bearerTokenNode?.convert()?.tokenVariableName??this.bearerTokenVariableNameNode?.convert()};case"header":return this.headerAuthNode?.convert();case"oauth":return this.oauth2Node?.convert();case void 0:return;default:new BBh.UnreachableCaseError(this.authScheme);return}}};var wua=class extends po{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(i=>{let n=Lgu(i,this.context.document);if(n==null){this.context.errors.warning({message:`No auth scheme found for ${i}. Inline security schemes are not supported.`,path:this.accessPath});return}let a=new jua({input:n,context:this.context,accessPath:this.accessPath,pathId:["security",`${r}`]});a.convert()!=null?(this.authNodesMap??={},this.authNodesMap[i]=a):this.context.errors.warning({message:`No auth scheme found for ${i}`,path:this.accessPath})}))}convert(){return Object.fromEntries(Object.entries(this.authNodesMap??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[t,i]}).filter(No))}};var fOu=class extends po{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[wDh],this.basePath!=null?(this.basePath.startsWith("/")&&(this.basePath=this.basePath.slice(1)),this.basePath.endsWith("/")&&(this.basePath=this.basePath.slice(0,-1))):this.basePath=void 0}convert(){return this.basePath}};function IBh(e){return"required"in e&&typeof e.required=="boolean"?e.required:!1}function CBh(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function Eua(e,t){return e==null?void 0:Object.entries(e).map(([i,n])=>RP(n.convert())?.map(o=>((t!=null&&!t.includes(i)||t==null&&!IBh(n))&&(o=CBh(o,o.type==="enum"?o.default:void 0)),{key:Ys.PropertyKey(i),valueShape:o,description:n.description,availability:n.availability?.convert()})).filter(No)).filter(No).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(o=>[...a,o]):[[...a]]),[[]])}function dOu(e,t){return zv(e)?iL(e,t,void 0):e}function a$i(e,t){return e!=null&&e!==""?e:t!=null&&t!==""?t:void 0}function qBh(e,t){let r={...e};for(let[i,n]of Object.entries(t??{}))r[i]=[...r[i]??[],...n];return Object.keys(r).length>0?r:void 0}function TBh(e,t){if(e==null)return t;if(t==null)return e;let r=[];for(let i of e)for(let n of t)r.push({path:i.path??n.path,responseStatusCode:i.responseStatusCode??n.responseStatusCode,name:i.name??n.name,description:i.description??n.description,pathParameters:i.pathParameters??n.pathParameters,queryParameters:i.queryParameters??n.queryParameters,headers:i.headers??n.headers,requestBody:i.requestBody??n.requestBody,responseBody:i.responseBody??n.responseBody,snippets:{...n.snippets,...i.snippets}});return r}var RBh=ce(VS());var Oxc=["decimal","decimal128","double-int","double","float","sf-decimal"],Axc=["int16","int32","int64","int8","sf-integer","uint8"],mxc=["base64url","binary","byte","char","commonmark","date-time","date","decimal","decimal128","duration","email","hostname","html","http-date","idn-email","idn-hostname","int64","ipv4","ipv6","iri-reference","iri","json-pointer","media-range","password","regex","relative-json-pointer","sf-binary","sf-boolean","sf-string","sf-token","time","uri-reference","uri-template","uri","uuid"],Pxc=["beta","pre-release","in-development","generally-available","deprecated"];function nC(e,t){return zv(e)?iL(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var FEe=class extends po{availability;constructor(t){super(t),this.safeParse()}parse(){if(nC(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[EDh];r!=null&&(Pxc.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${Pxc.join(", ")}. Received: ${r}`,path:this.accessPath}),this.availability=void 0))}}convert(){switch(this.availability){case"beta":case"pre-release":return Ys.Availability.Beta;case"in-development":return Ys.Availability.InDevelopment;case"generally-available":return Ys.Availability.GenerallyAvailable;case"deprecated":return Ys.Availability.Deprecated;case void 0:return;default:new RBh.UnreachableCaseError(this.availability);return}}};var _Ou=ce(VS());function zBh(e){return typeof e=="object"&&e!=null&&"language"in e}function NBh(e){return typeof e=="object"&&e!=null&&"sdk"in e}function FBh(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function QBh(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function pOu(e){return typeof e=="object"&&e!=null&&"event"in e}function jxc(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(pOu)}function o$i(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function UBh(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var hOu=class extends po{path;successResponseStatusCode;requestBodyByContentType;responseBodies;examples;constructor(t,r,i,n,a){super(t),this.path=r,this.successResponseStatusCode=i,this.requestBodyByContentType=n,this.responseBodies=a,this.safeParse()}parse(){this.examples=this.input[QDh]}convertFormDataExampleRequest(t,r){if(t.fields!=null)switch(t.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(t.fields).map(([n,a])=>{let o=typeof r=="object"?r[n]:void 0;switch(a.multipartType){case"file":return o$i(o)?[n,{type:"filenameWithData",filename:o.filename,data:Ys.FileId(o.data)}]:o!=null?[n,{type:"filename",value:o}]:void 0;case"files":{if(Array.isArray(o)){if(o.every(c=>o$i(c)))return[n,{type:"filenamesWithData",value:o.map(c=>({filename:c.filename,data:Ys.FileId(c.data)}))}];if(o.every(c=>typeof c=="string"))return[n,{type:"filenames",value:o}]}return}case"property":return[n,{type:"json",value:o}];case void 0:return;default:new _Ou.UnreachableCaseError(a.multipartType);return}}).filter(No))};case"json":return{type:"json",value:r};case"bytes":return typeof r=="string"?{type:"bytes",value:{type:"base64",value:r}}:void 0;default:return}}convert(){if(this.examples==null)return;this.requestBodyByContentType!=null&&Object.keys(this.requestBodyByContentType).length>1&&this.context.logger.warn(`Multiple request bodies found for #/${[this.accessPath,this.pathId,"x-fern-examples"].join("/")}. Coercing to first request body until supported.`);let t=Object.keys(this.requestBodyByContentType??{})[0];return this.examples.flatMap(r=>(this.responseBodies??[]).map(i=>{let n=t!=null?this.requestBodyByContentType?.[t]:void 0,a;if(n!=null)switch(n.contentType){case"form-data":a=UBh(r.request)?this.convertFormDataExampleRequest(n,r.request):void 0;break;case"json":a=r.request!=null?{type:"json",value:r.request}:void 0;break;case"bytes":a=typeof r.request=="string"&&r.request!=null?{type:"bytes",value:{type:"base64",value:r.request}}:void 0;break;case void 0:break;default:new _Ou.UnreachableCaseError(n.contentType);break}let o;switch(i.contentType){case"application/json":{FBh(r.response)&&(o={type:"json",value:r.response.body});break}case"text/event-stream":{jxc(r.response)&&(o={type:"sse",value:r.response.stream.map(f=>({event:f.event,data:f.data}))});break}case"application/octet-stream":!jxc(r.response)&&QBh(r.response)&&(o={type:"stream",value:r.response.stream});break;case void 0:break;default:new _Ou.UnreachableCaseError(i.contentType);break}let c={};r["code-samples"]?.forEach(f=>{zBh(f)?f.language!=null&&(c[f.language]??=[],c[f.language]?.push({name:f.name,language:f.language,install:f.install,code:f.code,generated:!1,description:f.docs})):NBh(f)&&f.sdk!=null&&(c[f.sdk]??=[],c[f.sdk]?.push({name:f.name,language:f.sdk,install:void 0,code:f.code,generated:!1,description:f.docs}))});let d=Object.fromEntries(Object.entries(r["path-parameters"]??{}).map(([f,p])=>[Ys.PropertyKey(f),p])),s=Object.fromEntries(Object.entries(r["query-parameters"]??{}).map(([f,p])=>[Ys.PropertyKey(f),p])),u=Object.fromEntries(Object.entries(r.headers??{}).map(([f,p])=>[Ys.PropertyKey(f),p]));return{path:this.path,responseStatusCode:this.successResponseStatusCode,name:r.name,description:r.docs,pathParameters:Object.keys(d).length>0?d:void 0,queryParameters:Object.keys(s).length>0?s:void 0,headers:Object.keys(u).length>0?u:void 0,requestBody:a,responseBody:o,snippets:c}}))}};var jKa=class extends po{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[Fgu]}convert(){if(this.groupName==null)return;let t;return Array.isArray(this.groupName)?t=this.groupName:t=[this.groupName],t.map(r=>Ys.api.v1.SubpackageId(o8t(r)))}};var yOu=class extends po{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[MDh]}convert(){return this.sdkMethodName}};var bOu=class extends po{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[DDh]}convert(){return this.isWebhook}};var vOu=class extends po{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[VDh]??[],...this.input[WDh]??[]],this.codeSamples.forEach(t=>{[...Object.values(Ys.api.v1.read.SupportedLanguage),"Kotlin","Swift","PHP"].map(r=>r.toLowerCase()).includes(t.lang.toLowerCase())||this.context.errors.warning({message:`Unsupported language: ${t.lang}. This may not render correctly.`,path:this.accessPath})})}convert(){let t={};if(this.codeSamples?.forEach(r=>{t[r.lang.toLowerCase()]??=[],t[r.lang.toLowerCase()]?.push({name:r.label,language:r.lang,code:r.source,install:void 0,generated:!1,description:void 0})}),Object.keys(t).length!==0)return t}};var _vn=ce(VS());function wxc(e,t){return zv(e)?iL(e,t,void 0):e}function LBh(e,t){return e.replace(/{(\w+)}/g,(r,i)=>t[i]!=null&&typeof t[i]=="string"||typeof t[i]=="number"||typeof t[i]=="boolean"?`${t[i]}`:r)}var nF="",MYt=class extends po{path;responseStatusCode;name;shapes;resolvedRequestInput;resolvedResponseInput;summary;constructor(t,r,i,n,a){super(t),this.path=r,this.responseStatusCode=i,this.name=n,this.shapes=a,this.safeParse()}validateFormDataRequestExample(){return typeof this.resolvedRequestInput?.value!="object"?!1:Object.entries(this.shapes.requestBody?.fields??{}).reduce((t,[r,i])=>{let n=this.resolvedRequestInput?.value[r];switch(i.multipartType){case"file":return t&&(o$i(n)||typeof n=="string");case"files":return t&&Array.isArray(n)&&n.every(a=>o$i(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new _vn.UnreachableCaseError(i.multipartType),t}},!0)}parse(){let t=this.shapes.requestBody?.schema?.example({includeOptionals:!1,override:void 0});this.resolvedRequestInput=wxc(this.input?.requestExample,this.context.document)??(t!=null?{value:t}:void 0);let r=this.shapes.responseBody?.schema?.example({includeOptionals:!1,override:void 0});if(this.resolvedResponseInput=wxc(this.input?.responseExample,this.context.document)??(r!=null?{value:r}:void 0),this.summary=this.input?.requestExample?.summary??this.input?.responseExample?.summary,this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody?.contentType){case"json":{if(typeof this.resolvedRequestInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break}case"bytes":{if(typeof this.resolvedRequestInput.value!="string"){this.context.errors.error({message:"Invalid example, expected string for bytes",path:this.accessPath});return}break}case"form-data":{if(!this.validateFormDataRequestExample()){this.context.errors.error({message:"Invalid example, expected valid form-data",path:this.accessPath});return}break}case void 0:break;default:new _vn.UnreachableCaseError(this.shapes.requestBody?.contentType),this.context.errors.error({message:"Invalid example, unsupported content type",path:this.accessPath});return}if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody?.contentType){case"application/json":if(this.resolvedResponseInput!=null&&typeof this.resolvedResponseInput!="object"||this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break;case"text/event-stream":if(this.resolvedResponseInput.value!=null&&!Array.isArray(this.resolvedResponseInput.value)&&!this.resolvedResponseInput.value.every(pOu)){this.context.errors.error({message:"Invalid example, expected array of SSE events for event-stream",path:this.accessPath});return}break;case"application/octet-stream":if(this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="string"&&!Array.isArray(this.resolvedResponseInput.value)){this.context.errors.error({message:"Invalid example, expected string or array for octet-stream",path:this.accessPath});return}break;case void 0:break;default:new _vn.UnreachableCaseError(this.shapes.responseBody?.contentType);return}}convertFormDataExampleRequest(){if(!(this.resolvedRequestInput==null||this.shapes.requestBody?.fields==null))switch(this.shapes.requestBody?.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(this.shapes.requestBody.fields).map(([r,i])=>{let n=this.resolvedRequestInput?.value?.[r];switch(i.multipartType){case"file":return o$i(n)?[r,{type:"filenameWithData",filename:n.filename,data:Ys.FileId(n.data)}]:[r,{type:"filename",value:n}];case"files":{if(Array.isArray(n)){if(n.every(a=>o$i(a)))return[r,{type:"filenamesWithData",value:n.map(a=>({filename:a.filename,data:Ys.FileId(a.data)}))}];if(n.every(a=>typeof a=="string"))return[r,{type:"filenames",value:n}]}return}case"property":return[r,{type:"json",value:n}];case void 0:return;default:new _vn.UnreachableCaseError(i.multipartType);return}}).filter(No))};case"json":return{type:"json",value:this.resolvedRequestInput.value};case"bytes":return typeof this.resolvedRequestInput.value=="string"?{type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}}:void 0;default:return}}convertDescription(){if(this.resolvedRequestInput!=null&&this.resolvedResponseInput!=null)return this.resolvedResponseInput.description;if(this.resolvedRequestInput!=null)return this.resolvedRequestInput.description;if(this.resolvedResponseInput!=null)return this.resolvedResponseInput.description}convert(){let t;if(this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody.contentType){case"form-data":t=this.convertFormDataExampleRequest();break;case"json":t={type:"json",value:this.resolvedRequestInput.value};break;case"bytes":t={type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}};break;case void 0:break;default:new _vn.UnreachableCaseError(this.shapes.requestBody?.contentType);break}let r;if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody.contentType){case"application/json":{r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break}case"text/event-stream":r={type:"sse",value:this.resolvedResponseInput?.value};break;case"application/octet-stream":r={type:typeof this.resolvedResponseInput?.value=="string"?"filename":"stream",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;case void 0:r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;default:new _vn.UnreachableCaseError(this.shapes.responseBody?.contentType);break}let i=Object.fromEntries(Object.entries(this.shapes.pathParameters??{}).map(([o,c])=>[o,c.example({includeOptionals:!1,override:o})]));i=Object.keys(i).length>0?i:void 0;let n=Object.fromEntries(Object.entries(this.shapes.queryParameters??{}).map(([o,c])=>c.required||c.inputExample!=null?[o,c.example({includeOptionals:!1,override:o})]:void 0).filter(No));n=Object.keys(n).length>0?n:void 0;let a=Object.fromEntries(Object.entries(this.shapes.requestHeaders??{}).map(([o,c])=>c.required||c.inputExample!=null?[o,c.example({includeOptionals:!1,override:o})]:void 0).filter(No));if(a=Object.keys(a).length>0?a:void 0,!(this.path==null&&t==null&&r==null&&a==null&&n==null&&i==null))return{path:LBh(this.path,i??{}),responseStatusCode:this.responseStatusCode,name:this.name!=null?SYt(this.name):this.summary!=null?SYt(this.summary):void 0,description:this.convertDescription(),pathParameters:i,queryParameters:n,headers:a,requestBody:t,responseBody:r,snippets:void 0}}};function VBh(e,t){return zv(e)?iL(e,t,void 0):e}var tIh=ce(VS());var WBh="#/components/schemas/";function Sua(e){if(e.$ref.startsWith(WBh))return e.$ref.replace(WBh,"")}function bUi(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}function u$i(e){return typeof e.type=="string"&&e.type==="array"}function GBh(e){return e.type==="boolean"}function HBh(e){return e.type==="integer"}function s$i(e){return!Array.isArray(e.type)&&!u$i(e)}function xBh(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||s$i(t)||u$i(t))}function KBh(e){return"nullable"in e&&typeof e.nullable=="boolean"}function JBh(e){return e.type==="null"}function $Bh(e){return e.type==="number"}function Exc(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function YBh(e){return e.type==="string"}var gOu=class extends K${item;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.item=new G0({input:this.input.items,context:this.context,accessPath:this.accessPath,pathId:"items",seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}),this.input.items==null&&this.context.errors.error({message:"Expected 'items' property to be specified",path:this.accessPath})}convert(){return RP(this.item?.convert())?.map(r=>({type:"alias",value:{type:"list",itemShape:r}}))}example(t){return this.input.example??this.input.examples?.[0]??[this.item?.example(t)]}};var OOu=class extends iC{constValue;description;availability;constructor(t){super(t),this.safeParse()}parse(){this.input.const!=null&&(typeof this.input.const=="string"||typeof this.input.const=="number"||typeof this.input.const=="boolean")?this.constValue=this.input.const.toString():this.context.errors.warning({message:`Unsupported const type: ${typeof this.input}`,path:this.accessPath}),this.description=this.input.description,this.availability=new FEe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"})}convert(){if(this.constValue!=null)return{type:"enum",default:this.constValue,values:[{value:this.constValue,description:this.description,availability:this.availability?.convert()}]}}example(){return this.input.example??this.input.examples?.[0]??this.constValue}};var AOu=class extends K${typeNodes;nullable;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.parse()}parse(){this.typeNodes=this.input.map(t=>{if(t.type==="null")this.nullable=!0;else return new G0({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName})}).filter(No)}convert(){if(this.typeNodes==null)return;let i=this.typeNodes.map(n=>RP(n.convert())?.map(o=>({displayName:n.name,shape:o,description:n.description,availability:n.availability?.convert()}))).filter(No).reduce((n,a)=>n.flatMap(o=>a.length>0?a.map(c=>[...o,c]):[[...o]]),[[]]).map(n=>({type:"undiscriminatedUnion",variants:n}));return this.nullable?i.map(bUi).filter(No):i}example(t){return this.nullable?null:this.typeNodes?.[0]?.example(t)}};function mOu(e){return e!=null&&e.length>0?e:[void 0]}var Mua=class extends K${description;extends=[];properties;extraProperties;requiredProperties;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.extends=[],this.requiredProperties=this.input.required,this.properties=Object.fromEntries(Object.entries(this.input.properties??{}).map(([t,r])=>[t,new G0({input:r,context:this.context,accessPath:this.accessPath,pathId:["properties",t],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})])),this.extraProperties=this.input.additionalProperties!=null?typeof this.input.additionalProperties=="boolean"?this.input.additionalProperties?this.input.title:void 0:new G0({input:this.input.additionalProperties,context:this.context,accessPath:this.accessPath,pathId:["additionalProperties"],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0,this.input.allOf!=null&&(this.extends=this.extends.concat(this.input.allOf.map((t,r)=>{if(zv(t))return Sua(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([i,n])=>[i,new G0({input:n,context:this.context,accessPath:this.accessPath,pathId:["allOf",r.toString(),"properties",i],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))}}).filter(No))),this.description=this.input.description}convertProperties(){if(this.properties!=null)return Eua(this.properties,this.requiredProperties)}convertExtraProperties(){return this.extraProperties==null?void 0:typeof this.extraProperties=="string"?[{type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:{type:"alias",value:{type:"unknown",displayName:this.extraProperties}}}]:RP(this.extraProperties.convert())?.map(r=>({type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:r})).filter(No)}convert(){let t=this.convertProperties();if(t==null)return;let r=this.convertExtraProperties();return t.flatMap(i=>mOu(r).map(n=>(this.extends==null||this.extends.length===0)&&i.length===0&&n!=null?{type:"alias",value:n}:{type:"object",extends:this.extends.map(a=>Ys.TypeId(a)),properties:i,extraProperties:n}))}example({includeOptionals:t}){let r={...this.properties};return this.input.allOf?.forEach(i=>{let n=nC(i,this.context.document);n!=null&&(r={...r,...Object.fromEntries(Object.entries(n.properties??{}).map(([a,o])=>[a,new G0({input:o,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))})}),this.input.example??this.input.examples?.[0]??(!t&&this.requiredProperties!=null&&this.requiredProperties.length>0?this.requiredProperties?.reduce((i,n)=>{let a=r?.[n];return i[n]=a?.example({includeOptionals:t,override:n}),i},{}):Object.entries(r).reduce((i,[n,a])=>(i[n]=a?.example({includeOptionals:t,override:n}),i),{}))}};var POu=class extends K${isNullable;discriminated;discriminant;discriminatedMapping;undiscriminatedMapping;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.input.oneOf!=null||this.input.anyOf!=null)if(this.isNullable=(this.input.oneOf??this.input.anyOf)?.some(t=>nC(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>nC(t,this.context.document)?.type!=="null"?new G0({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0).filter(No);else{let t=this.input.discriminator.mapping;if(t!=null){this.discriminated=!0,this.discriminant=this.input.discriminator.propertyName,this.discriminatedMapping={};let r=this.discriminatedMapping;Object.entries(t).map(([i,n])=>{let a=nC({$ref:n},this.context.document);if(a==null){this.context.errors.warning({message:`Expected schema reference. Received undefined reference: ${n}`,path:[...this.accessPath,"discriminator","mapping",i]});return}r[i]=new G0({input:a,context:this.context,accessPath:[...this.accessPath,"discriminator","mapping",i],pathId:i,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})})}}}convert(){if(!this.discriminated&&this.undiscriminatedMapping?.length===1){let n=this.undiscriminatedMapping?.flatMap(a=>a.convert()).filter(No);return this.isNullable&&n!=null?n.map(bUi).filter(No):n}let t=0,r=this.discriminated&&this.discriminant!=null&&this.discriminatedMapping!=null?{type:"discriminatedUnion",discriminant:Ys.PropertyKey(this.discriminant),variants:Object.entries(this.discriminatedMapping).flatMap(([n,a])=>RP(a.convert())?.map(c=>{if(!(c==null||c.type!=="object"))return{discriminantValue:n,displayName:a.name??SYt(n),availability:a.availability?.convert(),description:a.description,...c}}).filter(No)).filter(No)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(n=>RP(n.convert())?.map(o=>{if(o==null)return;t+=1;let c=o.type==="object"?SYt(`${this.schemaName??"Variant"} ${t}`):void 0;return{displayName:n.name??(o.type==="alias"&&o.value.type==="id"?SYt(o.value.id):c),shape:o,description:n.description,availability:n.availability?.convert()}}).filter(No)).filter(No)}:void 0,i=this.isNullable?bUi(r):r;return i!=null?[i]:void 0}example(t){return this.input.example??this.input.examples?.[0]??this.undiscriminatedMapping?.[0]?.example(t)??Object.values(this.discriminatedMapping??{})[0]?.example(t)}};var jOu=class extends iC{default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.input.default!=null&&typeof this.input.default!="boolean"&&this.context.errors.warning({message:`Expected default value to be a boolean. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default}convert(){return{type:"alias",value:{type:"primitive",value:{type:"boolean",default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:!1)}};var c$i=class extends iC{default;values=[];nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){if(this.input.enum!=null){let t=!0;this.values=this.input.enum.map((r,i)=>{if(t){if(zv(r)){let n=nC(r,this.context.document);r=typeof n=="string"?n:typeof n?.default=="string"?n?.default:typeof n?.example=="string"?n.example:void 0}if(typeof r!="string"){this.context.errors.error({message:`Expected enum values to be strings. Received ${r}`,path:[...this.accessPath,`enum[${i}]`]}),t=!1;return}return r}}).filter(No),this.values=Array.from(new Set(this.values))}this.default=this.input.default}convert(){return{type:"enum",values:this.values.map(t=>({value:t,description:void 0,availability:void 0})),default:this.default}}example(){return this.input.example??this.input.examples?.[0]??this.default??this.values[0]??(this.nullable?null:void 0)}};var XBh=ce(VS());function jfB(e){return Axc.includes(e)}var wOu=class extends iC{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be an integer. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(jfB(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${Axc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="integer";if(this.format!=null)switch(this.format){case"int64":t="long";break;case"int8":case"int16":case"int32":case"uint8":case"sf-integer":case void 0:t="integer";break;default:new XBh.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var EOu=class extends iC{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return bUi({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var ZBh=ce(VS());function wfB(e){return Oxc.includes(e)}var SOu=class extends iC{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be a number. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(wfB(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${Oxc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="double";if(this.format!=null)switch(this.format){case"decimal":case"decimal128":case"double-int":case"double":case"float":case"sf-decimal":case void 0:t="double";break;default:new ZBh.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var kBh=ce(VS());function EfB(e){return mxc.includes(e)}var MOu=class extends iC{format;regex;default;minLength;maxLength;enum;mimeType;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}mapToFdrType(t){switch(t){case"base64url":case"binary":case"byte":case"sf-binary":return"base64";case"date-time":return"datetime";case"int64":return"bigInteger";case"date":return"date";case"uuid":return"uuid";case"char":case"commonmark":case"decimal":case"decimal128":case"duration":case"email":case"hostname":case"html":case"http-date":case"idn-email":case"idn-hostname":case"ipv4":case"ipv6":case"iri-reference":case"iri":case"json-pointer":case"media-range":case"password":case"regex":case"relative-json-pointer":case"sf-boolean":case"sf-string":case"sf-token":case"time":case"uri-reference":case"uri-template":case"uri":case void 0:return"string";default:return new kBh.UnreachableCaseError(t),"string"}}parse(){this.regex=this.input.pattern,this.minLength=this.input.minLength,this.maxLength=this.input.maxLength,this.mimeType=this.input.contentMediaType,this.input.default!=null&&typeof this.input.default!="string"&&this.context.errors.warning({message:`Expected default value to be a string. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(EfB(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${mxc.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new c$i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"enum",nullable:this.nullable}))}convert(){if(this.enum!=null)return this.enum.convert();let t="string";return this.format!=null&&(t=this.mapToFdrType(this.format)),{type:"alias",value:{type:"primitive",value:t==="base64"?{type:t,mimeType:this.mimeType,default:this.default}:{type:t,format:t==="string"?this.format:void 0,regex:this.regex,minLength:this.minLength,maxLength:this.maxLength,default:this.default}}}}example({override:t}){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:t??"string")}};var eIh=ce(VS());var DOu=class extends iC{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,eIh.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var hvn=class extends K${description;availability;schemaId;maybeEnumConverterNode;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.description=t.description,this.availability=t.availability,this.safeParse()}parse(){this.schemaId=Sua(this.input);let t=nC(this.input,this.context.document);t?.enum!=null&&s$i(t)&&(this.maybeEnumConverterNode=new c$i({input:t,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",nullable:this.nullable})),this.schemaId==null&&this.context.errors.error({message:`Unprocessable reference: ${this.input.$ref}`,path:this.accessPath})}convert(){if(this.schemaId!=null)return{type:"alias",value:{type:"id",id:Ys.TypeId(this.schemaId),default:this.maybeEnumConverterNode?.default!=null?{type:"enum",value:this.maybeEnumConverterNode.default}:void 0}}}example(t){let r=nC(this.input,this.context.document);if(r!=null)return new G0({input:r,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName}).example(t)}};var G0=class e extends K${typeShapeNode;description;name;examples;availability;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.description=this.input.description,this.availability=new FEe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),s$i(this.input)&&KBh(this.input)&&(this.nullable=this.input.nullable!=null?this.input.nullable:this.nullable),zv(this.input)){let t=Sua(this.input);if(t==null){this.context.errors.error({message:"Reference object does not have a valid schema ID",path:this.accessPath});return}if(this.seenSchemas.has(t)){this.context.errors.warning({message:"Circular or deeply nested schema found, terminating",path:this.accessPath});return}this.seenSchemas.add(t),this.typeShapeNode=new hvn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName,description:this.description,availability:this.availability})}else if(this.name=this.input.title,this.examples=this.input.example,this.input.const!=null)this.typeShapeNode=new OOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(xBh(this.input))this.typeShapeNode=new AOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(s$i(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new POu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(Exc(this.input)&&this.input.allOf!=null)this.typeShapeNode=new Mua({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(s$i(this.input)&&this.input.enum!=null)this.typeShapeNode=new c$i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable});else if(typeof this.input.type=="string"||Array.isArray(this.input.type)&&this.input.type.length===1){if(this.input.type=Array.isArray(this.input.type)?this.input.type[0]:this.input.type,!Array.isArray(this.input.type))switch(this.input.type){case"object":Exc(this.input)&&(this.typeShapeNode=new Mua({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"array":u$i(this.input)&&(this.typeShapeNode=new gOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"boolean":GBh(this.input)&&(this.typeShapeNode=new jOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"integer":HBh(this.input)&&(this.typeShapeNode=new wOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"number":$Bh(this.input)&&(this.typeShapeNode=new SOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"string":YBh(this.input)&&(this.typeShapeNode=new MOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"null":JBh(this.input)&&(this.typeShapeNode=new EOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case void 0:break;default:new tIh.UnreachableCaseError(this.input.type);break}}else if(Array.isArray(this.input.type)&&this.input.type.includes("null")&&this.input.type.length===2){let t=this.input.type.filter(r=>r!=="null")[0];t!=="array"&&(this.typeShapeNode=new e({input:{...this.input,type:t},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:!0,schemaName:this.schemaName}))}else this.input.properties!=null&&(this.typeShapeNode=new Mua({input:{...this.input,type:"object"},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));this.typeShapeNode==null&&(this.typeShapeNode=new DOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),!zv(this.input)&&(!u$i(this.input)&&this.input==null||u$i(this.input)&&this.input.items==null)&&this.context.errors.error({message:"Expected type declaration. Received: null",path:this.accessPath}))}convert(){let t=this.typeShapeNode?.convert();if(t==null)return;let r=RP(t)?.map(i=>this.nullable?bUi(i):i).filter(No);return Array.isArray(t)&&t.length>1?r:r?.[0]}example(t){return this.availability?.availability!=="deprecated"?this.typeShapeNode?.example(t):void 0}};function l$i(e){if(e!=null)return Eua(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(No))}var DYt=class extends iC{availability;required;schema;description;inputExample;constructor(t){super(t),this.safeParse(t.parameterName)}parse(t){this.description=this.input.description;let r;zv(this.input)?r=this.input:this.input.schema!=null?(r=this.input.schema,this.required=this.input.required):(r={type:"string"},this.required=!1),this.availability=new FEe({input:r,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new G0({input:r,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:t});let i=VBh(this.input,this.context.document);this.inputExample=i?.example??Object.values(i?.examples??{})[0]}convert(){return this.schema?.convert()}example(t){return this.inputExample??this.schema?.example(t)}};function rIh(e,t){return zv(e)?iL(e,t,void 0):e}var Sxc=ce(VS());function BOu(e){let{uniqueId:t,type:r,contextTypes:i,description:n,availability:a}=e;i[Ys.TypeId(t)]={name:t,shape:r,description:n,availability:a}}var iIh=ce(IZs(),1),Dua=class e{type;subtype;essence;parameters;mimeType;input;constructor(t,r,i,n,a,o){this.type=t,this.subtype=r,this.essence=i,this.parameters=n,this.mimeType=a,this.input=o}static APPLICATION_JSON="application/json";static APPLICATION_OCTET_STREAM="application/octet-stream";static MULTIPART_FORM_DATA="multipart/form-data";static parse(t){if(t==null)return null;let r=iIh.default.parse(t);return r==null?null:new e(r.type,r.subtype,r.essence,r.parameters,r,t)}toString(){return this.input}isText(){return this.type==="text"}isImage(){return this.type==="image"}isAudio(){return this.type==="audio"}isVideo(){return this.type==="video"}isFont(){return this.type==="font"}isMultipart(){return this.type==="multipart"}isApplication(){return this.type==="application"}isMessage(){return this.type==="message"}isModel(){return this.type==="model"}isCSS(){return this.isText()&&this.subtype==="css"}isCSV(){return this.isText()&&this.subtype==="csv"}isMarkdown(){return this.isText()&&this.subtype==="markdown"}isPlainText(){return this.isText()&&this.subtype==="plain"}isEventStream(){return this.isText()&&this.subtype==="event-stream"}isMultiPartFormData(){return this.isMultipart()&&this.subtype==="form-data"}isJSON(){return this.isApplication()&&this.subtype==="json"}containsJSON(){return this.isApplication()&&this.subtype.includes("json")}isURLEncoded(){return this.isApplication()&&this.subtype==="x-www-form-urlencoded"}isOctetStream(){return this.isApplication()&&this.subtype==="octet-stream"}isPDF(){return this.isApplication()&&this.subtype==="pdf"}isZip(){return this.isApplication()&&this.subtype==="zip"}isGzip(){return this.isApplication()&&this.subtype==="gzip"}isTar(){return this.isApplication()&&this.subtype==="tar"}isBrotli(){return this.isApplication()&&this.subtype==="br"}isDeflate(){return this.isApplication()&&this.subtype==="deflate"}isProtobuf(){return this.isApplication()&&this.subtype==="protobuf"}isAvif(){return this.isImage()&&this.subtype==="avif"}isWebP(){return this.isImage()&&this.subtype==="webp"}isSVG(){return this.isImage()&&this.subtype==="svg+xml"}isPNG(){return this.isImage()&&this.subtype==="png"}isJPEG(){return this.isImage()&&this.subtype==="jpeg"}isGIF(){return this.isImage()&&this.subtype==="gif"}isMPEG(){return this.isAudio()&&this.subtype==="mpeg"}isWAV(){return this.isAudio()&&this.subtype==="wav"}isHTML(){return this.mimeType.isHTML()}isXML(){return this.mimeType.isXML()}isJavaScript(){return this.mimeType.isJavaScript()}};function SfB(e){return typeof e.securitySchemes=="object"&&e.securitySchemes!=null}var IOu=class extends po{typeSchemas;securitySchemes;constructor(t){super(t),this.safeParse()}parse(){this.input.schemas!=null&&(this.typeSchemas=Object.fromEntries(Object.entries(this.input.schemas).map(([t,r])=>[t,new G0({input:r,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:new Set,nullable:void 0,schemaName:t})]))),SfB(this.input)&&this.input.securitySchemes!=null&&(this.securitySchemes=Object.fromEntries(Object.entries(this.input.securitySchemes??{}).map(([t,r],i)=>{let n;if(zv(r)?n=Lgu(r.$ref,this.context.document):n=r,n!=null)return[t,new jua({input:n,context:this.context,accessPath:this.accessPath,pathId:["securitySchemes",`${i}`]})]}).filter(No)))}convert(){return{auths:this.securitySchemes!=null?Object.fromEntries(Object.entries(this.securitySchemes??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[Ys.api.latest.AuthSchemeId(t),i]}).filter(No)):void 0,types:this.typeSchemas!=null?Object.fromEntries(Object.entries(this.typeSchemas).map(([t,r])=>{let i=r.name??t,n=RP(r.convert());return n==null?[t,void 0]:[Ys.TypeId(t),{name:i,shape:n[0],description:r.description,availability:void 0}]}).filter(([t,r])=>No(r))):void 0}}};var COu=class extends G0{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=nC(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${zv(this.input)?`Received undefined reference: ${this.input.$ref}`:""}`,path:this.accessPath});return}if(t.type==="string"&&t.format==="binary")this.multipartType="file",this.contentType=t.contentMediaType;else if(t.type==="array"){let r=nC(t.items,this.context.document);r?.type==="string"&&r?.format==="binary"?(this.multipartType="files",this.contentType=r?.contentMediaType):(this.context.errors.warning({message:"Expected multipart form data files definition with array type with internal string type and binary format.",path:this.accessPath}),this.multipartType=void 0,this.contentType=void 0)}else this.multipartType="property",this.contentType=t.contentMediaType}};var qOu=class extends po{description;method;path;schema;isOptional;contentType;availability;requiredFields;fields;examples;constructor(t){super(t),this.method=t.method,this.path=t.path,this.safeParse(t)}parse({contentType:t}){if(this.input.schema!=null){let i=nC(this.input.schema,this.context.document);this.availability=new FEe({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=zv(this.input.schema)?new hvn({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:!1,schemaName:"Request Body",description:this.input.schema.description,availability:this.availability}):void 0;let n=Dua.parse(t);n?.containsJSON()?(this.contentType="json",this.schema=this.schema??new G0({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:"Request Body"})):n?.isOctetStream()?(this.contentType="bytes",this.isOptional=i?.required==null):n?.isMultiPartFormData()?(this.contentType="form-data",this.requiredFields=i?.required,this.fields=Object.fromEntries(Object.entries(i?.properties??{}).map(([a,o])=>{if(o!=null)return[a,new COu({input:o,context:this.context,accessPath:this.accessPath,pathId:`schema.${a}`,seenSchemas:new Set,nullable:void 0,schemaName:a})]}).filter(No))):this.context.errors.warning({message:`Expected request body of reference or object with json, streaming or form-data content types. Received: ${t}`,path:this.accessPath})}let r=this.schema?.example({includeOptionals:!0,override:void 0});this.examples={...this.input.example!=null?{[nF]:{value:this.input.example}}:{},...this.input.examples},r!=null&&Object.keys(this.examples).length===0&&(this.examples={[nF]:{value:r}})}convertJsonLike(){let t=this.schema?.convert();return t==null?void 0:RP(t)?.map(i=>{let n=i.type;switch(n){case"object":case"alias":return i;case"enum":case"undiscriminatedUnion":case"discriminatedUnion":{let a=o8t([this.method,this.path,this.contentType,"request"].join("_"));return BOu({uniqueId:a,type:i,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:Ys.TypeId(a),default:i.type==="enum"&&i.default!=null?{type:"enum",value:i.default}:void 0}}}case void 0:return;default:new Sxc.UnreachableCaseError(n);return}}).filter(No)}convert(){if(this.schema instanceof hvn)return this.schema.convert();switch(this.contentType){case"json":return this.convertJsonLike();case"bytes":return{type:"bytes",isOptional:this.isOptional??!1,contentType:this.contentType};case"form-data":return Object.entries(this.fields??{}).map(([i,n])=>{switch(n.multipartType){case"file":return[{type:n.multipartType,key:Ys.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"files":return[{type:n.multipartType,key:Ys.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"property":{let a=RP(n.convert()),o=n.multipartType;return a?.map(c=>({type:o,key:Ys.PropertyKey(i),contentType:n.contentType,exploded:void 0,valueShape:c,description:n.description,availability:n.availability?.convert()}))}case void 0:return[];default:return new Sxc.UnreachableCaseError(n.multipartType),[]}}).filter(No).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(o=>[...a,o]):[[...a]]),[[]]).map(i=>({type:"formData",fields:i,availability:this.availability?.convert(),description:this.description}));case void 0:return this.convertJsonLike();default:return}}};var TOu=class extends po{description;requestBodiesByContentType;constructor(t){super(t),this.safeParse(t)}parse({method:t,path:r}){let i=rIh(this.input,this.context.document);if(i==null){this.context.errors.error({message:"Expected request body. Received: null",path:this.accessPath});return}Object.entries(i.content).forEach(([n,a])=>{this.requestBodiesByContentType??={},this.requestBodiesByContentType[n]=new qOu({input:a,context:this.context,accessPath:this.accessPath,pathId:"content",contentType:n,method:t,path:r})})}convert(){return Object.entries(this.requestBodiesByContentType??{}).flatMap(([t,r])=>RP(r.convert())?.map(n=>({description:this.description,contentType:t,body:n}))).filter(No)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>RP(t.convert())?.map(i=>{if(!(i.type!=="alias"&&i.type!=="object"))return{description:this.description,shape:i}})).filter(No)}webhookExample(){return{payload:this.requestBodiesByContentType?.["application/json"]?.schema?.example({includeOptionals:!0,override:void 0})}}};var nIh={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};function aIh(e,t){if(zv(e)){let r=iL(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var ROu=ce(VS());var oIh="application/json";var uIh="application/octet-stream";function sIh(e,t){return e===t||t===nF||e===nF}var wKa=class extends po{streamingFormat;path;method;statusCode;requests;shapes;schema;contentType;unsupportedContentType;contentSubtype;examples;empty;constructor(t,r,i,n,a,o,c,d){super(t),this.streamingFormat=i,this.path=n,this.method=a,this.statusCode=o,this.requests=c,this.shapes=d,this.safeParse(r)}matchRequestResponseExamplesByName(t,r,i){for(let n of t)for(let[a,o]of Object.entries(n?.examples??{}))for(let[c,d]of Object.entries(r))for(let s of d)sIh(c,a)&&(i.add(c),this.examples?.push(new MYt({input:{requestExample:o,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,a$i(a,c),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}matchExamplesByIndex(t,r){let i=0;for(let n of t){let a=0;for(let[o,c]of r){if(a===i){let[d,s,u]=n??[void 0,void 0,void 0];this.examples?.push(...c.map(f=>new MYt({input:{requestExample:u,responseExample:f},context:this.context,accessPath:this.accessPath,pathId:s!=null&&s!==""?["examples",s]:"examples"},this.path,this.statusCode,a$i(s,o),{requestBody:d,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}a++}i++}if(t.length>r.length)for(let n of t.slice(r.length)){let[a,o]=r[r.length-1]??[void 0,void 0],[c,d,s]=n??[void 0,void 0,void 0];this.examples?.push(...(o??[void 0]).map(u=>new MYt({input:{requestExample:s,responseExample:u},context:this.context,accessPath:this.accessPath,pathId:d!=null&&d!==""?["examples",d]:"examples"},this.path,this.statusCode,a$i(d,a),{requestBody:c,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}if(r.length>t.length){let[n,a,o]=t[t.length-1]??[void 0,void 0,void 0];for(let[c,d]of r.slice(t.length))this.examples?.push(...d.map(s=>new MYt({input:{requestExample:o,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,a$i(a,c),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}}pushResponseExample(t,r,i,n){let a=t[nF];if(a!=null)for(let o of a)this.examples?.push(new MYt({input:{requestExample:n,responseExample:o},context:this.context,accessPath:this.accessPath,pathId:i!=null&&i!==""?["examples",i]:"examples"},this.path,this.statusCode,a$i(i,void 0),{requestBody:r,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders}))}addGlobalFallbackExample(t,r){if(t==null||t.length===0)this.pushResponseExample(r,void 0,void 0,void 0);else for(let i of t)if(Object.keys(i.examples??{}).length===0)this.pushResponseExample(r,i,void 0,void 0);else for(let[n,a]of Object.entries(i.examples??{}))this.pushResponseExample(r,i,n,a)}parse(t){if(t==="empty")this.empty=!0;else{let c=Dua.parse(t);if(c?.isJSON()||c?.isEventStream())this.contentType=oIh,this.input.schema==null?(this.streamingFormat==null||this.streamingFormat==="json")&&this.context.errors.error({message:"Expected schema for JSON response body. Received null",path:this.accessPath}):this.schema=new G0({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"type",seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"});else if(c?.isOctetStream())this.contentType=uIh,this.contentSubtype=nC(this.input.schema,this.context.document)?.contentMediaType;else if(this.unsupportedContentType=t,this.input.schema==null){this.context.errors.error({message:"Expected schema for plain text response body. Received null",path:this.accessPath});return}else this.schema=new G0({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"})}let r={};this.input.examples!=null&&(r=uOu(this.input.examples,c=>[c])),this.input.example!=null&&Object.keys(r).length===0&&(r[nF]??=[],r[nF]=[{value:this.input.example}]);let i=nC(this.input.schema,this.context.document);if(i!=null&&(i.examples!=null&&Object.keys(r).length===0&&(r=uOu(i.examples,c=>[c])),i.example!=null&&Object.keys(r).length===0&&(r[nF]??=[],r[nF]?.push({value:i.example}))),Object.keys(r).length===0){let c=this.schema?.example({includeOptionals:!0,override:void 0});r[nF]??=[],r[nF]?.push(c!=null?{value:c}:void 0)}this.examples??=[];let n=new Set;this.matchRequestResponseExamplesByName(this.requests,r,n);let a=[];for(let c of this.requests)a.push(...Object.entries(c.examples??{}).filter(([d])=>!n.has(d)&&d!==nF).map(([d,s])=>[c,d,s]));let o=Object.entries(r).filter(([c,d])=>!n.has(c)&&No(d)&&c!==nF);Object.keys(r).every(c=>c===nF)||this.matchExamplesByIndex(a,o),!n.has(nF)&&this.examples.length===0&&this.addGlobalFallbackExample(this.requests,r),this.examples.length===0&&(this.examples=void 0)}convertStreamingFormat(){switch(this.streamingFormat){case"json":return RP(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new ROu.UnreachableCaseError(this.streamingFormat);return}}convertJsonLike(){return RP(this.schema?.convert())?.map(r=>{let i=r.type;switch(i){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":{let n=o8t([this.method,this.path,this.statusCode,"response"].join("_"));return BOu({uniqueId:n,type:r,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:Ys.TypeId(n),default:r.type==="enum"&&r.default!=null?{type:"enum",value:r.default}:void 0}}}case"object":return r;default:new ROu.UnreachableCaseError(i);return}}).filter(No)}convert(){if(this.empty)return{type:"empty"};if(this.contentType!=null)switch(this.contentType){case"application/json":return this.streamingFormat==null?this.convertJsonLike():this.convertStreamingFormat();case"application/octet-stream":return{type:"fileDownload",contentType:this.contentSubtype};case"text/event-stream":return this.convertStreamingFormat();case void 0:return;default:new ROu.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?this.convertJsonLike():void 0}};var EKa=class extends po{path;method;statusCode;requests;shapes;headers;responses;description;constructor(t,r,i,n,a,o){super(t),this.path=r,this.method=i,this.statusCode=n,this.requests=a,this.shapes=o,this.safeParse()}parse(t){this.description=this.input.description;let r=aIh(this.input,this.context.document);if(r==null){this.context.errors.error({message:zv(this.input)?`Undefined reference: ${this.input.$ref}`:"Expected response, received null",path:this.accessPath});return}Object.entries(r.headers??{}).forEach(([i,n])=>{this.headers??={},this.headers[i]=new DYt({input:n,context:this.context,accessPath:this.accessPath,pathId:"headers",parameterName:i})}),r.content==null?(this.responses??=[],this.responses.push(new wKa({input:{},context:this.context,accessPath:this.accessPath,pathId:["content"]},"empty",t,this.path,this.method,this.statusCode,this.requests,this.shapes))):Object.entries(r.content??{}).forEach(([i,n])=>{this.responses??=[],this.responses.push(new wKa({input:n,context:this.context,accessPath:this.accessPath,pathId:["content",i]},i,t,this.path,this.method,this.statusCode,this.requests,this.shapes))})}convert(){return this.responses?.flatMap(t=>t.convert()).filter(No)}};var zOu=class extends po{path;method;requests;shapes;responsesByStatusCode;errorsByStatusCode;constructor(t,r,i,n,a){super(t),this.path=r,this.method=i,this.requests=n,this.shapes=a,this.safeParse()}parse(){let t=this.input.default;Object.entries(this.input).forEach(([r,i])=>{r!=="default"&&(parseInt(r)>=400?(this.errorsByStatusCode??={},this.errorsByStatusCode[r]=new EKa({input:{...t,...i},context:this.context,accessPath:this.accessPath,pathId:"errors"},this.path,this.method,parseInt(r),[],this.shapes)):(this.responsesByStatusCode??={},this.responsesByStatusCode[r]=new EKa({input:i,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,parseInt(r),this.requests,this.shapes)))})}convertResponseObjectToHttpResponses(){return Object.entries(this.responsesByStatusCode??{}).flatMap(([t,r])=>{let i=r.convert();if(i!=null)return mOu(l$i(r.headers)).flatMap(n=>i?.map(a=>({headers:n,response:{statusCode:parseInt(t),body:a,description:r.description},examples:(r.responses??[]).flatMap(o=>(o.examples??[]).map(c=>c.convert()).filter(No))})))}).filter(No)}convertResponseObjectToErrors(){return Object.entries(this.errorsByStatusCode??{}).flatMap(([t,r])=>r.responses?.flatMap(i=>{let n=i.schema,a=RP(n?.convert());if(n!=null)return a?.map(o=>({statusCode:parseInt(t),shape:o,description:r.description??n.description,availability:n.availability?.convert(),name:n.name??nIh[parseInt(t)]??"UNKNOWN ERROR",examples:i.examples?.map(c=>{let d=c.convert();if(d!=null&&d.responseBody?.type==="json")return{name:d.name,description:d.description,responseBody:d.responseBody}}).filter(No)})).filter(No)})).filter(No)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var f$i=class extends po{servers;globalAuth;path;method;basePath;isWebhook;endpointIds;description;displayName;operationId;pathParameters;queryParameters;requestHeaders;requests;responses;availability;auth;namespaces;xFernExamplesNode;redocExamplesNode;emptyResponseExamples;constructor(t){super(t),this.servers=t.servers,this.globalAuth=t.globalAuth,this.path=t.path,this.method=t.method,this.basePath=t.basePath,this.isWebhook=t.isWebhook,this.safeParse()}pushEmptyResponseExample(t,r,i){this.emptyResponseExamples??=[],this.emptyResponseExamples.push(new MYt({input:{requestExample:t,responseExample:void 0},context:this.context,accessPath:this.accessPath,pathId:"examples"},this.path,200,a$i(i,void 0),{requestBody:r,pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}))}parse(){if(this.isWebhook&&this.method!=="POST"&&this.method!=="GET"){this.context.errors.error({message:`Webhook method must be POST or GET. Received: ${this.method}`,path:this.accessPath});return}this.description=this.input.description,this.displayName=this.input.summary,this.operationId=this.input.operationId,this.availability=new FEe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=i$i(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new bOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((i,n)=>{if(zv(i)){let a=dOu(i,this.context.document);if(a!=null)i=a;else{this.context.errors.warning({message:`Expected parameter reference to resolve to an object. Received undefined reference: ${i.$ref}`,path:[...this.accessPath,`parameters[${n}]`]});return}}i.in==="path"?i.schema!=null&&(this.pathParameters??={},this.pathParameters[i.name]=new DYt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="query"?i.schema!=null&&(this.queryParameters??={},this.queryParameters[i.name]=new DYt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="header"&&i.schema!=null&&(this.requestHeaders??={},this.requestHeaders[i.name]=new DYt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name}))});for(let i of this.extractPathParameterIds()??[])this.pathParameters?.[i]==null&&this.context.errors.warning({message:`Path parameter not defined: ${i}`,path:[...this.accessPath,"parameters"]});if(this.redocExamplesNode=new vOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new TOu({input:this.input.requestBody,context:this.context,accessPath:this.accessPath,pathId:"requestBody",method:this.method,path:this.path}):void 0,this.responses=this.input.responses!=null?new zOu({input:this.input.responses,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,Object.values(this.requests?.requestBodiesByContentType??{}),{pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}):void 0,this.responses==null){let i=this.requests?.requestBodiesByContentType;i==null||Object.keys(i).length===0?this.pushEmptyResponseExample(void 0,void 0,void 0):Object.values(i).forEach(n=>{if(Object.keys(n.examples??{}).length===0){let a=n.schema?.example({includeOptionals:!1,override:void 0});a!=null&&this.pushEmptyResponseExample({value:a},n,void 0)}else Object.entries(n.examples??{}).forEach(([a,o])=>{this.pushEmptyResponseExample(o,n,a)})})}let t=200;this.responses?.responsesByStatusCode!=null&&(t=Number(Object.keys(this.responses.responsesByStatusCode)?.filter(i=>Number(i)>=200&&Number(i)<300)[0])),this.globalAuth!=null&&(this.auth=this.globalAuth),this.input.security!=null&&(this.auth=new wua({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespaces=[new jKa({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-group-name"})],this.namespaces?.every(i=>i.groupName==null)&&this.input.tags!=null&&(this.namespaces=this.input.tags.slice(0,1).map((i,n)=>new jKa({input:{[Fgu]:i},context:this.context,accessPath:this.accessPath,pathId:["tags",`${n}`]})));let r=new yOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointIds=this.namespaces.map(i=>sOu({namespace:RP(i?.groupName),path:this.path,method:this.method,sdkMethodName:r.sdkMethodName,operationId:this.input.operationId,displayName:this.displayName,isWebhook:this.isWebhook})).filter(No),this.xFernExamplesNode=new hOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-examples"},this.path,t,this.requests?.requestBodiesByContentType,this.responses?.responsesByStatusCode?.[t]?.responses)}extractPathParameterIds(){if(this.path!=null)return this.path.split("/").map(t=>{if(t.startsWith("{")&&t.endsWith("}"))return t.slice(1,-1).trim()}).filter(No)}convertPathToPathParts(){if(this.path===void 0)return;let t=this.path.startsWith("/")?this.path.slice(1):this.path,r=this.basePath?.convert();return(r?[r,...t.split("/")]:t.split("/")).reduce((n,a)=>(n.push({type:"literal",value:"/"}),a.startsWith("{")&&a.endsWith("}")?n.push({type:"pathParameter",value:Ys.PropertyKey(a.slice(1,-1).trim())}):n.push({type:"literal",value:a}),n),[])}convert(){if(this.path==null||this.endpointIds==null)return;let{responses:t,errors:r}=this.responses?.convert()??{responses:void 0,errors:void 0},i=this.emptyResponseExamples?.map(u=>u.convert()).filter(No),n=TBh(this.xFernExamplesNode?.convert(),[...i??[],...t?.flatMap(u=>u.examples)??[]])?.map(u=>({...u,snippets:qBh(u.snippets,this.redocExamplesNode?.convert())}));if(this.isWebhook)return this.endpointIds.map((u,f)=>{if(!(this.method!=="POST"&&this.method!=="GET"))return{id:Ys.WebhookId(u),description:this.description,availability:this.availability?.convert(),displayName:this.displayName,operationId:this.operationId,namespace:this.namespaces?.[f]?.convert(),method:this.method,path:this.convertPathToPathParts()?.map(p=>p.value.toString())??[],queryParameters:l$i(this.queryParameters)?.flat(),headers:l$i(this.requestHeaders)?.flat(),payloads:this.requests?.convertToWebhookPayload(),examples:[this.requests?.webhookExample()].filter(No)}}).filter(No);let a=this.servers?.map(u=>u.convert()).filter(No),o=this.convertPathToPathParts();if(o==null)return;let c,d=this.auth?.convert();d!=null&&(c=Object.keys(d));let s=t?.flatMap(u=>u.headers).filter(No);return this.endpointIds.map((u,f)=>({id:Ys.EndpointId(u),description:this.description,availability:this.availability?.convert(),namespace:this.namespaces?.[f]?.convert()?.map(p=>Ys.api.v1.SubpackageId(p)),displayName:this.displayName,operationId:this.operationId,method:this.method,path:o,auth:c?.map(p=>Ys.api.latest.AuthSchemeId(p)),defaultEnvironment:a?.[0]?.id,environments:a,pathParameters:l$i(this.pathParameters)?.flat(),queryParameters:l$i(this.queryParameters)?.flat(),requestHeaders:l$i(this.requestHeaders)?.flat(),responseHeaders:s!=null&&s.length>0?s:void 0,requests:this.requests?.convert(),responses:t?.map(p=>p.response),errors:r,examples:n,snippetTemplates:void 0,protocol:{type:"rest"}}))}};var Bua=class extends po{description;get;post;put;patch;delete;path;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i,isWebhook:n}){this.description=this.input.description;let a=i$i(t,this.input.servers,this.context,this.accessPath),o=Array.isArray(this.pathId)?this.pathId.join("/"):this.pathId;this.input.get!=null&&(this.get=new f$i({input:this.input.get,context:this.context,accessPath:this.accessPath,pathId:"get",servers:a,globalAuth:r,path:o,method:"GET",basePath:i,isWebhook:n})),this.input.post!=null&&(this.post=new f$i({input:this.input.post,context:this.context,accessPath:this.accessPath,pathId:"post",servers:a,globalAuth:r,path:o,method:"POST",basePath:i,isWebhook:n})),this.input.put!=null&&(this.put=new f$i({input:this.input.put,context:this.context,accessPath:this.accessPath,pathId:"put",servers:a,globalAuth:r,path:o,method:"PUT",basePath:i,isWebhook:!1})),this.input.patch!=null&&(this.patch=new f$i({input:this.input.patch,context:this.context,accessPath:this.accessPath,pathId:"patch",servers:a,globalAuth:r,path:o,method:"PATCH",basePath:i,isWebhook:!1})),this.input.delete!=null&&(this.delete=new f$i({input:this.input.delete,context:this.context,accessPath:this.accessPath,pathId:"delete",servers:a,globalAuth:r,path:o,method:"DELETE",basePath:i,isWebhook:!1}))}convert(){return[...this.get?.convert()??[],...this.post?.convert()??[],...this.put?.convert()??[],...this.patch?.convert()??[],...this.delete?.convert()??[]].filter(No)}};function NOu(e){return"payloads"in e}var FOu=class extends po{paths;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.paths=Object.entries(this.input).map(([n,a])=>{if(a!=null)return new Bua({input:a,context:this.context,accessPath:this.accessPath,pathId:n,servers:i$i(t,a.servers,this.context,this.accessPath),globalAuth:r,basePath:i,isWebhook:void 0})}).filter(No)}convert(){if(this.paths==null)return;let t={},r={};return this.paths.forEach(i=>{let n=i.convert();n?.forEach(a=>{NOu(a)?r[Ys.WebhookId(a.id)]=a:t[Ys.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var QOu=class extends po{globalHeaders;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[SDh]?.map(r=>{let{header:i,...n}=r;return(n.optional!=null&&!n.optional||dOu(n,this.context.document)?.required)&&(this.requiredProperties??=[],this.requiredProperties?.push(i)),[i,new DYt({input:n,context:this.context,accessPath:this.accessPath,pathId:this.pathId,parameterName:i})]});t!=null&&(this.globalHeaders=Object.fromEntries(t))}convert(){return Eua(this.globalHeaders,this.requiredProperties)?.flat()}};function cIh(e,t){if(zv(e)){let r=iL(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var UOu=class extends po{webhooks;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.webhooks=Object.entries(this.input??{}).map(([n,a])=>{let o=cIh(a,this.context.document);if(o!=null)return new Bua({input:o,context:this.context,accessPath:this.accessPath,pathId:n,servers:t,globalAuth:r,basePath:i,isWebhook:!0})}).filter(No)}convert(){return this.webhooks?.reduce((t,r)=>(r.convert()?.forEach(i=>{NOu(i)&&(t[Ys.WebhookId(i.id)]=i)}),t),{})}};var LOu=class extends po{paths;webhooks;components;auth;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){let t=i$i(void 0,this.input.servers,this.context,this.accessPath);this.input.security!=null&&(this.auth=new wua({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"}));let r=new fOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});this.input.paths==null&&this.input.webhooks==null&&this.context.errors.warning({message:"Expected 'paths' or 'webhooks' property to be specified",path:this.accessPath}),this.input.paths!=null&&(this.paths=new FOu({input:this.input.paths,context:this.context,accessPath:this.accessPath,pathId:"paths",basePath:r,servers:t,globalAuth:this.auth})),this.input.webhooks!=null&&(this.webhooks=new UOu({input:this.input.webhooks,context:this.context,accessPath:this.accessPath,pathId:"webhooks",basePath:r,servers:t,globalAuth:this.auth})),this.input.components!=null&&(this.components=new IOu({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"})),this.globalHeaders=new QOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=Hbe(),{webhookEndpoints:r,endpoints:i}=this.paths?.convert()??{},n={...this.webhooks?.convert()??{},...r??{}},a=PDh({endpoints:i,webhookEndpoints:n}),{types:o,auths:c}=this.components?.convert()??{};return{id:Ys.ApiDefinitionId(t),endpoints:i??{},websockets:{},webhooks:n,types:{...o,...this.context.generatedTypes},subpackages:a,auths:{...c,...this.auth?.convert()??{}},globalHeaders:this.globalHeaders?.convert(),snippetsConfiguration:void 0}}};async function Mxc(e,t){if(e instanceof SEe){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof ZE))return;let r=new J3t(e.absoluteFilePath),i=await DEe({context:t,specs:e.specs}),n=await r.loadDocuments({context:t,specs:i}),a;for(let o of n){if(o.type!=="openapi")continue;let c={document:o.value,logger:t.logger,errors:new zgu,generatedTypes:{}},d=new LOu({input:o.value,context:c,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=KZs(a,d.convert())}return a}var S4h=ce(Ixc(),1),M4h=ce(DAu(),1),kmu=require("fs/promises"),D4h=ce(require("http"),1),B4h=ce(require("path"),1);var pRh=require("events"),TAu=ce(require("fs"),1),wvn=ce(require("path"),1);var $Th=ce(require("os"),1),YTh=300,v$i=20,$Ka=1e7,XTh=$Th.default.platform();var $vB=XTh==="darwin",XKc=XTh==="win32",g$i=$vB||XKc,ZTh=3e3,kTh=2e4,ZKc=1250;var qYt;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(qYt||(qYt={}));var jvn;(function(e){e.CHANGE="change",e.RENAME="rename"})(jvn||(jvn={}));var YKa;(function(e){e.CHANGE="change",e.ERROR="error"})(YKa||(YKa={}));var Hl;(function(e){e.ADD="add",e.ADD_DIR="addDir",e.CHANGE="change",e.RENAME="rename",e.RENAME_DIR="renameDir",e.UNLINK="unlink",e.UNLINK_DIR="unlinkDir"})(Hl||(Hl={}));var nH;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(nH||(nH={}));var YvB=(e,t=1,r)=>{t=Math.max(1,t);let i=r?.leading??!1,n=r?.trailing??!0,a=Math.max(r?.maxWait??1/0,t),o,c,d=0,s=0,u=()=>{let g=Date.now(),m=g-d,j=g-s,S=m>=t||j>=a;return[g,S]},f=g=>{if(s=g,!o)return;let m=o;o=void 0,e.apply(void 0,m)},p=()=>{O(0)},_=()=>{c&&(p(),f(Date.now()))},h=g=>{if(s=g,i)return f(g)},y=g=>{if(n&&o)return f(g);o=void 0},b=()=>{c=void 0;let[g,m]=u();return m?y(g):v(g)},v=g=>{let m=g-d,j=g-s,S=t-m,w=a-j,D=Math.min(S,w);return O(D)},O=g=>{c&&clearTimeout(c),!(g<=0)&&(c=setTimeout(b,g))},A=(...g)=>{let[m,j]=u(),S=!!c;if(o=g,d=m,(j||!c)&&O(t),j)return S?f(m):h(m)};return A.cancel=p,A.flush=_,A},BAu=YvB;var rJc=ce(require("fs"),1),CAu=ce(require("path"),1);var KO=ce(require("fs"),1),nL=require("util");var gUi=(e,t)=>function(...i){return e.apply(void 0,i).catch(t)},TYt=(e,t)=>function(...i){try{return e.apply(void 0,i)}catch(n){return t(n)}};var kKc=ce(require("process"),1),eRh=kKc.default.getuid?!kKc.default.getuid():!1,tRh=1e4,X$=()=>{};var XKa={isChangeErrorOk:e=>{if(!XKa.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!eRh&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!XKa.isNodeError(e))return!1;let{code:t}=e;return t==="EMFILE"||t==="ENFILE"||t==="EAGAIN"||t==="EBUSY"||t==="EACCESS"||t==="EACCES"||t==="EACCS"||t==="EPERM"},onChangeError:e=>{if(!XKa.isNodeError(e))throw e;if(!XKa.isChangeErrorOk(e))throw e}},aC=XKa;var eJc=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=tRh,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(i),i=()=>t(r);this.add(i)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},rRh=new eJc;var OUi=(e,t)=>function(i){return function n(...a){return rRh.schedule().then(o=>{let c=s=>(o(),s),d=s=>{if(o(),Date.now()>=i)throw s;if(t(s)){let u=Math.round(100*Math.random());return new Promise(p=>setTimeout(p,u)).then(()=>n.apply(void 0,a))}throw s};return e.apply(void 0,a).then(c,d)})}},AUi=(e,t)=>function(i){return function n(...a){try{return e.apply(void 0,a)}catch(o){if(Date.now()>i)throw o;if(t(o))return n.apply(void 0,a);throw o}}};var XvB={attempt:{chmod:gUi((0,nL.promisify)(KO.default.chmod),aC.onChangeError),chown:gUi((0,nL.promisify)(KO.default.chown),aC.onChangeError),close:gUi((0,nL.promisify)(KO.default.close),X$),fsync:gUi((0,nL.promisify)(KO.default.fsync),X$),mkdir:gUi((0,nL.promisify)(KO.default.mkdir),X$),realpath:gUi((0,nL.promisify)(KO.default.realpath),X$),stat:gUi((0,nL.promisify)(KO.default.stat),X$),unlink:gUi((0,nL.promisify)(KO.default.unlink),X$),chmodSync:TYt(KO.default.chmodSync,aC.onChangeError),chownSync:TYt(KO.default.chownSync,aC.onChangeError),closeSync:TYt(KO.default.closeSync,X$),existsSync:TYt(KO.default.existsSync,X$),fsyncSync:TYt(KO.default.fsync,X$),mkdirSync:TYt(KO.default.mkdirSync,X$),realpathSync:TYt(KO.default.realpathSync,X$),statSync:TYt(KO.default.statSync,X$),unlinkSync:TYt(KO.default.unlinkSync,X$)},retry:{close:OUi((0,nL.promisify)(KO.default.close),aC.isRetriableError),fsync:OUi((0,nL.promisify)(KO.default.fsync),aC.isRetriableError),open:OUi((0,nL.promisify)(KO.default.open),aC.isRetriableError),readFile:OUi((0,nL.promisify)(KO.default.readFile),aC.isRetriableError),rename:OUi((0,nL.promisify)(KO.default.rename),aC.isRetriableError),stat:OUi((0,nL.promisify)(KO.default.stat),aC.isRetriableError),write:OUi((0,nL.promisify)(KO.default.write),aC.isRetriableError),writeFile:OUi((0,nL.promisify)(KO.default.writeFile),aC.isRetriableError),closeSync:AUi(KO.default.closeSync,aC.isRetriableError),fsyncSync:AUi(KO.default.fsyncSync,aC.isRetriableError),openSync:AUi(KO.default.openSync,aC.isRetriableError),readFileSync:AUi(KO.default.readFileSync,aC.isRetriableError),renameSync:AUi(KO.default.renameSync,aC.isRetriableError),statSync:AUi(KO.default.statSync,aC.isRetriableError),writeSync:AUi(KO.default.writeSync,aC.isRetriableError),writeFileSync:AUi(KO.default.writeFileSync,aC.isRetriableError)}},iRh=XvB;var IAu=ce(require("fs"),1),ZKa=ce(require("path"),1);var tJc=()=>{};var ZvB=()=>{let e=tJc,t=tJc,r=!1,i=!1;return{promise:new Promise((d,s)=>{e=u=>(r=!0,d(u)),t=u=>(i=!0,s(u))}),resolve:e,reject:t,isPending:()=>!r&&!i,isResolved:()=>r,isRejected:()=>i}},nRh=ZvB;var kvB=()=>{let{promise:e,resolve:t,isPending:r}=nRh(),i=0,n=()=>{i+=1},a=()=>{i-=1,!i&&t()};return(()=>{n(),queueMicrotask(a)})(),{promise:e,isPending:r,increment:n,decrement:a}},aRh=kvB;var oRh={then:e=>{e()}};var uRh=e=>Array.isArray(e)?e:[e],sRh=e=>typeof e=="function";var egB=(e,t)=>{let r=t?.followSymlinks??!1,i=t?.depth??1/0,n=t?.limit??1/0,a=t?.ignore??[],o=uRh(a).map(H=>sRh(H)?H:G=>H.test(G)),c=H=>o.some(G=>G(H)),d=t?.signal??{aborted:!1},s=t?.onDirents||(()=>{}),u=[],f=new Set,p={},_=[],h=new Set,y={},b=[],v=new Set,O={},A={},g=new Set,m={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},j={directories:u,directoriesNames:f,directoriesNamesToPaths:p,files:_,filesNames:h,filesNamesToPaths:y,symlinks:b,symlinksNames:v,symlinksNamesToPaths:O,map:A},{promise:S,increment:w,decrement:D}=aRh(),B=0,q=(H,G,Ee,ue)=>{g.has(G)||B>=n||(B+=1,H.directories.push(G),H.directoriesNames.add(Ee),u.push(G),f.add(Ee),p.propertyIsEnumerable(Ee)||(p[Ee]=[]),p[Ee].push(G),g.add(G),!(ue>=i)&&(B>=n||ee(G,ue+1)))},U=(H,G,Ee)=>{g.has(G)||B>=n||(B+=1,H.files.push(G),H.filesNames.add(Ee),_.push(G),h.add(Ee),y.propertyIsEnumerable(Ee)||(y[Ee]=[]),y[Ee].push(G),g.add(G))},R=(H,G,Ee,ue)=>{g.has(G)||B>=n||(B+=1,H.symlinks.push(G),H.symlinksNames.add(Ee),b.push(G),v.add(Ee),O.propertyIsEnumerable(Ee)||(O[Ee]=[]),O[Ee].push(G),g.add(G),r&&(ue>=i||B>=n||me(G,ue+1)))},N=(H,G,Ee,ue,ge)=>{d.aborted||c(G)||(ue.isDirectory()?q(H,G,Ee,ge):ue.isFile()?U(H,G,Ee):ue.isSymbolicLink()&&R(H,G,Ee,ge))},F=(H,G,Ee,ue)=>{if(d.aborted)return;let ge=G===ZKa.default.sep?"":ZKa.default.sep,We=Ee.name,se=`${G}${ge}${We}`;c(se)||(Ee.isDirectory()?q(H,se,We,ue):Ee.isFile()?U(H,se,We):Ee.isSymbolicLink()&&R(H,se,We,ue))},x=(H,G,Ee,ue)=>{for(let ge=0,We=Ee.length;ge<We;ge++)F(H,G,Ee[ge],ue)},ee=(H,G)=>{d.aborted||G>i||B>=n||(w(),IAu.default.readdir(H,{withFileTypes:!0},(Ee,ue)=>{if(Ee||d.aborted||!ue.length)return D();(s(ue)||oRh).then(()=>{let We=A[H]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};x(We,H,ue,G),D()})}))},me=(H,G)=>{w(),IAu.default.realpath(H,(Ee,ue)=>{if(Ee||d.aborted)return D();IAu.default.stat(ue,(ge,We)=>{if(ge||d.aborted)return D();let se=ZKa.default.basename(ue),ne=A[H]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};N(ne,ue,se,We,G),D()})})};return(async(H,G=1)=>(H=ZKa.default.normalize(H),g.add(H),ee(H,G),await S,d.aborted?m:j))(e)},cRh=egB;var RYt={lang:{debounce:BAu,attempt:e=>{try{return e()}catch(t){return RYt.lang.castError(t)}},castArray:e=>RYt.lang.isArray(e)?e:[e],castError:e=>RYt.lang.isError(e)?e:RYt.lang.isString(e)?new Error(e):new Error("Unknown error"),defer:e=>setTimeout(e,0),isArray:e=>Array.isArray(e),isError:e=>e instanceof Error,isFunction:e=>typeof e=="function",isNaN:e=>Number.isNaN(e),isNumber:e=>typeof e=="number",isPrimitive:e=>{if(e===null)return!0;let t=typeof e;return t!=="object"&&t!=="function"},isShallowEqual:(e,t)=>{if(e===t)return!0;if(RYt.lang.isNaN(e))return RYt.lang.isNaN(t);if(RYt.lang.isPrimitive(e)||RYt.lang.isPrimitive(t))return e===t;for(let r in e)if(!(r in t))return!1;for(let r in t)if(e[r]!==t[r])return!1;return!0},isSet:e=>e instanceof Set,isString:e=>typeof e=="string",isUndefined:e=>e===void 0,noop:()=>{},uniq:e=>e.length<2?e:Array.from(new Set(e))},fs:{getDepth:e=>Math.max(0,e.split(CAu.default.sep).length-1),getRealPath:(e,t)=>{try{return t?rJc.default.realpathSync.native(e):rJc.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===CAu.default.sep&&t.length-e.length>CAu.default.sep.length,poll:(e,t=kTh)=>iRh.retry.stat(t)(e,{bigint:!0}).catch(RYt.lang.noop),readdir:async(e,t,r=1/0,i=1/0,n,a)=>{if(a&&r===1&&e in a){let o=a[e];return[o.directories,o.files]}else{let o=await cRh(e,{depth:r,limit:i,ignore:t,signal:n});return[o.directories,o.files]}}}},Mp=RYt;var qAu=ce(require("path"),1);var iJc=class{constructor(t,r,i){this.base=i,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||Mp.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=YTh){return(()=>{let r=this.watcher._readyWait,i=[],n=new Set,a=async(c,d)=>{let s=this.options.ignoreInitial?[]:c,u=await this.eventsPopulate([...d]),f=this.eventsDeduplicate([...s,...u]);this.onTargetEvents(f)},o=Mp.lang.debounce(()=>{this.watcher.isClosed()||(r=a(i,n),i=[],n=new Set)},t);return async(c,d="",s=!1)=>{s?await this.eventsPopulate([d],i,!0):n.add(d),r.then(o)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((i,n)=>{let[a,o]=n,c=r[o];return a===c||a===Hl.CHANGE&&c===Hl.ADD||(r[o]=a,i.push(n)),i},[])}async eventsPopulate(t,r=[],i=!1){return await Promise.all(t.map(async n=>{let a=await this.watcher._poller.update(n,this.options.pollingTimeout);await Promise.all(a.map(async o=>{r.push([o,n]),o===Hl.ADD_DIR?await this.eventsPopulateAddDir(t,n,r,i):o===Hl.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,n,r,i)}))})),r}async eventsPopulateAddDir(t,r,i=[],n=!1){if(n)return i;let a=this.options.recursive?this.options.depth??v$i:Math.min(1,this.options.depth??v$i),o=this.options.limit??$Ka,[c,d]=await Mp.fs.readdir(r,this.options.ignore,a,o,this.watcher._closeSignal),s=[...c,...d];return await Promise.all(s.map(u=>{if(!this.watcher.isIgnored(u,this.options.ignore)&&!t.includes(u))return this.eventsPopulate([u],i,!0)})),i}async eventsPopulateUnlinkDir(t,r,i=[],n=!1){if(n)return i;for(let a of this.watcher._poller.stats.keys())Mp.fs.isSubPath(r,a)&&(t.includes(a)||await this.eventsPopulate([a],i,!0));return i}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(Hl.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!g$i&&this.options.native!==!1&&this.watcher.watchDirectory(t,this.options,this.handler,void 0,this.base||this),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAddDir(t,this.options.renameTimeout):this.watcher.event(Hl.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(Hl.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(qAu.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(Hl.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(qAu.default.dirname(t),t,!1),this.watcher.watchersClose(t),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlinkDir(t,this.options.renameTimeout):this.watcher.event(Hl.UNLINK_DIR,t))}onTargetEvent(t){let[r,i]=t;r===Hl.ADD?this.onTargetAdd(i):r===Hl.ADD_DIR?this.onTargetAddDir(i):r===Hl.CHANGE?this.onTargetChange(i):r===Hl.UNLINK?this.onTargetUnlink(i):r===Hl.UNLINK_DIR&&this.onTargetUnlinkDir(i)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,i=!1){return this.handlerBatched(t,r,i)}onWatcherChange(t=jvn.CHANGE,r){if(this.watcher.isClosed())return;let i=qAu.default.resolve(this.folderPath,r||"");this.filePath&&i!==this.folderPath&&i!==this.filePath||this.watcher.isIgnored(i,this.options.ignore)||this.onWatcherEvent(t,i)}onWatcherError(t){XKc&&t.code==="EPERM"?this.onWatcherChange(jvn.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(YKa.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(YKa.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(jvn.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&g$i&&this.options.native!==!1?this.options.depth??v$i:Math.min(1,this.options.depth??v$i),i=this.options.limit??$Ka,[n,a]=await Mp.fs.readdir(this.folderPath,this.options.ignore,r,i,this.watcher._closeSignal,this.options.readdirMap),o=[this.folderPath,...n,...a];await Promise.all(o.map(c=>{if(!this.watcher._poller.stats.has(c)&&!this.watcher.isIgnored(c,this.options.ignore))return this.onWatcherEvent(jvn.CHANGE,c,t)}))}}},lRh=iJc;var aH={interval:100,intervalId:void 0,fns:new Map,init:()=>{aH.intervalId||(aH.intervalId=setInterval(aH.resolve,aH.interval))},reset:()=>{aH.intervalId&&(clearInterval(aH.intervalId),delete aH.intervalId)},add:(e,t)=>{aH.fns.set(e,Date.now()+t),aH.init()},remove:e=>{aH.fns.delete(e)},resolve:()=>{if(!aH.fns.size)return aH.reset();let e=Date.now();for(let[t,r]of aH.fns)r>=e||(aH.remove(t),t())}},kKa=aH;var eJa=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=ZKc){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{let f=this._watcher._poller.paths.find(i||-1,p=>p!==n);if(f&&f!==n){if(Mp.fs.getRealPath(n,!0)===f)return;this._watcher.event(a.rename,f,n)}else this._watcher.event(a.add,n)};if(!i)return c();let d=()=>{o.add.delete(i),kKa.remove(s)},s=()=>{d(),c()};kKa.add(s,r);let u=()=>{let f=o.unlink.get(i);if(!f)return;d();let p=f();n===p?a.change&&this._watcher._poller.stats.has(n)&&this._watcher.event(a.change,n):this._watcher.event(a.rename,p,n)};o.add.set(i,u),u()}getLockUnlink(t,r=ZKc){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{this._watcher.event(a.unlink,n)};if(!i)return c();let d=()=>{o.unlink.delete(i),kKa.remove(s)},s=()=>{d(),c()};kKa.add(s,r);let u=()=>(d(),n);o.unlink.set(i,u),o.add.get(i)?.()}getLockTargetAdd(t,r){let i=this._watcher._poller.getIno(t,Hl.ADD,qYt.FILE);return this.getLockAdd({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let i=this._watcher._poller.getIno(t,Hl.ADD_DIR,qYt.DIR);return this.getLockAdd({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let i=this._watcher._poller.getIno(t,Hl.UNLINK,qYt.FILE);return this.getLockUnlink({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let i=this._watcher._poller.getIno(t,Hl.UNLINK_DIR,qYt.DIR);return this.getLockUnlink({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};eJa.DIR_EVENTS={add:Hl.ADD_DIR,rename:Hl.RENAME_DIR,unlink:Hl.UNLINK_DIR};eJa.FILE_EVENTS={add:Hl.ADD,change:Hl.CHANGE,rename:Hl.RENAME,unlink:Hl.UNLINK};var fRh=eJa;var nJc=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(Mp.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let i=this.map.get(t);if(Mp.lang.isSet(i)){let n=i.delete(r);return i.size||this.map.delete(t),n}else if(i===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let i=this.map.get(t);if(Mp.lang.isSet(i))return Array.from(i).find(r);if(r(i))return i}}get(t){return this.map.get(t)}has(t,r){if(Mp.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let i=this.map.get(t);return Mp.lang.isSet(i)?i.has(r):i===r}return!1}set(t,r){if(this.map.has(t)){let i=this.map.get(t);Mp.lang.isSet(i)?i.add(r):i!==r&&this.map.set(t,new Set([i,r]))}else this.map.set(t,r);return this}},aJc=nJc;var oJc=class{constructor(t){this.ino=t.ino<=Number.MAX_SAFE_INTEGER?Number(t.ino):t.ino,this.size=Number(t.size),this.atimeMs=Number(t.atimeMs),this.mtimeMs=Number(t.mtimeMs),this.ctimeMs=Number(t.ctimeMs),this.birthtimeMs=Number(t.birthtimeMs),this._isFile=t.isFile(),this._isDirectory=t.isDirectory(),this._isSymbolicLink=t.isSymbolicLink()}isFile(){return this._isFile}isDirectory(){return this._isDirectory}isSymbolicLink(){return this._isSymbolicLink}},dRh=oJc;var uJc=class{constructor(){this.inos={},this.paths=new aJc,this.stats=new Map}getIno(t,r,i){let n=this.inos[r];if(!n)return;let a=n[t];if(a&&!(i&&a[1]!==i))return a[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let i=await Mp.fs.poll(t,r);if(!(!i||!(i.isFile()||i.isDirectory())))return new dRh(i)}reset(){this.inos={},this.paths=new aJc,this.stats=new Map}async update(t,r){let i=this.getStats(t),n=await this.poll(t,r);if(this.updateStats(t,n),!i&&n){if(n.isFile())return this.updateIno(t,Hl.ADD,n),[Hl.ADD];if(n.isDirectory())return this.updateIno(t,Hl.ADD_DIR,n),[Hl.ADD_DIR]}else if(i&&!n){if(i.isFile())return this.updateIno(t,Hl.UNLINK,i),[Hl.UNLINK];if(i.isDirectory())return this.updateIno(t,Hl.UNLINK_DIR,i),[Hl.UNLINK_DIR]}else if(i&&n){if(i.isFile()){if(n.isFile())return i.ino===n.ino&&!i.size&&!n.size?[]:(this.updateIno(t,Hl.CHANGE,n),[Hl.CHANGE]);if(n.isDirectory())return this.updateIno(t,Hl.UNLINK,i),this.updateIno(t,Hl.ADD_DIR,n),[Hl.UNLINK,Hl.ADD_DIR]}else if(i.isDirectory()){if(n.isFile())return this.updateIno(t,Hl.UNLINK_DIR,i),this.updateIno(t,Hl.ADD,n),[Hl.UNLINK_DIR,Hl.ADD];if(n.isDirectory())return i.ino===n.ino?[]:(this.updateIno(t,Hl.UNLINK_DIR,i),this.updateIno(t,Hl.ADD_DIR,n),[Hl.UNLINK_DIR,Hl.ADD_DIR])}}return[]}updateIno(t,r,i){let n=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=i.isFile()?qYt.FILE:qYt.DIR;n[t]=[i.ino,a]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let i=this.stats.get(t)?.ino||-1;this.paths.delete(i,t),this.stats.delete(t)}}},sJc=uJc;var cJc=class e extends pRh.EventEmitter{constructor(t,r,i){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(nH.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(n=>this.on(nH.CLOSE,n)),this._readyWait=new Promise(n=>this.on(nH.READY,n)),this._locker=new fRh(this),this._roots=new Set,this._poller=new sJc,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,i)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(Mp.lang.isFunction(r)?!!r(t):r.test(t))}isReady(){return this._ready}close(){return this._locker.reset(),this._poller.reset(),this._roots.clear(),this.watchersClose(),this.isClosed()?!1:(this._closed=!0,this.emit(nH.CLOSE))}error(t){if(this.isClosed())return!1;let r=Mp.lang.castError(t);return this.emit(nH.ERROR,r)}event(t,r,i){return this.isClosed()?!1:(this.emit(nH.ALL,t,r,i),this.emit(t,r,i))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(nH.READY))}pollerExists(t,r){for(let i of this._pollers)if(i.targetPath===t&&Mp.lang.isShallowEqual(i.options,r))return!0;return!1}subwatcherExists(t,r){for(let i of this._subwatchers)if(i.targetPath===t&&Mp.lang.isShallowEqual(i.options,r))return!0;return!1}watchersClose(t,r,i=!0){if(t){let n=this._watchers[t];if(n)for(let a of[...n])r&&a.filePath!==r||this.watcherClose(a);if(i)for(let a in this._watchers)Mp.fs.isSubPath(t,a)&&this.watchersClose(a,r,!1)}else for(let n in this._watchers)this.watchersClose(n,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,i]of t)this.watchPath(r,i.options,i.handler)}async watcherAdd(t,r){let{folderPath:i}=t;(this._watchers[i]=this._watchers[i]||[]).push(t);let a=new lRh(this,t,r);return await a.init(),a}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let a=r.indexOf(t);r.splice(a,1),r.length||delete this._watchers[t.folderPath]}let i=t.filePath||t.folderPath;this._roots.has(i)&&(this._watchersRestorable[i]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=Mp.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,i,n){if(this._watchers[t]?.find(c=>c.handler===i&&(!c.filePath||c.filePath===n)&&c.options.ignore===r.ignore&&!!c.options.native==!!r.native&&(!r.recursive||c.options.recursive)))return!0;let o=wvn.default.dirname(t);for(let c=1;c<1/0;c++){if(this._watchers[o]?.find(u=>(c===1||u.options.recursive&&c<=(u.options.depth??v$i))&&u.handler===i&&(!u.filePath||u.filePath===n)&&u.options.ignore===r.ignore&&!!u.options.native==!!r.native&&(!r.recursive||u.options.recursive&&g$i&&u.options.native!==!1)))return!0;if(!g$i)break;let s=wvn.default.dirname(t);if(o===s)break;o=s}return!1}async watchDirectories(t,r,i,n,a){if(this.isClosed())return;t=Mp.lang.uniq(t).sort();let o;for(let c of t)if(!this.isIgnored(c,r.ignore)&&!this.watcherExists(c,r,i,n))try{let d=!r.recursive||g$i&&r.native!==!1?r:{...r,recursive:!1},u={watcher:TAu.default.watch(c,d),handler:i,options:r,folderPath:c,filePath:n},f=o=await this.watcherAdd(u,a);if(this._roots.has(n||c)){let _={...r,ignoreInitial:!0,recursive:!1},h=wvn.default.dirname(c),y=c;await this.watchDirectories([h],_,i,y,f)}}catch(d){this.error(d)}return o}async watchDirectory(t,r,i,n,a){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||g$i&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,i,n,a));{r={...r,recursive:!0};let o=r.depth??v$i,c=r.limit??$Ka,[d]=await Mp.fs.readdir(t,r.ignore,o,c,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let s=await this.watchDirectories([t],r,i,n,a);if(d.length){let u=Mp.fs.getDepth(t);for(let f of d){let p=Mp.fs.getDepth(f),_=Math.max(0,o-(p-u)),h={...r,depth:_};await this.watchDirectories([f],h,i,n,a||s)}}})}}}async watchFileOnce(t,r,i){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let n={targetPath:t,options:r},a=(s,u)=>{u===t&&(d(),i())},o=new e(a),c=()=>{this._subwatchers.add(n),this.on(nH.CLOSE,d),o.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(n),this.removeListener(nH.CLOSE,d),o.close()};return c()}async watchFile(t,r,i){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let n=wvn.default.dirname(t);return this.watchDirectory(n,r,i,t)}async watchPollingOnce(t,r,i){if(this.isClosed())return;let n=!1,a=new sJc,o=await this.watchPolling(t,r,async()=>{n||!(await a.update(t,r.pollingTimeout)).length||n||(n=!0,o(),i())})}async watchPolling(t,r,i){if(this.isClosed())return Mp.lang.noop;if(this.pollerExists(t,r))return Mp.lang.noop;let n={...r,interval:r.pollingInterval??ZTh},a={targetPath:t,options:r},o=()=>{this._pollers.add(a),this.on(nH.CLOSE,c),TAu.default.watchFile(t,n,i)},c=()=>{this._pollers.delete(a),this.removeListener(nH.CLOSE,c),TAu.default.unwatchFile(t,i)};return Mp.lang.attempt(o),()=>Mp.lang.attempt(c)}async watchUnknownChild(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchFileOnce(t,r,n)}async watchUnknownTarget(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchPollingOnce(t,r,n)}async watchPaths(t,r,i){if(this.isClosed())return;if(t=Mp.lang.uniq(t).sort(),t.every((a,o)=>t.every((c,d)=>d===o||!Mp.fs.isSubPath(a,c))))await Promise.all(t.map(a=>this.watchPath(a,r,i)));else for(let a of t)await this.watchPath(a,r,i)}async watchPath(t,r,i){if(this.isClosed()||(t=wvn.default.resolve(t),this.isIgnored(t,r.ignore)))return;let n=await Mp.fs.poll(t,r.pollingTimeout);if(n){if(n.isFile())return this.watchFile(t,r,i);if(n.isDirectory())return this.watchDirectory(t,r,i);this.error(`"${t}" is not supported`)}else{let a=wvn.default.dirname(t);return(await Mp.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,i):this.watchUnknownTarget(t,r,i)}}async watch(t,r,i=Mp.lang.noop){if(Mp.lang.isFunction(t))return this.watch([],{},t);if(Mp.lang.isUndefined(t))return this.watch([],r,i);if(Mp.lang.isFunction(r))return this.watch(t,{},r);if(Mp.lang.isUndefined(r))return this.watch(t,{},i);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let n=Mp.lang.castArray(t);n.forEach(a=>this._roots.add(a)),await this.watchPaths(n,r,i),!this.isClosed()&&(i!==Mp.lang.noop&&this.on(nH.ALL,i),r.readdirMap=void 0,this.ready())}},RAu=cJc;bXo();var xua=require("fs/promises"),_Rh=require("os"),hRh=ce(require("path"),1),tgB=".fern",rgB="logs";function igB(){return"cli@3.37.5"}var tJa=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=It(Sr.of((0,_Rh.homedir)()),Xe.of(tgB)),r=It(t,Xe.of(rgB));await mi(r)||await(0,xua.mkdir)(r,{recursive:!0});let n=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=It(r,Xe.of(n));let a=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${hRh.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
1787
1787
  `);await(0,xua.writeFile)(this.logFilePath,a,"utf-8"),this.initialized=!0}getLogFilePath(){return this.logFilePath}async writeEntry(t){if(!this.initialized||!this.logFilePath)return;let r=JSON.stringify(t)+`
1788
1788
  `;try{await(0,xua.appendFile)(this.logFilePath,r,"utf-8")}catch{}}async logFrontendMetrics(t){let r={timestamp:t.timestamp,source:t.source,level:t.level,eventType:this.getEventType(t.payload,t.isAggregate),isAggregate:t.isAggregate,data:t.payload};await this.writeEntry(r)}async logCliMetric(t,r="info"){let i={timestamp:t.timestamp,source:igB(),level:r,eventType:t.type,data:{durationMs:t.durationMs,metadata:t.metadata}};await this.writeEntry(i)}async logCliMemory(){let t=process.memoryUsage(),r={type:"cli_memory",timestamp:new Date().toISOString(),metadata:{heapUsed:t.heapUsed,heapTotal:t.heapTotal,external:t.external,rss:t.rss,heapUsedMB:Math.round(t.heapUsed/1024/1024*100)/100,heapTotalMB:Math.round(t.heapTotal/1024/1024*100)/100,rssMB:Math.round(t.rss/1024/1024*100)/100}};await this.logCliMetric(r)}async logCliReloadStart(){let t={type:"cli_reload_start",timestamp:new Date().toISOString()};await this.logCliMetric(t)}async logCliReloadFinish(t,r){let i={type:"cli_reload_finish",timestamp:new Date().toISOString(),durationMs:t,metadata:r};await this.logCliMetric(i)}async logCliDocsGeneration(t,r){let i={type:"cli_docs_generation",timestamp:new Date().toISOString(),durationMs:t,metadata:r};await this.logCliMetric(i)}async logCliValidation(t,r){let i={type:"cli_validation",timestamp:new Date().toISOString(),durationMs:t,metadata:{success:r}};await this.logCliMetric(i)}getEventType(t,r){return r?"aggregate_summary":"type"in t&&typeof t.type=="string"?t.type:"unknown"}static isMetricsMessage(t){if(typeof t!="object"||t===null)return!1;let r=t;return r.type==="metrics"&&typeof r.timestamp=="string"&&typeof r.source=="string"}};var z$c=ce(vJc(),1),u4h=ce(Emu(),1),Z$=require("fs/promises"),s4h=require("os"),c4h=ce(Z9(),1),l4h=ce(a4h(),1),Wmu=process.platform==="win32",R$c=Ct.cyan("[docs]:"),PPB="etag",jPB=23,o4h=e=>e.padEnd(jPB," "),wPB="preview",EPB="app-preview",SPB="bundle",MPB=".next",DPB="standalone",BPB=".fern",IPB="packages/fern-docs/bundle/.next/server/instrumentation.js",CPB=".npmrc",qPB=".pnpmfile.cjs",TPB="pnpm-workspace.yaml",RPB='Cannot find matching keyid: {"signatures":';function zPB(){return It(Sr.of((0,s4h.homedir)()),Xe.of(BPB))}function csa({app:e=!1}){return It(zPB(),Xe.of(e?EPB:wPB))}function M$i({app:e=!1}){return It(csa({app:e}),Xe.of(e?MPB:SPB))}function wJa({app:e=!1}){return It(M$i({app:e}),Xe.of(DPB))}function NPB({app:e=!1}){return It(wJa({app:e}),Xe.of(IPB))}function FPB({app:e=!1}){return It(wJa({app:e}),Xe.of(TPB))}function QPB({app:e=!1}){return It(wJa({app:e}),Xe.of(qPB))}function UPB({app:e=!1}){return It(wJa({app:e}),Xe.of(CPB))}function Cvn(e){return new Error(`${e}. Please reach out to support@buildwithfern.com.`)}function LPB({app:e=!1}){return It(csa({app:e}),Xe.of(PPB))}var VPB=`module.exports = {
1789
1789
  hooks: {
@@ -1866,10 +1866,10 @@ More information: https://mdxjs.com/docs/troubleshooting-mdx`);return n.stack=""
1866
1866
  `),u++,i.push({severity:"warning",name:"Invalid OpenAPI example",message:h.trim(),relativeFilepath:d})}if(c.totalExamples>0){let p=`Validated ${c.totalExamples} examples: ${c.validExamples} valid, ${c.invalidExamples} invalid`;if(c.invalidExamples>0){t.warn(`${d}: ${p}`),t.debug(`Example validation details for ${d}:`);for(let _ of c.endpoints)_.hasInvalidExamples&&t.debug(` ${_.method.toUpperCase()} ${_.endpointPath}: ${_.results.length} examples, ${_.invalidExampleCount} invalid`)}else t.debug(`${d}: ${p}`)}}}catch(c){t.warn(`Could not validate examples in OpenAPI spec file: ${o.absoluteFilepath} - ${c}`);continue}}}return i}})};async function aEB({specPath:e,logger:t}){try{let r=await(0,a3h.readFile)(e,"utf-8"),i;try{i=JSON.parse(r)}catch{i=Di.load(r)}if(!i||typeof i!="object")return t.debug(`Invalid OpenAPI spec format: ${e}`),null;if(!i.openapi||!i.openapi.startsWith("3."))return t.debug(`Skipping non-OpenAPI v3 spec: ${e}`),null;let n=new $we({logger:t}),a=new nUi({namespace:void 0,generationLanguage:"typescript",logger:t,smartCasing:!1,spec:i,exampleGenerationArgs:{disabled:!1},errorCollector:n,enableUniqueErrorsPerEndpoint:!1,generateV1Examples:!1,settings:W3t()});return new _yn({context:a}).validateHumanExamples({spec:i})}catch(r){return t.warn(`Error validating examples in ${e}: ${r}`),null}}function oEB(e,t,r){let i=t.length,n=t+" ",a=r-i,o=r-n.length;if(e.length<=a)return t+e;let c=e.split(" "),d=[],s="";for(let u of c){let f=s==="",_=s+(f?"":" ")+u,h=d.length===0?a:o;if(_.length>h&&!f){let y=d.length===0?t:n;d.push(y+s),s=u}else s=_}if(s.length>0){let u=d.length===0?t:n;d.push(u+s)}return d.join(`
1867
1867
  `)}function uEB(e){let t=e.message||"",r=e.path||[];t.startsWith("Invalid response example: ")?t=t.substring(26):t.startsWith("Invalid request example: ")&&(t=t.substring(25));let i=r.length>0?r.join("."):"",n=r.length>0?r[r.length-1]:"value";if(t.includes("cannot be converted to string")&&t.includes("undefined"))return`Required property '${n}' is missing from example${i?` at path: ${i}`:""}`;if(t.includes("is not one of the allowed enum values")||t.includes("Invalid response example")){let a=t.match(/\[\s*([\s\S]*?)\s*\]/);if(a){let c=(a[1]??"").split(/[,\n]/).map(s=>s.trim().replace(/^"(.*)"$/,"$1")).filter(s=>s&&s!==""),d;return c.length>5?d=`[${c.slice(0,4).join(", ")}, ...]`:d=`[${c.join(", ")}]`,`Property '${n}' has an invalid enum value${i?` at path: ${i}`:""}. Allowed values are: ${d}`}return`Property '${n}' has an invalid enum value${i?` at path: ${i}`:""}. Please check the schema for allowed values.`}return t.includes("is not a number")?`Property '${n}' should be a number${i?` at path: ${i}`:""}`:t.includes("is not an integer")?`Property '${n}' should be an integer${i?` at path: ${i}`:""}`:t.includes("is not a string")?`Property '${n}' should be a string${i?` at path: ${i}`:""}`:t.includes("is not a boolean")?`Property '${n}' should be a boolean${i?` at path: ${i}`:""}`:t.includes("is not an object")?`Property '${n}' should be an object${i?` at path: ${i}`:""}`:t.includes("is not an array")?`Property '${n}' should be an array${i?` at path: ${i}`:""}`:t.includes("Additional properties are not allowed")||t.includes("additional property")||t.includes("not allowed")?`Found unexpected property '${(t.match(/additional property[s]? (.+?) (?:is|are) not allowed/i)||t.match(/property (.+?) is not allowed/i)||t.match(/Additional properties are not allowed: (.+)/i))?.[1]?.replace(/['"]/g,"")||n}' in example. This property does not exist in the schema${i?` at path: ${i}`:""}`:t.includes("Required properties are missing")?`Missing required properties in example${i?` at path: ${i}`:""}`:t.includes("does not match pattern")?`Property '${n}' does not match the required format/pattern${i?` at path: ${i}`:""}`:t.includes("unexpected")||t.includes("unknown")||t.includes("extra")?`Found unexpected property '${n}' in example. This property does not exist in the schema${i?` at path: ${i}`:""}`:t.includes("does not match schema")||t.includes("schema validation failed")?`Schema validation failed for property '${n}'${i?` at path: ${i}`:""}. Please check if this property exists in the schema and has the correct type`:t.toLowerCase().includes("enum")||t.toLowerCase().includes("allowed")?`Property '${n}' has an invalid value${i?` at path: ${i}`:""}. Please check the schema for allowed values. (Debug: ${t})`:`Property '${n}' validation error${i?` at path: ${i}`:""}. (Debug: ${t})`}var o3h=[aPu,JYc,XYc,KYc,YYc,sPu,FPu,NPu,$Yc,uPu,aYc,C$i,hPu,cPu,oYc,yPu];function u3h(e){if(!e)return o3h;let t=new Set(e);return o3h.filter(r=>!t.has(r.name))}async function gsa(e,t,r,i,n,a){let o=n?[C$i]:u3h(a);return sEB({workspace:e,rules:o,context:t,apiWorkspaces:r,ossWorkspaces:i})}async function sEB({workspace:e,rules:t,context:r,apiWorkspaces:i,ossWorkspaces:n}){let a=process.memoryUsage();r.logger.debug(`Starting docs validation with ${t.length} rules: ${t.map(h=>h.name).join(", ")}`),r.logger.debug(`Initial memory usage: RSS=${(a.rss/1024/1024).toFixed(2)}MB, Heap=${(a.heapUsed/1024/1024).toFixed(2)}MB`);let o=[],c=performance.now(),d=await Promise.all(t.map(h=>h.create({workspace:e,apiWorkspaces:i,ossWorkspaces:n,logger:r.logger}))),s=performance.now()-c;r.logger.debug(`Created ${t.length} rule visitors in ${s.toFixed(0)}ms`);let u=e3h({relativeFilepath:Xe.of(kj),allRuleVisitors:d,addViolations:h=>{o.push(...h)}}),f=performance.now();await T4h({contents:e.config,visitor:u,absoluteFilepathToConfiguration:It(e.absoluteFilePath,Xe.of(kj)),absolutePathToFernFolder:e.absoluteFilePath,context:r,apiWorkspaces:i});let p=performance.now()-f;r.logger.debug(`Completed AST traversal in ${p.toFixed(0)}ms`);let _=process.memoryUsage();return r.logger.debug(`Final memory usage: RSS=${(_.rss/1024/1024).toFixed(2)}MB, Heap=${(_.heapUsed/1024/1024).toFixed(2)}MB`),r.logger.debug(`Memory delta: RSS=${((_.rss-a.rss)/1024/1024).toFixed(2)}MB, Heap=${((_.heapUsed-a.heapUsed)/1024/1024).toFixed(2)}MB`),o}function Osa({context:e,violations:t,logWarnings:r,logSummary:i=!0,logBreadcrumbs:n=!0,elapsedMillis:a=0}){let o=[],c={};for(let u of t){let f=JSON.stringify(u.nodePath),p=c[f]??[];p.some(h=>h.message===u.message&&h.nodePath.length===u.nodePath.length&&h.nodePath.every((y,b)=>dbe(y,u.nodePath[b]))&&h.relativeFilepath===u.relativeFilepath&&h.severity===u.severity)||(o.push(u),c[f]=[...p,u])}t=o;let d=hEB(t),s=cEB(t);for(let u of Array.from(s.keys()).sort()){let f=s.get(u);if(f){let p=f.violations[0]?.relativeFilepath??"";lEB({logWarnings:r,logBreadcrumbs:n,configRelativeFilepath:p,nodePath:f.nodePath,violations:f.violations,context:e})}}return i&&_EB({context:e,stats:d,logWarnings:r,elapsedMillis:a}),{hasErrors:d.numFatal>0}}function cEB(e){let t={};for(let r of e){let n=r.nodePath.length===0?`file:${r.relativeFilepath}`:`node:${JSON.stringify(r.nodePath)}`;t[n]||(t[n]={nodePath:r.nodePath,violations:[]}),t[n].violations.push(r)}return new Map(Object.entries(t))}function lEB({logWarnings:e,logBreadcrumbs:t,configRelativeFilepath:r,nodePath:i,violations:n,context:a}){let o=fEB(n);if(o==="warning"&&!e)return;let c="",d=n.map(s=>s.severity==="warning"&&!e?null:(c===""&&(c=s.relativeFilepath),`${pEB(s.severity)} ${s.message}`)).filter(s=>s!=null).join(`
1868
1868
  `);a.logger.log(dEB(o),OEe({breadcrumbs:t?[r,...i.map(s=>{let u=typeof s=="string"?s:s.key;return typeof s!="string"&&s.arrayIndex!=null&&(u+=`[${s.arrayIndex}]`),u})]:[],title:c,subtitle:d})+`
1869
- `)}function fEB(e){return e.some(t=>t.severity==="fatal")?"fatal":e.some(t=>t.severity==="error")?"error":"warning"}function dEB(e){switch(e){case"fatal":return oc.Error;case"error":return oc.Error;case"warning":return oc.Warn;default:vt(e)}}function pEB(e){switch(e){case"fatal":return Ct.red("[error]");case"error":return Ct.red("[error]");case"warning":return Ct.yellow("[warning]");default:vt(e)}}function _EB({stats:e,context:t,logWarnings:r,elapsedMillis:i=0}){let{numFatal:n,numErrors:a,numWarnings:o}=e,c=i>0?` in ${(i/1e3).toFixed(3)} seconds.`:".",d=`Found ${n+a} errors and ${o} warnings`+c;!r&&o>0&&(d+=" Run fern check --warnings to print out the warnings not shown."),n+a>0?t.logger.error(d):o>0?t.logger.warn(d):t.logger.info(Ct.green("\u2713 All checks passed"))}function hEB(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:vt(n.severity)}return{numFatal:t,numErrors:r,numWarnings:i}}async function s3h({workspace:e,apiWorkspaces:t,ossWorkspaces:r,context:i,errorOnBrokenLinks:n,excludeRules:a}){e.config.settings?.substituteEnvVars&&(e.config=MT(e.config,{onError:u=>i.failAndThrow(u)}));let o=performance.now(),c=await gsa(e,i,t,r,!1,a),d=performance.now()-o,s=c.some(u=>u.severity==="fatal"||u.severity==="error");return n&&(s=s||c.some(u=>u.name==="valid-markdown-links")),{violations:c,elapsedMillis:d,hasErrors:s}}async function Asa({workspace:e,apiWorkspaces:t,ossWorkspaces:r,context:i,logWarnings:n,errorOnBrokenLinks:a,logSummary:o=!0,excludeRules:c}){e.config.settings?.substituteEnvVars&&(e.config=MT(e.config,{onError:p=>i.failAndThrow(p)}));let d=performance.now(),s=await gsa(e,i,t,r,!1,c),u=performance.now()-d,{hasErrors:f}=Osa({violations:s,context:i,logWarnings:n,logSummary:o,logBreadcrumbs:!1,elapsedMillis:u});return a&&(f=f||s.some(p=>p.name==="valid-markdown-links")),{hasErrors:f}}async function c3h({workspace:e,apiWorkspaces:t,ossWorkspaces:r,context:i,logWarnings:n,errorOnBrokenLinks:a,excludeRules:o}){let{hasErrors:c}=await Asa({workspace:e,context:i,logWarnings:n,apiWorkspaces:t,ossWorkspaces:r,errorOnBrokenLinks:a,excludeRules:o});c&&i.failAndThrow()}async function l3h({loadProject:e,cliContext:t,port:r,bundlePath:i,brokenLinks:n,legacyPreview:a,backendPort:o,forceDownload:c}){let d=await e(),s=d.docsWorkspaces;s!=null&&(a&&(await t.instrumentPostHogEvent({orgId:d.config.organization,command:"fern docs dev --legacy"}),await t.runTaskForWorkspace(s,async u=>{u.logger.info(`Starting server on port ${r}`),await eYc({initialProject:d,reloadProject:e,validateProject:async f=>{let p=f.docsWorkspaces;if(p==null)return;let _=n?[]:["valid-markdown-links"],h=p.config.experimental?.openapiParserV3;h==null||h?await Asa({workspace:p,context:u,logWarnings:!0,logSummary:!1,apiWorkspaces:[],ossWorkspaces:await rL(f),excludeRules:_}):await Asa({workspace:p,context:u,logWarnings:!0,logSummary:!1,apiWorkspaces:f.apiWorkspaces,ossWorkspaces:await rL(f),excludeRules:_})},context:u,port:r,bundlePath:i})})),await t.instrumentPostHogEvent({orgId:d.config.organization,command:"fern docs dev --beta"}),await t.runTaskForWorkspace(s,async u=>{u.logger.info("Bootstrapping docs preview (this may take a few seconds)..."),await Z$c({initialProject:d,reloadProject:e,validateProject:async f=>{let p=f.docsWorkspaces;if(p==null)return;let _=n?[]:["valid-markdown-links"],h=p.config.experimental?.openapiParserV3;h==null||h?await Asa({workspace:p,context:u,logWarnings:!0,logSummary:!1,apiWorkspaces:[],ossWorkspaces:await rL(f),excludeRules:_}):await Asa({workspace:p,context:u,logWarnings:!0,logSummary:!1,apiWorkspaces:f.apiWorkspaces,ossWorkspaces:await rL(f),excludeRules:_})},context:u,port:r,bundlePath:i,backendPort:o,forceDownload:c})}))}var yEB=/^[a-z0-9-]+-preview-[a-z0-9]+\.docs\.buildwithfern\.com$/i;function bEB(e){let t=e.toLowerCase().trim();t.startsWith("https://")?t=t.slice(8):t.startsWith("http://")&&(t=t.slice(7));let r=t.indexOf("/");return r!==-1&&(t=t.slice(0,r)),yEB.test(t)}async function f3h({cliContext:e,previewUrl:t}){if(!bEB(t)){e.failAndThrow(`Invalid preview URL: ${t}
1869
+ `)}function fEB(e){return e.some(t=>t.severity==="fatal")?"fatal":e.some(t=>t.severity==="error")?"error":"warning"}function dEB(e){switch(e){case"fatal":return oc.Error;case"error":return oc.Error;case"warning":return oc.Warn;default:vt(e)}}function pEB(e){switch(e){case"fatal":return Ct.red("[error]");case"error":return Ct.red("[error]");case"warning":return Ct.yellow("[warning]");default:vt(e)}}function _EB({stats:e,context:t,logWarnings:r,elapsedMillis:i=0}){let{numFatal:n,numErrors:a,numWarnings:o}=e,c=i>0?` in ${(i/1e3).toFixed(3)} seconds.`:".",d=`Found ${n+a} errors and ${o} warnings`+c;!r&&o>0&&(d+=" Run fern check --warnings to print out the warnings not shown."),n+a>0?t.logger.error(d):o>0?t.logger.warn(d):t.logger.info(Ct.green("\u2713 All checks passed"))}function hEB(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:vt(n.severity)}return{numFatal:t,numErrors:r,numWarnings:i}}async function s3h({workspace:e,apiWorkspaces:t,ossWorkspaces:r,context:i,errorOnBrokenLinks:n,excludeRules:a}){e.config.settings?.substituteEnvVars&&(e.config=MT(e.config,{onError:u=>i.failAndThrow(u)}));let o=performance.now(),c=await gsa(e,i,t,r,!1,a),d=performance.now()-o,s=c.some(u=>u.severity==="fatal"||u.severity==="error");return n&&(s=s||c.some(u=>u.name==="valid-markdown-links")),{violations:c,elapsedMillis:d,hasErrors:s}}async function Asa({workspace:e,apiWorkspaces:t,ossWorkspaces:r,context:i,logWarnings:n,errorOnBrokenLinks:a,logSummary:o=!0,excludeRules:c}){e.config.settings?.substituteEnvVars&&(e.config=MT(e.config,{onError:p=>i.failAndThrow(p)}));let d=performance.now(),s=await gsa(e,i,t,r,!1,c),u=performance.now()-d,{hasErrors:f}=Osa({violations:s,context:i,logWarnings:n,logSummary:o,logBreadcrumbs:!1,elapsedMillis:u});return a&&(f=f||s.some(p=>p.name==="valid-markdown-links")),{hasErrors:f}}async function c3h({workspace:e,apiWorkspaces:t,ossWorkspaces:r,context:i,logWarnings:n,errorOnBrokenLinks:a,excludeRules:o}){let{hasErrors:c}=await Asa({workspace:e,context:i,logWarnings:n,apiWorkspaces:t,ossWorkspaces:r,errorOnBrokenLinks:a,excludeRules:o});c&&i.failAndThrow()}async function l3h({loadProject:e,cliContext:t,port:r,bundlePath:i,brokenLinks:n,legacyPreview:a,backendPort:o,forceDownload:c}){let d=await e(),s=d.docsWorkspaces;s!=null&&(a&&(await t.instrumentPostHogEvent({orgId:d.config.organization,command:"fern docs dev --legacy"}),await t.runTaskForWorkspace(s,async u=>{u.logger.info(`Starting server on port ${r}`),await eYc({initialProject:d,reloadProject:e,validateProject:async f=>{let p=f.docsWorkspaces;if(p==null)return;let _=n?[]:["valid-markdown-links"],h=p.config.experimental?.openapiParserV3;h==null||h?await Asa({workspace:p,context:u,logWarnings:!0,logSummary:!1,apiWorkspaces:[],ossWorkspaces:await rL(f),excludeRules:_}):await Asa({workspace:p,context:u,logWarnings:!0,logSummary:!1,apiWorkspaces:f.apiWorkspaces,ossWorkspaces:await rL(f),excludeRules:_})},context:u,port:r,bundlePath:i})})),await t.instrumentPostHogEvent({orgId:d.config.organization,command:"fern docs dev --beta"}),await t.runTaskForWorkspace(s,async u=>{u.logger.info("Bootstrapping docs preview (this may take a few seconds)..."),await Z$c({initialProject:d,reloadProject:e,validateProject:async f=>{let p=f.docsWorkspaces;if(p==null)return;let _=n?[]:["valid-markdown-links"],h=p.config.experimental?.openapiParserV3;h==null||h?await Asa({workspace:p,context:u,logWarnings:!0,logSummary:!1,apiWorkspaces:[],ossWorkspaces:await rL(f),excludeRules:_}):await Asa({workspace:p,context:u,logWarnings:!0,logSummary:!1,apiWorkspaces:f.apiWorkspaces,ossWorkspaces:await rL(f),excludeRules:_})},context:u,port:r,bundlePath:i,backendPort:o,forceDownload:c})}))}var yEB=/^[a-z0-9-]+-preview-[a-z0-9-]+\.docs\.buildwithfern\.com$/i;function bEB(e){let t=e.toLowerCase().trim();t.startsWith("https://")?t=t.slice(8):t.startsWith("http://")&&(t=t.slice(7));let r=t.indexOf("/");return r!==-1&&(t=t.slice(0,r)),yEB.test(t)}async function f3h({cliContext:e,previewUrl:t}){if(!bEB(t)){e.failAndThrow(`Invalid preview URL: ${t}
1870
1870
  Only preview sites can be deleted with this command.
1871
1871
  Preview URLs follow the pattern: {org}-preview-{hash}.docs.buildwithfern.com
1872
- Example: acme-preview-abc123.docs.buildwithfern.com`);return}let r=await e.runTask(async i=>g8(i));if(r==null){e.failAndThrow("Failed to authenticate. Please run 'fern login' first.");return}await e.runTask(async i=>{i.logger.info(`Deleting preview site: ${t}`);let a=await TVt({token:r.value}).docs.v2.write.deleteDocsSite({url:t});if(a.ok)i.logger.info(Ct.green(`Successfully deleted preview site: ${t}`));else switch(a.error.error){case"UnauthorizedError":return i.failAndThrow("You do not have permissions to delete this preview site. Reach out to support@buildwithfern.com");case"DocsNotFoundError":return i.failAndThrow(`Preview site not found: ${t}`);default:return i.failAndThrow(`Failed to delete preview site: ${t}`,a.error)}})}async function d3h({cliContext:e,limit:t,page:r}){let i=await e.runTask(async n=>g8(n));if(i==null){e.failAndThrow("Failed to authenticate. Please run 'fern login' first.");return}await e.runTask(async n=>{n.logger.info("Fetching preview deployments...");let o=await TVt({token:i.value}).docs.v2.read.listAllDocsUrls({page:r,limit:t??100});if(!o.ok)return n.failAndThrow("Failed to fetch docs URLs",o.error);let c=/-preview-[a-f0-9]+\.docs\.buildwithfern\.com$/,d=o.body.urls.filter(s=>c.test(s.domain)).map(s=>({url:s.basePath!=null?`${s.domain}${s.basePath}`:s.domain,organizationId:s.organizationId,updatedAt:s.updatedAt}));if(d.length===0){n.logger.info("No preview deployments found.");return}n.logger.info(Ct.bold(`
1872
+ Example: acme-preview-abc123.docs.buildwithfern.com`);return}let r=await e.runTask(async i=>g8(i));if(r==null){e.failAndThrow("Failed to authenticate. Please run 'fern login' first.");return}await e.runTask(async i=>{i.logger.info(`Deleting preview site: ${t}`);let a=await TVt({token:r.value}).docs.v2.write.deleteDocsSite({url:t});if(a.ok)i.logger.info(Ct.green(`Successfully deleted preview site: ${t}`));else switch(a.error.error){case"UnauthorizedError":return i.failAndThrow("You do not have permissions to delete this preview site. Reach out to support@buildwithfern.com");case"DocsNotFoundError":return i.failAndThrow(`Preview site not found: ${t}`);default:return i.failAndThrow(`Failed to delete preview site: ${t}`,a.error)}})}async function d3h({cliContext:e,limit:t,page:r}){let i=await e.runTask(async n=>g8(n));if(i==null){e.failAndThrow("Failed to authenticate. Please run 'fern login' first.");return}await e.runTask(async n=>{n.logger.info("Fetching preview deployments...");let o=await TVt({token:i.value}).docs.v2.read.listAllDocsUrls({page:r,limit:t??100});if(!o.ok)return n.failAndThrow("Failed to fetch docs URLs",o.error);let c=/-preview-[a-f0-9-]+\.docs\.buildwithfern\.com$/,d=o.body.urls.filter(s=>c.test(s.domain)).map(s=>({url:s.basePath!=null?`${s.domain}${s.basePath}`:s.domain,organizationId:s.organizationId,updatedAt:s.updatedAt}));if(d.length===0){n.logger.info("No preview deployments found.");return}n.logger.info(Ct.bold(`
1873
1873
  Found ${d.length} preview deployment(s):
1874
1874
  `));for(let s of d){let u=new Date(s.updatedAt).toLocaleString();n.logger.info(` ${Ct.cyan(s.url)}`),n.logger.info(` Organization: ${s.organizationId}`),n.logger.info(` Updated: ${u}
1875
1875
  `)}})}var j3h=require("fs/promises");var v3h=Symbol.for("immer-nothing"),p3h=Symbol.for("immer-draftable"),$ve=Symbol.for("immer-state"),vEB=process.env.NODE_ENV!=="production"?[function(e){return`The plugin for '${e}' has not been loaded into Immer. To enable the plugin, import and call \`enable${e}()\` when initializing your application.`},function(e){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${e}'`},"This object has been frozen and should not be mutated",function(e){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+e},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(e){return`'current' expects a draft, got: ${e}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(e){return`'original' expects a draft, got: ${e}`}]:[];function eY(e,...t){if(process.env.NODE_ENV!=="production"){let r=vEB[e],i=typeof r=="function"?r.apply(null,t):r;throw new Error(`[Immer] ${i}`)}throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var msa=Object.getPrototypeOf;function Psa(e){return!!e&&!!e[$ve]}function Qvn(e){return e?g3h(e)||Array.isArray(e)||!!e[p3h]||!!e.constructor?.[p3h]||QJa(e)||GPu(e):!1}var gEB=Object.prototype.constructor.toString();function g3h(e){if(!e||typeof e!="object")return!1;let t=msa(e);if(t===null)return!0;let r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object?!0:typeof r=="function"&&Function.toString.call(r)===gEB}function UPu(e,t){WPu(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,i)=>t(i,r,e))}function WPu(e){let t=e[$ve];return t?t.type_:Array.isArray(e)?1:QJa(e)?2:GPu(e)?3:0}function eXc(e,t){return WPu(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function O3h(e,t,r){let i=WPu(e);i===2?e.set(t,r):i===3?e.add(r):e[t]=r}function OEB(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function QJa(e){return e instanceof Map}function GPu(e){return e instanceof Set}function Fvn(e){return e.copy_||e.base_}function tXc(e,t){if(QJa(e))return new Map(e);if(GPu(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=g3h(e);if(t===!0||t==="class_only"&&!r){let i=Object.getOwnPropertyDescriptors(e);delete i[$ve];let n=Reflect.ownKeys(i);for(let a=0;a<n.length;a++){let o=n[a],c=i[o];c.writable===!1&&(c.writable=!0,c.configurable=!0),(c.get||c.set)&&(i[o]={configurable:!0,writable:!0,enumerable:c.enumerable,value:e[o]})}return Object.create(msa(e),i)}else{let i=msa(e);if(i!==null&&r)return{...e};let n=Object.create(i);return Object.assign(n,e)}}function oXc(e,t=!1){return HPu(e)||Psa(e)||!Qvn(e)||(WPu(e)>1&&Object.defineProperties(e,{set:{value:QPu},add:{value:QPu},clear:{value:QPu},delete:{value:QPu}}),Object.freeze(e),t&&Object.values(e).forEach(r=>oXc(r,!0))),e}function QPu(){eY(2)}function HPu(e){return Object.isFrozen(e)}var AEB={};function Uvn(e){let t=AEB[e];return t||eY(0,e),t}var NJa;function A3h(){return NJa}function mEB(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function _3h(e,t){t&&(Uvn("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function rXc(e){iXc(e),e.drafts_.forEach(PEB),e.drafts_=null}function iXc(e){e===NJa&&(NJa=e.parent_)}function h3h(e){return NJa=mEB(NJa,e)}function PEB(e){let t=e[$ve];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function y3h(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[$ve].modified_&&(rXc(t),eY(4)),Qvn(e)&&(e=LPu(t,e),t.parent_||VPu(t,e)),t.patches_&&Uvn("Patches").generateReplacementPatches_(r[$ve].base_,e,t.patches_,t.inversePatches_)):e=LPu(t,r,[]),rXc(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==v3h?e:void 0}function LPu(e,t,r){if(HPu(t))return t;let i=t[$ve];if(!i)return UPu(t,(n,a)=>b3h(e,i,t,n,a,r)),t;if(i.scope_!==e)return t;if(!i.modified_)return VPu(e,i.base_,!0),i.base_;if(!i.finalized_){i.finalized_=!0,i.scope_.unfinalizedDrafts_--;let n=i.copy_,a=n,o=!1;i.type_===3&&(a=new Set(n),n.clear(),o=!0),UPu(a,(c,d)=>b3h(e,i,n,c,d,r,o)),VPu(e,n,!1),r&&e.patches_&&Uvn("Patches").generatePatches_(i,r,e.patches_,e.inversePatches_)}return i.copy_}function b3h(e,t,r,i,n,a,o){if(process.env.NODE_ENV!=="production"&&n===r&&eY(5),Psa(n)){let c=a&&t&&t.type_!==3&&!eXc(t.assigned_,i)?a.concat(i):void 0,d=LPu(e,n,c);if(O3h(r,i,d),Psa(d))e.canAutoFreeze_=!1;else return}else o&&r.add(n);if(Qvn(n)&&!HPu(n)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;LPu(e,n),(!t||!t.scope_.parent_)&&typeof i!="symbol"&&(QJa(r)?r.has(i):Object.prototype.propertyIsEnumerable.call(r,i))&&VPu(e,n)}}function VPu(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&oXc(t,r)}function jEB(e,t){let r=Array.isArray(e),i={type_:r?1:0,scope_:t?t.scope_:A3h(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},n=i,a=uXc;r&&(n=[i],a=FJa);let{revoke:o,proxy:c}=Proxy.revocable(n,a);return i.draft_=c,i.revoke_=o,c}var uXc={get(e,t){if(t===$ve)return e;let r=Fvn(e);if(!eXc(r,t))return wEB(e,r,t);let i=r[t];return e.finalized_||!Qvn(i)?i:i===ZYc(e.base_,t)?(kYc(e),e.copy_[t]=aXc(i,e)):i},has(e,t){return t in Fvn(e)},ownKeys(e){return Reflect.ownKeys(Fvn(e))},set(e,t,r){let i=m3h(Fvn(e),t);if(i?.set)return i.set.call(e.draft_,r),!0;if(!e.modified_){let n=ZYc(Fvn(e),t),a=n?.[$ve];if(a&&a.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(OEB(r,n)&&(r!==void 0||eXc(e.base_,t)))return!0;kYc(e),nXc(e)}return e.copy_[t]===r&&(r!==void 0||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty(e,t){return ZYc(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,kYc(e),nXc(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=Fvn(e),i=Reflect.getOwnPropertyDescriptor(r,t);return i&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:i.enumerable,value:r[t]}},defineProperty(){eY(11)},getPrototypeOf(e){return msa(e.base_)},setPrototypeOf(){eY(12)}},FJa={};UPu(uXc,(e,t)=>{FJa[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});FJa.deleteProperty=function(e,t){return process.env.NODE_ENV!=="production"&&isNaN(parseInt(t))&&eY(13),FJa.set.call(this,e,t,void 0)};FJa.set=function(e,t,r){return process.env.NODE_ENV!=="production"&&t!=="length"&&isNaN(parseInt(t))&&eY(14),uXc.set.call(this,e[0],t,r,e[0])};function ZYc(e,t){let r=e[$ve];return(r?Fvn(r):e)[t]}function wEB(e,t,r){let i=m3h(t,r);return i?"value"in i?i.value:i.get?.call(e.draft_):void 0}function m3h(e,t){if(!(t in e))return;let r=msa(e);for(;r;){let i=Object.getOwnPropertyDescriptor(r,t);if(i)return i;r=msa(r)}}function nXc(e){e.modified_||(e.modified_=!0,e.parent_&&nXc(e.parent_))}function kYc(e){e.copy_||(e.copy_=tXc(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var EEB=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,r,i)=>{if(typeof t=="function"&&typeof r!="function"){let a=r;r=t;let o=this;return function(d=a,...s){return o.produce(d,u=>r.call(this,u,...s))}}typeof r!="function"&&eY(6),i!==void 0&&typeof i!="function"&&eY(7);let n;if(Qvn(t)){let a=h3h(this),o=aXc(t,void 0),c=!0;try{n=r(o),c=!1}finally{c?rXc(a):iXc(a)}return _3h(a,i),y3h(n,a)}else if(!t||typeof t!="object"){if(n=r(t),n===void 0&&(n=t),n===v3h&&(n=void 0),this.autoFreeze_&&oXc(n,!0),i){let a=[],o=[];Uvn("Patches").generateReplacementPatches_(t,n,a,o),i(a,o)}return n}else eY(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(o,...c)=>this.produceWithPatches(o,d=>t(d,...c));let i,n;return[this.produce(t,r,(o,c)=>{i=o,n=c}),i,n]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Qvn(e)||eY(8),Psa(e)&&(e=SEB(e));let t=h3h(this),r=aXc(e,void 0);return r[$ve].isManual_=!0,iXc(t),r}finishDraft(e,t){let r=e&&e[$ve];(!r||!r.isManual_)&&eY(9);let{scope_:i}=r;return _3h(i,t),y3h(void 0,i)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){let n=t[r];if(n.path.length===0&&n.op==="replace"){e=n.value;break}}r>-1&&(t=t.slice(r+1));let i=Uvn("Patches").applyPatches_;return Psa(e)?i(e,t):this.produce(e,n=>i(n,t))}};function aXc(e,t){let r=QJa(e)?Uvn("MapSet").proxyMap_(e,t):GPu(e)?Uvn("MapSet").proxySet_(e,t):jEB(e,t);return(t?t.scope_:A3h()).drafts_.push(r),r}function SEB(e){return Psa(e)||eY(10,e),P3h(e)}function P3h(e){if(!Qvn(e)||HPu(e))return e;let t=e[$ve],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=tXc(e,t.scope_.immer_.useStrictShallowCopy_)}else r=tXc(e,!0);return UPu(r,(i,n)=>{O3h(r,i,P3h(n))}),t&&(t.finalized_=!1),r}var MEB=new EEB,xPu=MEB.produce;function DEB(e){return e.endsWith(`