fern-api 3.47.4 → 3.47.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/cli.cjs +5 -5
  2. package/package.json +1 -1
package/cli.cjs CHANGED
@@ -1261,7 +1261,7 @@ ${G6_.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&uRc(th
1261
1261
  `+Hhn.default.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?Hhn.default.cyan(k6_(t,this.opt.mask)):Hhn.default.italic(Hhn.default.dim("[hidden]")):this.opt.mask?k6_(t,this.opt.mask):Hhn.default.italic(Hhn.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 MXo=ue(PR(),1);var k9_=ue(VRc(),1),EXo=require("child_process"),Nta=require("fs"),wXo=ue(require("path"),1),eG_=ue(require("os"),1),tG_=require("crypto"),Ezc=ue(X9_(),1);var AXo=class extends Error{originalError;constructor(t){super(`Failed to create temporary file. ${t.message}`),this.originalError=t}};var _Ga=class extends Error{originalError;constructor(t){super(`Failed to launch editor. ${t.message}`),this.originalError=t}};var PXo=class extends Error{originalError;constructor(t){super(`Failed to read temporary file. ${t.message}`),this.originalError=t}};var jXo=class extends Error{originalError;constructor(t){super(`Failed to remove temporary file. ${t.message}`),this.originalError=t}};function SXo(e="",t,r){let i=new Szc(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 Z9_(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}function zdD(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 Szc=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=zdD(t).map(n=>n.replace("\\ "," ")),i=r.shift();this.editor={args:r,bin:i}}createTemporaryFile(){try{let t=this.fileOptions.dir??eG_.default.tmpdir(),r=(0,tG_.randomUUID)(),i=Z9_(this.fileOptions.prefix),n=Z9_(this.fileOptions.postfix),a=`${i}${r}${n}`,o=wXo.default.resolve(t,a),c=wXo.default.resolve(t)+wXo.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,Nta.writeFileSync)(this.tempFile,this.text,d)}catch(t){throw new AXo(t)}}readTemporaryFile(){try{let t=(0,Nta.readFileSync)(this.tempFile);if(t.length===0)this.text="";else{let r=(0,k9_.detect)(t)??"utf8";Ezc.default.encodingExists(r)||(r="utf8"),this.text=Ezc.default.decode(t,r)}}catch(t){throw new PXo(t)}}removeTemporaryFile(){try{(0,Nta.unlinkSync)(this.tempFile)}catch(t){throw new jXo(t)}}launchEditor(){try{let t=(0,EXo.spawnSync)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"});this.lastExitStatus=t.status??0}catch(t){throw new _Ga(t)}}launchEditorAsync(t){try{(0,EXo.spawn)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"}).on("exit",i=>{this.lastExitStatus=i,setImmediate(t)})}catch(r){throw new _Ga(r)}}};var rG_=ue(Cve(),1);var hGa=class extends jR{_run(t){this.done=t,this.editorResult=new rG_.Subject;let r=aL(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"?MXo.default.dim("Received"):MXo.default.dim("Press <enter> to launch your preferred editor."),t&&(r=MXo.default.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),SXo(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 uG_=require("stream");var aG_=ue(require("readline"),1),oG_=ue(nG_(),1),Yhn=class{constructor(t){this.rl||=aG_.default.createInterface(FdD(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 FdD(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 oG_.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var yGa=class extends Yhn{constructor(t={}){super(t),this.log=new uG_.Writable({write:(r,i,n)=>{this.writeLog(r),n()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return k9a(this.rl,this.bottomBar.split(`
1262
1262
  `).length),this}updateBottomBar(t){return k9a(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+`
1263
1263
  `}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&&YYo(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var sm=ue(Cve(),1),lG_=ue(B9a(),1);var DXo=ue(Cve(),1),sG_=ue(B9a(),1),BXo=function(e,t,r){return typeof e[t]!="function"?(0,DXo.of)(e):(0,DXo.from)((0,sG_.default)(e[t])(r).then(i=>(e[t]=i,e)))};var cG_={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}},Fta=class extends Yhn{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,sm.from)(t):(0,sm.isObservable)(t)?i=t:Object.values(t).every(n=>typeof n=="object"&&!Array.isArray(n)&&n!=null)?i=(0,sm.from)(Object.entries(t).map(([n,a])=>({name:n,...a}))):i=(0,sm.from)([t]),this.process=i.pipe((0,sm.concatMap)(this.processQuestion.bind(this)),(0,sm.publish)()),this.process.connect(),this.process.pipe((0,sm.reduce)((n,a)=>(cG_.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,sm.defer)(()=>(0,sm.of)(t).pipe((0,sm.concatMap)(this.setDefaultType.bind(this)),(0,sm.concatMap)(this.filterIfRunnable.bind(this)),(0,sm.concatMap)(()=>BXo(t,"message",this.answers)),(0,sm.concatMap)(()=>BXo(t,"default",this.answers)),(0,sm.concatMap)(()=>BXo(t,"choices",this.answers)),(0,sm.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,sm.defer)(()=>(0,sm.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,sm.defer)(()=>(0,sm.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&cG_.get(this.answers,t.name)!==void 0)return sm.EMPTY;if(t.when===!1)return sm.EMPTY;if(typeof t.when!="function")return(0,sm.of)(t);let{answers:r}=this;return(0,sm.defer)(()=>(0,sm.from)((0,lG_.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,sm.filter)(i=>i!=null)))}};function fG_(e){let t=function(r,i){let n;try{n=new Fta(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",tGa),this.registerPrompt("input",xhn),this.registerPrompt("number",rGa),this.registerPrompt("confirm",iGa),this.registerPrompt("rawlist",nGa),this.registerPrompt("expand",aGa),this.registerPrompt("checkbox",oGa),this.registerPrompt("password",uGa),this.registerPrompt("editor",hGa)},t.restoreDefaultPrompts(),t}var Dzc=fG_();function UdD(e,t){Dzc.registerPrompt(e,t)}function LdD(){Dzc.restoreDefaultPrompts()}var VdD={prompt:Dzc,ui:{BottomBar:yGa,Prompt:Fta},createPromptModule:fG_,registerPrompt:UdD,restoreDefaultPrompts:LdD,Separator:F$},IXo=VdD;var Qta=require("path");function pG_(){let e=WdD();return async t=>{for(let r of t)r.module=e(r.filename);return t}}function WdD(e=process.argv[1]?(0,Qta.dirname)(process.argv[1]):process.cwd(),t=Qta.sep==="\\"){let r=t?dG_(e):e;return i=>{if(!i)return;let n=t?dG_(i):i,{dir:a,base:o,ext:c}=Qta.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 dG_(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var Bzc=e=>{if("flags"in e){let t=_G_(e.flags),r=hG_(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([n,a])=>[n,yG_(a)])),i=Object.fromEntries(Object.entries(t).map(([n,a])=>[n,GdD(n,a,r[n])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}};function GdD(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 _G_=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,Xhn(r)]).filter(([,t])=>t!==void 0)),hG_=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?yG_(i):void 0]}))};var Xhn=e=>e===void 0?void 0:e.variant??e.enabled,yG_=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var CXo="0123456789abcdef",qXo=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+=CXo.charAt(this.bytes[r]>>>4),t+=CXo.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+=CXo.charAt(this.bytes[r]>>>4),t+=CXo.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}},Izc=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??xdD()}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 qXo.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,qXo.ofInner(t)}},xdD=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),bG_,T$t=()=>HdD().toString(),HdD=()=>(bG_||(bG_=new Izc)).generate();var KdD=["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"],vG_=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return KdD.concat(t).some(i=>{let n=i.toLowerCase();return r.indexOf(n)!==-1})};var U$=(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 $dD=Array.isArray,gG_=Object.prototype,XL9=gG_.hasOwnProperty,Czc=gG_.toString,OG_=$dD||function(e){return Czc.call(e)==="[object Array]"};var Uta=e=>e===void 0,bGa=e=>Czc.call(e)=="[object String]",mG_=e=>bGa(e)&&e.trim().length===0;var AG_=e=>Czc.call(e)=="[object Number]";var qzc=e=>e instanceof Error;function YdD(e,t){try{return e instanceof t}catch{return!1}}function vGa(e){return e===null||typeof e!="object"}function Zhn(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function PG_(e){return Zhn(e,"ErrorEvent")}function TXo(e){return!Uta(Event)&&YdD(e,Event)}function jG_(e){return Zhn(e,"Object")}function gGa(e,t,r,i,n){return t>r&&(i.warn("min cannot be greater than max."),t=r),AG_(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),gGa(n||r,t,r,i))}var XdD=864e5,RXo=class{constructor(t){this._buckets={},this._onBucketRateLimited=t._onBucketRateLimited,this._bucketSize=gGa(t.bucketSize,0,100,t._logger),this._refillRate=gGa(t.refillRate,0,this._bucketSize,t._logger),this._refillInterval=gGa(t.refillInterval,0,XdD,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 zXo=class{add(t){let r=T$t();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 ZdD(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var wG_=(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=>wG_(`${e} ${a}`,t,r)}},kdD=e=>e();function EG_(e,t=kdD){return wG_(e,t,ZdD())}var Vta="Mobile",FXo="iOS",Lta="Android",SG_="Tablet",cV9=Lta+" "+SG_;var epD="Apple",lV9=epD+" Watch",MG_="Safari",QXo="BlackBerry",DG_="Samsung",tpD=DG_+"Browser",rpD=DG_+" Internet",UXo="Chrome",ipD=UXo+" OS",npD=UXo+" "+FXo,BG_="Internet Explorer",apD=BG_+" "+Vta,Rzc="Opera",fV9=Rzc+" Mini",IG_="Edge",opD="Microsoft "+IG_,zzc="Firefox",upD=zzc+" "+FXo,Nzc="Nintendo",Fzc="PlayStation",NXo="Xbox",spD=Lta+" "+Vta,cpD=Vta+" "+MG_,OGa="Windows",lpD=OGa+" Phone";var CG_="Generic",dV9=CG_+" "+Vta.toLowerCase(),pV9=CG_+" "+SG_.toLowerCase(),fpD="Konqueror",KG="(\\d+(\\.\\d+)?)",Tzc=new RegExp("Version/"+KG),_V9=new RegExp(NXo,"i"),hV9=new RegExp(Fzc+" \\w+","i"),yV9=new RegExp(Nzc+" \\w+","i"),dpD=new RegExp(QXo+"|PlayBook|BB10","i"),ppD={"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 bV9={[apD]:[new RegExp("rv:"+KG)],[opD]:[new RegExp(IG_+"?\\/"+KG)],[UXo]:[new RegExp("("+UXo+"|CrMo)\\/"+KG)],[npD]:[new RegExp("CriOS\\/"+KG)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+KG)],[MG_]:[Tzc],[cpD]:[Tzc],[Rzc]:[new RegExp("("+Rzc+"|OPR)\\/"+KG)],[zzc]:[new RegExp(zzc+"\\/"+KG)],[upD]:[new RegExp("FxiOS\\/"+KG)],[fpD]:[new RegExp("Konqueror[:/]?"+KG,"i")],[QXo]:[new RegExp(QXo+" "+KG),Tzc],[spD]:[new RegExp("android\\s"+KG,"i")],[rpD]:[new RegExp(tpD+"\\/"+KG)],[BG_]:[new RegExp("(rv:|MSIE )"+KG)],Mozilla:[new RegExp("rv:"+KG)]};var vV9=[[new RegExp(NXo+"; "+NXo+" (.*?)[);]","i"),e=>[NXo,e&&e[1]||""]],[new RegExp(Nzc,"i"),[Nzc,""]],[new RegExp(Fzc,"i"),[Fzc,""]],[dpD,[QXo,""]],[new RegExp(OGa,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[lpD,""];if(new RegExp(Vta).test(t)&&!/IEMobile\b/.test(t))return[OGa+" "+Vta,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let i=r[1],n=ppD[i]||"";return/arm/i.test(t)&&(n="RT"),[OGa,n]}return[OGa,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[FXo,t.join(".")]}return[FXo,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=Uta(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+Lta+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Lta+")","i"),e=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[Lta,t.join(".")]}return[Lta,""]}],[/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/,[ipD,""]],[/Linux|debian/i,["Linux",""]]];var qG_="utf8";function TG_(e,t){if(!e||typeof e!="string"||_pD(e))throw new Error(t)}function _pD(e){return e.trim().length===0}function RG_(e){return e?.replace(/\/+$/,"")}async function zG_(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 LXo(){return new Date().toISOString()}function khn(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var NG_=e=>e instanceof Error;function Qzc(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var VXo=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 FG_(){return"CompressionStream"in globalThis}async function Uzc(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 Wta=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()}},mGa=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function QG_(e){if(e instanceof Wta){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 Lzc(e){return typeof e=="object"&&(e instanceof Wta||e instanceof mGa)}function UG_(e){return typeof e=="object"&&e instanceof Wta&&e.status===413}var AGa=class{constructor(t,r={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new zXo,this._events=new VXo,this._isInitialized=!1,TG_(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=RG_(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:Lzc},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=EG_("[PostHog]",this.logMsgIfDebug.bind(this)),this.disableCompression=!FG_()||(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(U$.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(U$.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(U$.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(l=>l.json()).then(l=>Bzc(l)).catch(l=>{this._events.emit("error",l)})}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=Xhn(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(U$.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(U$.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(U$.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(U$.Queue)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.info("Queue is full, the oldest event is dropped.")),a.push({message:n}),this.setPersistedProperty(U$.Queue,a),this._events.emit(t,n),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=khn(()=>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:LXo()};this.historicalMigration&&(n.historical_migration=!0);let a=JSON.stringify(n),o=`${this.host}/batch/`,c=this.disableCompression?null:await Uzc(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:LXo(),uuid:i?.uuid?i.uuid:T$t()};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 QG_(t)})}async flush(){let t=Qzc([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),Qzc([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(U$.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(U$.Queue)||[]).slice(n.length);this.setPersistedProperty(U$.Queue,h),t=h},c={api_key:this.apiKey,batch:a,sent_at:LXo()};this.historicalMigration&&(c.historical_migration=!0);let d=JSON.stringify(c),s=`${this.host}/batch/`,u=this.disableCompression?null:await Uzc(d,this.isDebug),l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...u!==null&&{"Content-Encoding":"gzip"}},body:u||d},p={retryCheck:_=>UG_(_)?!1:Lzc(_)};try{await this.fetchWithRetry(s,l,p)}catch(_){if(UG_(_)&&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 mGa||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,qG_)}catch{a instanceof Blob?o=a.size:o=new TextEncoder().encode(a).length}return await zG_(async()=>{let c=null;try{c=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(s){throw new mGa(s)}if(!(r.mode==="no-cors")&&(c.status<200||c.status>=400))throw new Wta(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(U$.Queue)||[]).length===0||(await this.flush(),r)););}catch(n){if(!Lzc(n))throw n;await QG_(n)}};return Promise.race([new Promise((n,a)=>{khn(()=>{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 L$={};Yt(L$,{DOMExceptionCoercer:()=>Wzc,ErrorCoercer:()=>Gzc,ErrorEventCoercer:()=>xzc,ErrorPropertiesBuilder:()=>Vzc,EventCoercer:()=>Jzc,ObjectCoercer:()=>Kzc,PrimitiveCoercer:()=>$zc,PromiseRejectionEventCoercer:()=>Yzc,ReduceableCache:()=>Xzc,StringCoercer:()=>Hzc,chromeStackLineParser:()=>WG_,createStackParser:()=>MpD,geckoStackLineParser:()=>xG_,nodeStackLineParser:()=>$G_,opera10StackLineParser:()=>HG_,opera11StackLineParser:()=>KG_,reverseAndStripFrames:()=>ZG_,winjsStackLineParser:()=>GG_});var WXo,LG_,GXo;function VG_(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);return GXo&&r.length===LG_||(LG_=r.length,GXo=r.reduce((i,n)=>{WXo||(WXo={});let a=WXo[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,WXo[n]=[s,u];break}}}return i},{})),GXo}var hpD=4,Vzc=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&&OG_(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:VG_(this.stackParser)}}buildCoercingContext(t,r,i=0){let n=(o,c)=>{if(c<=hpD){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 uL="?";function R$t(e,t,r,i,n){let a={platform:e,filename:t,function:r==="<anonymous>"?uL:r,in_app:!0};return Uta(i)||(a.lineno=i),Uta(n)||(a.colno=n),a}var xXo=(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]:uL,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var ypD=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,bpD=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,vpD=/\((\S*)(?::(\d+))(?::(\d+))\)/,WG_=(e,t)=>{let r=ypD.exec(e);if(r){let[,n,a,o]=r;return R$t(t,n,uL,+a,+o)}let i=bpD.exec(e);if(i){if(i[2]&&i[2].indexOf("eval")===0){let c=vpD.exec(i[2]);c&&(i[2]=c[1],i[3]=c[2],i[4]=c[3])}let[a,o]=xXo(i[1]||uL,i[2]);return R$t(t,o,a,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}};var gpD=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,GG_=(e,t)=>{let r=gpD.exec(e);return r?R$t(t,r[2],r[1]||uL,+r[3],r[4]?+r[4]:void 0):void 0};var OpD=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,mpD=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,xG_=(e,t)=>{let r=OpD.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let o=mpD.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]||uL;return[a,n]=xXo(a,n),R$t(t,n,a,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var ApD=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,HG_=(e,t)=>{let r=ApD.exec(e);return r?R$t(t,r[2],r[3]||uL,+r[1]):void 0},PpD=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,KG_=(e,t)=>{let r=PpD.exec(e);return r?R$t(t,r[5],r[3]||r[4]||uL,+r[1],+r[2]):void 0};var jpD=/^\s*[-]{4,}$/,wpD=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,$G_=(e,t)=>{let r=e.match(wpD);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 l=i.indexOf(".Module");l>0&&(a=a.slice(l+1),i=i.slice(0,l))}o=void 0}n&&(o=i,c=n),n==="<anonymous>"&&(c=void 0,a=void 0),a===void 0&&(c=c||uL,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:JG_(r[3]),colno:JG_(r[4]),in_app:EpD(d||"",s),platform:t}}if(e.match(jpD))return{filename:e,platform:t}};function EpD(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 JG_(e){return parseInt(e||"",10)||void 0}var YG_=/\(error: (.*)\)/,XG_=50;function ZG_(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,XG_).map(r=>({...r,filename:r.filename||SpD(t).filename,function:r.function||uL}))}function SpD(e){return e[e.length-1]||{}}function MpD(e,...t){return(r,i=0)=>{let n=[],a=r.split(`
1264
- `);for(let o=i;o<a.length;o++){let c=a[o];if(c.length>1024)continue;let d=YG_.test(c)?c.replace(YG_,"$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>=XG_)break}}return ZG_(n)}}var Wzc=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let i=bGa(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 Zhn(t,"DOMException")}isDOMError(t){return Zhn(t,"DOMError")}};var Gzc=class{match(t){return qzc(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 xzc=class{constructor(){}match(t){return PG_(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 DpD=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,Hzc=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(DpD);return n&&(r=n[1],i=n[2]),[r,i]}};var kG_=["fatal","error","warning","log","info","debug"];function HXo(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 Kzc=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 TXo(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=HXo(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${i}`}isSeverityLevel(t){return bGa(t)&&!mG_(t)&&kG_.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let i=t[r];if(NG_(i))return i}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var Jzc=class{match(t){return TXo(t)}coerce(t,r){let i=t.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${HXo(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var $zc=class{match(t){return vGa(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var Yzc=class{match(t){return Zhn(t,"PromiseRejectionEvent")}coerce(t,r){let i=this.getUnhandledRejectionReason(t);return vGa(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(vGa(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 Xzc=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 rx_=require("fs"),ix_=require("readline"),KXo=new L$.ReduceableCache(25),nx_=new L$.ReduceableCache(20),Zzc=7,BpD=1e3,IpD=1e4;async function ax_(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"||RpD(o)||zpD(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(nx_.get(n))continue;let a=t[n];if(!a)continue;a.sort((d,s)=>d-s);let o=FpD(a);if(o.every(d=>NpD(n,d)))continue;let c=QpD(KXo,n,{});i.push(CpD(n,o,c))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&qpD(e,KXo),KXo.reduce(),e}function CpD(e,t,r){return new Promise(i=>{let n=(0,rx_.createReadStream)(e),a=(0,ix_.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],l=s[1];function p(){nx_.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]=UpD(_,0),c>=l)){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],l=h[1]}})})}function qpD(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;TpD(r.lineno,r,i)}}function TpD(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=ox_(e);n<e;n++){let a=r[n];if(a===void 0)return void ex_(t);t.pre_context.push(a)}if(r[e]===void 0)return void ex_(t);t.context_line=r[e];let i=ux_(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 ex_(e){delete e.pre_context,delete e.context_line,delete e.post_context}function RpD(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function zpD(e){return e.lineno!==void 0&&e.lineno>IpD||e.colno!==void 0&&e.colno>BpD}function NpD(e,t){let r=KXo.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 FpD(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=tx_(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+Zzc:(n.push(i),i=tx_(a)),t++}return n}function tx_(e){return[ox_(e),ux_(e)]}function ox_(e){return Math.max(1,e-Zzc)}function ux_(e){return e+Zzc}function QpD(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function UpD(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 LpD(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 sx_(e,t){globalThis.process?.on("uncaughtException",LpD(e,t))}function cx_(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var VpD=2e3,bQi=class e{constructor(t,r,i){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=i,this._rateLimiter=new RXo({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||T$t(),properties:{...o,...a}}}startAutocaptureIfEnabled(){this.isEnabled()&&(sx_(this.onException.bind(this),this.onFatalError.bind(this)),cx_(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(VpD),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var lx_="5.17.4";async function fx_(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 WpD=6e4,GpD=1152921504606847e3,xpD=["is_not"],Gta=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},q0=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},z$t=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},JXo=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 z$t||d instanceof q0?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(l=>this.featureFlagsByKey[l]).filter(Boolean):this.featureFlags,u={};return await Promise.all(s.map(async l=>{try{let{value:p,payload:_}=await this.computeFlagAndPayloadLocally(l,t,r,i,n,void 0,u);o[l.key]=p,_&&(c[l.key]=_)}catch(p){p instanceof z$t||p instanceof q0?this.logMsgIfDebug(()=>console.debug(`${p.name} when computing flag locally: ${l.key}: ${p.message}`)):p instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${l.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 q0("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 q0("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 q0("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new q0(`Flag dependency property for '${a}' is missing required 'dependency_chain' field`);let o=t.dependency_chain;if(!Array.isArray(o))throw new q0(`Flag dependency property for '${a}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new q0(`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 l=await this.matchFeatureFlagProperties(u,r,i,n);n[d]=l}catch(l){throw new q0(`Error evaluating flag dependency '${d}' for flag '${a}': ${l}`)}else n[d]=!1;else throw new q0(`Missing flag dependency '${d}' for flag '${a}'`)}if(n[d]==null)throw new q0(`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,l=a.multivariate?.variants||[];d=u&&l.some(p=>p.key===u)?u:await this.getMatchingVariant(t,r)||!0;break}}catch(u){if(u instanceof z$t)throw u;if(u instanceof q0)c=!0;else throw u}if(d!==void 0)return d;if(c)throw new q0("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"?yx_(d,n,this.cohorts,this.debugMode):s==="flag"?await this.evaluateFlagDependency(d,r,n,a):hx_(d,n,c),!u)return!1}if(o==null)return!0}return!(o!=null&&await dx_(t.key,r)>o/100)}async getMatchingVariant(t,r){let i=await dx_(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(WpD,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 Gta(`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 Gta(`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 Gta(`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 Gta&&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=khn(()=>{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 dx_(e,t,r=""){let i=await fx_(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/GpD}function hx_(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 q0("Operator is_not_set is not supported")}else throw new q0(`Property ${i} not found in propertyValues`);let o=t[i];if(o==null&&!xpD.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(l=>String(l).toLowerCase()).includes(String(u).toLowerCase()):String(s).toLowerCase()===String(u).toLowerCase()}function d(s,u,l){if(l==="gt")return s>u;if(l==="gte")return s>=u;if(l==="lt")return s<u;if(l==="lte")return s<=u;throw new Error(`Invalid operator: ${l}`)}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 px_(String(n))&&String(o).match(String(n))!==null;case"not_regex":return px_(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 q0("Date operations cannot be performed on boolean values");let s=KpD(String(n));if(s==null&&(s=_x_(n)),s==null)throw new q0(`Invalid date: ${n}`);let u=_x_(o);return["is_date_before"].includes(a)?u<s:u>s}default:throw new q0(`Unknown operator: ${a}`)}}function HpD(e,t){if(!(e in t))throw new z$t(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function yx_(e,t,r,i=!1){let n=String(e.value);HpD(n,r);let a=r[n];return bx_(a,t,r,i)}function bx_(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=bx_(c,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof z$t)throw d;if(d instanceof q0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new q0("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=yx_(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=hx_(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 z$t)throw d;if(d instanceof q0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new q0("can't match cohort without a given cohort property value");return n==="AND"}function px_(e){try{return new RegExp(e),!0}catch{return!1}}function _x_(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 q0(`${e} is in an invalid date format`)}throw new q0(`The date provided ${e} must be a string, number, or date object`)}function KpD(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 $Xo=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var JpD=100,vx_=3e4,$pD=5e4,YXo=class extends AGa{constructor(t,r={}){if(super(t,r),this._memoryStorage=new $Xo,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,JpD):vx_,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 JXo({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 bQi(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||$pD}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 lx_}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=vx_){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 l=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,d,s),p=l!==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,l=Xhn(y),_=v?.requestId,h=v?.evaluatedAt}let b=`${t}_${l}`;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:l,$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}`]:l,$feature_flag_request_id:_,$feature_flag_evaluated_at:h},groups:n,disableGeoip:a})),l}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 l;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,l=y.payload)}catch(y){if(y instanceof z$t||y instanceof q0)this._logger?.info(`${y.name} when computing flag locally: ${h.key}: ${y.message}`);else throw y}}return c==null&&(c=!1),!(l!==void 0)&&!c&&(l=await super.getFeatureFlagPayloadStateless(t,r,a,d,s,o)),l}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),l={},p={},_=!0;if(u&&(l=u.response,p=u.payloads,_=u.fallbackToFlags),_&&!o){let h=await super.getFeatureFlagsAndPayloadsStateless(t,i,c,d,n,a);l={...l,...h.flags||{}},p={...p,...h.payloads||{}}}return{featureFlags:l,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=khn(()=>{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(jG_(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,l]of Object.entries(r||{}))s[u]=String(l);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,l]of Object.entries(r||{}))s[u]=String(l);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(bQi.buildEventMessage(t,{syntheticException:n},r,i).then(a=>this.capture(a)))}async captureExceptionImmediate(t,r,i){let n=new Error("PostHog syntheticException");this.addPendingPromise(bQi.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(),l=r||u?.distinctId,p={...u?.properties||{},...n||{}};l||(l=T$t(),p.$process_person_profile=!1),u?.sessionId&&!p.$session_id&&(p.$session_id=u.sessionId);let _=this._runBeforeSend({distinctId:l,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[g,m]of Object.entries(y))b[`$feature/${g}`]=m;let v=Object.keys(y||{}).filter(g=>y?.[g]!==!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"&&vG_(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 gx_=require("async_hooks"),XXo=class{constructor(){this.storage=new gx_.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 Ox_="posthog-node";function YpD(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[kzc.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 l=o.exception?.values||[],p=l.map(h=>({...h,stacktrace:h.stacktrace?{...h.stacktrace,type:"raw",frames:(h.stacktrace.frames||[]).map(y=>({...y,platform:"node:javascript"}))}:void 0})),_={$exception_message:l[0]?.value||o.message,$exception_type:l[0]?.type,$exception_level:o.level,$exception_list:p,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:l[0]?.value||o.message,$sentry_exception_type:l[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 kzc=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,i,n,a){this.name=Ox_,this.name=Ox_,this.setupOnce=function(o,c){let d=c()?.getClient()?.getDsn()?.projectId;o(YpD(t,{organization:r,projectId:d,prefix:i,severityAllowList:n,sendExceptionsToPostHog:a??!0}))}}};bQi.errorPropertiesBuilder=new L$.ErrorPropertiesBuilder([new L$.EventCoercer,new L$.ErrorCoercer,new L$.ObjectCoercer,new L$.StringCoercer,new L$.PrimitiveCoercer],L$.createStackParser("node:javascript",L$.nodeStackLineParser),[pG_(),ax_]);var xta=class extends YXo{getLibraryId(){return"posthog-node"}initializeContext(){return new XXo}};var ZXo=class{posthog;constructor({posthogApiKey:t}){this.posthog=new xta(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"3.47.4",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var PGa=class{async sendEvent(){}async identify(){}async flush(){}};var Hta=require("fs/promises"),jx_=require("os"),wx_=require("path");var mx_=ue(require("crypto")),eZo=new Uint8Array(256),kXo=eZo.length;function eNc(){return kXo>eZo.length-16&&(mx_.default.randomFillSync(eZo),kXo=0),eZo.slice(kXo,kXo+=16)}var sL=[];for(let e=0;e<256;++e)sL.push((e+256).toString(16).slice(1));function Ax_(e,t=0){return sL[e[t+0]]+sL[e[t+1]]+sL[e[t+2]]+sL[e[t+3]]+"-"+sL[e[t+4]]+sL[e[t+5]]+"-"+sL[e[t+6]]+sL[e[t+7]]+"-"+sL[e[t+8]]+sL[e[t+9]]+"-"+sL[e[t+10]]+sL[e[t+11]]+sL[e[t+12]]+sL[e[t+13]]+sL[e[t+14]]+sL[e[t+15]]}var Px_=ue(require("crypto")),tNc={randomUUID:Px_.default.randomUUID};function XpD(e,t,r){if(tNc.randomUUID&&!t&&!e)return tNc.randomUUID();e=e||{};let i=e.random||(e.rng||eNc)();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 Ax_(i)}var Tve=XpD;var ZpD="id",kpD=".fern",jGa=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new xta(r),this.userId=t==null?void 0:SIc(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.47.4",...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 Z4({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=Tt(Sr.of((0,jx_.homedir)()),He.of(kpD),He.of(ZpD));await mi(t)||(await(0,Hta.mkdir)((0,wx_.dirname)(t),{recursive:!0}),await(0,Hta.writeFile)(t,Tve())),this.persistedDistinctId=(await(0,Hta.readFile)(t)).toString()}return this.persistedDistinctId}};var rNc;async function Kta(){return rNc==null&&(rNc=await e_D()),rNc}async function e_D(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new PGa;let r=await KHo();return r!=null?new jGa({token:r,posthogApiKey:e}):await cea()!=null?new ZXo({posthogApiKey:e}):new jGa({token:void 0,posthogApiKey:e})}catch{return new PGa}}function wGa(e,t){return function(){return e.apply(t,arguments)}}var{toString:t_D}=Object.prototype,{getPrototypeOf:nNc}=Object,{iterator:rZo,toStringTag:Sx_}=Symbol,iZo=(e=>t=>{let r=t_D.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),x3t=e=>(e=e.toLowerCase(),t=>iZo(t)===e),nZo=e=>t=>typeof t===e,{isArray:$ta}=Array,Jta=nZo("undefined");function EGa(e){return e!==null&&!Jta(e)&&e.constructor!==null&&!Jta(e.constructor)&&V$(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var Mx_=x3t("ArrayBuffer");function r_D(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Mx_(e.buffer),t}var i_D=nZo("string"),V$=nZo("function"),Dx_=nZo("number"),SGa=e=>e!==null&&typeof e=="object",n_D=e=>e===!0||e===!1,tZo=e=>{if(iZo(e)!=="object")return!1;let t=nNc(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Sx_ in e)&&!(rZo in e)},a_D=e=>{if(!SGa(e)||EGa(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},o_D=x3t("Date"),u_D=x3t("File"),s_D=x3t("Blob"),c_D=x3t("FileList"),l_D=e=>SGa(e)&&V$(e.pipe),f_D=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||V$(e.append)&&((t=iZo(e))==="formdata"||t==="object"&&V$(e.toString)&&e.toString()==="[object FormData]"))},d_D=x3t("URLSearchParams"),[p_D,__D,h_D,y_D]=["ReadableStream","Request","Response","Headers"].map(x3t),b_D=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function MGa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),$ta(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{if(EGa(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 Bx_(e,t){if(EGa(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 eyn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Ix_=e=>!Jta(e)&&e!==eyn;function iNc(){let{caseless:e,skipUndefined:t}=Ix_(this)&&this||{},r={},i=(n,a)=>{let o=e&&Bx_(r,a)||a;tZo(r[o])&&tZo(n)?r[o]=iNc(r[o],n):tZo(n)?r[o]=iNc({},n):$ta(n)?r[o]=n.slice():(!t||!Jta(n))&&(r[o]=n)};for(let n=0,a=arguments.length;n<a;n++)arguments[n]&&MGa(arguments[n],i);return r}var v_D=(e,t,r,{allOwnKeys:i}={})=>(MGa(t,(n,a)=>{r&&V$(n)?e[a]=wGa(n,r):e[a]=n},{allOwnKeys:i}),e),g_D=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),O_D=(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)},m_D=(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&&nNc(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},A_D=(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},P_D=e=>{if(!e)return null;if($ta(e))return e;let t=e.length;if(!Dx_(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},j_D=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&nNc(Uint8Array)),w_D=(e,t)=>{let i=(e&&e[rZo]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},E_D=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},S_D=x3t("HTMLFormElement"),M_D=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),Ex_=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),D_D=x3t("RegExp"),Cx_=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};MGa(r,(n,a)=>{let o;(o=t(n,a,e))!==!1&&(i[a]=o||n)}),Object.defineProperties(e,i)},B_D=e=>{Cx_(e,(t,r)=>{if(V$(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(V$(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+"'")})}})},I_D=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return $ta(e)?i(e):i(String(e).split(t)),r},C_D=()=>{},q_D=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function T_D(e){return!!(e&&V$(e.append)&&e[Sx_]==="FormData"&&e[rZo])}var R_D=e=>{let t=new Array(10),r=(i,n)=>{if(SGa(i)){if(t.indexOf(i)>=0)return;if(EGa(i))return i;if(!("toJSON"in i)){t[n]=i;let a=$ta(i)?[]:{};return MGa(i,(o,c)=>{let d=r(o,n+1);!Jta(d)&&(a[c]=d)}),t[n]=void 0,a}}return i};return r(e,0)},z_D=x3t("AsyncFunction"),N_D=e=>e&&(SGa(e)||V$(e))&&V$(e.then)&&V$(e.catch),qx_=((e,t)=>e?setImmediate:t?((r,i)=>(eyn.addEventListener("message",({source:n,data:a})=>{n===eyn&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),eyn.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",V$(eyn.postMessage)),F_D=typeof queueMicrotask<"u"?queueMicrotask.bind(eyn):typeof process<"u"&&process.nextTick||qx_,Q_D=e=>e!=null&&V$(e[rZo]),ir={isArray:$ta,isArrayBuffer:Mx_,isBuffer:EGa,isFormData:f_D,isArrayBufferView:r_D,isString:i_D,isNumber:Dx_,isBoolean:n_D,isObject:SGa,isPlainObject:tZo,isEmptyObject:a_D,isReadableStream:p_D,isRequest:__D,isResponse:h_D,isHeaders:y_D,isUndefined:Jta,isDate:o_D,isFile:u_D,isBlob:s_D,isRegExp:D_D,isFunction:V$,isStream:l_D,isURLSearchParams:d_D,isTypedArray:j_D,isFileList:c_D,forEach:MGa,merge:iNc,extend:v_D,trim:b_D,stripBOM:g_D,inherits:O_D,toFlatObject:m_D,kindOf:iZo,kindOfTest:x3t,endsWith:A_D,toArray:P_D,forEachEntry:w_D,matchAll:E_D,isHTMLForm:S_D,hasOwnProperty:Ex_,hasOwnProp:Ex_,reduceDescriptors:Cx_,freezeMethods:B_D,toObjectSet:I_D,toCamelCase:M_D,noop:C_D,toFiniteNumber:q_D,findKey:Bx_,global:eyn,isContextDefined:Ix_,isSpecCompliantForm:T_D,toJSONObject:R_D,isAsyncFn:z_D,isThenable:N_D,setImmediate:qx_,asap:F_D,isIterable:Q_D};function Yta(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)}ir.inherits(Yta,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:ir.toJSONObject(this.config),code:this.code,status:this.status}}});var Tx_=Yta.prototype,Rx_={};["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=>{Rx_[e]={value:e}});Object.defineProperties(Yta,Rx_);Object.defineProperty(Tx_,"isAxiosError",{value:!0});Yta.from=(e,t,r,i,n,a)=>{let o=Object.create(Tx_);ir.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 Yta.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 za=Yta;var zx_=ue(Skn(),1),aZo=zx_.default;function aNc(e){return ir.isPlainObject(e)||ir.isArray(e)}function Fx_(e){return ir.endsWith(e,"[]")?e.slice(0,-2):e}function Nx_(e,t,r){return e?e.concat(t).map(function(n,a){return n=Fx_(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function U_D(e){return ir.isArray(e)&&!e.some(aNc)}var L_D=ir.toFlatObject(ir,{},null,function(t){return/^is[A-Z]/.test(t)});function V_D(e,t,r){if(!ir.isObject(e))throw new TypeError("target must be an object");t=t||new(aZo||FormData),r=ir.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,b){return!ir.isUndefined(b[y])});let i=r.metaTokens,n=r.visitor||u,a=r.dots,o=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&ir.isSpecCompliantForm(t);if(!ir.isFunction(n))throw new TypeError("visitor must be a function");function s(h){if(h===null)return"";if(ir.isDate(h))return h.toISOString();if(ir.isBoolean(h))return h.toString();if(!d&&ir.isBlob(h))throw new za("Blob is not supported. Use a Buffer instead.");return ir.isArrayBuffer(h)||ir.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(ir.endsWith(y,"{}"))y=i?y:y.slice(0,-2),h=JSON.stringify(h);else if(ir.isArray(h)&&U_D(h)||(ir.isFileList(h)||ir.endsWith(y,"[]"))&&(v=ir.toArray(h)))return y=Fx_(y),v.forEach(function(m,O){!(ir.isUndefined(m)||m===null)&&t.append(o===!0?Nx_([y],O,a):o===null?y:y+"[]",s(m))}),!1}return aNc(h)?!0:(t.append(Nx_(b,y,a),s(h)),!1)}let l=[],p=Object.assign(L_D,{defaultVisitor:u,convertValue:s,isVisitable:aNc});function _(h,y){if(!ir.isUndefined(h)){if(l.indexOf(h)!==-1)throw Error("Circular reference detected in "+y.join("."));l.push(h),ir.forEach(h,function(v,g){(!(ir.isUndefined(v)||v===null)&&n.call(t,v,ir.isString(g)?g.trim():g,y,p))===!0&&_(v,y?y.concat(g):[g])}),l.pop()}}if(!ir.isObject(e))throw new TypeError("data must be an object");return _(e),t}var X7i=V_D;function Qx_(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function Ux_(e,t){this._pairs=[],e&&X7i(e,this,t)}var Lx_=Ux_.prototype;Lx_.append=function(t,r){this._pairs.push([t,r])};Lx_.toString=function(t){let r=t?function(i){return t.call(this,i,Qx_)}:Qx_;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var Vx_=Ux_;function W_D(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function tyn(e,t,r){if(!t)return e;let i=r&&r.encode||W_D;ir.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=ir.isURLSearchParams(t)?t.toString():new Vx_(t,r).toString(i),a){let o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var oNc=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){ir.forEach(this.handlers,function(i){i!==null&&t(i)})}},uNc=oNc;var Xta={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var Hx_=ue(require("crypto"),1);var Wx_=ue(require("url"),1),Gx_=Wx_.default.URLSearchParams;var sNc="abcdefghijklmnopqrstuvwxyz",xx_="0123456789",Kx_={DIGIT:xx_,ALPHA:sNc,ALPHA_DIGIT:sNc+sNc.toUpperCase()+xx_},G_D=(e=16,t=Kx_.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);Hx_.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},Jx_={isNode:!0,classes:{URLSearchParams:Gx_,FormData:aZo,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:Kx_,generateString:G_D,protocols:["http","https","file","data"]};var fNc={};Yt(fNc,{hasBrowserEnv:()=>lNc,hasStandardBrowserEnv:()=>x_D,hasStandardBrowserWebWorkerEnv:()=>H_D,navigator:()=>cNc,origin:()=>K_D});var lNc=typeof window<"u"&&typeof document<"u",cNc=typeof navigator=="object"&&navigator||void 0,x_D=lNc&&(!cNc||["ReactNative","NativeScript","NS"].indexOf(cNc.product)<0),H_D=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",K_D=lNc&&window.location.href||"http://localhost";var vA={...fNc,...Jx_};function dNc(e,t){return X7i(e,new vA.classes.URLSearchParams,{visitor:function(r,i,n,a){return vA.isNode&&ir.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function J_D(e){return ir.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function $_D(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 Y_D(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&&ir.isArray(n)?n.length:o,d?(ir.hasOwnProp(n,o)?n[o]=[n[o],i]:n[o]=i,!c):((!n[o]||!ir.isObject(n[o]))&&(n[o]=[]),t(r,i,n[o],a)&&ir.isArray(n[o])&&(n[o]=$_D(n[o])),!c)}if(ir.isFormData(e)&&ir.isFunction(e.entries)){let r={};return ir.forEachEntry(e,(i,n)=>{t(J_D(i),n,r,0)}),r}return null}var oZo=Y_D;function X_D(e,t,r){if(ir.isString(e))try{return(t||JSON.parse)(e),ir.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var pNc={transitional:Xta,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=ir.isObject(t);if(a&&ir.isHTMLForm(t)&&(t=new FormData(t)),ir.isFormData(t))return n?JSON.stringify(oZo(t)):t;if(ir.isArrayBuffer(t)||ir.isBuffer(t)||ir.isStream(t)||ir.isFile(t)||ir.isBlob(t)||ir.isReadableStream(t))return t;if(ir.isArrayBufferView(t))return t.buffer;if(ir.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 dNc(t,this.formSerializer).toString();if((c=ir.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return X7i(c?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),X_D(t)):t}],transformResponse:[function(t){let r=this.transitional||pNc.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(ir.isResponse(t)||ir.isReadableStream(t))return t;if(t&&ir.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"?za.from(c,za.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:vA.classes.FormData,Blob:vA.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ir.forEach(["delete","get","head","post","put","patch"],e=>{pNc.headers[e]={}});var Zta=pNc;var Z_D=ir.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"]),$x_=e=>{let t={},r,i,n;return e&&e.split(`
1264
+ `);for(let o=i;o<a.length;o++){let c=a[o];if(c.length>1024)continue;let d=YG_.test(c)?c.replace(YG_,"$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>=XG_)break}}return ZG_(n)}}var Wzc=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let i=bGa(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 Zhn(t,"DOMException")}isDOMError(t){return Zhn(t,"DOMError")}};var Gzc=class{match(t){return qzc(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 xzc=class{constructor(){}match(t){return PG_(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 DpD=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,Hzc=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(DpD);return n&&(r=n[1],i=n[2]),[r,i]}};var kG_=["fatal","error","warning","log","info","debug"];function HXo(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 Kzc=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 TXo(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=HXo(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${i}`}isSeverityLevel(t){return bGa(t)&&!mG_(t)&&kG_.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let i=t[r];if(NG_(i))return i}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var Jzc=class{match(t){return TXo(t)}coerce(t,r){let i=t.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${HXo(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var $zc=class{match(t){return vGa(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var Yzc=class{match(t){return Zhn(t,"PromiseRejectionEvent")}coerce(t,r){let i=this.getUnhandledRejectionReason(t);return vGa(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(vGa(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 Xzc=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 rx_=require("fs"),ix_=require("readline"),KXo=new L$.ReduceableCache(25),nx_=new L$.ReduceableCache(20),Zzc=7,BpD=1e3,IpD=1e4;async function ax_(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"||RpD(o)||zpD(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(nx_.get(n))continue;let a=t[n];if(!a)continue;a.sort((d,s)=>d-s);let o=FpD(a);if(o.every(d=>NpD(n,d)))continue;let c=QpD(KXo,n,{});i.push(CpD(n,o,c))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&qpD(e,KXo),KXo.reduce(),e}function CpD(e,t,r){return new Promise(i=>{let n=(0,rx_.createReadStream)(e),a=(0,ix_.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],l=s[1];function p(){nx_.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]=UpD(_,0),c>=l)){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],l=h[1]}})})}function qpD(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;TpD(r.lineno,r,i)}}function TpD(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=ox_(e);n<e;n++){let a=r[n];if(a===void 0)return void ex_(t);t.pre_context.push(a)}if(r[e]===void 0)return void ex_(t);t.context_line=r[e];let i=ux_(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 ex_(e){delete e.pre_context,delete e.context_line,delete e.post_context}function RpD(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function zpD(e){return e.lineno!==void 0&&e.lineno>IpD||e.colno!==void 0&&e.colno>BpD}function NpD(e,t){let r=KXo.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 FpD(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=tx_(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+Zzc:(n.push(i),i=tx_(a)),t++}return n}function tx_(e){return[ox_(e),ux_(e)]}function ox_(e){return Math.max(1,e-Zzc)}function ux_(e){return e+Zzc}function QpD(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function UpD(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 LpD(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 sx_(e,t){globalThis.process?.on("uncaughtException",LpD(e,t))}function cx_(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var VpD=2e3,bQi=class e{constructor(t,r,i){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=i,this._rateLimiter=new RXo({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||T$t(),properties:{...o,...a}}}startAutocaptureIfEnabled(){this.isEnabled()&&(sx_(this.onException.bind(this),this.onFatalError.bind(this)),cx_(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(VpD),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var lx_="5.17.4";async function fx_(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 WpD=6e4,GpD=1152921504606847e3,xpD=["is_not"],Gta=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},q0=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},z$t=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},JXo=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 z$t||d instanceof q0?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(l=>this.featureFlagsByKey[l]).filter(Boolean):this.featureFlags,u={};return await Promise.all(s.map(async l=>{try{let{value:p,payload:_}=await this.computeFlagAndPayloadLocally(l,t,r,i,n,void 0,u);o[l.key]=p,_&&(c[l.key]=_)}catch(p){p instanceof z$t||p instanceof q0?this.logMsgIfDebug(()=>console.debug(`${p.name} when computing flag locally: ${l.key}: ${p.message}`)):p instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${l.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 q0("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 q0("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 q0("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new q0(`Flag dependency property for '${a}' is missing required 'dependency_chain' field`);let o=t.dependency_chain;if(!Array.isArray(o))throw new q0(`Flag dependency property for '${a}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new q0(`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 l=await this.matchFeatureFlagProperties(u,r,i,n);n[d]=l}catch(l){throw new q0(`Error evaluating flag dependency '${d}' for flag '${a}': ${l}`)}else n[d]=!1;else throw new q0(`Missing flag dependency '${d}' for flag '${a}'`)}if(n[d]==null)throw new q0(`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,l=a.multivariate?.variants||[];d=u&&l.some(p=>p.key===u)?u:await this.getMatchingVariant(t,r)||!0;break}}catch(u){if(u instanceof z$t)throw u;if(u instanceof q0)c=!0;else throw u}if(d!==void 0)return d;if(c)throw new q0("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"?yx_(d,n,this.cohorts,this.debugMode):s==="flag"?await this.evaluateFlagDependency(d,r,n,a):hx_(d,n,c),!u)return!1}if(o==null)return!0}return!(o!=null&&await dx_(t.key,r)>o/100)}async getMatchingVariant(t,r){let i=await dx_(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(WpD,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 Gta(`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 Gta(`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 Gta(`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 Gta&&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=khn(()=>{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 dx_(e,t,r=""){let i=await fx_(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/GpD}function hx_(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 q0("Operator is_not_set is not supported")}else throw new q0(`Property ${i} not found in propertyValues`);let o=t[i];if(o==null&&!xpD.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(l=>String(l).toLowerCase()).includes(String(u).toLowerCase()):String(s).toLowerCase()===String(u).toLowerCase()}function d(s,u,l){if(l==="gt")return s>u;if(l==="gte")return s>=u;if(l==="lt")return s<u;if(l==="lte")return s<=u;throw new Error(`Invalid operator: ${l}`)}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 px_(String(n))&&String(o).match(String(n))!==null;case"not_regex":return px_(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 q0("Date operations cannot be performed on boolean values");let s=KpD(String(n));if(s==null&&(s=_x_(n)),s==null)throw new q0(`Invalid date: ${n}`);let u=_x_(o);return["is_date_before"].includes(a)?u<s:u>s}default:throw new q0(`Unknown operator: ${a}`)}}function HpD(e,t){if(!(e in t))throw new z$t(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function yx_(e,t,r,i=!1){let n=String(e.value);HpD(n,r);let a=r[n];return bx_(a,t,r,i)}function bx_(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=bx_(c,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof z$t)throw d;if(d instanceof q0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new q0("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=yx_(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=hx_(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 z$t)throw d;if(d instanceof q0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new q0("can't match cohort without a given cohort property value");return n==="AND"}function px_(e){try{return new RegExp(e),!0}catch{return!1}}function _x_(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 q0(`${e} is in an invalid date format`)}throw new q0(`The date provided ${e} must be a string, number, or date object`)}function KpD(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 $Xo=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var JpD=100,vx_=3e4,$pD=5e4,YXo=class extends AGa{constructor(t,r={}){if(super(t,r),this._memoryStorage=new $Xo,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,JpD):vx_,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 JXo({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 bQi(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||$pD}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 lx_}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=vx_){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 l=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,d,s),p=l!==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,l=Xhn(y),_=v?.requestId,h=v?.evaluatedAt}let b=`${t}_${l}`;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:l,$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}`]:l,$feature_flag_request_id:_,$feature_flag_evaluated_at:h},groups:n,disableGeoip:a})),l}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 l;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,l=y.payload)}catch(y){if(y instanceof z$t||y instanceof q0)this._logger?.info(`${y.name} when computing flag locally: ${h.key}: ${y.message}`);else throw y}}return c==null&&(c=!1),!(l!==void 0)&&!c&&(l=await super.getFeatureFlagPayloadStateless(t,r,a,d,s,o)),l}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),l={},p={},_=!0;if(u&&(l=u.response,p=u.payloads,_=u.fallbackToFlags),_&&!o){let h=await super.getFeatureFlagsAndPayloadsStateless(t,i,c,d,n,a);l={...l,...h.flags||{}},p={...p,...h.payloads||{}}}return{featureFlags:l,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=khn(()=>{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(jG_(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,l]of Object.entries(r||{}))s[u]=String(l);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,l]of Object.entries(r||{}))s[u]=String(l);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(bQi.buildEventMessage(t,{syntheticException:n},r,i).then(a=>this.capture(a)))}async captureExceptionImmediate(t,r,i){let n=new Error("PostHog syntheticException");this.addPendingPromise(bQi.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(),l=r||u?.distinctId,p={...u?.properties||{},...n||{}};l||(l=T$t(),p.$process_person_profile=!1),u?.sessionId&&!p.$session_id&&(p.$session_id=u.sessionId);let _=this._runBeforeSend({distinctId:l,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[g,m]of Object.entries(y))b[`$feature/${g}`]=m;let v=Object.keys(y||{}).filter(g=>y?.[g]!==!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"&&vG_(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 gx_=require("async_hooks"),XXo=class{constructor(){this.storage=new gx_.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 Ox_="posthog-node";function YpD(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[kzc.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 l=o.exception?.values||[],p=l.map(h=>({...h,stacktrace:h.stacktrace?{...h.stacktrace,type:"raw",frames:(h.stacktrace.frames||[]).map(y=>({...y,platform:"node:javascript"}))}:void 0})),_={$exception_message:l[0]?.value||o.message,$exception_type:l[0]?.type,$exception_level:o.level,$exception_list:p,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:l[0]?.value||o.message,$sentry_exception_type:l[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 kzc=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,i,n,a){this.name=Ox_,this.name=Ox_,this.setupOnce=function(o,c){let d=c()?.getClient()?.getDsn()?.projectId;o(YpD(t,{organization:r,projectId:d,prefix:i,severityAllowList:n,sendExceptionsToPostHog:a??!0}))}}};bQi.errorPropertiesBuilder=new L$.ErrorPropertiesBuilder([new L$.EventCoercer,new L$.ErrorCoercer,new L$.ObjectCoercer,new L$.StringCoercer,new L$.PrimitiveCoercer],L$.createStackParser("node:javascript",L$.nodeStackLineParser),[pG_(),ax_]);var xta=class extends YXo{getLibraryId(){return"posthog-node"}initializeContext(){return new XXo}};var ZXo=class{posthog;constructor({posthogApiKey:t}){this.posthog=new xta(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"3.47.6",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var PGa=class{async sendEvent(){}async identify(){}async flush(){}};var Hta=require("fs/promises"),jx_=require("os"),wx_=require("path");var mx_=ue(require("crypto")),eZo=new Uint8Array(256),kXo=eZo.length;function eNc(){return kXo>eZo.length-16&&(mx_.default.randomFillSync(eZo),kXo=0),eZo.slice(kXo,kXo+=16)}var sL=[];for(let e=0;e<256;++e)sL.push((e+256).toString(16).slice(1));function Ax_(e,t=0){return sL[e[t+0]]+sL[e[t+1]]+sL[e[t+2]]+sL[e[t+3]]+"-"+sL[e[t+4]]+sL[e[t+5]]+"-"+sL[e[t+6]]+sL[e[t+7]]+"-"+sL[e[t+8]]+sL[e[t+9]]+"-"+sL[e[t+10]]+sL[e[t+11]]+sL[e[t+12]]+sL[e[t+13]]+sL[e[t+14]]+sL[e[t+15]]}var Px_=ue(require("crypto")),tNc={randomUUID:Px_.default.randomUUID};function XpD(e,t,r){if(tNc.randomUUID&&!t&&!e)return tNc.randomUUID();e=e||{};let i=e.random||(e.rng||eNc)();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 Ax_(i)}var Tve=XpD;var ZpD="id",kpD=".fern",jGa=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new xta(r),this.userId=t==null?void 0:SIc(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.47.6",...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 Z4({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=Tt(Sr.of((0,jx_.homedir)()),He.of(kpD),He.of(ZpD));await mi(t)||(await(0,Hta.mkdir)((0,wx_.dirname)(t),{recursive:!0}),await(0,Hta.writeFile)(t,Tve())),this.persistedDistinctId=(await(0,Hta.readFile)(t)).toString()}return this.persistedDistinctId}};var rNc;async function Kta(){return rNc==null&&(rNc=await e_D()),rNc}async function e_D(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new PGa;let r=await KHo();return r!=null?new jGa({token:r,posthogApiKey:e}):await cea()!=null?new ZXo({posthogApiKey:e}):new jGa({token:void 0,posthogApiKey:e})}catch{return new PGa}}function wGa(e,t){return function(){return e.apply(t,arguments)}}var{toString:t_D}=Object.prototype,{getPrototypeOf:nNc}=Object,{iterator:rZo,toStringTag:Sx_}=Symbol,iZo=(e=>t=>{let r=t_D.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),x3t=e=>(e=e.toLowerCase(),t=>iZo(t)===e),nZo=e=>t=>typeof t===e,{isArray:$ta}=Array,Jta=nZo("undefined");function EGa(e){return e!==null&&!Jta(e)&&e.constructor!==null&&!Jta(e.constructor)&&V$(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var Mx_=x3t("ArrayBuffer");function r_D(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Mx_(e.buffer),t}var i_D=nZo("string"),V$=nZo("function"),Dx_=nZo("number"),SGa=e=>e!==null&&typeof e=="object",n_D=e=>e===!0||e===!1,tZo=e=>{if(iZo(e)!=="object")return!1;let t=nNc(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Sx_ in e)&&!(rZo in e)},a_D=e=>{if(!SGa(e)||EGa(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},o_D=x3t("Date"),u_D=x3t("File"),s_D=x3t("Blob"),c_D=x3t("FileList"),l_D=e=>SGa(e)&&V$(e.pipe),f_D=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||V$(e.append)&&((t=iZo(e))==="formdata"||t==="object"&&V$(e.toString)&&e.toString()==="[object FormData]"))},d_D=x3t("URLSearchParams"),[p_D,__D,h_D,y_D]=["ReadableStream","Request","Response","Headers"].map(x3t),b_D=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function MGa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),$ta(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{if(EGa(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 Bx_(e,t){if(EGa(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 eyn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Ix_=e=>!Jta(e)&&e!==eyn;function iNc(){let{caseless:e,skipUndefined:t}=Ix_(this)&&this||{},r={},i=(n,a)=>{let o=e&&Bx_(r,a)||a;tZo(r[o])&&tZo(n)?r[o]=iNc(r[o],n):tZo(n)?r[o]=iNc({},n):$ta(n)?r[o]=n.slice():(!t||!Jta(n))&&(r[o]=n)};for(let n=0,a=arguments.length;n<a;n++)arguments[n]&&MGa(arguments[n],i);return r}var v_D=(e,t,r,{allOwnKeys:i}={})=>(MGa(t,(n,a)=>{r&&V$(n)?e[a]=wGa(n,r):e[a]=n},{allOwnKeys:i}),e),g_D=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),O_D=(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)},m_D=(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&&nNc(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},A_D=(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},P_D=e=>{if(!e)return null;if($ta(e))return e;let t=e.length;if(!Dx_(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},j_D=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&nNc(Uint8Array)),w_D=(e,t)=>{let i=(e&&e[rZo]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},E_D=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},S_D=x3t("HTMLFormElement"),M_D=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),Ex_=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),D_D=x3t("RegExp"),Cx_=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};MGa(r,(n,a)=>{let o;(o=t(n,a,e))!==!1&&(i[a]=o||n)}),Object.defineProperties(e,i)},B_D=e=>{Cx_(e,(t,r)=>{if(V$(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(V$(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+"'")})}})},I_D=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return $ta(e)?i(e):i(String(e).split(t)),r},C_D=()=>{},q_D=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function T_D(e){return!!(e&&V$(e.append)&&e[Sx_]==="FormData"&&e[rZo])}var R_D=e=>{let t=new Array(10),r=(i,n)=>{if(SGa(i)){if(t.indexOf(i)>=0)return;if(EGa(i))return i;if(!("toJSON"in i)){t[n]=i;let a=$ta(i)?[]:{};return MGa(i,(o,c)=>{let d=r(o,n+1);!Jta(d)&&(a[c]=d)}),t[n]=void 0,a}}return i};return r(e,0)},z_D=x3t("AsyncFunction"),N_D=e=>e&&(SGa(e)||V$(e))&&V$(e.then)&&V$(e.catch),qx_=((e,t)=>e?setImmediate:t?((r,i)=>(eyn.addEventListener("message",({source:n,data:a})=>{n===eyn&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),eyn.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",V$(eyn.postMessage)),F_D=typeof queueMicrotask<"u"?queueMicrotask.bind(eyn):typeof process<"u"&&process.nextTick||qx_,Q_D=e=>e!=null&&V$(e[rZo]),ir={isArray:$ta,isArrayBuffer:Mx_,isBuffer:EGa,isFormData:f_D,isArrayBufferView:r_D,isString:i_D,isNumber:Dx_,isBoolean:n_D,isObject:SGa,isPlainObject:tZo,isEmptyObject:a_D,isReadableStream:p_D,isRequest:__D,isResponse:h_D,isHeaders:y_D,isUndefined:Jta,isDate:o_D,isFile:u_D,isBlob:s_D,isRegExp:D_D,isFunction:V$,isStream:l_D,isURLSearchParams:d_D,isTypedArray:j_D,isFileList:c_D,forEach:MGa,merge:iNc,extend:v_D,trim:b_D,stripBOM:g_D,inherits:O_D,toFlatObject:m_D,kindOf:iZo,kindOfTest:x3t,endsWith:A_D,toArray:P_D,forEachEntry:w_D,matchAll:E_D,isHTMLForm:S_D,hasOwnProperty:Ex_,hasOwnProp:Ex_,reduceDescriptors:Cx_,freezeMethods:B_D,toObjectSet:I_D,toCamelCase:M_D,noop:C_D,toFiniteNumber:q_D,findKey:Bx_,global:eyn,isContextDefined:Ix_,isSpecCompliantForm:T_D,toJSONObject:R_D,isAsyncFn:z_D,isThenable:N_D,setImmediate:qx_,asap:F_D,isIterable:Q_D};function Yta(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)}ir.inherits(Yta,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:ir.toJSONObject(this.config),code:this.code,status:this.status}}});var Tx_=Yta.prototype,Rx_={};["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=>{Rx_[e]={value:e}});Object.defineProperties(Yta,Rx_);Object.defineProperty(Tx_,"isAxiosError",{value:!0});Yta.from=(e,t,r,i,n,a)=>{let o=Object.create(Tx_);ir.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 Yta.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 za=Yta;var zx_=ue(Skn(),1),aZo=zx_.default;function aNc(e){return ir.isPlainObject(e)||ir.isArray(e)}function Fx_(e){return ir.endsWith(e,"[]")?e.slice(0,-2):e}function Nx_(e,t,r){return e?e.concat(t).map(function(n,a){return n=Fx_(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function U_D(e){return ir.isArray(e)&&!e.some(aNc)}var L_D=ir.toFlatObject(ir,{},null,function(t){return/^is[A-Z]/.test(t)});function V_D(e,t,r){if(!ir.isObject(e))throw new TypeError("target must be an object");t=t||new(aZo||FormData),r=ir.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,b){return!ir.isUndefined(b[y])});let i=r.metaTokens,n=r.visitor||u,a=r.dots,o=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&ir.isSpecCompliantForm(t);if(!ir.isFunction(n))throw new TypeError("visitor must be a function");function s(h){if(h===null)return"";if(ir.isDate(h))return h.toISOString();if(ir.isBoolean(h))return h.toString();if(!d&&ir.isBlob(h))throw new za("Blob is not supported. Use a Buffer instead.");return ir.isArrayBuffer(h)||ir.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(ir.endsWith(y,"{}"))y=i?y:y.slice(0,-2),h=JSON.stringify(h);else if(ir.isArray(h)&&U_D(h)||(ir.isFileList(h)||ir.endsWith(y,"[]"))&&(v=ir.toArray(h)))return y=Fx_(y),v.forEach(function(m,O){!(ir.isUndefined(m)||m===null)&&t.append(o===!0?Nx_([y],O,a):o===null?y:y+"[]",s(m))}),!1}return aNc(h)?!0:(t.append(Nx_(b,y,a),s(h)),!1)}let l=[],p=Object.assign(L_D,{defaultVisitor:u,convertValue:s,isVisitable:aNc});function _(h,y){if(!ir.isUndefined(h)){if(l.indexOf(h)!==-1)throw Error("Circular reference detected in "+y.join("."));l.push(h),ir.forEach(h,function(v,g){(!(ir.isUndefined(v)||v===null)&&n.call(t,v,ir.isString(g)?g.trim():g,y,p))===!0&&_(v,y?y.concat(g):[g])}),l.pop()}}if(!ir.isObject(e))throw new TypeError("data must be an object");return _(e),t}var X7i=V_D;function Qx_(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function Ux_(e,t){this._pairs=[],e&&X7i(e,this,t)}var Lx_=Ux_.prototype;Lx_.append=function(t,r){this._pairs.push([t,r])};Lx_.toString=function(t){let r=t?function(i){return t.call(this,i,Qx_)}:Qx_;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var Vx_=Ux_;function W_D(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function tyn(e,t,r){if(!t)return e;let i=r&&r.encode||W_D;ir.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=ir.isURLSearchParams(t)?t.toString():new Vx_(t,r).toString(i),a){let o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var oNc=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){ir.forEach(this.handlers,function(i){i!==null&&t(i)})}},uNc=oNc;var Xta={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var Hx_=ue(require("crypto"),1);var Wx_=ue(require("url"),1),Gx_=Wx_.default.URLSearchParams;var sNc="abcdefghijklmnopqrstuvwxyz",xx_="0123456789",Kx_={DIGIT:xx_,ALPHA:sNc,ALPHA_DIGIT:sNc+sNc.toUpperCase()+xx_},G_D=(e=16,t=Kx_.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);Hx_.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},Jx_={isNode:!0,classes:{URLSearchParams:Gx_,FormData:aZo,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:Kx_,generateString:G_D,protocols:["http","https","file","data"]};var fNc={};Yt(fNc,{hasBrowserEnv:()=>lNc,hasStandardBrowserEnv:()=>x_D,hasStandardBrowserWebWorkerEnv:()=>H_D,navigator:()=>cNc,origin:()=>K_D});var lNc=typeof window<"u"&&typeof document<"u",cNc=typeof navigator=="object"&&navigator||void 0,x_D=lNc&&(!cNc||["ReactNative","NativeScript","NS"].indexOf(cNc.product)<0),H_D=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",K_D=lNc&&window.location.href||"http://localhost";var vA={...fNc,...Jx_};function dNc(e,t){return X7i(e,new vA.classes.URLSearchParams,{visitor:function(r,i,n,a){return vA.isNode&&ir.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function J_D(e){return ir.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function $_D(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 Y_D(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&&ir.isArray(n)?n.length:o,d?(ir.hasOwnProp(n,o)?n[o]=[n[o],i]:n[o]=i,!c):((!n[o]||!ir.isObject(n[o]))&&(n[o]=[]),t(r,i,n[o],a)&&ir.isArray(n[o])&&(n[o]=$_D(n[o])),!c)}if(ir.isFormData(e)&&ir.isFunction(e.entries)){let r={};return ir.forEachEntry(e,(i,n)=>{t(J_D(i),n,r,0)}),r}return null}var oZo=Y_D;function X_D(e,t,r){if(ir.isString(e))try{return(t||JSON.parse)(e),ir.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var pNc={transitional:Xta,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=ir.isObject(t);if(a&&ir.isHTMLForm(t)&&(t=new FormData(t)),ir.isFormData(t))return n?JSON.stringify(oZo(t)):t;if(ir.isArrayBuffer(t)||ir.isBuffer(t)||ir.isStream(t)||ir.isFile(t)||ir.isBlob(t)||ir.isReadableStream(t))return t;if(ir.isArrayBufferView(t))return t.buffer;if(ir.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 dNc(t,this.formSerializer).toString();if((c=ir.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return X7i(c?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),X_D(t)):t}],transformResponse:[function(t){let r=this.transitional||pNc.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(ir.isResponse(t)||ir.isReadableStream(t))return t;if(t&&ir.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"?za.from(c,za.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:vA.classes.FormData,Blob:vA.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ir.forEach(["delete","get","head","post","put","patch"],e=>{pNc.headers[e]={}});var Zta=pNc;var Z_D=ir.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"]),$x_=e=>{let t={},r,i,n;return e&&e.split(`
1265
1265
  `).forEach(function(o){n=o.indexOf(":"),r=o.substring(0,n).trim().toLowerCase(),i=o.substring(n+1).trim(),!(!r||t[r]&&Z_D[r])&&(r==="set-cookie"?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t};var Yx_=Symbol("internals");function DGa(e){return e&&String(e).trim().toLowerCase()}function uZo(e){return e===!1||e==null?e:ir.isArray(e)?e.map(uZo):String(e)}function k_D(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 ehD=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function _Nc(e,t,r,i,n){if(ir.isFunction(i))return i.call(this,t,r);if(n&&(t=r),!!ir.isString(t)){if(ir.isString(i))return t.indexOf(i)!==-1;if(ir.isRegExp(i))return i.test(t)}}function thD(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,i)=>r.toUpperCase()+i)}function rhD(e,t){let r=ir.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 kta=class{constructor(t){t&&this.set(t)}set(t,r,i){let n=this;function a(c,d,s){let u=DGa(d);if(!u)throw new Error("header name must be a non-empty string");let l=ir.findKey(n,u);(!l||n[l]===void 0||s===!0||s===void 0&&n[l]!==!1)&&(n[l||d]=uZo(c))}let o=(c,d)=>ir.forEach(c,(s,u)=>a(s,u,d));if(ir.isPlainObject(t)||t instanceof this.constructor)o(t,r);else if(ir.isString(t)&&(t=t.trim())&&!ehD(t))o($x_(t),r);else if(ir.isObject(t)&&ir.isIterable(t)){let c={},d,s;for(let u of t){if(!ir.isArray(u))throw TypeError("Object iterator must return a key-value pair");c[s=u[0]]=(d=c[s])?ir.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=DGa(t),t){let i=ir.findKey(this,t);if(i){let n=this[i];if(!r)return n;if(r===!0)return k_D(n);if(ir.isFunction(r))return r.call(this,n,i);if(ir.isRegExp(r))return r.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=DGa(t),t){let i=ir.findKey(this,t);return!!(i&&this[i]!==void 0&&(!r||_Nc(this,this[i],i,r)))}return!1}delete(t,r){let i=this,n=!1;function a(o){if(o=DGa(o),o){let c=ir.findKey(i,o);c&&(!r||_Nc(i,i[c],c,r))&&(delete i[c],n=!0)}}return ir.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||_Nc(this,this[a],a,t,!0))&&(delete this[a],n=!0)}return n}normalize(t){let r=this,i={};return ir.forEach(this,(n,a)=>{let o=ir.findKey(i,a);if(o){r[o]=uZo(n),delete r[a];return}let c=t?thD(a):String(a).trim();c!==a&&delete r[a],r[c]=uZo(n),i[c]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return ir.forEach(this,(i,n)=>{i!=null&&i!==!1&&(r[n]=t&&ir.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(`
1266
1266
  `)}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[Yx_]=this[Yx_]={accessors:{}}).accessors,n=this.prototype;function a(o){let c=DGa(o);i[c]||(rhD(n,o),i[c]=!0)}return ir.isArray(t)?t.forEach(a):a(t),this}};kta.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);ir.reduceDescriptors(kta.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(i){this[r]=i}}});ir.freezeMethods(kta);var mD=kta;function BGa(e,t){let r=this||Zta,i=t||r,n=mD.from(i.headers),a=i.data;return ir.forEach(e,function(c){a=c.call(r,a,n.normalize(),t?t.status:void 0)}),n.normalize(),a}function IGa(e){return!!(e&&e.__CANCEL__)}function Xx_(e,t,r){za.call(this,e??"canceled",za.ERR_CANCELED,t,r),this.name="CanceledError"}ir.inherits(Xx_,za,{__CANCEL__:!0});var Rve=Xx_;function N$t(e,t,r){let i=r.config.validateStatus;!r.status||!i||i(r.status)?e(r):t(new za("Request failed with status code "+r.status,[za.ERR_BAD_REQUEST,za.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function hNc(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function yNc(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function ryn(e,t,r){let i=!hNc(t);return e&&(i||r==!1)?yNc(e,t):t}var mH_=ue(bNc(),1),AH_=ue(require("http"),1),PH_=ue(require("https"),1),jH_=ue(require("util"),1),wH_=ue(aH_(),1),gQi=ue(require("zlib"),1);var ayn="1.12.2";function zGa(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var ghD=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function BNc(e,t,r){let i=r&&r.Blob||vA.classes.Blob,n=zGa(e);if(t===void 0&&i&&(t=!0),n==="data"){e=n.length?e.slice(n.length+1):e;let a=ghD.exec(e);if(!a)throw new za("Invalid URL",za.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 za("Blob is not supported",za.ERR_NOT_SUPPORT);return new i([s],{type:o})}return s}throw new za("Unsupported protocol "+n,za.ERR_NOT_SUPPORT)}var uyn=ue(require("stream"),1);var oH_=ue(require("stream"),1);var INc=Symbol("internals"),CNc=class extends oH_.default.Transform{constructor(t){t=ir.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(i,n)=>!ir.isUndefined(n[i])),super({readableHighWaterMark:t.chunkSize});let r=this[INc]={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[INc];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,i){let n=this[INc],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,l=(_,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,g,m=0;if(a){let O=Date.now();(!n.ts||(m=O-n.ts)>=c)&&(n.ts=O,g=s-n.bytes,n.bytes=g<0?-g:0,m=0),g=s-n.bytes}if(a){if(g<=0)return setTimeout(()=>{h(null,_)},c-m);g<v&&(v=g)}v&&y>v&&y-v>u&&(b=_.subarray(v),_=_.subarray(0,v)),l(_,b?()=>{process.nextTick(h,null,b)}:h)};p(t,function _(h,y){if(h)return i(h);y?p(y,_):i(null)})}},qNc=CNc;var EH_=require("events");var sH_=ue(require("util"),1),cH_=require("stream");var{asyncIterator:uH_}=Symbol,OhD=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[uH_]?yield*e[uH_]():yield e},sZo=OhD;var mhD=vA.ALPHABET.ALPHA_DIGIT+"-_",NGa=typeof TextEncoder=="function"?new TextEncoder:new sH_.default.TextEncoder,oyn=`\r
1267
1267
  `,AhD=NGa.encode(oyn),PhD=2,TNc=class{constructor(t,r){let{escapeName:i}=this.constructor,n=ir.isString(r),a=`Content-Disposition: form-data; name="${i(t)}"${!n&&r.name?`; filename="${i(r.name)}"`:""}${oyn}`;n?r=NGa.encode(String(r).replace(/\r?\n|\r\n?/g,oyn)):a+=`Content-Type: ${r.type||"application/octet-stream"}${oyn}`,this.headers=NGa.encode(a+oyn),this.contentLength=n?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+PhD,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;ir.isTypedArray(t)?yield t:yield*sZo(t),yield AhD}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},jhD=(e,t,r)=>{let{tag:i="form-data-boundary",size:n=25,boundary:a=i+"-"+vA.generateString(n,mhD)}=r||{};if(!ir.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=NGa.encode("--"+a+oyn),c=NGa.encode("--"+a+"--"+oyn),d=c.byteLength,s=Array.from(e.entries()).map(([l,p])=>{let _=new TNc(l,p);return d+=_.size,_});d+=o.byteLength*s.length,d=ir.toFiniteNumber(d);let u={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(d)&&(u["Content-Length"]=d),t&&t(u),cH_.Readable.from((async function*(){for(let l of s)yield o,yield*l.encode();yield c})())},lH_=jhD;var fH_=ue(require("stream"),1),RNc=class extends fH_.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)}},dH_=RNc;var whD=(e,t)=>ir.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,pH_=whD;function EhD(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 l=a,p=0;for(;l!==n;)p+=r[l++],l=l%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 _H_=EhD;function ShD(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(),l=u-r;l>=i?o(s,u):(n=s,a||(a=setTimeout(()=>{a=null,o(n)},i-l)))},()=>n&&o(n)]}var hH_=ShD;var vQi=(e,t,r=3)=>{let i=0,n=_H_(50,250);return hH_(a=>{let o=a.loaded,c=a.lengthComputable?a.total:void 0,d=o-i,s=n(d),u=o<=c;i=o;let l={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(l)},r)},tra=(e,t)=>{let r=e!=null;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},rra=e=>(...t)=>ir.asap(()=>e(...t));function zNc(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 l=Math.floor(a/4)*3-(c||0);return l>0?l:0}return Buffer.byteLength(i,"utf8")}var yH_={flush:gQi.default.constants.Z_SYNC_FLUSH,finishFlush:gQi.default.constants.Z_SYNC_FLUSH},MhD={flush:gQi.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:gQi.default.constants.BROTLI_OPERATION_FLUSH},bH_=ir.isFunction(gQi.default.createBrotliDecompress),{http:DhD,https:BhD}=wH_.default,IhD=/https:?/,vH_=vA.protocols.map(e=>e+":"),gH_=(e,[t,r])=>(e.on("end",r).on("error",r),t);function ChD(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function SH_(e,t,r){let i=t;if(!i&&i!==!1){let n=mH_.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){SH_(a,t,a.href)}}var qhD=typeof process<"u"&&ir.kindOf(process)==="process",ThD=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)}),RhD=({address:e,family:t})=>{if(!ir.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},OH_=(e,t)=>RhD(ir.isObject(e)?e:{address:e,family:t}),MH_=qhD&&function(t){return ThD(async function(i,n,a){let{data:o,lookup:c,family:d}=t,{responseType:s,responseEncoding:u}=t,l=t.method.toUpperCase(),p,_=!1,h;if(c){let $=pH_(c,de=>ir.isArray(de)?de:[de]);c=(de,be,W)=>{$(de,be,(x,Ee,se)=>{if(x)return W(x);let Oe=ir.isArray(Ee)?Ee.map(Fe=>OH_(Fe)):[OH_(Ee,se)];be.all?W(x,Oe):W(x,Oe[0].address,Oe[0].family)})}}let y=new EH_.EventEmitter,b=()=>{t.cancelToken&&t.cancelToken.unsubscribe(v),t.signal&&t.signal.removeEventListener("abort",v),y.removeAllListeners()};a(($,de)=>{p=!0,de&&(_=!0,b())});function v($){y.emit("abort",!$||$.type?new Rve(null,t,h):$)}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 g=ryn(t.baseURL,t.url,t.allowAbsoluteUrls),m=new URL(g,vA.hasBrowserEnv?vA.origin:void 0),O=m.protocol||vH_[0];if(O==="data:"){if(t.maxContentLength>-1){let de=String(t.url||g||"");if(zNc(de)>t.maxContentLength)return n(new za("maxContentLength size of "+t.maxContentLength+" exceeded",za.ERR_BAD_RESPONSE,t))}let $;if(l!=="GET")return N$t(i,n,{status:405,statusText:"method not allowed",headers:{},config:t});try{$=BNc(t.url,s==="blob",{Blob:t.env&&t.env.Blob})}catch(de){throw za.from(de,za.ERR_BAD_REQUEST,t)}return s==="text"?($=$.toString(u),(!u||u==="utf8")&&($=ir.stripBOM($))):s==="stream"&&($=uyn.default.Readable.from($)),N$t(i,n,{data:$,status:200,statusText:"OK",headers:new mD,config:t})}if(vH_.indexOf(O)===-1)return n(new za("Unsupported protocol "+O,za.ERR_BAD_REQUEST,t));let A=mD.from(t.headers).normalize();A.set("User-Agent","axios/"+ayn,!1);let{onUploadProgress:j,onDownloadProgress:M}=t,w=t.maxRate,D,B;if(ir.isSpecCompliantForm(o)){let $=A.getContentType(/boundary=([-_\w\d]{10,70})/i);o=lH_(o,de=>{A.set(de)},{tag:`axios-${ayn}-boundary`,boundary:$&&$[1]||void 0})}else if(ir.isFormData(o)&&ir.isFunction(o.getHeaders)){if(A.set(o.getHeaders()),!A.hasContentLength())try{let $=await jH_.default.promisify(o.getLength).call(o);Number.isFinite($)&&$>=0&&A.setContentLength($)}catch{}}else if(ir.isBlob(o)||ir.isFile(o))o.size&&A.setContentType(o.type||"application/octet-stream"),A.setContentLength(o.size||0),o=uyn.default.Readable.from(sZo(o));else if(o&&!ir.isStream(o)){if(!Buffer.isBuffer(o))if(ir.isArrayBuffer(o))o=Buffer.from(new Uint8Array(o));else if(ir.isString(o))o=Buffer.from(o,"utf-8");else return n(new za("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",za.ERR_BAD_REQUEST,t));if(A.setContentLength(o.length,!1),t.maxBodyLength>-1&&o.length>t.maxBodyLength)return n(new za("Request body larger than maxBodyLength limit",za.ERR_BAD_REQUEST,t))}let T=ir.toFiniteNumber(A.getContentLength());ir.isArray(w)?(D=w[0],B=w[1]):D=B=w,o&&(j||D)&&(ir.isStream(o)||(o=uyn.default.Readable.from(o,{objectMode:!1})),o=uyn.default.pipeline([o,new qNc({maxRate:ir.toFiniteNumber(D)})],ir.noop),j&&o.on("progress",gH_(o,tra(T,vQi(rra(j),!1,3)))));let R;if(t.auth){let $=t.auth.username||"",de=t.auth.password||"";R=$+":"+de}if(!R&&m.username){let $=m.username,de=m.password;R=$+":"+de}R&&A.delete("authorization");let q;try{q=tyn(m.pathname+m.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch($){let de=new Error($.message);return de.config=t,de.url=t.url,de.exists=!0,n(de)}A.set("Accept-Encoding","gzip, compress, deflate"+(bH_?", br":""),!1);let z={path:q,method:l,headers:A.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:R,protocol:O,family:d,beforeRedirect:ChD,beforeRedirects:{}};!ir.isUndefined(c)&&(z.lookup=c),t.socketPath?z.socketPath=t.socketPath:(z.hostname=m.hostname.startsWith("[")?m.hostname.slice(1,-1):m.hostname,z.port=m.port,SH_(z,t.proxy,O+"//"+m.hostname+(m.port?":"+m.port:"")+z.path));let N,H=IhD.test(z.protocol);if(z.agent=H?t.httpsAgent:t.httpAgent,t.transport?N=t.transport:t.maxRedirects===0?N=H?PH_.default:AH_.default:(t.maxRedirects&&(z.maxRedirects=t.maxRedirects),t.beforeRedirect&&(z.beforeRedirects.config=t.beforeRedirect),N=H?BhD:DhD),t.maxBodyLength>-1?z.maxBodyLength=t.maxBodyLength:z.maxBodyLength=1/0,t.insecureHTTPParser&&(z.insecureHTTPParser=t.insecureHTTPParser),h=N.request(z,function(de){if(h.destroyed)return;let be=[de],W=+de.headers["content-length"];if(M||B){let Fe=new qNc({maxRate:ir.toFiniteNumber(B)});M&&Fe.on("progress",gH_(Fe,tra(W,vQi(rra(M),!0,3)))),be.push(Fe)}let x=de,Ee=de.req||h;if(t.decompress!==!1&&de.headers["content-encoding"])switch((l==="HEAD"||de.statusCode===204)&&delete de.headers["content-encoding"],(de.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":be.push(gQi.default.createUnzip(yH_)),delete de.headers["content-encoding"];break;case"deflate":be.push(new dH_),be.push(gQi.default.createUnzip(yH_)),delete de.headers["content-encoding"];break;case"br":bH_&&(be.push(gQi.default.createBrotliDecompress(MhD)),delete de.headers["content-encoding"])}x=be.length>1?uyn.default.pipeline(be,ir.noop):be[0];let se=uyn.default.finished(x,()=>{se(),b()}),Oe={status:de.statusCode,statusText:de.statusMessage,headers:new mD(de.headers),config:t,request:Ee};if(s==="stream")Oe.data=x,N$t(i,n,Oe);else{let Fe=[],ae=0;x.on("data",function(Ge){Fe.push(Ge),ae+=Ge.length,t.maxContentLength>-1&&ae>t.maxContentLength&&(_=!0,x.destroy(),n(new za("maxContentLength size of "+t.maxContentLength+" exceeded",za.ERR_BAD_RESPONSE,t,Ee)))}),x.on("aborted",function(){if(_)return;let Ge=new za("stream has been aborted",za.ERR_BAD_RESPONSE,t,Ee);x.destroy(Ge),n(Ge)}),x.on("error",function(Ge){h.destroyed||n(za.from(Ge,null,t,Ee))}),x.on("end",function(){try{let Ge=Fe.length===1?Fe[0]:Buffer.concat(Fe);s!=="arraybuffer"&&(Ge=Ge.toString(u),(!u||u==="utf8")&&(Ge=ir.stripBOM(Ge))),Oe.data=Ge}catch(Ge){return n(za.from(Ge,null,t,Oe.request,Oe))}N$t(i,n,Oe)})}y.once("abort",Fe=>{x.destroyed||(x.emit("error",Fe),x.destroy())})}),y.once("abort",$=>{n($),h.destroy($)}),h.on("error",function(de){n(za.from(de,null,t,h))}),h.on("socket",function(de){de.setKeepAlive(!0,1e3*60)}),t.timeout){let $=parseInt(t.timeout,10);if(Number.isNaN($)){n(new za("error trying to parse `config.timeout` to int",za.ERR_BAD_OPTION_VALUE,t,h));return}h.setTimeout($,function(){if(p)return;let be=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",W=t.transitional||Xta;t.timeoutErrorMessage&&(be=t.timeoutErrorMessage),n(new za(be,W.clarifyTimeoutError?za.ETIMEDOUT:za.ECONNABORTED,t,h)),v()})}if(ir.isStream(o)){let $=!1,de=!1;o.on("end",()=>{$=!0}),o.once("error",be=>{de=!0,h.destroy(be)}),o.on("close",()=>{!$&&!de&&v(new Rve("Request stream has been aborted",t,h))}),o.pipe(h)}else h.end(o)})};var DH_=vA.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,vA.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(vA.origin),vA.navigator&&/(msie|trident)/i.test(vA.navigator.userAgent)):()=>!0;var BH_=vA.hasStandardBrowserEnv?{write(e,t,r,i,n,a){let o=[e+"="+encodeURIComponent(t)];ir.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),ir.isString(i)&&o.push("path="+i),ir.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 IH_=e=>e instanceof mD?{...e}:e;function H3t(e,t){t=t||{};let r={};function i(s,u,l,p){return ir.isPlainObject(s)&&ir.isPlainObject(u)?ir.merge.call({caseless:p},s,u):ir.isPlainObject(u)?ir.merge({},u):ir.isArray(u)?u.slice():u}function n(s,u,l,p){if(ir.isUndefined(u)){if(!ir.isUndefined(s))return i(void 0,s,l,p)}else return i(s,u,l,p)}function a(s,u){if(!ir.isUndefined(u))return i(void 0,u)}function o(s,u){if(ir.isUndefined(u)){if(!ir.isUndefined(s))return i(void 0,s)}else return i(void 0,u)}function c(s,u,l){if(l in t)return i(s,u);if(l 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,l)=>n(IH_(s),IH_(u),l,!0)};return ir.forEach(Object.keys({...e,...t}),function(u){let l=d[u]||n,p=l(e[u],t[u],u);ir.isUndefined(p)&&l!==c||(r[u]=p)}),r}var cZo=e=>{let t=H3t({},e),{data:r,withXSRFToken:i,xsrfHeaderName:n,xsrfCookieName:a,headers:o,auth:c}=t;if(t.headers=o=mD.from(o),t.url=tyn(ryn(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&o.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),ir.isFormData(r)){if(vA.hasStandardBrowserEnv||vA.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if(ir.isFunction(r.getHeaders)){let d=r.getHeaders(),s=["content-type","content-length"];Object.entries(d).forEach(([u,l])=>{s.includes(u.toLowerCase())&&o.set(u,l)})}}if(vA.hasStandardBrowserEnv&&(i&&ir.isFunction(i)&&(i=i(t)),i||i!==!1&&DH_(t.url))){let d=n&&a&&BH_.read(a);d&&o.set(n,d)}return t};var zhD=typeof XMLHttpRequest<"u",CH_=zhD&&function(e){return new Promise(function(r,i){let n=cZo(e),a=n.data,o=mD.from(n.headers).normalize(),{responseType:c,onUploadProgress:d,onDownloadProgress:s}=n,u,l,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 m=mD.from("getAllResponseHeaders"in b&&b.getAllResponseHeaders()),A={data:!c||c==="text"||c==="json"?b.responseText:b.response,status:b.status,statusText:b.statusText,headers:m,config:e,request:b};N$t(function(M){r(M),y()},function(M){i(M),y()},A),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 za("Request aborted",za.ECONNABORTED,e,b)),b=null)},b.onerror=function(O){let A=O&&O.message?O.message:"Network Error",j=new za(A,za.ERR_NETWORK,e,b);j.event=O||null,i(j),b=null},b.ontimeout=function(){let O=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded",A=n.transitional||Xta;n.timeoutErrorMessage&&(O=n.timeoutErrorMessage),i(new za(O,A.clarifyTimeoutError?za.ETIMEDOUT:za.ECONNABORTED,e,b)),b=null},a===void 0&&o.setContentType(null),"setRequestHeader"in b&&ir.forEach(o.toJSON(),function(O,A){b.setRequestHeader(A,O)}),ir.isUndefined(n.withCredentials)||(b.withCredentials=!!n.withCredentials),c&&c!=="json"&&(b.responseType=n.responseType),s&&([p,h]=vQi(s,!0),b.addEventListener("progress",p)),d&&b.upload&&([l,_]=vQi(d),b.upload.addEventListener("progress",l),b.upload.addEventListener("loadend",_)),(n.cancelToken||n.signal)&&(u=m=>{b&&(i(!m||m.type?new Rve(null,e,b):m),b.abort(),b=null)},n.cancelToken&&n.cancelToken.subscribe(u),n.signal&&(n.signal.aborted?u():n.signal.addEventListener("abort",u)));let g=zGa(n.url);if(g&&vA.protocols.indexOf(g)===-1){i(new za("Unsupported protocol "+g+":",za.ERR_BAD_REQUEST,e));return}b.send(a||null)})};var NhD=(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 za?u:new Rve(u instanceof Error?u.message:u))}},o=t&&setTimeout(()=>{o=null,a(new za(`timeout ${t} of ms exceeded`,za.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=()=>ir.asap(c),d}},qH_=NhD;var FhD=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},QhD=async function*(e,t){for await(let r of UhD(e))yield*FhD(r,t)},UhD=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()}},NNc=(e,t,r,i)=>{let n=QhD(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 l=u.byteLength;if(r){let p=a+=l;r(p)}d.enqueue(new Uint8Array(u))}catch(s){throw c(s),s}},cancel(d){return c(d),n.return()}},{highWaterMark:2})};var TH_=64*1024,{isFunction:lZo}=ir,LhD=(({Request:e,Response:t})=>({Request:e,Response:t}))(ir.global),{ReadableStream:RH_,TextEncoder:zH_}=ir.global,NH_=(e,...t)=>{try{return!!e(...t)}catch{return!1}},VhD=e=>{e=ir.merge.call({skipUndefined:!0},LhD,e);let{fetch:t,Request:r,Response:i}=e,n=t?lZo(t):typeof fetch=="function",a=lZo(r),o=lZo(i);if(!n)return!1;let c=n&&lZo(RH_),d=n&&(typeof zH_=="function"?(h=>y=>h.encode(y))(new zH_):async h=>new Uint8Array(await new r(h).arrayBuffer())),s=a&&c&&NH_(()=>{let h=!1,y=new r(vA.origin,{body:new RH_,method:"POST",get duplex(){return h=!0,"half"}}).headers.has("Content-Type");return h&&!y}),u=o&&c&&NH_(()=>ir.isReadableStream(new i("").body)),l={stream:u&&(h=>h.body)};n&&["text","arrayBuffer","blob","formData","stream"].forEach(h=>{!l[h]&&(l[h]=(y,b)=>{let v=y&&y[h];if(v)return v.call(y);throw new za(`Response type '${h}' is not supported`,za.ERR_NOT_SUPPORT,b)})});let p=async h=>{if(h==null)return 0;if(ir.isBlob(h))return h.size;if(ir.isSpecCompliantForm(h))return(await new r(vA.origin,{method:"POST",body:h}).arrayBuffer()).byteLength;if(ir.isArrayBufferView(h)||ir.isArrayBuffer(h))return h.byteLength;if(ir.isURLSearchParams(h)&&(h=h+""),ir.isString(h))return(await d(h)).byteLength},_=async(h,y)=>{let b=ir.toFiniteNumber(h.getContentLength());return b??p(y)};return async h=>{let{url:y,method:b,data:v,signal:g,cancelToken:m,timeout:O,onDownloadProgress:A,onUploadProgress:j,responseType:M,headers:w,withCredentials:D="same-origin",fetchOptions:B}=cZo(h),T=t||fetch;M=M?(M+"").toLowerCase():"text";let R=qH_([g,m&&m.toAbortSignal()],O),q=null,z=R&&R.unsubscribe&&(()=>{R.unsubscribe()}),N;try{if(j&&s&&b!=="get"&&b!=="head"&&(N=await _(w,v))!==0){let x=new r(y,{method:"POST",body:v,duplex:"half"}),Ee;if(ir.isFormData(v)&&(Ee=x.headers.get("content-type"))&&w.setContentType(Ee),x.body){let[se,Oe]=tra(N,vQi(rra(j)));v=NNc(x.body,TH_,se,Oe)}}ir.isString(D)||(D=D?"include":"omit");let H=a&&"credentials"in r.prototype,$={...B,signal:R,method:b.toUpperCase(),headers:w.normalize().toJSON(),body:v,duplex:"half",credentials:H?D:void 0};q=a&&new r(y,$);let de=await(a?T(q,B):T(y,$)),be=u&&(M==="stream"||M==="response");if(u&&(A||be&&z)){let x={};["status","statusText","headers"].forEach(Fe=>{x[Fe]=de[Fe]});let Ee=ir.toFiniteNumber(de.headers.get("content-length")),[se,Oe]=A&&tra(Ee,vQi(rra(A),!0))||[];de=new i(NNc(de.body,TH_,se,()=>{Oe&&Oe(),z&&z()}),x)}M=M||"text";let W=await l[ir.findKey(l,M)||"text"](de,h);return!be&&z&&z(),await new Promise((x,Ee)=>{N$t(x,Ee,{data:W,headers:mD.from(de.headers),status:de.status,statusText:de.statusText,config:h,request:q})})}catch(H){throw z&&z(),H&&H.name==="TypeError"&&/Load failed|fetch/i.test(H.message)?Object.assign(new za("Network Error",za.ERR_NETWORK,h,q),{cause:H.cause||H}):za.from(H,H&&H.code,h,q)}}},WhD=new Map,FNc=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=WhD;for(;c--;)d=a[c],s=u.get(d),s===void 0&&u.set(d,s=c?new Map:VhD(t)),u=s;return s},X69=FNc();var QNc={http:MH_,xhr:CH_,fetch:{get:FNc}};ir.forEach(QNc,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var FH_=e=>`- ${e}`,xhD=e=>ir.isFunction(e)||e===null||e===!1,fZo={getAdapter:(e,t)=>{e=ir.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,!xhD(i)&&(n=QNc[(c=String(i)).toLowerCase()],n===void 0))throw new za(`Unknown adapter '${c}'`);if(n&&(ir.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 :
@@ -1465,7 +1465,7 @@ For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides
1465
1465
  `)),super.launch(t)}async computeLaunchArguments(t={}){let{ignoreDefaultArgs:r=!1,args:i=[],pipe:n=!1,debuggingPort:a,channel:o,executablePath:c}=t,d=[];r?Array.isArray(r)?d.push(...this.defaultArgs(t).filter(_=>!r.includes(_))):d.push(...i):d.push(...this.defaultArgs(t)),d.some(_=>_.startsWith("--remote-debugging-"))||(n?(Ti(!a,"Browser should be launched with either pipe or debugging port - not both."),d.push("--remote-debugging-pipe")):d.push(`--remote-debugging-port=${a||0}`));let s=!1,u=d.findIndex(_=>_.startsWith("--user-data-dir"));u<0&&(s=!0,d.push(`--user-data-dir=${await(0,ish.mkdtemp)(this.getProfilePath())}`),u=d.length-1);let l=d[u].split("=",2)[1];Ti(typeof l=="string","`--user-data-dir` is malformed");let p=c;return p||(Ti(o||!this.puppeteer._isPuppeteerCore,"An `executablePath` or `channel` must be specified for `puppeteer-core`"),p=o?this.executablePath(o):this.resolveExecutablePath(t.headless??!0)),{executablePath:p,args:d,isTempUserDataDir:s,userDataDir:l}}async cleanUserDataDir(t,r){if(r.isTemp)try{await cnu(t)}catch(i){throw Ui(i),i}}defaultArgs(t={}){let r=tsh("--disable-features",t.args);t.args&&r.length>0&&rsh(t.args,"--disable-features");let n=["Translate","AcceptCHFrame","MediaRouter","OptimizationHints","RenderDocument",...process.env.PUPPETEER_TEST_EXPERIMENTAL_CHROME_FEATURES==="true"?[]:["ProcessPerSiteUpToMainFrameThreshold","IsolateSandboxedIframes"],...r].filter(_=>_!==""),a=tsh("--enable-features",t.args);t.args&&a.length>0&&rsh(t.args,"--enable-features");let o=["PdfOopif",...a].filter(_=>_!==""),c=["--allow-pre-commit-input","--disable-background-networking","--disable-background-timer-throttling","--disable-backgrounding-occluded-windows","--disable-breakpad","--disable-client-side-phishing-detection","--disable-component-extensions-with-background-pages","--disable-crash-reporter","--disable-default-apps","--disable-dev-shm-usage","--disable-hang-monitor","--disable-infobars","--disable-ipc-flooding-protection","--disable-popup-blocking","--disable-prompt-on-repost","--disable-renderer-backgrounding","--disable-search-engine-choice-screen","--disable-sync","--enable-automation","--export-tagged-pdf","--force-color-profile=srgb","--generate-pdf-document-outline","--metrics-recording-only","--no-first-run","--password-store=basic","--use-mock-keychain",`--disable-features=${n.join(",")}`,`--enable-features=${o.join(",")}`].filter(_=>_!==""),{devtools:d=!1,headless:s=!d,args:u=[],userDataDir:l,enableExtensions:p=!1}=t;return l&&c.push(`--user-data-dir=${ash.default.resolve(l)}`),d&&c.push("--auto-open-devtools-for-tabs"),s&&c.push(s==="shell"?"--headless":"--headless=new","--hide-scrollbars","--mute-audio"),c.push(p?"--enable-unsafe-extension-debugging":"--disable-extensions"),u.every(_=>_.startsWith("-"))&&c.push("about:blank"),c.push(...u),c}executablePath(t,r=!0){return t?anu({browser:Nc.CHROME,channel:FFD(t)}):this.resolveExecutablePath(void 0,r)}};function FFD(e){switch(e){case"chrome":return Dg.STABLE;case"chrome-dev":return Dg.DEV;case"chrome-beta":return Dg.BETA;case"chrome-canary":return Dg.CANARY}}function tsh(e,t=[]){return t.filter(r=>r.startsWith(e.endsWith("=")?e:`${e}=`)).map(r=>r.split(new RegExp(`${e}=\\s*`))[1]?.trim()).filter(r=>r)}function rsh(e,t){let r=new RegExp(`^${t}=.*`),i=0;for(;i<e.length;)r.test(e[i])?e.splice(i,1):i++;return e}var osh=ue(require("fs"),1),Fna=require("fs/promises"),ush=ue(require("os"),1),o6c=ue(require("path"),1);wd();$A();var fnu=class e extends Nna{constructor(t){super(t,"firefox")}static getPreferences(t){return{...t,"fission.webContentIsolationStrategy":0}}async computeLaunchArguments(t={}){let{ignoreDefaultArgs:r=!1,args:i=[],executablePath:n,pipe:a=!1,extraPrefsFirefox:o={},debuggingPort:c=null}=t,d=[];r?Array.isArray(r)?d.push(...this.defaultArgs(t).filter(_=>!r.includes(_))):d.push(...i):d.push(...this.defaultArgs(t)),d.some(_=>_.startsWith("--remote-debugging-"))||(a&&Ti(c===null,"Browser should be launched with either pipe or debugging port - not both."),d.push(`--remote-debugging-port=${c||0}`));let s,u=!0,l=d.findIndex(_=>["-profile","--profile"].includes(_));if(l!==-1){if(s=d[l+1],!s)throw new Error("Missing value for profile command line argument");u=!1}else s=await(0,Fna.mkdtemp)(this.getProfilePath()),d.push("--profile"),d.push(s);await $5c(Nc.FIREFOX,{path:s,preferences:e.getPreferences(o)});let p;return this.puppeteer._isPuppeteerCore||n?(Ti(n,"An `executablePath` must be specified for `puppeteer-core`"),p=n):p=this.executablePath(void 0),{isTempUserDataDir:u,userDataDir:s,args:d,executablePath:p}}async cleanUserDataDir(t,r){if(r.isTemp)try{await cnu(t)}catch(i){throw Ui(i),i}else try{let i=".puppeteer",n=["prefs.js","user.js"],a=await Promise.allSettled(n.map(async o=>{let c=o6c.default.join(t,o+i);if(osh.default.existsSync(c)){let d=o6c.default.join(t,o);await(0,Fna.unlink)(d),await(0,Fna.rename)(c,d)}}));for(let o of a)if(o.status==="rejected")throw o.reason}catch(i){Ui(i)}}executablePath(t,r=!0){return this.resolveExecutablePath(void 0,r)}defaultArgs(t={}){let{devtools:r=!1,headless:i=!r,args:n=[],userDataDir:a=null}=t,o=[];switch(ush.default.platform()){case"darwin":o.push("--foreground");break;case"win32":o.push("--wait-for-browser");break}return a&&(o.push("--profile"),o.push(a)),i&&o.push("--headless"),r&&o.push("--devtools"),n.every(c=>c.startsWith("-"))&&o.push("about:blank"),o.push(...n),o}};var Qna=class extends sru{#e;#t;defaultBrowserRevision;configuration={};constructor(t){let{configuration:r,...i}=t;switch(super(i),r&&(this.configuration=r),this.configuration.defaultBrowser){case"firefox":this.defaultBrowserRevision=Jia.firefox;break;default:this.configuration.defaultBrowser="chrome",this.defaultBrowserRevision=Jia.chrome;break}this.connect=this.connect.bind(this),this.launch=this.launch.bind(this),this.executablePath=this.executablePath.bind(this),this.defaultArgs=this.defaultArgs.bind(this),this.trimCache=this.trimCache.bind(this)}connect(t){return super.connect(t)}launch(t={}){let{browser:r=this.defaultBrowser}=t;switch(this.#t=r,r){case"chrome":this.defaultBrowserRevision=Jia.chrome;break;case"firefox":this.defaultBrowserRevision=Jia.firefox;break;default:throw new Error(`Unknown product: ${r}`)}return this.#e=this.#r(r),this.#e.launch(t)}#r(t){if(this.#e&&this.#e.browser===t)return this.#e;switch(t){case"chrome":return new lnu(this);case"firefox":return new fnu(this);default:throw new Error(`Unknown product: ${t}`)}}executablePath(t){return t===void 0?this.#r(this.lastLaunchedBrowser).executablePath(void 0,!1):typeof t=="string"?this.#r("chrome").executablePath(t,!1):this.#r(t.browser??this.lastLaunchedBrowser).resolveExecutablePath(t.headless,!1)}get browserVersion(){return this.configuration?.[this.lastLaunchedBrowser]?.version??this.defaultBrowserRevision}get defaultDownloadPath(){return this.configuration.cacheDirectory}get lastLaunchedBrowser(){return this.#t??this.defaultBrowser}get defaultBrowser(){return this.configuration.defaultBrowser??"chrome"}get product(){return this.lastLaunchedBrowser}defaultArgs(t={}){return this.#r(t.browser??this.lastLaunchedBrowser).defaultArgs(t)}async trimCache(){let t=o8t();if(!t)throw new Error("The current platform is not supported.");let r=this.configuration.cacheDirectory,i=await a6c({cacheDir:r}),n=[{product:"chrome",browser:Nc.CHROME,currentBuildId:""},{product:"firefox",browser:Nc.FIREFOX,currentBuildId:""}];for(let c of n){let d=this.configuration?.[c.product]?.version??Jia[c.product];c.currentBuildId=await kiu(c.browser,t,d)}let a=new Set(n.map(c=>`${c.browser}_${c.currentBuildId}`)),o=new Set(n.map(c=>c.browser));for(let c of i)o.has(c.browser)&&(a.has(`${c.browser}_${c.buildId}`)||await n6c({browser:c.browser,platform:t,cacheDir:r,buildId:c.buildId}))}};var dnu=require("child_process"),lsh=ue(require("fs"),1),fsh=ue(require("os"),1),dsh=require("path"),psh=require("stream"),_sh=ue(vD(),1);lEe();$$();wd();cC();JA();var QFD=function(e,t,r){for(var i=arguments.length>2,n=0;n<t.length;n++)r=i?t[n].call(e,r):t[n].call(e);return i?r:void 0},ssh=function(e,t,r,i,n,a){function o(v){if(v!==void 0&&typeof v!="function")throw new TypeError("Function expected");return v}for(var c=i.kind,d=c==="getter"?"get":c==="setter"?"set":"value",s=!t&&e?i.static?e:e.prototype:null,u=t||(s?Object.getOwnPropertyDescriptor(s,i.name):{}),l,p=!1,_=r.length-1;_>=0;_--){var h={};for(var y in i)h[y]=y==="access"?{}:i[y];for(var y in i.access)h.access[y]=i.access[y];h.addInitializer=function(v){if(p)throw new TypeError("Cannot add initializers after decoration has completed");a.push(o(v||null))};var b=(0,r[_])(c==="accessor"?{get:u.get,set:u.set}:u[d],h);if(c==="accessor"){if(b===void 0)continue;if(b===null||typeof b!="object")throw new TypeError("Object expected");(l=o(b.get))&&(u.get=l),(l=o(b.set))&&(u.set=l),(l=o(b.init))&&n.unshift(l)}else(l=o(b))&&(c==="field"?n.unshift(l):u[d]=l)}s&&Object.defineProperty(s,i.name,u),p=!0},UFD=function(e,t,r){return typeof t=="symbol"&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(e,"name",{configurable:!0,value:r?"".concat(r," ",t):t})},LFD=30,csh=30,VFD=(0,_sh.default)("puppeteer:ffmpeg"),hsh=(()=>{let e=psh.PassThrough,t=[],r,i,n;return class extends e{static{let o=typeof Symbol=="function"&&Symbol.metadata?Object.create(e[Symbol.metadata]??null):void 0;ssh(this,i={value:UFD(async function(c){let d=await new Promise(s=>{this.#t.stdin.write(c,s)});d&&console.log(`ffmpeg failed to write: ${d.message}.`)},"#writeFrame")},r,{kind:"method",name:"#writeFrame",static:!1,private:!0,access:{has:c=>#o in c,get:c=>c.#o},metadata:o},null,t),ssh(this,null,n,{kind:"method",name:"stop",static:!1,private:!1,access:{has:c=>"stop"in c,get:c=>c.stop},metadata:o},null,t),o&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})}#e=QFD(this,t);#t;#r=new AbortController;#i;#n;constructor(o,c,d,{ffmpegPath:s,speed:u,scale:l,crop:p,format:_,fps:h,loop:y,delay:b,quality:v,colors:g,path:m,overwrite:O}={}){super({allowHalfOpen:!1}),s??="ffmpeg",_??="webm",h??=csh,y||=-1,b??=-1,v??=LFD,g??=256,O??=!0,this.#n=h;let{error:A}=(0,dnu.spawnSync)(s);if(A)throw A;let j=[`crop='min(${c},iw):min(${d},ih):0:0'`,`pad=${c}:${d}:0:0`];u&&j.push(`setpts=${1/u}*PTS`),p&&j.push(`crop=${p.width}:${p.height}:${p.x}:${p.y}`),l&&j.push(`scale=iw*${l}:-1:flags=lanczos`);let M=this.#a(_,h,y,b,v,g),w=M.indexOf("-vf");w!==-1&&j.push(M.splice(w,2).at(-1)??""),m&&lsh.default.mkdirSync((0,dsh.dirname)(m),{recursive:O}),this.#t=(0,dnu.spawn)(s,[["-loglevel","error"],["-avioflags","direct"],["-fpsprobesize","0","-probesize","32","-analyzeduration","0","-fflags","nobuffer"],["-f","image2pipe","-vcodec","png","-i","pipe:0"],["-an"],["-threads","1"],["-framerate",`${h}`],["-b:v","0"],M,["-vf",j.join()],[O?"-y":"-n"],"pipe:1"].flat(),{stdio:["pipe","pipe","pipe"]}),this.#t.stdout.pipe(this),this.#t.stderr.on("data",B=>{VFD(B.toString("utf8"))}),this.#e=o;let{client:D}=this.#e.mainFrame();D.once(Zv.Disconnected,()=>{this.stop().catch(Ui)}),this.#i=c2_(Sg(D,"Page.screencastFrame").pipe(Fyn(B=>{D.send("Page.screencastFrameAck",{sessionId:B.sessionId})}),Uve(B=>B.metadata.timestamp!==void 0),KA(B=>({buffer:Buffer.from(B.data,"base64"),timestamp:B.metadata.timestamp})),_2_(2,1),h2_(([{timestamp:B,buffer:T},{timestamp:R}])=>Id(Array(Math.round(h*Math.max(R-B,0))).fill(T))),KA(B=>(this.#o(B),[B,performance.now()])),eko(Tra(this.#r.signal,"abort"))),{defaultValue:[Buffer.from([]),performance.now()]})}#a(o,c,d,s,u,l){let p=[["-vcodec","vp9"],["-crf",`${u}`],["-deadline","realtime","-cpu-used",`${Math.min(fsh.default.cpus().length/2,8)}`]];switch(o){case"webm":return[...p,["-f","webm"]].flat();case"gif":return c=csh===c?20:"source_fps",d===1/0&&(d=0),s!==-1&&(s/=10),[["-vf",`fps=${c},split[s0][s1];[s0]palettegen=stats_mode=diff:max_colors=${l}[p];[s1][p]paletteuse=dither=bayer`],["-loop",`${d}`],["-final_delay",`${s}`],["-f","gif"]].flat();case"mp4":return[...p,["-movflags","hybrid_fragmented"],["-f","mp4"]].flat()}}get#o(){return i.value}async stop(){if(this.#r.signal.aborted)return;await this.#e._stopScreencast().catch(Ui),this.#r.abort();let[o,c]=await this.#i;await Promise.all(Array(Math.max(1,Math.round(this.#n*(performance.now()-c)/1e3))).fill(o).map(this.#o.bind(this))),this.#t.stdin.end(),await new Promise(d=>{this.#t.once("close",d)})}async[(r=[Kxa()],n=[Kxa()],uC)](){await this.stop()}}})();var ysh=ue(require("fs"),1),bsh=ue(require("path"),1);QQi();rx.value={fs:ysh.default,path:bsh.default,ScreenRecorder:hsh};var GFD=new Qna({isPuppeteerCore:!0}),{connect:cEG,defaultArgs:lEG,executablePath:fEG,launch:dEG}=GFD;var $lh=require("os"),Ylh=require("path"),Xlh=ue(Jlh(),1);function d9c(e){let t=process.env[e];if(t!==void 0)switch(t.toLowerCase()){case"":case"0":case"false":case"off":return!1;default:return!0}}function mLD(e){switch(e){case"chrome":case"firefox":return!0;default:return!1}}function ALD(e){if(e&&!mLD(e))throw new Error(`Unsupported browser ${e}`);switch(e){case"firefox":return"firefox";default:return"chrome"}}function PLD(e){switch(e){case"silent":return"silent";case"error":return"error";default:return"warn"}}function f9c(e,t,r={}){if(t.skipDownload)return{skipDownload:!0};let i={},n=e.replaceAll("-","_").toUpperCase();return i.version=process.env[`PUPPETEER_${n}_VERSION`]??t[e]?.version??r.version,i.downloadBaseUrl=process.env[`PUPPETEER_${n}_DOWNLOAD_BASE_URL`]??t[e]?.downloadBaseUrl??r.downloadBaseUrl,i.skipDownload=d9c(`PUPPETEER_${n}_SKIP_DOWNLOAD`)??d9c(`PUPPETEER_SKIP_${n}_DOWNLOAD`)??t[e]?.skipDownload??r.skipDownload,i}var Zlh=()=>{let e=(0,Xlh.cosmiconfigSync)("puppeteer",{searchStrategy:"global"}).search(),t=e?e.config:{};return t.logLevel=PLD(process.env.PUPPETEER_LOGLEVEL??t.logLevel),t.defaultBrowser=ALD(process.env.PUPPETEER_BROWSER??t.defaultBrowser),t.executablePath=process.env.PUPPETEER_EXECUTABLE_PATH??t.executablePath,t.executablePath&&(t.skipDownload=!0),t.skipDownload=d9c("PUPPETEER_SKIP_DOWNLOAD")??t.skipDownload,t.chrome=f9c("chrome",t),t["chrome-headless-shell"]=f9c("chrome-headless-shell",t),t.firefox=f9c("firefox",t,{skipDownload:!0}),t.cacheDirectory=process.env.PUPPETEER_CACHE_DIR??t.cacheDirectory??(0,Ylh.join)((0,$lh.homedir)(),".cache","puppeteer"),t.temporaryDirectory=process.env.PUPPETEER_TMP_DIR??t.temporaryDirectory,t.experiments??={},t};var jLD=Zlh(),wLD=new Qna({isPuppeteerCore:!1,configuration:jLD}),{connect:pSG,defaultArgs:_SG,executablePath:hSG,launch:klh,trimCache:ySG}=wLD;var ELD="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",SLD={"Accept-Language":"en-US,en;q=0.9",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36","Accept-Encoding":"gzip, deflate, br, zstd",Connection:"keep-alive"};async function M7a(e,t=3,r=1e3,i=2){try{return await e()}catch(n){if(t>0)return await new Promise(a=>setTimeout(a,r)),M7a(e,t-1,r*i,i);throw n}}async function efh(){try{return await klh({headless:!0,args:["--ignore-certificate-errors"]})}catch{throw new Error("Could not create a Puppeteer instance")}}async function MLD(e,t){try{let r=await e.newPage();await r.setViewport({width:3072,height:2048,deviceScaleFactor:2,isMobile:!1,hasTouch:!1,isLandscape:!0}),await r.setExtraHTTPHeaders(SLD),await r.setUserAgent(ELD),await r.setJavaScriptEnabled(!0),await M7a(()=>r.goto(t.toString(),{waitUntil:"networkidle2",timeout:3e4}));let i=await M7a(()=>r.content());return await r.close(),i}catch{throw new Error("Failed to download page from Puppeteer")}}async function DLD(e){try{let t=await fetch(e);if(!t.ok)throw new Error(`${t.status} ${t.statusText}`);return await t.text()}catch{throw new Error("Failed to fetch page from source")}}async function p9c({url:e,browser:t}){try{let r;if(t?r=await MLD(t,e):r=await M7a(()=>DLD(e)),r)return r;throw new Error("An unknown error occurred.")}catch{throw new Error(`Error retrieving HTML for ${e.toString()}`)}}async function tfh(e){try{let t=await M7a(()=>fetch(e));if(!t.ok)throw new Error(`${t.status} ${t.statusText}`);let r=await t.arrayBuffer();return new Uint8Array(r)}catch{throw new Error(`Failed to retrieve image from source url ${e}`)}}var BLD=["png","jpeg","jpg","webp","avif","svg","ico","jfif","pjpeg","pjp","svgz","bmp"];async function rfh(e){if(!e)return{success:!1,data:void 0};if(e.startsWith("data:image/"))return{success:!0,data:[e,e]};let t=(0,Yna.join)(process.cwd(),"fern");try{let r=await ILD(e,(0,Yna.join)(t,"images"));return r=r.replace(t,""),{success:!0,data:[e,r]}}catch{return{success:!1,data:void 0}}}async function ILD(e,t){let r=qLD(e),i=(0,Yna.join)(t,r);if(!CLD(r))throw new Error(`${r} - file extension not supported`);if((0,Bnu.existsSync)(i))return i;try{(0,Bnu.mkdirSync)((0,Yna.dirname)(i),{recursive:!0})}catch{throw new Error(`${i} - failed to create directory`)}try{let n=await tfh(e);return mX_(i,n),i}catch{throw new Error(`${i}: failed to download file from source`)}}function CLD(e){if(!e)return!1;let t=e.lastIndexOf(".")+1,r=e.substring(t);if(e===r)return!1;let i=r.toLowerCase();return!(i&&!BLD.includes(i))}function qLD(e){e.startsWith("http")&&(e=new URL(e).pathname);let t=e.split("#");if(t.length===0)return"image";let r=t[0];if(!r)return"image";let i=r.split("?");if(i.length===0)return"image";let n=i[0];return n&&decodeURIComponent(n.replace(/[/]{2,}/g,"/")).replace(/(?:_{2,}|[\s%#&{}\\<>*?$!'":@+`|=])/g,"-")||"image"}function TLD(e){let t=[];return Li(e,"element",r=>{r.tagName==="img"&&Array.isArray(r.properties.className)&&r.properties.className.includes("rm-Logo-img")&&t.push(r)}),t.length>0?t:void 0}async function ifh(e,t){let r=Cra(e),i=TLD(r);if(i!=null){let n=await Promise.all(i.map(async a=>{let o=await rfh(a.properties.src);return o.success&&o.data?o.data[1]:""}));t.push(...n)}for(let n=t.length-1;n>=0;n--)t[n]||t.splice(n,1)}var nfh=28;async function afh(e,t){e=new URL(e);let r=[];if(t){let n=[];try{let a=await t.newPage();await a.goto(e.toString(),{waitUntil:"networkidle2"}),n.push(await a.content()),await a.click(".rm-ThemeToggle"),n.push(await a.content())}catch{}await Promise.all(n.map(async a=>await ifh(a,r)))}let i=[...new Set(r).values()];if(i.length!==0){if(i.length===1&&i[0]!=null){let n=He.of(y8(i[0]));return{light:n,dark:n,height:nfh}}if(i[0]!=null&&i[1]!=null){let n=He.of(y8(i[0])),a=He.of(y8(i[1]));return{light:n,dark:a,height:nfh}}}}var Inu=class extends cyn{url;logger;absolutePathToFernDirectory;constructor(t){super({context:t.context}),this.url=typeof t.url=="string"?new URL(t.url):t.url,this.logger=t.context.logger,this.absolutePathToFernDirectory=t.absolutePathToFernDirectory}async import({args:t,builder:r}){r.setLayout({layout:HGa});let i=await this.getHastForUrl(this.url),n=qZ_(i)??[];if(n.length===0)this.logger.debug("No tabs found on the page");else{this.logger.debug(`Found ${n.length} tabs:`);for(let u of n)this.logger.debug(` - Tab: ${u.name} (${u.url})`)}for(let u of n){let l=await this.scrapeTab({name:u.name,url:u.url});if(!l)continue;let p=r.getNavigationBuilder({tabId:this.kebabCaseWithoutEmojis(u.name),tabConfig:{slug:u.url,displayName:u.name}}),_=Tt(this.absolutePathToFernDirectory,He.of(this.kebabCaseWithoutEmojis(u.name)));await this.downloadMarkdownPages({absolutePathToOutputDirectory:_,sections:l});let h=await this.getNavigationItems({absolutePathToOutputDirectory:_,sections:l});for(let y of h)p.addItem({item:y})}let a=await efh(),o=await afh(this.url,a);o!=null&&r.setLogo({logo:o});let c=await sK_(i);r.setTitle({title:c});let d=await nK_(i);if(d!=null){let u=await this.getAndCreateAssetsDirectory(),l=await fetch(d);if(l.ok){let p=Buffer.from(await l.arrayBuffer()),_=Tt(u,He.of("favicon"));await(0,XKi.writeFile)(_,new Uint8Array(p)),r.setFavicon({favicon:CJ(this.absolutePathToFernDirectory,_)})}}let s=await RZ_(i);r.setColors({colors:s}),a&&await a.close(),r.build({outputDirectory:this.absolutePathToFernDirectory})}async getAndCreateAssetsDirectory(){let t=Tt(this.absolutePathToFernDirectory,He.of("assets"));return await(0,XKi.mkdir)(t,{recursive:!0}),t}async scrapeTab({name:t,url:r}){try{this.logger.debug(`Scraping tab: ${t} (${r})`);let i=new URL(r,this.url),n=await this.getHastForUrl(i),a=BZ_(n);if(!a){this.logger.debug(`No sidebar element found for tab: ${t} (${r})`);return}let o=IZ_(a);return this.logger.debug(`Successfully scraped tab: ${t}`),o}catch(i){this.logger.error(`Failed to scrape tab ${t}: ${i instanceof Error?i.message:String(i)}`),i instanceof Error&&i.stack&&this.logger.error(`Stack trace: ${i.stack}`)}}async getHastForUrl(t){let r=await p9c({url:t});return Cra(r)}async downloadMarkdownPages({absolutePathToOutputDirectory:t,sections:r}){for(let i of r){this.logger.debug(`Processing section: ${i.group}`);let n=this.getAbsolutePathToOutputDirectoryForSection({absolutePathToOutputDirectory:t,section:i});await(0,XKi.mkdir)(n,{recursive:!0}),await Promise.all(i.pages.filter(a=>a.type==="page").map(async a=>{let o=new URL(a.slug.toString(),this.url);this.logger.debug(`Fetching page: ${o.toString()}`);let c=await p9c({url:o}),d=await DZ_({logger:this.logger,html:c,url:o});if(d.success&&d.data){let s=this.getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:n,page:a.slug});await(0,XKi.writeFile)(s,d.data.mdx),d.data.images.imageURLs.length>0&&(this.logger.debug(`Found ${d.data.images.imageURLs.length} images to download for ${o.toString()}`),await Promise.all(Object.entries(d.data.images.imageURLToFilename).map(async([u,l])=>{try{let p=await fetch(u);if(!p.ok){this.logger.warn(`Failed to download image ${u}, status: ${p.status}`);return}let _=Buffer.from(await p.arrayBuffer()),h=Tt(n,He.of(l)),y=rn(h);await(0,XKi.mkdir)(y,{recursive:!0}),await(0,XKi.writeFile)(h,new Uint8Array(_)),this.logger.debug(`Saved image to ${h}`)}catch(p){this.logger.warn(`Error downloading image ${u}: ${p}`)}})))}else this.logger.warn(`Failed to parse page ${o.toString()}, skipping`)})),await Promise.all(i.pages.filter(a=>a.type==="group").map(async a=>{this.logger.debug(`Processing nested group: ${a.group}`),await this.downloadMarkdownPages({absolutePathToOutputDirectory:n,sections:[{type:"group",group:a.group,pages:a.pages}]})}))}}async getNavigationItems({absolutePathToOutputDirectory:t,sections:r}){let i=[];for(let n of r){let a=this.getAbsolutePathToOutputDirectoryForSection({absolutePathToOutputDirectory:t,section:n}),o={section:n.group,contents:[],slug:this.kebabCaseWithoutEmojis(n.group)};for(let c of n.pages)if(c.type==="page")o.contents.push({page:c.page,path:CJ(this.absolutePathToFernDirectory,this.getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:a,page:c.slug}))});else{let d=await this.getNavigationItems({absolutePathToOutputDirectory:a,sections:[c]});o.contents.push(...d)}i.push(o)}return i}getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:t,page:r}){return Tt(t,He.of(`${this.kebabCaseWithoutEmojis(r.split("/").pop()||r)}.mdx`))}getAbsolutePathToOutputDirectoryForSection({absolutePathToOutputDirectory:t,section:r}){return Tt(t,He.of(this.kebabCaseWithoutEmojis(r.group)))}kebabCaseWithoutEmojis(t){return t.replace(/[\u{1F600}-\u{1F64F}\u{1F300}-\u{1F5FF}\u{1F680}-\u{1F6FF}\u{1F700}-\u{1F77F}\u{1F780}-\u{1F7FF}\u{1F800}-\u{1F8FF}\u{1F900}-\u{1F9FF}\u{1FA00}-\u{1FA6F}\u{1FA70}-\u{1FAFF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}]/gu,"").toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}};var ofh=require("fs/promises");async function _9c({readmeUrl:e,outputPath:t,taskContext:r,versionOfCli:i,organization:n}){let a=new lyn;a.setInstance({companyName:n}),await new Inu({url:e,context:r,builder:a,absolutePathToFernDirectory:Tt(Sr.of(process.cwd()),He.of("fern"))}).import({args:{},builder:a}),await a.build({outputDirectory:t}),await(0,ofh.writeFile)(Tt(Sr.of(t),He.of(uR),He.of(E4)),JSON.stringify({version:i,organization:n},void 0,4))}var h9c=async({readmeUrl:e,organization:t,taskContext:r,versionOfCli:i})=>{if(!e||!sdn(e)){r.failAndThrow("Provide a URL to a readme-generated site");return}let n=Sr.of(aA());await _9c({readmeUrl:e,outputPath:n,taskContext:r,versionOfCli:i,organization:t})};var ufh="0.0.0";var sfh={[an.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,Z0(e)])),[an.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"]),[an.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"]),[an.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"]),[an.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"]),[an.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"]),[an.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"]),[an.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"]),[an.GenerationLanguage.SWIFT]:new Set([])};var zLD=["go","ruby"];function lx({generationLanguage:e,keywords:t,smartCasing:r}){let i={generateName:(n,a)=>{let o=xLD(n),c=p=>({unsafeName:p,safeName:NLD({name:p,keywords:FLD({generationLanguage:e,keywords:t})})}),d=ou(o),s=Z0(d),u=Ifn(o),l=Sfn(d);return r&&(!LLD(l)&&(e==null||zLD.includes(e))&&(d=l.map((p,_)=>{if(_>0){let h=Cnu(p);if(h!=null)return h;if(qnu(p))return p.toUpperCase()}return p}).join(""),s=Z0(l.map((p,_)=>{let h=Cnu(p);return h??(qnu(p)?p.toUpperCase():_===0?Z0(p):p)}).join(""))),u=o.split(" ").map(p=>p.split(/(\d+)/).map(Ifn).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 NLD({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":ULD(e)?"_"+e:e}function FLD({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return sfh[e]}var QLD=/^[0-9]/;function ULD(e){return QLD.test(e)}function LLD(e){return e.some((t,r)=>{if(r===0)return!1;let i=e[r-1];if(i==null)return!1;let n=Cnu(i)!=null||qnu(i),a=Cnu(t)!=null||qnu(t);return n&&a})}function Cnu(e){return WLD.get(e.toUpperCase())}function qnu(e){return VLD.has(e.toUpperCase())}var VLD=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"]),WLD=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]),GLD=[[/\[\]/g,"Array"]];function xLD(e){return GLD.reduce((t,[r,i])=>t.replace(r,i),e)}var Ar={};Yt(Ar,{ApiDefinitionSource:()=>uY,ApiVersionScheme:()=>tJi,AuthScheme:()=>PA,AuthSchemesRequirement:()=>qR,AvailabilityStatus:()=>E1,ContainerType:()=>Es,Environments:()=>SM,ErrorDeclarationDiscriminantValue:()=>eJi,ErrorDiscriminationStrategy:()=>Yve,ExampleCodeSample:()=>Jve,ExampleContainer:()=>Up,ExampleEndpointSuccessResponse:()=>cw,ExamplePrimitive:()=>Rn,ExampleQueryParameterShape:()=>TR,ExampleRequestBody:()=>vW,ExampleResponse:()=>$j,ExampleSingleUnionTypeProperties:()=>_C,ExampleStyle:()=>Nnu,ExampleTypeReferenceShape:()=>Tu,ExampleTypeShape:()=>hy,ExampleWebSocketMessageBody:()=>Xve,FileProperty:()=>aY,FileUploadBodyPropertyEncoding:()=>D7a,FileUploadRequestProperty:()=>M1,HttpEndpointSource:()=>yW,HttpMethod:()=>sw,HttpRequestBody:()=>Nm,HttpResponseBody:()=>Ed,JsonResponse:()=>dC,Literal:()=>lF,NamedTypeDefault:()=>Xna,NonStreamHttpResponseBody:()=>fL,OAuthConfiguration:()=>ZKi,ObjectPropertyAccess:()=>mYt,Pagination:()=>bW,PathParameterLocation:()=>IEe,PrimitiveTypeV1:()=>ku,PrimitiveTypeV2:()=>vn,ProtobufMethodType:()=>s8t,ProtobufType:()=>_y,PublishTarget:()=>pC,PublishingConfig:()=>OYt,RequestPropertyValue:()=>oY,ResolvedTypeReference:()=>dL,SdkRequestBodyType:()=>u8t,SdkRequestShape:()=>CEe,ShapeType:()=>c8t,SingleUnionTypeProperties:()=>cF,Source:()=>cUi,StreamingResponse:()=>sI,SupportedSdkLanguage:()=>$ve,Transport:()=>BEe,Type:()=>Al,TypeReference:()=>ii,V2AuthValues:()=>DEe,V2EndpointLocationHttpMethod:()=>gYt,V2HttpEndpointResponseBody:()=>S1,WebSocketMessageBody:()=>pL,WebSocketMessageOrigin:()=>Qnu,WebhookHttpMethod:()=>Fnu,WebhookPayload:()=>fF,WellKnownProtobufType:()=>bn,audience:()=>cfh,auth:()=>y9c,commons:()=>b9c,constants:()=>lfh,dynamic:()=>Xt,environment:()=>w9c,errors:()=>E9c,examples:()=>S9c,generatorExec:()=>ll,http:()=>D9c,ir:()=>B9c,proto:()=>I9c,publish:()=>C9c,types:()=>q9c,variables:()=>qfh,webhooks:()=>T9c,websocket:()=>R9c});var cfh={};var y9c={};Yt(y9c,{AuthScheme:()=>PA,AuthSchemesRequirement:()=>qR,OAuthConfiguration:()=>ZKi});var qR={All:"ALL",Any:"ANY",EndpointSecurity:"ENDPOINT_SECURITY",_visit:(e,t)=>{switch(e){case qR.All:return t.all();case qR.Any:return t.any();case qR.EndpointSecurity:return t.endpointSecurity();default:return t._other()}}};var PA={bearer:e=>({...e,type:"bearer",_visit:function(t){return PA._visit(this,t)}}),basic:e=>({...e,type:"basic",_visit:function(t){return PA._visit(this,t)}}),header:e=>({...e,type:"header",_visit:function(t){return PA._visit(this,t)}}),oauth:e=>({...e,type:"oauth",_visit:function(t){return PA._visit(this,t)}}),inferred:e=>({...e,type:"inferred",_visit:function(t){return PA._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"bearer":return t.bearer(e);case"basic":return t.basic(e);case"header":return t.header(e);case"oauth":return t.oauth(e);case"inferred":return t.inferred(e);default:return t._other(e)}}};var ZKi={clientCredentials:e=>({...e,type:"clientCredentials",_visit:function(t){return ZKi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"clientCredentials":return t.clientCredentials(e);default:return t._other(e)}}};var b9c={};Yt(b9c,{AvailabilityStatus:()=>E1});var E1={InDevelopment:"IN_DEVELOPMENT",PreRelease:"PRE_RELEASE",GeneralAvailability:"GENERAL_AVAILABILITY",Deprecated:"DEPRECATED",_visit:(e,t)=>{switch(e){case E1.InDevelopment:return t.inDevelopment();case E1.PreRelease:return t.preRelease();case E1.GeneralAvailability:return t.generalAvailability();case E1.Deprecated:return t.deprecated();default:return t._other()}}};var lfh={};var Xt={};Yt(Xt,{Auth:()=>ffh,AuthValues:()=>dfh,Environments:()=>Ofh,ErrorSeverity:()=>Tnu,FileUploadRequestBodyProperty:()=>gfh,GeneratorOutputConfig:()=>mfh,HttpMethod:()=>kKi,InlinedRequestBody:()=>bfh,LiteralType:()=>Efh,NamedType:()=>Pfh,ObjectPropertyAccess:()=>Rnu,PrimitiveTypeV1:()=>fx,PublishInfo:()=>Afh,ReferencedRequestBodyType:()=>vfh,Request:()=>hfh,Response:()=>yfh,SingleDiscriminatedUnionType:()=>wfh,TypeReference:()=>jfh,auth:()=>v9c,commons:()=>pfh,declaration:()=>_fh,endpoints:()=>g9c,environment:()=>O9c,http:()=>m9c,ir:()=>A9c,snippets:()=>P9c,types:()=>j9c,variables:()=>Sfh});var v9c={};Yt(v9c,{Auth:()=>ffh,AuthValues:()=>dfh});var ffh={basic:e=>({...e,type:"basic",_visit:function(t){return Xt.Auth._visit(this,t)}}),bearer:e=>({...e,type:"bearer",_visit:function(t){return Xt.Auth._visit(this,t)}}),header:e=>({...e,type:"header",_visit:function(t){return Xt.Auth._visit(this,t)}}),oauth:e=>({...e,type:"oauth",_visit:function(t){return Xt.Auth._visit(this,t)}}),inferred:e=>({...e,type:"inferred",_visit:function(t){return Xt.Auth._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"basic":return t.basic(e);case"bearer":return t.bearer(e);case"header":return t.header(e);case"oauth":return t.oauth(e);case"inferred":return t.inferred(e);default:return t._other(e)}}};var dfh={basic:e=>({...e,type:"basic",_visit:function(t){return Xt.AuthValues._visit(this,t)}}),bearer:e=>({...e,type:"bearer",_visit:function(t){return Xt.AuthValues._visit(this,t)}}),header:e=>({...e,type:"header",_visit:function(t){return Xt.AuthValues._visit(this,t)}}),oauth:e=>({...e,type:"oauth",_visit:function(t){return Xt.AuthValues._visit(this,t)}}),inferred:e=>({...e,type:"inferred",_visit:function(t){return Xt.AuthValues._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"basic":return t.basic(e);case"bearer":return t.bearer(e);case"header":return t.header(e);case"oauth":return t.oauth(e);case"inferred":return t.inferred(e);default:return t._other(e)}}};var pfh={};var _fh={};var g9c={};Yt(g9c,{FileUploadRequestBodyProperty:()=>gfh,InlinedRequestBody:()=>bfh,ReferencedRequestBodyType:()=>vfh,Request:()=>hfh,Response:()=>yfh});var hfh={body:e=>({...e,type:"body",_visit:function(t){return Xt.Request._visit(this,t)}}),inlined:e=>({...e,type:"inlined",_visit:function(t){return Xt.Request._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"body":return t.body(e);case"inlined":return t.inlined(e);default:return t._other(e)}}};var yfh={json:()=>({type:"json",_visit:function(e){return Xt.Response._visit(this,e)}}),streaming:()=>({type:"streaming",_visit:function(e){return Xt.Response._visit(this,e)}}),streamParameter:()=>({type:"streamParameter",_visit:function(e){return Xt.Response._visit(this,e)}}),fileDownload:()=>({type:"fileDownload",_visit:function(e){return Xt.Response._visit(this,e)}}),text:()=>({type:"text",_visit:function(e){return Xt.Response._visit(this,e)}}),bytes:()=>({type:"bytes",_visit:function(e){return Xt.Response._visit(this,e)}}),_visit:(e,t)=>{switch(e.type){case"json":return t.json();case"streaming":return t.streaming();case"streamParameter":return t.streamParameter();case"fileDownload":return t.fileDownload();case"text":return t.text();case"bytes":return t.bytes();default:return t._other(e)}}};var bfh={properties:e=>({value:e,type:"properties",_visit:function(t){return Xt.InlinedRequestBody._visit(this,t)}}),referenced:e=>({...e,type:"referenced",_visit:function(t){return Xt.InlinedRequestBody._visit(this,t)}}),fileUpload:e=>({...e,type:"fileUpload",_visit:function(t){return Xt.InlinedRequestBody._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"properties":return t.properties(e.value);case"referenced":return t.referenced(e);case"fileUpload":return t.fileUpload(e);default:return t._other(e)}}};var vfh={bytes:()=>({type:"bytes",_visit:function(e){return Xt.ReferencedRequestBodyType._visit(this,e)}}),typeReference:e=>({value:e,type:"typeReference",_visit:function(t){return Xt.ReferencedRequestBodyType._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"bytes":return t.bytes();case"typeReference":return t.typeReference(e.value);default:return t._other(e)}}};var gfh={file:e=>({...e,type:"file",_visit:function(t){return Xt.FileUploadRequestBodyProperty._visit(this,t)}}),fileArray:e=>({...e,type:"fileArray",_visit:function(t){return Xt.FileUploadRequestBodyProperty._visit(this,t)}}),bodyProperty:e=>({...e,type:"bodyProperty",_visit:function(t){return Xt.FileUploadRequestBodyProperty._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"fileArray":return t.fileArray(e);case"bodyProperty":return t.bodyProperty(e);default:return t._other(e)}}};var O9c={};Yt(O9c,{Environments:()=>Ofh});var Ofh={singleBaseUrl:e=>({...e,type:"singleBaseUrl",_visit:function(t){return Xt.Environments._visit(this,t)}}),multipleBaseUrls:e=>({...e,type:"multipleBaseUrls",_visit:function(t){return Xt.Environments._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"singleBaseUrl":return t.singleBaseUrl(e);case"multipleBaseUrls":return t.multipleBaseUrls(e);default:return t._other(e)}}};var m9c={};Yt(m9c,{HttpMethod:()=>kKi});var kKi={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD",_visit:(e,t)=>{switch(e){case kKi.Get:return t.get();case kKi.Post:return t.post();case kKi.Put:return t.put();case kKi.Patch:return t.patch();case kKi.Delete:return t.delete();case kKi.Head:return t.head();default:return t._other()}}};var A9c={};Yt(A9c,{GeneratorOutputConfig:()=>mfh,PublishInfo:()=>Afh});var mfh={publish:e=>({value:e,type:"publish",_visit:function(t){return Xt.GeneratorOutputConfig._visit(this,t)}}),local:()=>({type:"local",_visit:function(e){return Xt.GeneratorOutputConfig._visit(this,e)}}),_visit:(e,t)=>{switch(e.type){case"publish":return t.publish(e.value);case"local":return t.local();default:return t._other(e)}}};var Afh={go:e=>({...e,type:"go",_visit:function(t){return Xt.PublishInfo._visit(this,t)}}),swift:e=>({...e,type:"swift",_visit:function(t){return Xt.PublishInfo._visit(this,t)}}),maven:e=>({...e,type:"maven",_visit:function(t){return Xt.PublishInfo._visit(this,t)}}),npm:e=>({...e,type:"npm",_visit:function(t){return Xt.PublishInfo._visit(this,t)}}),nuget:e=>({...e,type:"nuget",_visit:function(t){return Xt.PublishInfo._visit(this,t)}}),pypi:e=>({...e,type:"pypi",_visit:function(t){return Xt.PublishInfo._visit(this,t)}}),rubygems:e=>({...e,type:"rubygems",_visit:function(t){return Xt.PublishInfo._visit(this,t)}}),crates:e=>({...e,type:"crates",_visit:function(t){return Xt.PublishInfo._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"go":return t.go(e);case"swift":return t.swift(e);case"maven":return t.maven(e);case"npm":return t.npm(e);case"nuget":return t.nuget(e);case"pypi":return t.pypi(e);case"rubygems":return t.rubygems(e);case"crates":return t.crates(e);default:return t._other(e)}}};var P9c={};Yt(P9c,{ErrorSeverity:()=>Tnu});var Tnu={Critical:"CRITICAL",Warning:"WARNING",_visit:(e,t)=>{switch(e){case Tnu.Critical:return t.critical();case Tnu.Warning:return t.warning();default:return t._other()}}};var j9c={};Yt(j9c,{LiteralType:()=>Efh,NamedType:()=>Pfh,ObjectPropertyAccess:()=>Rnu,PrimitiveTypeV1:()=>fx,SingleDiscriminatedUnionType:()=>wfh,TypeReference:()=>jfh});var Pfh={alias:e=>({...e,type:"alias",_visit:function(t){return Xt.NamedType._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return Xt.NamedType._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Xt.NamedType._visit(this,t)}}),discriminatedUnion:e=>({...e,type:"discriminatedUnion",_visit:function(t){return Xt.NamedType._visit(this,t)}}),undiscriminatedUnion:e=>({...e,type:"undiscriminatedUnion",_visit:function(t){return Xt.NamedType._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"alias":return t.alias(e);case"enum":return t.enum(e);case"object":return t.object(e);case"discriminatedUnion":return t.discriminatedUnion(e);case"undiscriminatedUnion":return t.undiscriminatedUnion(e);default:return t._other(e)}}};var jfh={list:e=>({value:e,type:"list",_visit:function(t){return Xt.TypeReference._visit(this,t)}}),literal:e=>({value:e,type:"literal",_visit:function(t){return Xt.TypeReference._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return Xt.TypeReference._visit(this,t)}}),named:e=>({value:e,type:"named",_visit:function(t){return Xt.TypeReference._visit(this,t)}}),nullable:e=>({value:e,type:"nullable",_visit:function(t){return Xt.TypeReference._visit(this,t)}}),optional:e=>({value:e,type:"optional",_visit:function(t){return Xt.TypeReference._visit(this,t)}}),primitive:e=>({value:e,type:"primitive",_visit:function(t){return Xt.TypeReference._visit(this,t)}}),set:e=>({value:e,type:"set",_visit:function(t){return Xt.TypeReference._visit(this,t)}}),unknown:()=>({type:"unknown",_visit:function(e){return Xt.TypeReference._visit(this,e)}}),_visit:(e,t)=>{switch(e.type){case"list":return t.list(e.value);case"literal":return t.literal(e.value);case"map":return t.map(e);case"named":return t.named(e.value);case"nullable":return t.nullable(e.value);case"optional":return t.optional(e.value);case"primitive":return t.primitive(e.value);case"set":return t.set(e.value);case"unknown":return t.unknown();default:return t._other(e)}}};var wfh={samePropertiesAsObject:e=>({...e,type:"samePropertiesAsObject",_visit:function(t){return Xt.SingleDiscriminatedUnionType._visit(this,t)}}),singleProperty:e=>({...e,type:"singleProperty",_visit:function(t){return Xt.SingleDiscriminatedUnionType._visit(this,t)}}),noProperties:e=>({...e,type:"noProperties",_visit:function(t){return Xt.SingleDiscriminatedUnionType._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"samePropertiesAsObject":return t.samePropertiesAsObject(e);case"singleProperty":return t.singleProperty(e);case"noProperties":return t.noProperties(e);default:return t._other(e)}}};var Efh={boolean:e=>({value:e,type:"boolean",_visit:function(t){return Xt.LiteralType._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return Xt.LiteralType._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"boolean":return t.boolean(e.value);case"string":return t.string(e.value);default:return t._other(e)}}};var Rnu={ReadOnly:"READ_ONLY",WriteOnly:"WRITE_ONLY",_visit:(e,t)=>{switch(e){case Rnu.ReadOnly:return t.readOnly();case Rnu.WriteOnly:return t.writeOnly();default:return t._other()}}};var fx={Integer:"INTEGER",Long:"LONG",Uint:"UINT",Uint64:"UINT_64",Float:"FLOAT",Double:"DOUBLE",Boolean:"BOOLEAN",String:"STRING",Date:"DATE",DateTime:"DATE_TIME",Uuid:"UUID",Base64:"BASE_64",BigInteger:"BIG_INTEGER",_visit:(e,t)=>{switch(e){case fx.Integer:return t.integer();case fx.Long:return t.long();case fx.Uint:return t.uint();case fx.Uint64:return t.uint64();case fx.Float:return t.float();case fx.Double:return t.double();case fx.Boolean:return t.boolean();case fx.String:return t.string();case fx.Date:return t.date();case fx.DateTime:return t.dateTime();case fx.Uuid:return t.uuid();case fx.Base64:return t.base64();case fx.BigInteger:return t.bigInteger();default:return t._other()}}};var Sfh={};var w9c={};Yt(w9c,{Environments:()=>SM});var SM={singleBaseUrl:e=>({...e,type:"singleBaseUrl",_visit:function(t){return SM._visit(this,t)}}),multipleBaseUrls:e=>({...e,type:"multipleBaseUrls",_visit:function(t){return SM._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"singleBaseUrl":return t.singleBaseUrl(e);case"multipleBaseUrls":return t.multipleBaseUrls(e);default:return t._other(e)}}};var E9c={};Yt(E9c,{ErrorDeclarationDiscriminantValue:()=>eJi});var eJi={property:e=>({...e,type:"property",_visit:function(t){return eJi._visit(this,t)}}),statusCode:()=>({type:"statusCode",_visit:function(e){return eJi._visit(this,e)}}),_visit:(e,t)=>{switch(e.type){case"property":return t.property(e);case"statusCode":return t.statusCode();default:return t._other(e)}}};var S9c={};Yt(S9c,{V2AuthValues:()=>DEe,V2EndpointLocationHttpMethod:()=>gYt,V2HttpEndpointResponseBody:()=>S1});var S1={error:e=>({value:e,type:"error",_visit:function(t){return S1._visit(this,t)}}),json:e=>({value:e,type:"json",_visit:function(t){return S1._visit(this,t)}}),stream:e=>({value:e,type:"stream",_visit:function(t){return S1._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"error":return t.error(e.value);case"json":return t.json(e.value);case"stream":return t.stream(e.value);default:return t._other(e)}}};var gYt={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD",_visit:(e,t)=>{switch(e){case gYt.Get:return t.get();case gYt.Post:return t.post();case gYt.Put:return t.put();case gYt.Patch:return t.patch();case gYt.Delete:return t.delete();case gYt.Head:return t.head();default:return t._other()}}};var DEe={basic:e=>({...e,type:"basic",_visit:function(t){return DEe._visit(this,t)}}),bearer:e=>({...e,type:"bearer",_visit:function(t){return DEe._visit(this,t)}}),header:e=>({...e,type:"header",_visit:function(t){return DEe._visit(this,t)}}),oauth:e=>({...e,type:"oauth",_visit:function(t){return DEe._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"basic":return t.basic(e);case"bearer":return t.bearer(e);case"header":return t.header(e);case"oauth":return t.oauth(e);default:return t._other(e)}}};var ll={};Yt(ll,{GeneratorEnvironment:()=>Cfh,GeneratorPublishTarget:()=>Ifh,GithubPublishInfo:()=>Bfh,LicenseConfig:()=>Mfh,LicenseId:()=>znu,OutputMode:()=>Dfh,config:()=>M9c});var M9c={};Yt(M9c,{GeneratorEnvironment:()=>Cfh,GeneratorPublishTarget:()=>Ifh,GithubPublishInfo:()=>Bfh,LicenseConfig:()=>Mfh,LicenseId:()=>znu,OutputMode:()=>Dfh});var Mfh={basic:e=>({...e,type:"basic",_visit:function(t){return ll.LicenseConfig._visit(this,t)}}),custom:e=>({...e,type:"custom",_visit:function(t){return ll.LicenseConfig._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"basic":return t.basic(e);case"custom":return t.custom(e);default:return t._other(e)}}};var znu={Mit:"MIT",Apache2:"Apache-2.0",_visit:(e,t)=>{switch(e){case znu.Mit:return t.mit();case znu.Apache2:return t.apache2();default:return t._other()}}};var Dfh={publish:e=>({...e,type:"publish",_visit:function(t){return ll.OutputMode._visit(this,t)}}),downloadFiles:()=>({type:"downloadFiles",_visit:function(e){return ll.OutputMode._visit(this,e)}}),github:e=>({...e,type:"github",_visit:function(t){return ll.OutputMode._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"publish":return t.publish(e);case"downloadFiles":return t.downloadFiles();case"github":return t.github(e);default:return t._other(e)}}};var Bfh={npm:e=>({...e,type:"npm",_visit:function(t){return ll.GithubPublishInfo._visit(this,t)}}),maven:e=>({...e,type:"maven",_visit:function(t){return ll.GithubPublishInfo._visit(this,t)}}),postman:e=>({...e,type:"postman",_visit:function(t){return ll.GithubPublishInfo._visit(this,t)}}),pypi:e=>({...e,type:"pypi",_visit:function(t){return ll.GithubPublishInfo._visit(this,t)}}),rubygems:e=>({...e,type:"rubygems",_visit:function(t){return ll.GithubPublishInfo._visit(this,t)}}),nuget:e=>({...e,type:"nuget",_visit:function(t){return ll.GithubPublishInfo._visit(this,t)}}),crates:e=>({...e,type:"crates",_visit:function(t){return ll.GithubPublishInfo._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"npm":return t.npm(e);case"maven":return t.maven(e);case"postman":return t.postman(e);case"pypi":return t.pypi(e);case"rubygems":return t.rubygems(e);case"nuget":return t.nuget(e);case"crates":return t.crates(e);default:return t._other(e)}}};var Ifh={maven:e=>({...e,type:"maven",_visit:function(t){return ll.GeneratorPublishTarget._visit(this,t)}}),npm:e=>({...e,type:"npm",_visit:function(t){return ll.GeneratorPublishTarget._visit(this,t)}}),pypi:e=>({...e,type:"pypi",_visit:function(t){return ll.GeneratorPublishTarget._visit(this,t)}}),postman:e=>({...e,type:"postman",_visit:function(t){return ll.GeneratorPublishTarget._visit(this,t)}}),rubygems:e=>({...e,type:"rubygems",_visit:function(t){return ll.GeneratorPublishTarget._visit(this,t)}}),nuget:e=>({...e,type:"nuget",_visit:function(t){return ll.GeneratorPublishTarget._visit(this,t)}}),crates:e=>({...e,type:"crates",_visit:function(t){return ll.GeneratorPublishTarget._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"maven":return t.maven(e);case"npm":return t.npm(e);case"pypi":return t.pypi(e);case"postman":return t.postman(e);case"rubygems":return t.rubygems(e);case"nuget":return t.nuget(e);case"crates":return t.crates(e);default:return t._other(e)}}};var Cfh={local:()=>({type:"local",_visit:function(e){return ll.GeneratorEnvironment._visit(this,e)}}),remote:e=>({...e,type:"remote",_visit:function(t){return ll.GeneratorEnvironment._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"local":return t.local();case"remote":return t.remote(e);default:return t._other(e)}}};var D9c={};Yt(D9c,{ExampleCodeSample:()=>Jve,ExampleEndpointSuccessResponse:()=>cw,ExampleQueryParameterShape:()=>TR,ExampleRequestBody:()=>vW,ExampleResponse:()=>$j,FileProperty:()=>aY,FileUploadBodyPropertyEncoding:()=>D7a,FileUploadRequestProperty:()=>M1,HttpEndpointSource:()=>yW,HttpMethod:()=>sw,HttpRequestBody:()=>Nm,HttpResponseBody:()=>Ed,JsonResponse:()=>dC,NonStreamHttpResponseBody:()=>fL,Pagination:()=>bW,PathParameterLocation:()=>IEe,RequestPropertyValue:()=>oY,SdkRequestBodyType:()=>u8t,SdkRequestShape:()=>CEe,StreamingResponse:()=>sI,SupportedSdkLanguage:()=>$ve,Transport:()=>BEe});var BEe={http:()=>({type:"http",_visit:function(e){return BEe._visit(this,e)}}),grpc:e=>({...e,type:"grpc",_visit:function(t){return BEe._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"http":return t.http();case"grpc":return t.grpc(e);default:return t._other(e)}}};var yW={proto:e=>({...e,type:"proto",_visit:function(t){return yW._visit(this,t)}}),openapi:()=>({type:"openapi",_visit:function(e){return yW._visit(this,e)}}),openrpc:()=>({type:"openrpc",_visit:function(e){return yW._visit(this,e)}}),_visit:(e,t)=>{switch(e.type){case"proto":return t.proto(e);case"openapi":return t.openapi();case"openrpc":return t.openrpc();default:return t._other(e)}}};var sw={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD",_visit:(e,t)=>{switch(e){case sw.Get:return t.get();case sw.Post:return t.post();case sw.Put:return t.put();case sw.Patch:return t.patch();case sw.Delete:return t.delete();case sw.Head:return t.head();default:return t._other()}}};var IEe={Root:"ROOT",Service:"SERVICE",Endpoint:"ENDPOINT",_visit:(e,t)=>{switch(e){case IEe.Root:return t.root();case IEe.Service:return t.service();case IEe.Endpoint:return t.endpoint();default:return t._other()}}};var Nm={inlinedRequestBody:e=>({...e,type:"inlinedRequestBody",_visit:function(t){return Nm._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return Nm._visit(this,t)}}),fileUpload:e=>({...e,type:"fileUpload",_visit:function(t){return Nm._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return Nm._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"inlinedRequestBody":return t.inlinedRequestBody(e);case"reference":return t.reference(e);case"fileUpload":return t.fileUpload(e);case"bytes":return t.bytes(e);default:return t._other(e)}}};var M1={file:e=>({value:e,type:"file",_visit:function(t){return M1._visit(this,t)}}),bodyProperty:e=>({...e,type:"bodyProperty",_visit:function(t){return M1._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e.value);case"bodyProperty":return t.bodyProperty(e);default:return t._other(e)}}};var D7a={Exploded:"exploded",Json:"json",Form:"form",_visit:(e,t)=>{switch(e){case D7a.Exploded:return t.exploded();case D7a.Json:return t.json();case D7a.Form:return t.form();default:return t._other()}}};var aY={file:e=>({...e,type:"file",_visit:function(t){return aY._visit(this,t)}}),fileArray:e=>({...e,type:"fileArray",_visit:function(t){return aY._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"fileArray":return t.fileArray(e);default:return t._other(e)}}};var u8t={typeReference:e=>({...e,type:"typeReference",_visit:function(t){return u8t._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return u8t._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"typeReference":return t.typeReference(e);case"bytes":return t.bytes(e);default:return t._other(e)}}};var CEe={justRequestBody:e=>({value:e,type:"justRequestBody",_visit:function(t){return CEe._visit(this,t)}}),wrapper:e=>({...e,type:"wrapper",_visit:function(t){return CEe._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"justRequestBody":return t.justRequestBody(e.value);case"wrapper":return t.wrapper(e);default:return t._other(e)}}};var fL={json:e=>({value:e,type:"json",_visit:function(t){return fL._visit(this,t)}}),fileDownload:e=>({...e,type:"fileDownload",_visit:function(t){return fL._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return fL._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return fL._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"json":return t.json(e.value);case"fileDownload":return t.fileDownload(e);case"text":return t.text(e);case"bytes":return t.bytes(e);default:return t._other(e)}}};var Ed={json:e=>({value:e,type:"json",_visit:function(t){return Ed._visit(this,t)}}),fileDownload:e=>({...e,type:"fileDownload",_visit:function(t){return Ed._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return Ed._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return Ed._visit(this,t)}}),streaming:e=>({value:e,type:"streaming",_visit:function(t){return Ed._visit(this,t)}}),streamParameter:e=>({...e,type:"streamParameter",_visit:function(t){return Ed._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"json":return t.json(e.value);case"fileDownload":return t.fileDownload(e);case"text":return t.text(e);case"bytes":return t.bytes(e);case"streaming":return t.streaming(e.value);case"streamParameter":return t.streamParameter(e);default:return t._other(e)}}};var dC={response:e=>({...e,type:"response",_visit:function(t){return dC._visit(this,t)}}),nestedPropertyAsResponse:e=>({...e,type:"nestedPropertyAsResponse",_visit:function(t){return dC._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"response":return t.response(e);case"nestedPropertyAsResponse":return t.nestedPropertyAsResponse(e);default:return t._other(e)}}};var sI={json:e=>({...e,type:"json",_visit:function(t){return sI._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return sI._visit(this,t)}}),sse:e=>({...e,type:"sse",_visit:function(t){return sI._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"json":return t.json(e);case"text":return t.text(e);case"sse":return t.sse(e);default:return t._other(e)}}};var bW={cursor:e=>({...e,type:"cursor",_visit:function(t){return bW._visit(this,t)}}),offset:e=>({...e,type:"offset",_visit:function(t){return bW._visit(this,t)}}),custom:e=>({...e,type:"custom",_visit:function(t){return bW._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"cursor":return t.cursor(e);case"offset":return t.offset(e);case"custom":return t.custom(e);default:return t._other(e)}}};var oY={query:e=>({...e,type:"query",_visit:function(t){return oY._visit(this,t)}}),body:e=>({...e,type:"body",_visit:function(t){return oY._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"query":return t.query(e);case"body":return t.body(e);default:return t._other(e)}}};var Jve={language:e=>({...e,type:"language",_visit:function(t){return Jve._visit(this,t)}}),sdk:e=>({...e,type:"sdk",_visit:function(t){return Jve._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"language":return t.language(e);case"sdk":return t.sdk(e);default:return t._other(e)}}};var $ve={Curl:"curl",Python:"python",Javascript:"javascript",Typescript:"typescript",Go:"go",Ruby:"ruby",Csharp:"csharp",Java:"java",Php:"php",Rust:"rust",Swift:"swift",_visit:(e,t)=>{switch(e){case $ve.Curl:return t.curl();case $ve.Python:return t.python();case $ve.Javascript:return t.javascript();case $ve.Typescript:return t.typescript();case $ve.Go:return t.go();case $ve.Ruby:return t.ruby();case $ve.Csharp:return t.csharp();case $ve.Java:return t.java();case $ve.Php:return t.php();case $ve.Rust:return t.rust();case $ve.Swift:return t.swift();default:return t._other()}}};var TR={single:()=>({type:"single",_visit:function(e){return TR._visit(this,e)}}),exploded:()=>({type:"exploded",_visit:function(e){return TR._visit(this,e)}}),commaSeparated:()=>({type:"commaSeparated",_visit:function(e){return TR._visit(this,e)}}),_visit:(e,t)=>{switch(e.type){case"single":return t.single();case"exploded":return t.exploded();case"commaSeparated":return t.commaSeparated();default:return t._other(e)}}};var vW={inlinedRequestBody:e=>({...e,type:"inlinedRequestBody",_visit:function(t){return vW._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return vW._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"inlinedRequestBody":return t.inlinedRequestBody(e);case"reference":return t.reference(e);default:return t._other(e)}}};var $j={ok:e=>({value:e,type:"ok",_visit:function(t){return $j._visit(this,t)}}),error:e=>({...e,type:"error",_visit:function(t){return $j._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"ok":return t.ok(e.value);case"error":return t.error(e);default:return t._other(e)}}};var cw={body:e=>({value:e,type:"body",_visit:function(t){return cw._visit(this,t)}}),stream:e=>({value:e,type:"stream",_visit:function(t){return cw._visit(this,t)}}),sse:e=>({value:e,type:"sse",_visit:function(t){return cw._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"body":return t.body(e.value);case"stream":return t.stream(e.value);case"sse":return t.sse(e.value);default:return t._other(e)}}};var B9c={};Yt(B9c,{ApiDefinitionSource:()=>uY,ApiVersionScheme:()=>tJi,ErrorDiscriminationStrategy:()=>Yve,ExampleStyle:()=>Nnu});var Nnu={Minimal:"minimal",Comprehensive:"comprehensive",_visit:(e,t)=>{switch(e){case Nnu.Minimal:return t.minimal();case Nnu.Comprehensive:return t.comprehensive();default:return t._other()}}};var uY={proto:e=>({...e,type:"proto",_visit:function(t){return uY._visit(this,t)}}),openapi:()=>({type:"openapi",_visit:function(e){return uY._visit(this,e)}}),_visit:(e,t)=>{switch(e.type){case"proto":return t.proto(e);case"openapi":return t.openapi();default:return t._other(e)}}};var tJi={header:e=>({...e,type:"header",_visit:function(t){return tJi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"header":return t.header(e);default:return t._other(e)}}};var Yve={statusCode:()=>({type:"statusCode",_visit:function(e){return Yve._visit(this,e)}}),property:e=>({...e,type:"property",_visit:function(t){return Yve._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"statusCode":return t.statusCode();case"property":return t.property(e);default:return t._other(e)}}};var I9c={};Yt(I9c,{ProtobufMethodType:()=>s8t,ProtobufType:()=>_y,WellKnownProtobufType:()=>bn});var _y={wellKnown:e=>({value:e,type:"wellKnown",_visit:function(t){return _y._visit(this,t)}}),userDefined:e=>({...e,type:"userDefined",_visit:function(t){return _y._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"wellKnown":return t.wellKnown(e.value);case"userDefined":return t.userDefined(e);default:return t._other(e)}}};var bn={any:()=>({type:"any",_visit:function(e){return bn._visit(this,e)}}),api:()=>({type:"api",_visit:function(e){return bn._visit(this,e)}}),boolValue:()=>({type:"boolValue",_visit:function(e){return bn._visit(this,e)}}),bytesValue:()=>({type:"bytesValue",_visit:function(e){return bn._visit(this,e)}}),doubleValue:()=>({type:"doubleValue",_visit:function(e){return bn._visit(this,e)}}),duration:()=>({type:"duration",_visit:function(e){return bn._visit(this,e)}}),empty:()=>({type:"empty",_visit:function(e){return bn._visit(this,e)}}),enum:()=>({type:"enum",_visit:function(e){return bn._visit(this,e)}}),enumValue:()=>({type:"enumValue",_visit:function(e){return bn._visit(this,e)}}),field:()=>({type:"field",_visit:function(e){return bn._visit(this,e)}}),fieldCardinality:()=>({type:"fieldCardinality",_visit:function(e){return bn._visit(this,e)}}),fieldKind:()=>({type:"fieldKind",_visit:function(e){return bn._visit(this,e)}}),fieldMask:()=>({type:"fieldMask",_visit:function(e){return bn._visit(this,e)}}),floatValue:()=>({type:"floatValue",_visit:function(e){return bn._visit(this,e)}}),int32Value:()=>({type:"int32Value",_visit:function(e){return bn._visit(this,e)}}),int64Value:()=>({type:"int64Value",_visit:function(e){return bn._visit(this,e)}}),listValue:()=>({type:"listValue",_visit:function(e){return bn._visit(this,e)}}),method:()=>({type:"method",_visit:function(e){return bn._visit(this,e)}}),mixin:()=>({type:"mixin",_visit:function(e){return bn._visit(this,e)}}),nullValue:()=>({type:"nullValue",_visit:function(e){return bn._visit(this,e)}}),option:()=>({type:"option",_visit:function(e){return bn._visit(this,e)}}),sourceContext:()=>({type:"sourceContext",_visit:function(e){return bn._visit(this,e)}}),stringValue:()=>({type:"stringValue",_visit:function(e){return bn._visit(this,e)}}),struct:()=>({type:"struct",_visit:function(e){return bn._visit(this,e)}}),syntax:()=>({type:"syntax",_visit:function(e){return bn._visit(this,e)}}),timestamp:()=>({type:"timestamp",_visit:function(e){return bn._visit(this,e)}}),type:()=>({type:"type",_visit:function(e){return bn._visit(this,e)}}),uint32Value:()=>({type:"uint32Value",_visit:function(e){return bn._visit(this,e)}}),uint64Value:()=>({type:"uint64Value",_visit:function(e){return bn._visit(this,e)}}),value:()=>({type:"value",_visit:function(e){return bn._visit(this,e)}}),_visit:(e,t)=>{switch(e.type){case"any":return t.any();case"api":return t.api();case"boolValue":return t.boolValue();case"bytesValue":return t.bytesValue();case"doubleValue":return t.doubleValue();case"duration":return t.duration();case"empty":return t.empty();case"enum":return t.enum();case"enumValue":return t.enumValue();case"field":return t.field();case"fieldCardinality":return t.fieldCardinality();case"fieldKind":return t.fieldKind();case"fieldMask":return t.fieldMask();case"floatValue":return t.floatValue();case"int32Value":return t.int32Value();case"int64Value":return t.int64Value();case"listValue":return t.listValue();case"method":return t.method();case"mixin":return t.mixin();case"nullValue":return t.nullValue();case"option":return t.option();case"sourceContext":return t.sourceContext();case"stringValue":return t.stringValue();case"struct":return t.struct();case"syntax":return t.syntax();case"timestamp":return t.timestamp();case"type":return t.type();case"uint32Value":return t.uint32Value();case"uint64Value":return t.uint64Value();case"value":return t.value();default:return t._other(e)}}};var s8t={Unary:"UNARY",ClientStream:"CLIENT_STREAM",ServerStream:"SERVER_STREAM",BidirectionalStream:"BIDIRECTIONAL_STREAM",_visit:(e,t)=>{switch(e){case s8t.Unary:return t.unary();case s8t.ClientStream:return t.clientStream();case s8t.ServerStream:return t.serverStream();case s8t.BidirectionalStream:return t.bidirectionalStream();default:return t._other()}}};var C9c={};Yt(C9c,{PublishTarget:()=>pC,PublishingConfig:()=>OYt});var OYt={github:e=>({...e,type:"github",_visit:function(t){return OYt._visit(this,t)}}),direct:e=>({...e,type:"direct",_visit:function(t){return OYt._visit(this,t)}}),filesystem:e=>({...e,type:"filesystem",_visit:function(t){return OYt._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"github":return t.github(e);case"direct":return t.direct(e);case"filesystem":return t.filesystem(e);default:return t._other(e)}}};var pC={postman:e=>({...e,type:"postman",_visit:function(t){return pC._visit(this,t)}}),npm:e=>({...e,type:"npm",_visit:function(t){return pC._visit(this,t)}}),maven:e=>({...e,type:"maven",_visit:function(t){return pC._visit(this,t)}}),pypi:e=>({...e,type:"pypi",_visit:function(t){return pC._visit(this,t)}}),crates:e=>({...e,type:"crates",_visit:function(t){return pC._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"postman":return t.postman(e);case"npm":return t.npm(e);case"maven":return t.maven(e);case"pypi":return t.pypi(e);case"crates":return t.crates(e);default:return t._other(e)}}};var q9c={};Yt(q9c,{ContainerType:()=>Es,ExampleContainer:()=>Up,ExamplePrimitive:()=>Rn,ExampleSingleUnionTypeProperties:()=>_C,ExampleTypeReferenceShape:()=>Tu,ExampleTypeShape:()=>hy,Literal:()=>lF,NamedTypeDefault:()=>Xna,ObjectPropertyAccess:()=>mYt,PrimitiveTypeV1:()=>ku,PrimitiveTypeV2:()=>vn,ResolvedTypeReference:()=>dL,ShapeType:()=>c8t,SingleUnionTypeProperties:()=>cF,Source:()=>cUi,Type:()=>Al,TypeReference:()=>ii});var cUi={proto:e=>({value:e,type:"proto",_visit:function(t){return cUi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"proto":return t.proto(e.value);default:return t._other(e)}}};var Al={alias:e=>({...e,type:"alias",_visit:function(t){return Al._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return Al._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Al._visit(this,t)}}),union:e=>({...e,type:"union",_visit:function(t){return Al._visit(this,t)}}),undiscriminatedUnion:e=>({...e,type:"undiscriminatedUnion",_visit:function(t){return Al._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"alias":return t.alias(e);case"enum":return t.enum(e);case"object":return t.object(e);case"union":return t.union(e);case"undiscriminatedUnion":return t.undiscriminatedUnion(e);default:return t._other(e)}}};var dL={container:e=>({container:e,type:"container",_visit:function(t){return dL._visit(this,t)}}),named:e=>({...e,type:"named",_visit:function(t){return dL._visit(this,t)}}),primitive:e=>({primitive:e,type:"primitive",_visit:function(t){return dL._visit(this,t)}}),unknown:()=>({type:"unknown",_visit:function(e){return dL._visit(this,e)}}),_visit:(e,t)=>{switch(e.type){case"container":return t.container(e.container);case"named":return t.named(e);case"primitive":return t.primitive(e.primitive);case"unknown":return t.unknown();default:return t._other(e)}}};var c8t={Enum:"ENUM",Object:"OBJECT",Union:"UNION",UndiscriminatedUnion:"UNDISCRIMINATED_UNION",_visit:(e,t)=>{switch(e){case c8t.Enum:return t.enum();case c8t.Object:return t.object();case c8t.Union:return t.union();case c8t.UndiscriminatedUnion:return t.undiscriminatedUnion();default:return t._other()}}};var mYt={ReadOnly:"READ_ONLY",WriteOnly:"WRITE_ONLY",_visit:(e,t)=>{switch(e){case mYt.ReadOnly:return t.readOnly();case mYt.WriteOnly:return t.writeOnly();default:return t._other()}}};var cF={samePropertiesAsObject:e=>({...e,propertiesType:"samePropertiesAsObject",_visit:function(t){return cF._visit(this,t)}}),singleProperty:e=>({...e,propertiesType:"singleProperty",_visit:function(t){return cF._visit(this,t)}}),noProperties:()=>({propertiesType:"noProperties",_visit:function(e){return cF._visit(this,e)}}),_visit:(e,t)=>{switch(e.propertiesType){case"samePropertiesAsObject":return t.samePropertiesAsObject(e);case"singleProperty":return t.singleProperty(e);case"noProperties":return t.noProperties();default:return t._other(e)}}};var ii={container:e=>({container:e,type:"container",_visit:function(t){return ii._visit(this,t)}}),named:e=>({...e,type:"named",_visit:function(t){return ii._visit(this,t)}}),primitive:e=>({primitive:e,type:"primitive",_visit:function(t){return ii._visit(this,t)}}),unknown:()=>({type:"unknown",_visit:function(e){return ii._visit(this,e)}}),_visit:(e,t)=>{switch(e.type){case"container":return t.container(e.container);case"named":return t.named(e);case"primitive":return t.primitive(e.primitive);case"unknown":return t.unknown();default:return t._other(e)}}};var Xna={enum:e=>({...e,type:"enum",_visit:function(t){return Xna._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"enum":return t.enum(e);default:return t._other(e)}}};var Es={list:e=>({list:e,type:"list",_visit:function(t){return Es._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return Es._visit(this,t)}}),nullable:e=>({nullable:e,type:"nullable",_visit:function(t){return Es._visit(this,t)}}),optional:e=>({optional:e,type:"optional",_visit:function(t){return Es._visit(this,t)}}),set:e=>({set:e,type:"set",_visit:function(t){return Es._visit(this,t)}}),literal:e=>({literal:e,type:"literal",_visit:function(t){return Es._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"list":return t.list(e.list);case"map":return t.map(e);case"nullable":return t.nullable(e.nullable);case"optional":return t.optional(e.optional);case"set":return t.set(e.set);case"literal":return t.literal(e.literal);default:return t._other(e)}}};var ku={Integer:"INTEGER",Long:"LONG",Uint:"UINT",Uint64:"UINT_64",Float:"FLOAT",Double:"DOUBLE",Boolean:"BOOLEAN",String:"STRING",Date:"DATE",DateTime:"DATE_TIME",Uuid:"UUID",Base64:"BASE_64",BigInteger:"BIG_INTEGER",_visit:(e,t)=>{switch(e){case ku.Integer:return t.integer();case ku.Long:return t.long();case ku.Uint:return t.uint();case ku.Uint64:return t.uint64();case ku.Float:return t.float();case ku.Double:return t.double();case ku.Boolean:return t.boolean();case ku.String:return t.string();case ku.Date:return t.date();case ku.DateTime:return t.dateTime();case ku.Uuid:return t.uuid();case ku.Base64:return t.base64();case ku.BigInteger:return t.bigInteger();default:return t._other()}}};var vn={integer:e=>({...e,type:"integer",_visit:function(t){return vn._visit(this,t)}}),long:e=>({...e,type:"long",_visit:function(t){return vn._visit(this,t)}}),uint:e=>({...e,type:"uint",_visit:function(t){return vn._visit(this,t)}}),uint64:e=>({...e,type:"uint64",_visit:function(t){return vn._visit(this,t)}}),float:e=>({...e,type:"float",_visit:function(t){return vn._visit(this,t)}}),double:e=>({...e,type:"double",_visit:function(t){return vn._visit(this,t)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return vn._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return vn._visit(this,t)}}),date:e=>({...e,type:"date",_visit:function(t){return vn._visit(this,t)}}),dateTime:e=>({...e,type:"dateTime",_visit:function(t){return vn._visit(this,t)}}),uuid:e=>({...e,type:"uuid",_visit:function(t){return vn._visit(this,t)}}),base64:e=>({...e,type:"base64",_visit:function(t){return vn._visit(this,t)}}),bigInteger:e=>({...e,type:"bigInteger",_visit:function(t){return vn._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"integer":return t.integer(e);case"long":return t.long(e);case"uint":return t.uint(e);case"uint64":return t.uint64(e);case"float":return t.float(e);case"double":return t.double(e);case"boolean":return t.boolean(e);case"string":return t.string(e);case"date":return t.date(e);case"dateTime":return t.dateTime(e);case"uuid":return t.uuid(e);case"base64":return t.base64(e);case"bigInteger":return t.bigInteger(e);default:return t._other(e)}}};var lF={string:e=>({string:e,type:"string",_visit:function(t){return lF._visit(this,t)}}),boolean:e=>({boolean:e,type:"boolean",_visit:function(t){return lF._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"string":return t.string(e.string);case"boolean":return t.boolean(e.boolean);default:return t._other(e)}}};var hy={alias:e=>({...e,type:"alias",_visit:function(t){return hy._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return hy._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return hy._visit(this,t)}}),union:e=>({...e,type:"union",_visit:function(t){return hy._visit(this,t)}}),undiscriminatedUnion:e=>({...e,type:"undiscriminatedUnion",_visit:function(t){return hy._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"alias":return t.alias(e);case"enum":return t.enum(e);case"object":return t.object(e);case"union":return t.union(e);case"undiscriminatedUnion":return t.undiscriminatedUnion(e);default:return t._other(e)}}};var _C={samePropertiesAsObject:e=>({...e,type:"samePropertiesAsObject",_visit:function(t){return _C._visit(this,t)}}),singleProperty:e=>({...e,type:"singleProperty",_visit:function(t){return _C._visit(this,t)}}),noProperties:()=>({type:"noProperties",_visit:function(e){return _C._visit(this,e)}}),_visit:(e,t)=>{switch(e.type){case"samePropertiesAsObject":return t.samePropertiesAsObject(e);case"singleProperty":return t.singleProperty(e);case"noProperties":return t.noProperties();default:return t._other(e)}}};var Tu={primitive:e=>({primitive:e,type:"primitive",_visit:function(t){return Tu._visit(this,t)}}),container:e=>({container:e,type:"container",_visit:function(t){return Tu._visit(this,t)}}),unknown:e=>({unknown:e,type:"unknown",_visit:function(t){return Tu._visit(this,t)}}),named:e=>({...e,type:"named",_visit:function(t){return Tu._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e.primitive);case"container":return t.container(e.container);case"unknown":return t.unknown(e.unknown);case"named":return t.named(e);default:return t._other(e)}}};var Up={list:e=>({...e,type:"list",_visit:function(t){return Up._visit(this,t)}}),set:e=>({...e,type:"set",_visit:function(t){return Up._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return Up._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return Up._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return Up._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return Up._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"list":return t.list(e);case"set":return t.set(e);case"optional":return t.optional(e);case"nullable":return t.nullable(e);case"map":return t.map(e);case"literal":return t.literal(e);default:return t._other(e)}}};var Rn={integer:e=>({integer:e,type:"integer",_visit:function(t){return Rn._visit(this,t)}}),long:e=>({long:e,type:"long",_visit:function(t){return Rn._visit(this,t)}}),uint:e=>({uint:e,type:"uint",_visit:function(t){return Rn._visit(this,t)}}),uint64:e=>({uint64:e,type:"uint64",_visit:function(t){return Rn._visit(this,t)}}),float:e=>({float:e,type:"float",_visit:function(t){return Rn._visit(this,t)}}),double:e=>({double:e,type:"double",_visit:function(t){return Rn._visit(this,t)}}),boolean:e=>({boolean:e,type:"boolean",_visit:function(t){return Rn._visit(this,t)}}),string:e=>({string:e,type:"string",_visit:function(t){return Rn._visit(this,t)}}),date:e=>({date:e,type:"date",_visit:function(t){return Rn._visit(this,t)}}),datetime:e=>({...e,type:"datetime",_visit:function(t){return Rn._visit(this,t)}}),uuid:e=>({uuid:e,type:"uuid",_visit:function(t){return Rn._visit(this,t)}}),base64:e=>({base64:e,type:"base64",_visit:function(t){return Rn._visit(this,t)}}),bigInteger:e=>({bigInteger:e,type:"bigInteger",_visit:function(t){return Rn._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"integer":return t.integer(e.integer);case"long":return t.long(e.long);case"uint":return t.uint(e.uint);case"uint64":return t.uint64(e.uint64);case"float":return t.float(e.float);case"double":return t.double(e.double);case"boolean":return t.boolean(e.boolean);case"string":return t.string(e.string);case"date":return t.date(e.date);case"datetime":return t.datetime(e);case"uuid":return t.uuid(e.uuid);case"base64":return t.base64(e.base64);case"bigInteger":return t.bigInteger(e.bigInteger);default:return t._other(e)}}};var qfh={};var T9c={};Yt(T9c,{WebhookHttpMethod:()=>Fnu,WebhookPayload:()=>fF});var fF={inlinedPayload:e=>({...e,type:"inlinedPayload",_visit:function(t){return fF._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return fF._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"inlinedPayload":return t.inlinedPayload(e);case"reference":return t.reference(e);default:return t._other(e)}}};var Fnu={Get:"GET",Post:"POST",_visit:(e,t)=>{switch(e){case Fnu.Get:return t.get();case Fnu.Post:return t.post();default:return t._other()}}};var R9c={};Yt(R9c,{ExampleWebSocketMessageBody:()=>Xve,WebSocketMessageBody:()=>pL,WebSocketMessageOrigin:()=>Qnu});var Qnu={Client:"client",Server:"server",_visit:(e,t)=>{switch(e){case Qnu.Client:return t.client();case Qnu.Server:return t.server();default:return t._other()}}};var pL={inlinedBody:e=>({...e,type:"inlinedBody",_visit:function(t){return pL._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return pL._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"inlinedBody":return t.inlinedBody(e);case"reference":return t.reference(e);default:return t._other(e)}}};var Xve={inlinedBody:e=>({...e,type:"inlinedBody",_visit:function(t){return Xve._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return Xve._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"inlinedBody":return t.inlinedBody(e);case"reference":return t.reference(e);default:return t._other(e)}}};var $n={};Yt($n,{AliasTypeDeclaration:()=>ksu,ApiAuth:()=>cau,ApiDefinitionSource:()=>Kcu,ApiDefinitionSourceId:()=>xcu,ApiVersionScheme:()=>Ssu,AudienceDefinition:()=>Gnu,AudienceReference:()=>taa,AuthScheme:()=>sau,AuthSchemeKey:()=>raa,AuthSchemesRequirement:()=>Hnu,AuthScope:()=>xnu,AutogeneratedEndpointExample:()=>dsu,Availability:()=>jYt,AvailabilityStatus:()=>Ynu,Base64Type:()=>$su,BaseAuthScheme:()=>TEe,BasicAuthScheme:()=>Jnu,BasicAuthValues:()=>Rou,BearerAuthScheme:()=>Knu,BearerAuthValues:()=>zou,BigIntegerType:()=>Ysu,BooleanType:()=>Wsu,BytesRequest:()=>Eaa,BytesResponse:()=>Iaa,Constants:()=>dau,ContainerType:()=>Vaa,CratesPublishTarget:()=>kcu,CsharpProtobufFileOptions:()=>psu,CursorPagination:()=>Yuu,CustomPagination:()=>Zuu,DateTimeType:()=>Ksu,DateType:()=>Hsu,Declaration:()=>D1,DeclaredErrorName:()=>pJi,DeclaredServiceName:()=>muu,DeclaredTypeName:()=>iE,DirectPublish:()=>tlu,DisplayName:()=>sJi,DoubleType:()=>Vsu,DoubleValidationRules:()=>Lsu,Encoding:()=>Qaa,EndpointId:()=>lUi,EndpointName:()=>Puu,EndpointReference:()=>nJi,EnumTypeDeclaration:()=>Uaa,EnumTypeReference:()=>pdh,EnumValue:()=>fUi,EnvironmentBaseUrlId:()=>Zve,EnvironmentBaseUrlWithId:()=>wou,EnvironmentId:()=>MYt,EnvironmentUrl:()=>dJi,EnvironmentVariable:()=>qEe,Environments:()=>Mou,EnvironmentsConfig:()=>Dou,ErrorDeclaration:()=>Iou,ErrorDeclarationDiscriminantValue:()=>ldh,ErrorDiscriminationByPropertyStrategy:()=>Rcu,ErrorDiscriminationStrategy:()=>zcu,ErrorId:()=>cJi,EscapedString:()=>lau,ExampleAliasType:()=>llu,ExampleCodeSample:()=>rsu,ExampleCodeSampleLanguage:()=>esu,ExampleCodeSampleSdk:()=>tsu,ExampleContainer:()=>Olu,ExampleDatetime:()=>glu,ExampleEndpointCall:()=>zaa,ExampleEndpointErrorResponse:()=>csu,ExampleEndpointSuccessResponse:()=>ssu,ExampleEnumType:()=>clu,ExampleError:()=>Bou,ExampleExtraObjectProperty:()=>plu,ExampleHeader:()=>qbn,ExampleInlinedRequestBody:()=>Raa,ExampleInlinedRequestBodyExtraProperty:()=>asu,ExampleInlinedRequestBodyProperty:()=>nsu,ExampleKeyValuePair:()=>Mlu,ExampleListContainer:()=>Plu,ExampleLiteralContainer:()=>Alu,ExampleMapContainer:()=>Slu,ExampleNamedType:()=>mlu,ExampleNullableContainer:()=>Elu,ExampleObjectProperty:()=>Kaa,ExampleObjectType:()=>Haa,ExampleObjectTypeWithTypeId:()=>blu,ExampleOptionalContainer:()=>wlu,ExamplePathParameter:()=>hJi,ExamplePrimitive:()=>Jaa,ExampleQueryParameter:()=>Taa,ExampleQueryParameterShape:()=>isu,ExampleRequestBody:()=>osu,ExampleResponse:()=>lsu,ExampleServerSideEvent:()=>usu,ExampleSetContainer:()=>jlu,ExampleSingleUnionType:()=>hlu,ExampleSingleUnionTypeProperties:()=>ylu,ExampleStyle:()=>Wcu,ExampleType:()=>F7a,ExampleTypeReference:()=>bf,ExampleTypeReferenceShape:()=>vlu,ExampleTypeShape:()=>Waa,ExampleUndiscriminatedUnionType:()=>dlu,ExampleUnionBaseProperty:()=>_lu,ExampleUnionType:()=>flu,ExampleWebSocketMessage:()=>Bcu,ExampleWebSocketMessageBody:()=>Dcu,ExampleWebSocketSession:()=>Icu,ExampleWebhookCall:()=>gcu,FeatureId:()=>T7a,FernFilepath:()=>REe,FileDownloadResponse:()=>Daa,FileProperty:()=>Duu,FilePropertyArray:()=>Muu,FilePropertySingle:()=>Suu,FileUploadBodyProperty:()=>Iuu,FileUploadBodyPropertyEncoding:()=>Buu,FileUploadRequest:()=>waa,FileUploadRequestProperty:()=>Cuu,Filesystem:()=>rlu,FloatType:()=>Usu,FloatValidationRules:()=>Qsu,GenerationMetadata:()=>nlu,GithubPublish:()=>elu,GrpcTransport:()=>ysu,HeaderApiVersionScheme:()=>Esu,HeaderAuthScheme:()=>$nu,HeaderAuthValues:()=>Nou,HttpEndpoint:()=>Asu,HttpEndpointSecurityItem:()=>$uu,HttpEndpointSource:()=>gsu,HttpHeader:()=>hF,HttpMethod:()=>juu,HttpPath:()=>NEe,HttpPathPart:()=>Auu,HttpRequestBody:()=>Saa,HttpRequestBodyReference:()=>jaa,HttpResponse:()=>_Ji,HttpResponseBody:()=>xuu,HttpService:()=>wsu,InferredAuthScheme:()=>uau,InferredAuthSchemeTokenEndpoint:()=>oau,InferredAuthenticatedRequestHeader:()=>aau,InlinedRequestBody:()=>Euu,InlinedRequestBodyProperty:()=>Paa,InlinedWebSocketMessageBody:()=>wcu,InlinedWebSocketMessageBodyProperty:()=>jcu,InlinedWebhookPayload:()=>ycu,InlinedWebhookPayloadProperty:()=>hcu,IntegerType:()=>Csu,IntegerValidationRules:()=>Isu,IntermediateRepresentation:()=>ddh,JsonEncoding:()=>Psu,JsonResponse:()=>Maa,JsonResponseBody:()=>Fuu,JsonResponseBodyWithProperty:()=>Quu,JsonStreamChunk:()=>Uuu,Literal:()=>ulu,LongType:()=>Tsu,LongValidationRules:()=>qsu,MapType:()=>slu,MavenPublishTarget:()=>Xcu,MultipleBaseUrlsEnvironment:()=>Eou,MultipleBaseUrlsEnvironments:()=>Sou,MultipleEnvironmentUrlValues:()=>Tou,Name:()=>Ua,NameAndWireValue:()=>Yc,NamedType:()=>olu,NamedTypeDefault:()=>alu,NonStreamHttpResponseBody:()=>Wuu,NpmPublishTarget:()=>Ycu,OAuthAccessTokenRequestProperties:()=>Znu,OAuthAccessTokenResponseProperties:()=>naa,OAuthClientCredentials:()=>rau,OAuthConfiguration:()=>iau,OAuthRefreshEndpoint:()=>tau,OAuthRefreshTokenRequestProperties:()=>eau,OAuthScheme:()=>nau,OAuthTokenEndpoint:()=>knu,OAuthValues:()=>Fou,ObjectProperty:()=>dx,ObjectPropertyAccess:()=>oJi,ObjectTypeDeclaration:()=>ecu,OffsetPagination:()=>Xuu,Package:()=>xaa,PackageNavigationConfig:()=>qcu,Pagination:()=>kuu,PathParameter:()=>f8t,PathParameterLocation:()=>wuu,PlatformHeaders:()=>Fcu,PostmanPublishTarget:()=>$cu,PrimitiveType:()=>Laa,PrimitiveTypeV1:()=>Bsu,PrimitiveTypeV2:()=>Xsu,PropertyPathItem:()=>iaa,ProtoEncoding:()=>jsu,ProtoSource:()=>Hcu,ProtoSourceInfo:()=>vsu,ProtobufFile:()=>Naa,ProtobufFileOptions:()=>_su,ProtobufMethodType:()=>bsu,ProtobufService:()=>hsu,ProtobufType:()=>lcu,PublishTarget:()=>yJi,PublishingConfig:()=>ilu,PypiPublishTarget:()=>Zcu,QueryParameter:()=>aJi,ReadmeConfig:()=>Gcu,ReadmeCustomSection:()=>Vcu,RequestProperty:()=>OW,RequestPropertyValue:()=>Xnu,ResolvedNamedType:()=>Dsu,ResolvedTypeReference:()=>Zsu,ResponseError:()=>Kuu,ResponseErrors:()=>Juu,ResponseProperty:()=>_F,RetriesConfiguration:()=>msu,RetriesDisabledSchema:()=>Osu,SafeAndUnsafeString:()=>Ibn,SdkConfig:()=>Qcu,SdkRequest:()=>Nuu,SdkRequestBodyType:()=>Tuu,SdkRequestShape:()=>zuu,SdkRequestWrapper:()=>Ruu,ServiceId:()=>AYt,ServiceTypeReferenceInfo:()=>Lcu,ShapeType:()=>Msu,SingleBaseUrlEnvironment:()=>Pou,SingleBaseUrlEnvironments:()=>jou,SingleUnionType:()=>icu,SingleUnionTypeProperties:()=>rcu,SingleUnionTypeProperty:()=>tcu,Source:()=>fcu,SourceConfig:()=>Jcu,SseStreamChunk:()=>Vuu,StreamParameterResponse:()=>Guu,StreamingResponse:()=>Caa,StringType:()=>xsu,StringValidationRules:()=>Gsu,Subpackage:()=>Tcu,SubpackageId:()=>PYt,SupportedSdkLanguage:()=>qaa,TextResponse:()=>Baa,TextStreamChunk:()=>Luu,Transport:()=>Faa,Type:()=>ucu,TypeDeclaration:()=>dcu,TypeId:()=>_L,TypeReference:()=>Ss,Uint64Type:()=>Fsu,Uint64ValidationRules:()=>Nsu,UintType:()=>zsu,UintValidationRules:()=>Rsu,UndiscriminatedUnionMember:()=>acu,UndiscriminatedUnionTypeDeclaration:()=>ocu,UnionTypeDeclaration:()=>ncu,UserAgent:()=>Ncu,UserDefinedProtobufType:()=>ccu,UserSpecifiedEndpointExample:()=>fsu,UuidType:()=>Jsu,V2AuthValues:()=>daa,V2EndpointLocation:()=>qou,V2EndpointLocationHttpMethod:()=>Cou,V2EnvironmentValues:()=>faa,V2HttpEndpointCodeSample:()=>Vou,V2HttpEndpointExample:()=>R7a,V2HttpEndpointExamples:()=>Wou,V2HttpEndpointRequest:()=>Qou,V2HttpEndpointResponse:()=>Lou,V2HttpEndpointResponseBody:()=>Uou,V2HttpRequestBodies:()=>quu,V2HttpResponses:()=>Huu,V2SchemaExample:()=>q7a,V2SchemaExamples:()=>pF,V2ValueExamples:()=>DYt,V2WebSocketEndpointLocation:()=>Gou,V2WebSocketMessageExample:()=>xou,V2WebSocketSessionExample:()=>z7a,V2WebSocketSessionExamples:()=>Hou,V2WebhookExample:()=>N7a,V2WebhookExamples:()=>Kou,VariableDeclaration:()=>Ucu,VariableId:()=>Aaa,WebSocketChannel:()=>Ccu,WebSocketChannelId:()=>oaa,WebSocketMessage:()=>Mcu,WebSocketMessageBody:()=>Scu,WebSocketMessageBodyReference:()=>Ecu,WebSocketMessageId:()=>Gaa,WebSocketMessageOrigin:()=>Pcu,WebSocketName:()=>Acu,Webhook:()=>Ocu,WebhookGroup:()=>mcu,WebhookGroupId:()=>aaa,WebhookHttpMethod:()=>_cu,WebhookId:()=>fau,WebhookName:()=>pcu,WebhookPayload:()=>vcu,WebhookPayloadReference:()=>bcu,WellKnownProtobufType:()=>scu,WithContentType:()=>zEe,WithDocs:()=>Jn,WithDocsAndAvailability:()=>uJi,WithJsonExample:()=>wYt,WithV2Examples:()=>rE,audience:()=>U9c,auth:()=>L9c,commons:()=>V9c,constants:()=>W9c,dynamic:()=>MM,environment:()=>eGc,errors:()=>tGc,examples:()=>rGc,generatorExec:()=>nGc,http:()=>aGc,ir:()=>oGc,proto:()=>uGc,publish:()=>sGc,types:()=>cGc,variables:()=>lGc,webhooks:()=>fGc,websocket:()=>dGc});var U9c={};Yt(U9c,{AudienceDefinition:()=>Gnu,AudienceReference:()=>taa});var S={};Yt(S,{JsonError:()=>Zna,ParseError:()=>kna,any:()=>Jfh,bigint:()=>Rfh,boolean:()=>$fh,booleanLiteral:()=>Kfh,date:()=>zfh,discriminant:()=>ndh,enum_:()=>Lnu,getObjectLikeUtils:()=>l8t,getObjectUtils:()=>Bbn,getSchemaUtils:()=>YP,isProperty:()=>iJi,lazy:()=>Nfh,lazyObject:()=>Gfh,list:()=>Wnu,number:()=>Yfh,object:()=>Vnu,objectWithoutOptionalProperties:()=>Wfh,optional:()=>z9c,property:()=>Qfh,record:()=>edh,set:()=>tdh,string:()=>Xfh,stringLiteral:()=>Hfh,transform:()=>N9c,undiscriminatedUnion:()=>idh,union:()=>odh,unknown:()=>Zfh,withParsedProperties:()=>Q9c});var Fh={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 jA(e,t){return`Expected ${t}. Received ${HLD(e)}.`}function HLD(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 dF(e){return{...e,json:Tfh(e.json),parse:Tfh(e.parse)}}function Tfh(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(`
1466
1466
  `)),{ok:!0,value:t}):i}}function Unu(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var Zna=class e extends Error{errors;constructor(t){super(t.map(Unu).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var kna=class e extends Error{errors;constructor(t){super(t.map(Unu).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function YP(e){return{optional:()=>z9c(e),transform:t=>N9c(e,t),parseOrThrow:(t,r)=>{let i=e.parse(t,r);if(i.ok)return i.value;throw new kna(i.errors)},jsonOrThrow:(t,r)=>{let i=e.json(t,r);if(i.ok)return i.value;throw new Zna(i.errors)}}}function z9c(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:()=>Fh.OPTIONAL};return{...t,...YP(t)}}function N9c(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,...YP(r)}}function Rfh(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:jA(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:jA(t,"bigint")}]},getType:()=>Fh.BIGINT};return{...dF(e),...YP(e)}}var KLD=/^([+-]?\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 zfh(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:jA(t,"string")}]}:KLD.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:jA(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:jA(t,"Date object")}]},getType:()=>Fh.DATE};return{...dF(e),...YP(e)}}function gW(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{...dF(r),...YP(r)}}}function Lnu(e){let t=new Set(e);return gW(Fh.ENUM,(i,{allowUnrecognizedEnumValues:n,breadcrumbsPrefix:a=[]}={})=>typeof i!="string"?{ok:!1,errors:[{path:a,message:jA(i,"string")}]}:!t.has(i)&&!n?{ok:!1,errors:[{path:a,message:jA(i,"enum")}]}:{ok:!0,value:i})()}function Nfh(e){let t=F9c(e);return{...t,...YP(t)}}function F9c(e){return{parse:(t,r)=>eaa(e).parse(t,r),json:(t,r)=>eaa(e).json(t,r),getType:()=>eaa(e).getType()}}function eaa(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function B7a(e){return Object.entries(e)}function I7a(e,t){let r=new Set(t);return Object.entries(e).reduce((i,[n,a])=>(r.has(n)&&(i[n]=a),i),{})}function rJi(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 C7a(e){return Object.keys(e)}function Ffh(e,t){let r=[],i=[];for(let n of e)t(n)?r.push(n):i.push(n);return[r,i]}function l8t(e){return{withParsedProperties:t=>Q9c(e,t)}}function Q9c(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(!rJi(i))return{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:jA(i,"object")}]};let a=new Set(Object.keys(t)),o=I7a(i,Object.keys(i).filter(c=>!a.has(c)));return e.json(o,n)},getType:()=>e.getType()};return{...r,...YP(r),...l8t(r)}}function Qfh(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function iJi(e){return e.isProperty}function Vnu(e){let t={_getRawProperties:()=>Object.entries(e).map(([r,i])=>iJi(i)?i.rawKey:r),_getParsedProperties:()=>C7a(e),parse:(r,i)=>{let n={},a=[];for(let[o,c]of B7a(e)){let d=iJi(c)?c.rawKey:o,s=iJi(c)?c.valueSchema:c,u={rawKey:d,parsedKey:o,valueSchema:s};n[d]=u,Vfh(s)&&a.push(d)}return Ufh({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 B7a(e)){let c=iJi(o)?o.valueSchema:o;Vfh(c)&&n.push(a)}return Ufh({value:r,requiredKeys:n,getProperty:a=>{let o=e[a];if(o!=null)return iJi(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:()=>Fh.OBJECT};return{...dF(t),...YP(t),...l8t(t),...Bbn(t)}}function Ufh({value:e,requiredKeys:t,getProperty:r,unrecognizedObjectKeys:i="fail",skipValidation:n=!1,breadcrumbsPrefix:a=[]}){if(!rJi(e))return{ok:!1,errors:[{path:a,message:jA(e,"object")}]};let o=new Set(t),c=[],d={};for(let[s,u]of Object.entries(e)){let l=r(s);if(l!=null){o.delete(s);let p=l.transform(u);p.ok?d[l.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 Bbn(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(i,n)=>Lfh({extensionKeys:t._getRawProperties(),value:i,transformBase:a=>e.parse(a,n),transformExtension:a=>t.parse(a,n)}),json:(i,n)=>Lfh({extensionKeys:t._getParsedProperties(),value:i,transformBase:a=>e.json(a,n),transformExtension:a=>t.json(a,n)}),getType:()=>Fh.OBJECT};return{...r,...YP(r),...l8t(r),...Bbn(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:()=>Fh.OBJECT};return{...t,...YP(t),...l8t(t),...Bbn(t)}}}}function Lfh({extensionKeys:e,value:t,transformBase:r,transformExtension:i}){let n=new Set(e),[a,o]=Ffh(C7a(t),s=>n.has(s)),c=r(I7a(t,o)),d=i(I7a(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 Vfh(e){return!JLD(e)}function JLD(e){switch(e.getType()){case Fh.ANY:case Fh.UNKNOWN:case Fh.OPTIONAL:return!0;default:return!1}}function Wfh(e){return Vnu(e)}function Gfh(e){let t={...F9c(e),_getRawProperties:()=>eaa(e)._getRawProperties(),_getParsedProperties:()=>eaa(e)._getParsedProperties()};return{...t,...YP(t),...l8t(t),...Bbn(t)}}function Wnu(e){let t={parse:(r,i)=>xfh(r,(n,a)=>e.parse(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),json:(r,i)=>xfh(r,(n,a)=>e.json(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),getType:()=>Fh.LIST};return{...dF(t),...YP(t)}}function xfh(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:jA(e,"list"),path:[]}]}}function Hfh(e){return gW(Fh.STRING_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:jA(r,`"${e}"`)}]})()}function Kfh(e){return gW(Fh.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:jA(r,`${e.toString()}`)}]})()}var Jfh=gW(Fh.ANY,e=>({ok:!0,value:e}));var $fh=gW(Fh.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:jA(e,"boolean")}]});var Yfh=gW(Fh.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:jA(e,"number")}]});var Xfh=gW(Fh.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:jA(e,"string")}]});var Zfh=gW(Fh.UNKNOWN,e=>({ok:!0,value:e}));function edh(e,t){let r={parse:(i,n)=>kfh({value:i,isKeyNumeric:e.getType()===Fh.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)=>kfh({value:i,isKeyNumeric:e.getType()===Fh.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:()=>Fh.RECORD};return{...dF(r),...YP(r)}}function kfh({value:e,isKeyNumeric:t,transformKey:r,transformValue:i,breadcrumbsPrefix:n=[]}){return rJi(e)?B7a(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),l=i(c,s);if(d.ok&&u.ok&&l.ok)return{ok:!0,value:{...d.value,[u.value]:l.value}};let p=[];return d.ok||p.push(...d.errors),u.ok||p.push(...u.errors),l.ok||p.push(...l.errors),{ok:!1,errors:p}},{ok:!0,value:{}}):{ok:!1,errors:[{path:n,message:jA(e,"object")}]}}function tdh(e){let t=Wnu(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:jA(i,"Set")}]},getType:()=>Fh.SET};return{...dF(r),...YP(r)}}function idh(e){let t={parse:(r,i)=>rdh((n,a)=>n.parse(r,a),e,i),json:(r,i)=>rdh((n,a)=>n.json(r,a),e,i),getType:()=>Fh.UNDISCRIMINATED_UNION};return{...dF(t),...YP(t)}}function rdh(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 ndh(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}function odh(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,i=typeof e=="string"?e:e.parsedDiscriminant,n=Lnu(C7a(t)),a={parse:(o,c)=>adh({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)=>adh({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:()=>Fh.UNION};return{...dF(a),...YP(a),...l8t(a)}}function adh({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:i,getAdditionalPropertiesSchema:n,allowUnrecognizedUnionMembers:a=!1,transformAdditionalProperties:o,breadcrumbsPrefix:c=[]}){if(!rJi(e))return{ok:!1,errors:[{path:c,message:jA(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 l=n(u.value);if(l==null)return a?{ok:!0,value:{[r]:u.value,...s}}:{ok:!1,errors:[{path:[...c,t],message:"Unexpected discriminant value"}]};let p=o(s,l);return p.ok?{ok:!0,value:{[r]:d,...p.value}}:p}var Gnu=S.string();var taa=S.string();var L9c={};Yt(L9c,{ApiAuth:()=>cau,AuthScheme:()=>sau,AuthSchemeKey:()=>raa,AuthSchemesRequirement:()=>Hnu,AuthScope:()=>xnu,BaseAuthScheme:()=>TEe,BasicAuthScheme:()=>Jnu,BearerAuthScheme:()=>Knu,EnvironmentVariable:()=>qEe,HeaderAuthScheme:()=>$nu,InferredAuthScheme:()=>uau,InferredAuthSchemeTokenEndpoint:()=>oau,InferredAuthenticatedRequestHeader:()=>aau,OAuthAccessTokenRequestProperties:()=>Znu,OAuthAccessTokenResponseProperties:()=>naa,OAuthClientCredentials:()=>rau,OAuthConfiguration:()=>iau,OAuthRefreshEndpoint:()=>tau,OAuthRefreshTokenRequestProperties:()=>eau,OAuthScheme:()=>nau,OAuthTokenEndpoint:()=>knu});var qEe=S.string();var raa=S.string();var xnu=S.string();var Hnu=S.enum_(["ALL","ANY","ENDPOINT_SECURITY"]);var Ibn=S.objectWithoutOptionalProperties({unsafeName:S.string(),safeName:S.string()});var Ua=S.objectWithoutOptionalProperties({originalName:S.string(),camelCase:Ibn,pascalCase:Ibn,snakeCase:Ibn,screamingSnakeCase:Ibn});var Jn=S.objectWithoutOptionalProperties({docs:S.string().optional()});var TEe=S.objectWithoutOptionalProperties({key:raa}).extend(Jn);var Knu=S.objectWithoutOptionalProperties({token:Ua,tokenEnvVar:qEe.optional()}).extend(TEe);var Jnu=S.objectWithoutOptionalProperties({username:Ua,usernameEnvVar:qEe.optional(),password:Ua,passwordEnvVar:qEe.optional()}).extend(TEe);var Yc=S.objectWithoutOptionalProperties({wireValue:S.string(),name:Ua});var $nu=S.objectWithoutOptionalProperties({name:Yc,valueType:S.lazy(()=>Ss),prefix:S.string().optional(),headerEnvVar:qEe.optional()}).extend(TEe);var lUi=S.string();var AYt=S.string();var PYt=S.string();var nJi=S.objectWithoutOptionalProperties({endpointId:lUi,serviceId:AYt,subpackageId:PYt.optional()});var iaa=S.objectWithoutOptionalProperties({name:Ua,type:S.lazy(()=>Ss)});var q7a=S.unknown();var pF=S.objectWithoutOptionalProperties({userSpecifiedExamples:S.record(S.string(),q7a),autogeneratedExamples:S.record(S.string(),q7a)});var Ynu=S.enum_(["IN_DEVELOPMENT","PRE_RELEASE","GENERAL_AVAILABILITY","DEPRECATED"]);var jYt=S.objectWithoutOptionalProperties({status:Ynu,message:S.string().optional()});var D1=S.objectWithoutOptionalProperties({availability:jYt.optional()}).extend(Jn);var aJi=S.objectWithoutOptionalProperties({name:Yc,valueType:S.lazy(()=>Ss),allowMultiple:S.boolean(),v2Examples:pF.optional(),explode:S.boolean().optional()}).extend(D1);var oJi=S.enum_(["READ_ONLY","WRITE_ONLY"]);var dx=S.objectWithoutOptionalProperties({name:Yc,valueType:S.lazy(()=>Ss),propertyAccess:oJi.optional(),v2Examples:pF.optional()}).extend(D1);var Xnu=S.union("type",{query:aJi,body:dx}).transform({transform:e=>{switch(e.type){case"query":return oY.query(e);case"body":return oY.body(e);default:return e}},untransform:({_visit:e,...t})=>t});var OW=S.objectWithoutOptionalProperties({propertyPath:S.list(iaa).optional(),property:Xnu});var Znu=S.objectWithoutOptionalProperties({clientId:OW,clientSecret:OW,scopes:OW.optional(),customProperties:S.list(OW).optional()});var _F=S.objectWithoutOptionalProperties({propertyPath:S.list(iaa).optional(),property:dx});var naa=S.objectWithoutOptionalProperties({accessToken:_F,expiresIn:_F.optional(),refreshToken:_F.optional()});var knu=S.objectWithoutOptionalProperties({endpointReference:nJi,requestProperties:Znu,responseProperties:naa});var eau=S.objectWithoutOptionalProperties({refreshToken:OW});var tau=S.objectWithoutOptionalProperties({endpointReference:nJi,requestProperties:eau,responseProperties:naa});var rau=S.objectWithoutOptionalProperties({clientIdEnvVar:qEe.optional(),clientSecretEnvVar:qEe.optional(),tokenPrefix:S.string().optional(),tokenHeader:S.string().optional(),scopes:S.list(S.string()).optional(),tokenEndpoint:knu,refreshEndpoint:tau.optional()});var iau=S.union("type",{clientCredentials:rau}).transform({transform:e=>{switch(e.type){case"clientCredentials":return ZKi.clientCredentials(e);default:return e}},untransform:({_visit:e,...t})=>t});var nau=S.objectWithoutOptionalProperties({configuration:iau}).extend(TEe);var aau=S.objectWithoutOptionalProperties({responseProperty:_F,headerName:S.string(),valuePrefix:S.string().optional()});var oau=S.objectWithoutOptionalProperties({endpoint:nJi,expiryProperty:_F.optional(),authenticatedRequestHeaders:S.list(aau)});var uau=S.objectWithoutOptionalProperties({tokenEndpoint:oau}).extend(TEe);var sau=S.union(S.discriminant("type","_type"),{bearer:Knu,basic:Jnu,header:$nu,oauth:nau,inferred:uau}).transform({transform:e=>{switch(e.type){case"bearer":return PA.bearer(e);case"basic":return PA.basic(e);case"header":return PA.header(e);case"oauth":return PA.oauth(e);case"inferred":return PA.inferred(e);default:return e}},untransform:({_visit:e,...t})=>t});var cau=S.objectWithoutOptionalProperties({requirement:Hnu,schemes:S.list(sau)}).extend(Jn);var V9c={};Yt(V9c,{Availability:()=>jYt,AvailabilityStatus:()=>Ynu,Declaration:()=>D1,DisplayName:()=>sJi,EndpointId:()=>lUi,EndpointReference:()=>nJi,ErrorId:()=>cJi,EscapedString:()=>lau,FeatureId:()=>T7a,FernFilepath:()=>REe,Name:()=>Ua,NameAndWireValue:()=>Yc,SafeAndUnsafeString:()=>Ibn,ServiceId:()=>AYt,SubpackageId:()=>PYt,TypeId:()=>_L,WebSocketChannelId:()=>oaa,WebhookGroupId:()=>aaa,WebhookId:()=>fau,WithContentType:()=>zEe,WithDocs:()=>Jn,WithDocsAndAvailability:()=>uJi,WithJsonExample:()=>wYt});var uJi=S.objectWithoutOptionalProperties({availability:jYt.optional()}).extend(Jn);var REe=S.objectWithoutOptionalProperties({allParts:S.list(Ua),packagePath:S.list(Ua),file:Ua.optional()});var sJi=S.string();var lau=S.objectWithoutOptionalProperties({original:S.string()});var wYt=S.objectWithoutOptionalProperties({jsonExample:S.unknown()});var zEe=S.objectWithoutOptionalProperties({contentType:S.string().optional()});var _L=S.string();var cJi=S.string();var aaa=S.string();var fau=S.string();var oaa=S.string();var T7a=S.string();var W9c={};Yt(W9c,{Constants:()=>dau});var dau=S.objectWithoutOptionalProperties({errorInstanceIdKey:Yc});var MM={};Yt(MM,{AliasType:()=>Yau,Auth:()=>gau,AuthValues:()=>wau,BasicAuth:()=>pau,BasicAuthValues:()=>Oau,BearerAuth:()=>_au,BearerAuthValues:()=>mau,BodyRequest:()=>Dau,CratesPublishInfo:()=>_ou,Declaration:()=>mW,DiscriminatedUnionType:()=>iou,DynamicIntermediateRepresentation:()=>vou,Endpoint:()=>Vau,EndpointExample:()=>Lau,EndpointId:()=>Sau,EndpointLocation:()=>saa,EndpointSnippetRequest:()=>Uau,EndpointSnippetResponse:()=>udh,EnumType:()=>Xau,EnvironmentBaseUrlId:()=>lJi,EnvironmentBaseUrlWithId:()=>xau,EnvironmentId:()=>SYt,EnvironmentUrl:()=>fJi,EnvironmentValues:()=>Qau,Environments:()=>Jau,EnvironmentsConfig:()=>$au,ErrorSeverity:()=>gou,Error_:()=>Oou,FernFilepath:()=>Eau,FileUploadRequestBody:()=>Cau,FileUploadRequestBodyProperty:()=>Iau,GeneratorConfig:()=>bou,GeneratorOutputConfig:()=>you,GoPublishInfo:()=>uou,HeaderAuth:()=>yau,HeaderAuthValues:()=>Aau,HttpMethod:()=>Mau,InferredAuth:()=>vau,InferredAuthValues:()=>jau,InlinedRequest:()=>Rau,InlinedRequestBody:()=>qau,InlinedRequestMetadata:()=>Tau,LiteralType:()=>mou,MapType:()=>cdh,MavenPublishInfo:()=>cou,MultipleBaseUrlsEnvironment:()=>Hau,MultipleBaseUrlsEnvironments:()=>Kau,MultipleEnvironmentUrlValues:()=>Fau,Name:()=>tE,NameAndWireValue:()=>hL,NamedParameter:()=>lw,NamedType:()=>aou,NpmPublishInfo:()=>lou,NugetPublishInfo:()=>fou,OAuth:()=>bau,OAuthValues:()=>Pau,ObjectPropertyAccess:()=>hau,ObjectType:()=>Zau,PrimitiveTypeV1:()=>Aou,PublishInfo:()=>hou,PypiPublishInfo:()=>dou,ReferencedRequestBody:()=>Bau,ReferencedRequestBodyType:()=>caa,Request:()=>zau,Response:()=>Nau,RubyGemsPublishInfo:()=>pou,SafeAndUnsafeString:()=>Cbn,SingleBaseUrlEnvironment:()=>Wau,SingleBaseUrlEnvironments:()=>Gau,SingleDiscriminatedUnionType:()=>rou,SingleDiscriminatedUnionTypeNoProperties:()=>tou,SingleDiscriminatedUnionTypeObject:()=>kau,SingleDiscriminatedUnionTypeSingleProperty:()=>eou,SwiftPublishInfo:()=>sou,TypeId:()=>EYt,TypeReference:()=>sdh,UndiscriminatedUnionType:()=>nou,Values:()=>laa,VariableDeclaration:()=>oou,WithDocs:()=>uaa,auth:()=>G9c,commons:()=>x9c,declaration:()=>H9c,endpoints:()=>K9c,environment:()=>J9c,http:()=>$9c,ir:()=>Y9c,snippets:()=>X9c,types:()=>Z9c,variables:()=>k9c});var G9c={};Yt(G9c,{Auth:()=>gau,AuthValues:()=>wau,BasicAuth:()=>pau,BasicAuthValues:()=>Oau,BearerAuth:()=>_au,BearerAuthValues:()=>mau,HeaderAuth:()=>yau,HeaderAuthValues:()=>Aau,InferredAuth:()=>vau,InferredAuthValues:()=>jau,OAuth:()=>bau,OAuthValues:()=>Pau});var Cbn=S.objectWithoutOptionalProperties({unsafeName:S.string(),safeName:S.string()});var tE=S.objectWithoutOptionalProperties({originalName:S.string(),camelCase:Cbn,pascalCase:Cbn,snakeCase:Cbn,screamingSnakeCase:Cbn});var pau=S.objectWithoutOptionalProperties({username:tE,password:tE});var _au=S.objectWithoutOptionalProperties({token:tE});var hL=S.objectWithoutOptionalProperties({wireValue:S.string(),name:tE});var hau=S.enum_(["READ_ONLY","WRITE_ONLY"]);var lw=S.objectWithoutOptionalProperties({name:hL,typeReference:S.lazy(()=>MM.TypeReference),propertyAccess:hau.optional(),variable:S.string().optional()});var yau=S.objectWithoutOptionalProperties({header:lw});var bau=S.objectWithoutOptionalProperties({clientId:tE,clientSecret:tE});var vau=S.objectWithoutOptionalProperties({parameters:S.list(lw).optional()});var gau=S.union("type",{basic:pau,bearer:_au,header:yau,oauth:bau,inferred:vau}).transform({transform:e=>{switch(e.type){case"basic":return Xt.Auth.basic(e);case"bearer":return Xt.Auth.bearer(e);case"header":return Xt.Auth.header(e);case"oauth":return Xt.Auth.oauth(e);case"inferred":return Xt.Auth.inferred(e);default:return e}},untransform:({_visit:e,...t})=>t});var Oau=S.objectWithoutOptionalProperties({username:S.string(),password:S.string()});var mau=S.objectWithoutOptionalProperties({token:S.string()});var Aau=S.objectWithoutOptionalProperties({value:S.unknown()});var Pau=S.objectWithoutOptionalProperties({clientId:S.string(),clientSecret:S.string()});var jau=S.objectWithoutOptionalProperties({values:S.record(S.string(),S.unknown()).optional()});var wau=S.union("type",{basic:Oau,bearer:mau,header:Aau,oauth:Pau,inferred:jau}).transform({transform:e=>{switch(e.type){case"basic":return Xt.AuthValues.basic(e);case"bearer":return Xt.AuthValues.bearer(e);case"header":return Xt.AuthValues.header(e);case"oauth":return Xt.AuthValues.oauth(e);case"inferred":return Xt.AuthValues.inferred(e);default:return e}},untransform:({_visit:e,...t})=>t});var x9c={};Yt(x9c,{EndpointId:()=>Sau,FernFilepath:()=>Eau,Name:()=>tE,NameAndWireValue:()=>hL,SafeAndUnsafeString:()=>Cbn,TypeId:()=>EYt,WithDocs:()=>uaa});var uaa=S.objectWithoutOptionalProperties({docs:S.string().optional()});var Eau=S.objectWithoutOptionalProperties({allParts:S.list(tE),packagePath:S.list(tE),file:tE.optional()});var Sau=S.string();var EYt=S.string();var H9c={};Yt(H9c,{Declaration:()=>mW});var mW=S.objectWithoutOptionalProperties({fernFilepath:Eau,name:tE});var K9c={};Yt(K9c,{BodyRequest:()=>Dau,Endpoint:()=>Vau,EndpointExample:()=>Lau,EndpointLocation:()=>saa,FileUploadRequestBody:()=>Cau,FileUploadRequestBodyProperty:()=>Iau,InlinedRequest:()=>Rau,InlinedRequestBody:()=>qau,InlinedRequestMetadata:()=>Tau,ReferencedRequestBody:()=>Bau,ReferencedRequestBodyType:()=>caa,Request:()=>zau,Response:()=>Nau});var Mau=S.enum_(["GET","POST","PUT","PATCH","DELETE","HEAD"]);var saa=S.objectWithoutOptionalProperties({method:Mau,path:S.string()});var caa=S.union("type",{bytes:S.object({}),typeReference:S.object({value:S.lazy(()=>MM.TypeReference)})}).transform({transform:e=>{switch(e.type){case"bytes":return Xt.ReferencedRequestBodyType.bytes();case"typeReference":return Xt.ReferencedRequestBodyType.typeReference(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var Dau=S.objectWithoutOptionalProperties({pathParameters:S.list(lw).optional(),body:caa.optional()});var Bau=S.objectWithoutOptionalProperties({bodyKey:tE,bodyType:caa});var Iau=S.union("type",{file:hL,fileArray:hL,bodyProperty:lw}).transform({transform:e=>{switch(e.type){case"file":return Xt.FileUploadRequestBodyProperty.file(e);case"fileArray":return Xt.FileUploadRequestBodyProperty.fileArray(e);case"bodyProperty":return Xt.FileUploadRequestBodyProperty.bodyProperty(e);default:return e}},untransform:({_visit:e,...t})=>t});var Cau=S.objectWithoutOptionalProperties({properties:S.list(Iau)});var qau=S.union("type",{properties:S.object({value:S.list(lw)}),referenced:Bau,fileUpload:Cau}).transform({transform:e=>{switch(e.type){case"properties":return Xt.InlinedRequestBody.properties(e.value);case"referenced":return Xt.InlinedRequestBody.referenced(e);case"fileUpload":return Xt.InlinedRequestBody.fileUpload(e);default:return e}},untransform:({_visit:e,...t})=>t});var Tau=S.objectWithoutOptionalProperties({includePathParameters:S.boolean(),onlyPathParameters:S.boolean()});var Rau=S.objectWithoutOptionalProperties({declaration:mW,pathParameters:S.list(lw).optional(),queryParameters:S.list(lw).optional(),headers:S.list(lw).optional(),body:qau.optional(),metadata:Tau.optional()});var zau=S.union("type",{body:Dau,inlined:Rau}).transform({transform:e=>{switch(e.type){case"body":return Xt.Request.body(e);case"inlined":return Xt.Request.inlined(e);default:return e}},untransform:({_visit:e,...t})=>t});var Nau=S.union("type",{json:S.object({}),streaming:S.object({}),streamParameter:S.object({}),fileDownload:S.object({}),text:S.object({}),bytes:S.object({})}).transform({transform:e=>{switch(e.type){case"json":return Xt.Response.json();case"streaming":return Xt.Response.streaming();case"streamParameter":return Xt.Response.streamParameter();case"fileDownload":return Xt.Response.fileDownload();case"text":return Xt.Response.text();case"bytes":return Xt.Response.bytes();default:return e}},untransform:({_visit:e,...t})=>t});var SYt=S.string();var lJi=S.string();var fJi=S.string();var Fau=S.record(lJi,fJi);var Qau=S.undiscriminatedUnion([SYt,Fau]);var laa=S.record(S.string(),S.unknown());var Uau=S.objectWithoutOptionalProperties({endpoint:saa,baseUrl:S.property("baseURL",S.string().optional()),environment:Qau.optional(),auth:wau.optional(),pathParameters:laa.optional(),queryParameters:laa.optional(),headers:laa.optional(),requestBody:S.unknown().optional()});var Lau=S.objectWithoutOptionalProperties({id:S.string(),name:S.string().optional()}).extend(Uau);var Vau=S.objectWithoutOptionalProperties({auth:gau.optional(),declaration:mW,location:saa,request:zau,response:Nau,examples:S.list(Lau).optional()});var J9c={};Yt(J9c,{EnvironmentBaseUrlId:()=>lJi,EnvironmentBaseUrlWithId:()=>xau,EnvironmentId:()=>SYt,EnvironmentUrl:()=>fJi,EnvironmentValues:()=>Qau,Environments:()=>Jau,EnvironmentsConfig:()=>$au,MultipleBaseUrlsEnvironment:()=>Hau,MultipleBaseUrlsEnvironments:()=>Kau,MultipleEnvironmentUrlValues:()=>Fau,SingleBaseUrlEnvironment:()=>Wau,SingleBaseUrlEnvironments:()=>Gau});var Wau=S.objectWithoutOptionalProperties({id:SYt,name:tE,url:fJi}).extend(uaa);var Gau=S.objectWithoutOptionalProperties({environments:S.list(Wau)});var xau=S.objectWithoutOptionalProperties({id:lJi,name:tE});var Hau=S.objectWithoutOptionalProperties({id:SYt,name:tE,urls:S.record(lJi,fJi)}).extend(uaa);var Kau=S.objectWithoutOptionalProperties({baseUrls:S.list(xau),environments:S.list(Hau)});var Jau=S.union("type",{singleBaseUrl:Gau,multipleBaseUrls:Kau}).transform({transform:e=>{switch(e.type){case"singleBaseUrl":return Xt.Environments.singleBaseUrl(e);case"multipleBaseUrls":return Xt.Environments.multipleBaseUrls(e);default:return e}},untransform:({_visit:e,...t})=>t});var $au=S.objectWithoutOptionalProperties({defaultEnvironment:SYt.optional(),environments:Jau});var $9c={};Yt($9c,{HttpMethod:()=>Mau});var Y9c={};Yt(Y9c,{CratesPublishInfo:()=>_ou,DynamicIntermediateRepresentation:()=>vou,GeneratorConfig:()=>bou,GeneratorOutputConfig:()=>you,GoPublishInfo:()=>uou,MavenPublishInfo:()=>cou,NpmPublishInfo:()=>lou,NugetPublishInfo:()=>fou,PublishInfo:()=>hou,PypiPublishInfo:()=>dou,RubyGemsPublishInfo:()=>pou,SwiftPublishInfo:()=>sou});var Yau=S.objectWithoutOptionalProperties({declaration:mW,typeReference:S.lazy(()=>MM.TypeReference)});var Xau=S.objectWithoutOptionalProperties({declaration:mW,values:S.list(hL)});var Zau=S.objectWithoutOptionalProperties({declaration:mW,properties:S.list(lw),extends:S.list(EYt).optional(),additionalProperties:S.boolean().optional()});var kau=S.objectWithoutOptionalProperties({typeId:EYt,discriminantValue:hL,properties:S.list(lw)});var eou=S.objectWithoutOptionalProperties({typeReference:S.lazy(()=>MM.TypeReference),discriminantValue:hL,properties:S.list(lw).optional()});var tou=S.objectWithoutOptionalProperties({discriminantValue:hL,properties:S.list(lw).optional()});var rou=S.union("type",{samePropertiesAsObject:kau,singleProperty:eou,noProperties:tou}).transform({transform:e=>{switch(e.type){case"samePropertiesAsObject":return Xt.SingleDiscriminatedUnionType.samePropertiesAsObject(e);case"singleProperty":return Xt.SingleDiscriminatedUnionType.singleProperty(e);case"noProperties":return Xt.SingleDiscriminatedUnionType.noProperties(e);default:return e}},untransform:({_visit:e,...t})=>t});var iou=S.objectWithoutOptionalProperties({declaration:mW,discriminant:hL,types:S.record(S.string(),rou)});var nou=S.objectWithoutOptionalProperties({declaration:mW,types:S.list(S.lazy(()=>MM.TypeReference))});var aou=S.union("type",{alias:Yau,enum:Xau,object:Zau,discriminatedUnion:iou,undiscriminatedUnion:nou}).transform({transform:e=>{switch(e.type){case"alias":return Xt.NamedType.alias(e);case"enum":return Xt.NamedType.enum(e);case"object":return Xt.NamedType.object(e);case"discriminatedUnion":return Xt.NamedType.discriminatedUnion(e);case"undiscriminatedUnion":return Xt.NamedType.undiscriminatedUnion(e);default:return e}},untransform:({_visit:e,...t})=>t});var oou=S.objectWithoutOptionalProperties({id:S.string(),name:Ua,typeReference:S.lazy(()=>MM.TypeReference)});var uou=S.objectWithoutOptionalProperties({version:S.string(),repoUrl:S.string()});var sou=S.objectWithoutOptionalProperties({version:S.string(),repoUrl:S.string()});var cou=S.objectWithoutOptionalProperties({version:S.string(),coordinate:S.string(),repoUrl:S.string().optional()});var lou=S.objectWithoutOptionalProperties({version:S.string(),packageName:S.string(),repoUrl:S.string().optional()});var fou=S.objectWithoutOptionalProperties({version:S.string(),packageName:S.string(),repoUrl:S.string().optional()});var dou=S.objectWithoutOptionalProperties({version:S.string(),packageName:S.string(),repoUrl:S.string().optional()});var pou=S.objectWithoutOptionalProperties({version:S.string(),packageName:S.string(),repoUrl:S.string().optional()});var _ou=S.objectWithoutOptionalProperties({version:S.string(),packageName:S.string(),repoUrl:S.string().optional()});var hou=S.union("type",{go:uou,swift:sou,maven:cou,npm:lou,nuget:fou,pypi:dou,rubygems:pou,crates:_ou}).transform({transform:e=>{switch(e.type){case"go":return Xt.PublishInfo.go(e);case"swift":return Xt.PublishInfo.swift(e);case"maven":return Xt.PublishInfo.maven(e);case"npm":return Xt.PublishInfo.npm(e);case"nuget":return Xt.PublishInfo.nuget(e);case"pypi":return Xt.PublishInfo.pypi(e);case"rubygems":return Xt.PublishInfo.rubygems(e);case"crates":return Xt.PublishInfo.crates(e);default:return e}},untransform:({_visit:e,...t})=>t});var you=S.union("type",{publish:S.object({value:hou}),local:S.object({})}).transform({transform:e=>{switch(e.type){case"publish":return Xt.GeneratorOutputConfig.publish(e.value);case"local":return Xt.GeneratorOutputConfig.local();default:return e}},untransform:({_visit:e,...t})=>t});var bou=S.objectWithoutOptionalProperties({apiName:S.string(),organization:S.string(),customConfig:S.unknown(),outputConfig:you});var vou=S.objectWithoutOptionalProperties({version:S.stringLiteral("1.0.0"),types:S.record(EYt,aou),endpoints:S.record(Sau,Vau),environments:$au.optional(),headers:S.list(lw).optional(),pathParameters:S.list(lw).optional(),variables:S.list(oou).optional(),generatorConfig:bou.optional()});var X9c={};Yt(X9c,{EndpointSnippetRequest:()=>Uau,EndpointSnippetResponse:()=>udh,ErrorSeverity:()=>gou,Error_:()=>Oou,Values:()=>laa});var gou=S.enum_(["CRITICAL","WARNING"]);var Oou=S.objectWithoutOptionalProperties({severity:gou,message:S.string()});var udh=S.objectWithoutOptionalProperties({snippet:S.string(),errors:S.list(Oou).optional()});var Z9c={};Yt(Z9c,{AliasType:()=>Yau,DiscriminatedUnionType:()=>iou,EnumType:()=>Xau,LiteralType:()=>mou,MapType:()=>cdh,NamedParameter:()=>lw,NamedType:()=>aou,ObjectPropertyAccess:()=>hau,ObjectType:()=>Zau,PrimitiveTypeV1:()=>Aou,SingleDiscriminatedUnionType:()=>rou,SingleDiscriminatedUnionTypeNoProperties:()=>tou,SingleDiscriminatedUnionTypeObject:()=>kau,SingleDiscriminatedUnionTypeSingleProperty:()=>eou,TypeReference:()=>sdh,UndiscriminatedUnionType:()=>nou});var mou=S.union("type",{boolean:S.object({value:S.boolean()}),string:S.object({value:S.string()})}).transform({transform:e=>{switch(e.type){case"boolean":return Xt.LiteralType.boolean(e.value);case"string":return Xt.LiteralType.string(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var Aou=S.enum_(["INTEGER","LONG","UINT","UINT_64","FLOAT","DOUBLE","BOOLEAN","STRING","DATE","DATE_TIME","UUID","BASE_64","BIG_INTEGER"]);var sdh=S.union("type",{list:S.object({value:S.lazy(()=>MM.TypeReference)}),literal:S.object({value:mou}),map:S.lazyObject(()=>MM.MapType),named:S.object({value:EYt}),nullable:S.object({value:S.lazy(()=>MM.TypeReference)}),optional:S.object({value:S.lazy(()=>MM.TypeReference)}),primitive:S.object({value:Aou}),set:S.object({value:S.lazy(()=>MM.TypeReference)}),unknown:S.object({})}).transform({transform:e=>{switch(e.type){case"list":return Xt.TypeReference.list(e.value);case"literal":return Xt.TypeReference.literal(e.value);case"map":return Xt.TypeReference.map(e);case"named":return Xt.TypeReference.named(e.value);case"nullable":return Xt.TypeReference.nullable(e.value);case"optional":return Xt.TypeReference.optional(e.value);case"primitive":return Xt.TypeReference.primitive(e.value);case"set":return Xt.TypeReference.set(e.value);case"unknown":return Xt.TypeReference.unknown();default:return e}},untransform:({_visit:e,...t})=>t});var cdh=S.objectWithoutOptionalProperties({key:S.lazy(()=>MM.TypeReference),value:S.lazy(()=>MM.TypeReference)});var k9c={};Yt(k9c,{VariableDeclaration:()=>oou});var eGc={};Yt(eGc,{EnvironmentBaseUrlId:()=>Zve,EnvironmentBaseUrlWithId:()=>wou,EnvironmentId:()=>MYt,EnvironmentUrl:()=>dJi,Environments:()=>Mou,EnvironmentsConfig:()=>Dou,MultipleBaseUrlsEnvironment:()=>Eou,MultipleBaseUrlsEnvironments:()=>Sou,SingleBaseUrlEnvironment:()=>Pou,SingleBaseUrlEnvironments:()=>jou});var MYt=S.string();var Zve=S.string();var dJi=S.string();var Pou=S.objectWithoutOptionalProperties({id:MYt,name:Ua,url:dJi}).extend(Jn);var jou=S.objectWithoutOptionalProperties({environments:S.list(Pou)});var wou=S.objectWithoutOptionalProperties({id:Zve,name:Ua});var Eou=S.objectWithoutOptionalProperties({id:MYt,name:Ua,urls:S.record(Zve,dJi)}).extend(Jn);var Sou=S.objectWithoutOptionalProperties({baseUrls:S.list(wou),environments:S.list(Eou)});var Mou=S.union("type",{singleBaseUrl:jou,multipleBaseUrls:Sou}).transform({transform:e=>{switch(e.type){case"singleBaseUrl":return SM.singleBaseUrl(e);case"multipleBaseUrls":return SM.multipleBaseUrls(e);default:return e}},untransform:({_visit:e,...t})=>t});var Dou=S.objectWithoutOptionalProperties({defaultEnvironment:MYt.optional(),environments:Mou});var tGc={};Yt(tGc,{DeclaredErrorName:()=>pJi,ErrorDeclaration:()=>Iou,ErrorDeclarationDiscriminantValue:()=>ldh,ExampleError:()=>Bou});var pJi=S.objectWithoutOptionalProperties({errorId:cJi,fernFilepath:REe,name:Ua});var Bou=S.objectWithoutOptionalProperties({name:Ua.optional(),shape:S.lazyObject(()=>bf)}).extend(wYt).extend(Jn);var hF=S.objectWithoutOptionalProperties({name:Yc,valueType:S.lazy(()=>Ss),env:S.string().optional(),v2Examples:pF.optional()}).extend(D1);var Iou=S.objectWithoutOptionalProperties({name:pJi,displayName:S.string().optional(),discriminantValue:Yc,type:S.lazy(()=>Ss).optional(),statusCode:S.number(),isWildcardStatusCode:S.boolean().optional(),examples:S.list(Bou),v2Examples:pF.optional(),headers:S.list(hF).optional()}).extend(Jn);var ldh=S.union("type",{property:Yc,statusCode:S.object({})}).transform({transform:e=>{switch(e.type){case"property":return eJi.property(e);case"statusCode":return eJi.statusCode();default:return e}},untransform:({_visit:e,...t})=>t});var rGc={};Yt(rGc,{BasicAuthValues:()=>Rou,BearerAuthValues:()=>zou,HeaderAuthValues:()=>Nou,MultipleEnvironmentUrlValues:()=>Tou,OAuthValues:()=>Fou,V2AuthValues:()=>daa,V2EndpointLocation:()=>qou,V2EndpointLocationHttpMethod:()=>Cou,V2EnvironmentValues:()=>faa,V2HttpEndpointCodeSample:()=>Vou,V2HttpEndpointExample:()=>R7a,V2HttpEndpointExamples:()=>Wou,V2HttpEndpointRequest:()=>Qou,V2HttpEndpointResponse:()=>Lou,V2HttpEndpointResponseBody:()=>Uou,V2SchemaExample:()=>q7a,V2SchemaExamples:()=>pF,V2ValueExamples:()=>DYt,V2WebSocketEndpointLocation:()=>Gou,V2WebSocketMessageExample:()=>xou,V2WebSocketSessionExample:()=>z7a,V2WebSocketSessionExamples:()=>Hou,V2WebhookExample:()=>N7a,V2WebhookExamples:()=>Kou,WithV2Examples:()=>rE});var rE=S.objectWithoutOptionalProperties({v2Examples:pF.optional()});var Cou=S.enum_(["GET","POST","PUT","PATCH","DELETE","HEAD"]);var qou=S.objectWithoutOptionalProperties({method:Cou,path:S.string()});var Tou=S.record(Zve,dJi);var faa=S.undiscriminatedUnion([MYt,Tou]);var Rou=S.objectWithoutOptionalProperties({username:S.string(),password:S.string()});var zou=S.objectWithoutOptionalProperties({token:S.string()});var Nou=S.objectWithoutOptionalProperties({value:S.unknown()});var Fou=S.objectWithoutOptionalProperties({clientId:S.string(),clientSecret:S.string()});var daa=S.union("type",{basic:Rou,bearer:zou,header:Nou,oauth:Fou}).transform({transform:e=>{switch(e.type){case"basic":return DEe.basic(e);case"bearer":return DEe.bearer(e);case"header":return DEe.header(e);case"oauth":return DEe.oauth(e);default:return e}},untransform:({_visit:e,...t})=>t});var DYt=S.record(S.string(),S.unknown());var Qou=S.objectWithoutOptionalProperties({endpoint:qou,baseUrl:S.property("baseURL",S.string().optional()),environment:faa.optional(),auth:daa.optional(),pathParameters:DYt.optional(),queryParameters:DYt.optional(),headers:DYt.optional(),requestBody:S.unknown().optional()}).extend(Jn);var Uou=S.union("type",{error:S.object({value:S.unknown()}),json:S.object({value:S.unknown()}),stream:S.object({value:S.list(S.unknown())})}).transform({transform:e=>{switch(e.type){case"error":return S1.error(e.value);case"json":return S1.json(e.value);case"stream":return S1.stream(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var Lou=S.objectWithoutOptionalProperties({statusCode:S.number().optional(),body:Uou.optional()}).extend(Jn);var Vou=S.objectWithoutOptionalProperties({name:S.string().optional(),language:S.string(),code:S.string()}).extend(Jn);var R7a=S.objectWithoutOptionalProperties({displayName:S.string().optional(),request:Qou.optional(),response:Lou.optional(),codeSamples:S.list(Vou).optional()});var Wou=S.objectWithoutOptionalProperties({userSpecifiedExamples:S.record(S.string(),R7a),autogeneratedExamples:S.record(S.string(),R7a)});var Gou=S.objectWithoutOptionalProperties({path:S.string()});var xou=S.objectWithoutOptionalProperties({type:S.string(),body:S.unknown()});var z7a=S.objectWithoutOptionalProperties({channel:Gou,baseUrl:S.property("baseURL",S.string().optional()),environment:faa.optional(),auth:daa.optional(),pathParameters:DYt.optional(),queryParameters:DYt.optional(),headers:DYt.optional(),messages:S.list(xou).optional()});var Hou=S.objectWithoutOptionalProperties({autogeneratedExamples:S.record(S.string(),z7a),userSpecifiedExamples:S.record(S.string(),z7a)});var N7a=S.objectWithoutOptionalProperties({name:S.string().optional(),payload:S.unknown()});var Kou=S.objectWithoutOptionalProperties({userSpecifiedExamples:S.record(S.string(),N7a),autogeneratedExamples:S.record(S.string(),N7a)});var nGc={};Yt(nGc,{BasicLicense:()=>$ou,CratesGithubPublishInfo:()=>_uu,CratesRegistryConfig:()=>Oaa,CustomLicense:()=>You,EnvironmentVariable:()=>wD,GeneratorConfig:()=>fdh,GeneratorEnvironment:()=>Ouu,GeneratorOutputConfig:()=>vuu,GeneratorPublishConfig:()=>maa,GeneratorPublishTarget:()=>ouu,GeneratorRegistriesConfig:()=>tuu,GeneratorRegistriesConfigV2:()=>nuu,GithubOutputMode:()=>yuu,GithubPublishInfo:()=>huu,LicenseConfig:()=>Xou,LicenseId:()=>Jou,MavenCentralSignature:()=>paa,MavenCentralSignatureGithubInfo:()=>suu,MavenGithubPublishInfo:()=>cuu,MavenRegistryConfig:()=>kou,MavenRegistryConfigV2:()=>_aa,NpmGithubPublishInfo:()=>uuu,NpmRegistryConfig:()=>euu,NpmRegistryConfigV2:()=>haa,NugetGithubPublishInfo:()=>puu,NugetRegistryConfig:()=>gaa,OutputMetadata:()=>iuu,OutputMetadataAuthor:()=>ruu,OutputMode:()=>buu,PostmanConfig:()=>auu,PostmanGithubPublishInfo:()=>luu,PublishingMetadata:()=>Zou,PypiGithubPublishInfo:()=>fuu,PypiMetadata:()=>yaa,PypiRegistryConfig:()=>baa,RemoteGeneratorEnvironment:()=>guu,RubyGemsGithubPublishInfo:()=>duu,RubyGemsRegistryConfig:()=>vaa,config:()=>iGc});var iGc={};Yt(iGc,{BasicLicense:()=>$ou,CratesGithubPublishInfo:()=>_uu,CratesRegistryConfig:()=>Oaa,CustomLicense:()=>You,EnvironmentVariable:()=>wD,GeneratorConfig:()=>fdh,GeneratorEnvironment:()=>Ouu,GeneratorOutputConfig:()=>vuu,GeneratorPublishConfig:()=>maa,GeneratorPublishTarget:()=>ouu,GeneratorRegistriesConfig:()=>tuu,GeneratorRegistriesConfigV2:()=>nuu,GithubOutputMode:()=>yuu,GithubPublishInfo:()=>huu,LicenseConfig:()=>Xou,LicenseId:()=>Jou,MavenCentralSignature:()=>paa,MavenCentralSignatureGithubInfo:()=>suu,MavenGithubPublishInfo:()=>cuu,MavenRegistryConfig:()=>kou,MavenRegistryConfigV2:()=>_aa,NpmGithubPublishInfo:()=>uuu,NpmRegistryConfig:()=>euu,NpmRegistryConfigV2:()=>haa,NugetGithubPublishInfo:()=>puu,NugetRegistryConfig:()=>gaa,OutputMetadata:()=>iuu,OutputMetadataAuthor:()=>ruu,OutputMode:()=>buu,PostmanConfig:()=>auu,PostmanGithubPublishInfo:()=>luu,PublishingMetadata:()=>Zou,PypiGithubPublishInfo:()=>fuu,PypiMetadata:()=>yaa,PypiRegistryConfig:()=>baa,RemoteGeneratorEnvironment:()=>guu,RubyGemsGithubPublishInfo:()=>duu,RubyGemsRegistryConfig:()=>vaa});var Jou=S.enum_(["MIT","Apache-2.0"]);var $ou=S.objectWithoutOptionalProperties({id:Jou});var You=S.objectWithoutOptionalProperties({filename:S.string()});var Xou=S.union("type",{basic:$ou,custom:You}).transform({transform:e=>{switch(e.type){case"basic":return ll.LicenseConfig.basic(e);case"custom":return ll.LicenseConfig.custom(e);default:return e}},untransform:({_visit:e,...t})=>t});var Zou=S.objectWithoutOptionalProperties({packageDescription:S.property("package_description",S.string().optional()),publisherEmail:S.property("publisher_email",S.string().optional()),referenceUrl:S.property("reference_url",S.string().optional()),publisherName:S.property("publisher_name",S.string().optional())});var paa=S.objectWithoutOptionalProperties({keyId:S.string(),password:S.string(),secretKey:S.string()});var kou=S.objectWithoutOptionalProperties({registryUrl:S.string(),username:S.string(),password:S.string(),group:S.string(),signature:paa.optional()});var euu=S.objectWithoutOptionalProperties({registryUrl:S.string(),token:S.string(),scope:S.string()});var tuu=S.objectWithoutOptionalProperties({maven:kou,npm:euu});var _aa=S.objectWithoutOptionalProperties({registryUrl:S.string(),username:S.string(),password:S.string(),coordinate:S.string(),signature:paa.optional()});var haa=S.objectWithoutOptionalProperties({registryUrl:S.string(),token:S.string(),packageName:S.string()});var ruu=S.objectWithoutOptionalProperties({name:S.string(),email:S.string()});var iuu=S.objectWithoutOptionalProperties({description:S.string().optional(),authors:S.list(ruu).optional()});var yaa=S.objectWithoutOptionalProperties({keywords:S.list(S.string()).optional(),documentationLink:S.string().optional(),homepageLink:S.string().optional()}).extend(iuu);var baa=S.objectWithoutOptionalProperties({registryUrl:S.string(),username:S.string(),password:S.string(),packageName:S.string(),pypiMetadata:yaa.optional()});var vaa=S.objectWithoutOptionalProperties({registryUrl:S.string(),apiKey:S.string(),packageName:S.string()});var gaa=S.objectWithoutOptionalProperties({registryUrl:S.string(),apiKey:S.string(),packageName:S.string()});var Oaa=S.objectWithoutOptionalProperties({registryUrl:S.string(),token:S.string(),packageName:S.string()});var nuu=S.objectWithoutOptionalProperties({maven:_aa,npm:haa,pypi:baa,rubygems:vaa,nuget:gaa,crates:Oaa});var auu=S.objectWithoutOptionalProperties({apiKey:S.string(),workspaceId:S.string()});var ouu=S.union("type",{maven:_aa,npm:haa,pypi:baa,postman:auu,rubygems:vaa,nuget:gaa,crates:Oaa}).transform({transform:e=>{switch(e.type){case"maven":return ll.GeneratorPublishTarget.maven(e);case"npm":return ll.GeneratorPublishTarget.npm(e);case"pypi":return ll.GeneratorPublishTarget.pypi(e);case"postman":return ll.GeneratorPublishTarget.postman(e);case"rubygems":return ll.GeneratorPublishTarget.rubygems(e);case"nuget":return ll.GeneratorPublishTarget.nuget(e);case"crates":return ll.GeneratorPublishTarget.crates(e);default:return e}},untransform:({_visit:e,...t})=>t});var maa=S.objectWithoutOptionalProperties({registries:tuu,registriesV2:nuu,publishTarget:ouu.optional(),version:S.string()});var wD=S.string();var uuu=S.objectWithoutOptionalProperties({registryUrl:S.string(),packageName:S.string(),tokenEnvironmentVariable:wD,shouldGeneratePublishWorkflow:S.boolean().optional()});var suu=S.objectWithoutOptionalProperties({keyIdEnvironmentVariable:wD,passwordEnvironmentVariable:wD,secretKeyEnvironmentVariable:wD});var cuu=S.objectWithoutOptionalProperties({registryUrl:S.string(),coordinate:S.string(),usernameEnvironmentVariable:wD,passwordEnvironmentVariable:wD,signature:suu.optional(),shouldGeneratePublishWorkflow:S.boolean().optional()});var luu=S.objectWithoutOptionalProperties({apiKeyEnvironmentVariable:wD,workspaceIdEnvironmentVariable:wD});var fuu=S.objectWithoutOptionalProperties({registryUrl:S.string(),packageName:S.string(),usernameEnvironmentVariable:wD,passwordEnvironmentVariable:wD,pypiMetadata:yaa.optional(),shouldGeneratePublishWorkflow:S.boolean().optional()});var duu=S.objectWithoutOptionalProperties({registryUrl:S.string(),packageName:S.string(),apiKeyEnvironmentVariable:wD,shouldGeneratePublishWorkflow:S.boolean().optional()});var puu=S.objectWithoutOptionalProperties({registryUrl:S.string(),packageName:S.string(),apiKeyEnvironmentVariable:wD,shouldGeneratePublishWorkflow:S.boolean().optional()});var _uu=S.objectWithoutOptionalProperties({registryUrl:S.string(),packageName:S.string(),tokenEnvironmentVariable:wD,shouldGeneratePublishWorkflow:S.boolean().optional()});var huu=S.union("type",{npm:uuu,maven:cuu,postman:luu,pypi:fuu,rubygems:duu,nuget:puu,crates:_uu}).transform({transform:e=>{switch(e.type){case"npm":return ll.GithubPublishInfo.npm(e);case"maven":return ll.GithubPublishInfo.maven(e);case"postman":return ll.GithubPublishInfo.postman(e);case"pypi":return ll.GithubPublishInfo.pypi(e);case"rubygems":return ll.GithubPublishInfo.rubygems(e);case"nuget":return ll.GithubPublishInfo.nuget(e);case"crates":return ll.GithubPublishInfo.crates(e);default:return e}},untransform:({_visit:e,...t})=>t});var yuu=S.objectWithoutOptionalProperties({version:S.string(),repoUrl:S.string(),installationToken:S.string().optional(),branch:S.string().optional(),publishInfo:huu.optional()});var buu=S.union("type",{publish:maa,downloadFiles:S.object({}),github:yuu}).transform({transform:e=>{switch(e.type){case"publish":return ll.OutputMode.publish(e);case"downloadFiles":return ll.OutputMode.downloadFiles();case"github":return ll.OutputMode.github(e);default:return e}},untransform:({_visit:e,...t})=>t});var vuu=S.objectWithoutOptionalProperties({path:S.string(),snippetFilepath:S.string().optional(),snippetTemplateFilepath:S.string().optional(),publishingMetadata:Zou.optional(),mode:buu});var guu=S.objectWithoutOptionalProperties({coordinatorUrl:S.string(),coordinatorUrlV2:S.string(),id:S.string()});var Ouu=S.union(S.discriminant("type","_type"),{local:S.object({}),remote:guu}).transform({transform:e=>{switch(e.type){case"local":return ll.GeneratorEnvironment.local();case"remote":return ll.GeneratorEnvironment.remote(e);default:return e}},untransform:({_visit:e,...t})=>t});var fdh=S.objectWithoutOptionalProperties({dryRun:S.boolean(),irFilepath:S.string(),originalReadmeFilepath:S.string().optional(),license:Xou.optional(),output:vuu,publish:maa.optional(),workspaceName:S.string(),organization:S.string(),customConfig:S.unknown(),environment:Ouu,whitelabel:S.boolean(),writeUnitTests:S.boolean(),generatePaginatedClients:S.boolean().optional(),generateOauthClients:S.boolean()});var aGc={};Yt(aGc,{AutogeneratedEndpointExample:()=>dsu,BytesRequest:()=>Eaa,BytesResponse:()=>Iaa,CursorPagination:()=>Yuu,CustomPagination:()=>Zuu,DeclaredServiceName:()=>muu,EndpointName:()=>Puu,ExampleCodeSample:()=>rsu,ExampleCodeSampleLanguage:()=>esu,ExampleCodeSampleSdk:()=>tsu,ExampleEndpointCall:()=>zaa,ExampleEndpointErrorResponse:()=>csu,ExampleEndpointSuccessResponse:()=>ssu,ExampleHeader:()=>qbn,ExampleInlinedRequestBody:()=>Raa,ExampleInlinedRequestBodyExtraProperty:()=>asu,ExampleInlinedRequestBodyProperty:()=>nsu,ExamplePathParameter:()=>hJi,ExampleQueryParameter:()=>Taa,ExampleQueryParameterShape:()=>isu,ExampleRequestBody:()=>osu,ExampleResponse:()=>lsu,ExampleServerSideEvent:()=>usu,FileDownloadResponse:()=>Daa,FileProperty:()=>Duu,FilePropertyArray:()=>Muu,FilePropertySingle:()=>Suu,FileUploadBodyProperty:()=>Iuu,FileUploadBodyPropertyEncoding:()=>Buu,FileUploadRequest:()=>waa,FileUploadRequestProperty:()=>Cuu,GrpcTransport:()=>ysu,HttpEndpoint:()=>Asu,HttpEndpointSecurityItem:()=>$uu,HttpEndpointSource:()=>gsu,HttpHeader:()=>hF,HttpMethod:()=>juu,HttpPath:()=>NEe,HttpPathPart:()=>Auu,HttpRequestBody:()=>Saa,HttpRequestBodyReference:()=>jaa,HttpResponse:()=>_Ji,HttpResponseBody:()=>xuu,HttpService:()=>wsu,InlinedRequestBody:()=>Euu,InlinedRequestBodyProperty:()=>Paa,JsonResponse:()=>Maa,JsonResponseBody:()=>Fuu,JsonResponseBodyWithProperty:()=>Quu,JsonStreamChunk:()=>Uuu,NonStreamHttpResponseBody:()=>Wuu,OffsetPagination:()=>Xuu,Pagination:()=>kuu,PathParameter:()=>f8t,PathParameterLocation:()=>wuu,PropertyPathItem:()=>iaa,ProtoSourceInfo:()=>vsu,QueryParameter:()=>aJi,RequestProperty:()=>OW,RequestPropertyValue:()=>Xnu,ResponseError:()=>Kuu,ResponseErrors:()=>Juu,ResponseProperty:()=>_F,RetriesConfiguration:()=>msu,RetriesDisabledSchema:()=>Osu,SdkRequest:()=>Nuu,SdkRequestBodyType:()=>Tuu,SdkRequestShape:()=>zuu,SdkRequestWrapper:()=>Ruu,SseStreamChunk:()=>Vuu,StreamParameterResponse:()=>Guu,StreamingResponse:()=>Caa,SupportedSdkLanguage:()=>qaa,TextResponse:()=>Baa,TextStreamChunk:()=>Luu,Transport:()=>Faa,UserSpecifiedEndpointExample:()=>fsu,V2HttpRequestBodies:()=>quu,V2HttpResponses:()=>Huu});var muu=S.objectWithoutOptionalProperties({fernFilepath:REe});var Auu=S.objectWithoutOptionalProperties({pathParameter:S.string(),tail:S.string()});var NEe=S.objectWithoutOptionalProperties({head:S.string(),parts:S.list(Auu)});var Puu=Ua;var juu=S.enum_(["GET","POST","PUT","PATCH","DELETE","HEAD"]);var wuu=S.enum_(["ROOT","SERVICE","ENDPOINT"]);var Aaa=S.string();var f8t=S.objectWithoutOptionalProperties({name:Ua,valueType:S.lazy(()=>Ss),location:wuu,variable:Aaa.optional(),v2Examples:pF.optional(),explode:S.boolean().optional()}).extend(Jn);var iE=S.objectWithoutOptionalProperties({typeId:_L,fernFilepath:REe,name:Ua,displayName:sJi.optional()});var Paa=S.objectWithoutOptionalProperties({name:Yc,valueType:S.lazy(()=>Ss),v2Examples:pF.optional(),propertyAccess:oJi.optional()}).extend(uJi);var Euu=S.objectWithoutOptionalProperties({name:Ua,extends:S.list(iE),properties:S.list(Paa),extendedProperties:S.list(dx).optional(),extraProperties:S.property("extra-properties",S.boolean())}).extend(Jn).extend(rE).extend(zEe);var jaa=S.objectWithoutOptionalProperties({requestBodyType:S.lazy(()=>Ss)}).extend(Jn).extend(zEe).extend(rE);var Suu=S.objectWithoutOptionalProperties({key:Yc,isOptional:S.boolean(),contentType:S.string().optional()}).extend(Jn);var Muu=S.objectWithoutOptionalProperties({key:Yc,isOptional:S.boolean(),contentType:S.string().optional()}).extend(Jn);var Duu=S.union("type",{file:Suu,fileArray:Muu}).transform({transform:e=>{switch(e.type){case"file":return aY.file(e);case"fileArray":return aY.fileArray(e);default:return e}},untransform:({_visit:e,...t})=>t});var Buu=S.enum_(["exploded","json","form"]);var Iuu=S.objectWithoutOptionalProperties({style:Buu.optional()}).extend(Paa).extend(zEe);var Cuu=S.union("type",{file:S.object({value:Duu}),bodyProperty:Iuu}).transform({transform:e=>{switch(e.type){case"file":return M1.file(e.value);case"bodyProperty":return M1.bodyProperty(e);default:return e}},untransform:({_visit:e,...t})=>t});var waa=S.objectWithoutOptionalProperties({name:Ua,properties:S.list(Cuu)}).extend(Jn).extend(rE).extend(zEe);var Eaa=S.objectWithoutOptionalProperties({isOptional:S.boolean()}).extend(Jn).extend(rE).extend(zEe);var Saa=S.union("type",{inlinedRequestBody:Euu,reference:jaa,fileUpload:waa,bytes:Eaa}).transform({transform:e=>{switch(e.type){case"inlinedRequestBody":return Nm.inlinedRequestBody(e);case"reference":return Nm.reference(e);case"fileUpload":return Nm.fileUpload(e);case"bytes":return Nm.bytes(e);default:return e}},untransform:({_visit:e,...t})=>t});var quu=S.objectWithoutOptionalProperties({requestBodies:S.list(Saa).optional()});var Tuu=S.union("type",{typeReference:jaa,bytes:Eaa}).transform({transform:e=>{switch(e.type){case"typeReference":return u8t.typeReference(e);case"bytes":return u8t.bytes(e);default:return e}},untransform:({_visit:e,...t})=>t});var Ruu=S.objectWithoutOptionalProperties({wrapperName:Ua,bodyKey:Ua,includePathParameters:S.boolean().optional(),onlyPathParameters:S.boolean().optional()});var zuu=S.union("type",{justRequestBody:S.object({value:Tuu}),wrapper:Ruu}).transform({transform:e=>{switch(e.type){case"justRequestBody":return CEe.justRequestBody(e.value);case"wrapper":return CEe.wrapper(e);default:return e}},untransform:({_visit:e,...t})=>t});var Nuu=S.objectWithoutOptionalProperties({streamParameter:OW.optional(),requestParameterName:Ua,shape:zuu});var Fuu=S.objectWithoutOptionalProperties({responseBodyType:S.lazy(()=>Ss)}).extend(Jn).extend(rE);var Quu=S.objectWithoutOptionalProperties({responseBodyType:S.lazy(()=>Ss),responseProperty:dx.optional()}).extend(Jn).extend(rE);var Maa=S.union("type",{response:Fuu,nestedPropertyAsResponse:Quu}).transform({transform:e=>{switch(e.type){case"response":return dC.response(e);case"nestedPropertyAsResponse":return dC.nestedPropertyAsResponse(e);default:return e}},untransform:({_visit:e,...t})=>t});var Daa=S.objectWithoutOptionalProperties({}).extend(Jn).extend(rE);var Baa=S.objectWithoutOptionalProperties({}).extend(Jn).extend(rE);var Iaa=S.objectWithoutOptionalProperties({}).extend(Jn).extend(rE);var Uuu=S.objectWithoutOptionalProperties({payload:S.lazy(()=>Ss),terminator:S.string().optional()}).extend(Jn).extend(rE);var Luu=S.objectWithoutOptionalProperties({}).extend(Jn).extend(rE);var Vuu=S.objectWithoutOptionalProperties({payload:S.lazy(()=>Ss),terminator:S.string().optional()}).extend(Jn).extend(rE);var Caa=S.union("type",{json:Uuu,text:Luu,sse:Vuu}).transform({transform:e=>{switch(e.type){case"json":return sI.json(e);case"text":return sI.text(e);case"sse":return sI.sse(e);default:return e}},untransform:({_visit:e,...t})=>t});var Wuu=S.union("type",{json:S.object({value:Maa}),fileDownload:Daa,text:Baa,bytes:Iaa}).transform({transform:e=>{switch(e.type){case"json":return fL.json(e.value);case"fileDownload":return fL.fileDownload(e);case"text":return fL.text(e);case"bytes":return fL.bytes(e);default:return e}},untransform:({_visit:e,...t})=>t});var Guu=S.objectWithoutOptionalProperties({nonStreamResponse:Wuu,streamResponse:Caa});var xuu=S.union("type",{json:S.object({value:Maa}),fileDownload:Daa,text:Baa,bytes:Iaa,streaming:S.object({value:Caa}),streamParameter:Guu}).transform({transform:e=>{switch(e.type){case"json":return Ed.json(e.value);case"fileDownload":return Ed.fileDownload(e);case"text":return Ed.text(e);case"bytes":return Ed.bytes(e);case"streaming":return Ed.streaming(e.value);case"streamParameter":return Ed.streamParameter(e);default:return e}},untransform:({_visit:e,...t})=>t});var _Ji=S.objectWithoutOptionalProperties({statusCode:S.property("status-code",S.number().optional()),isWildcardStatusCode:S.boolean().optional(),body:xuu.optional()}).extend(Jn);var Huu=S.objectWithoutOptionalProperties({responses:S.list(_Ji).optional()});var Kuu=S.objectWithoutOptionalProperties({error:pJi}).extend(Jn);var Juu=S.list(Kuu);var $uu=S.record(raa,S.list(xnu));var Yuu=S.objectWithoutOptionalProperties({page:OW,next:_F,results:_F});var Xuu=S.objectWithoutOptionalProperties({page:OW,results:_F,hasNextPage:_F.optional(),step:OW.optional()});var Zuu=S.objectWithoutOptionalProperties({results:_F});var kuu=S.union("type",{cursor:Yuu,offset:Xuu,custom:Zuu}).transform({transform:e=>{switch(e.type){case"cursor":return bW.cursor(e);case"offset":return bW.offset(e);case"custom":return bW.custom(e);default:return e}},untransform:({_visit:e,...t})=>t});var esu=S.objectWithoutOptionalProperties({name:Ua.optional(),language:S.string(),code:S.string(),install:S.string().optional()}).extend(Jn);var qaa=S.enum_(["curl","python","javascript","typescript","go","ruby","csharp","java","php","rust","swift"]);var tsu=S.objectWithoutOptionalProperties({name:Ua.optional(),sdk:qaa,code:S.string()}).extend(Jn);var rsu=S.union("type",{language:esu,sdk:tsu}).transform({transform:e=>{switch(e.type){case"language":return Jve.language(e);case"sdk":return Jve.sdk(e);default:return e}},untransform:({_visit:e,...t})=>t});var hJi=S.objectWithoutOptionalProperties({name:Ua,value:S.lazyObject(()=>bf)});var qbn=S.objectWithoutOptionalProperties({name:Yc,value:S.lazyObject(()=>bf)});var isu=S.union("type",{single:S.object({}),exploded:S.object({}),commaSeparated:S.object({})}).transform({transform:e=>{switch(e.type){case"single":return TR.single();case"exploded":return TR.exploded();case"commaSeparated":return TR.commaSeparated();default:return e}},untransform:({_visit:e,...t})=>t});var Taa=S.objectWithoutOptionalProperties({name:Yc,value:S.lazyObject(()=>bf),shape:isu.optional()});var nsu=S.objectWithoutOptionalProperties({name:Yc,value:S.lazyObject(()=>bf),originalTypeDeclaration:iE.optional()});var asu=S.objectWithoutOptionalProperties({name:Yc,value:S.lazyObject(()=>bf)});var Raa=S.objectWithoutOptionalProperties({properties:S.list(nsu),extraProperties:S.list(asu).optional()}).extend(wYt);var osu=S.union("type",{inlinedRequestBody:Raa,reference:S.lazyObject(()=>bf)}).transform({transform:e=>{switch(e.type){case"inlinedRequestBody":return vW.inlinedRequestBody(e);case"reference":return vW.reference(e);default:return e}},untransform:({_visit:e,...t})=>t});var usu=S.objectWithoutOptionalProperties({event:S.string(),data:S.lazyObject(()=>bf)});var ssu=S.union("type",{body:S.object({value:S.lazyObject(()=>bf).optional()}),stream:S.object({value:S.list(S.lazyObject(()=>bf))}),sse:S.object({value:S.list(usu)})}).transform({transform:e=>{switch(e.type){case"body":return cw.body(e.value);case"stream":return cw.stream(e.value);case"sse":return cw.sse(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var csu=S.objectWithoutOptionalProperties({error:pJi,body:S.lazyObject(()=>bf).optional()});var lsu=S.union("type",{ok:S.object({value:ssu}),error:csu}).transform({transform:e=>{switch(e.type){case"ok":return $j.ok(e.value);case"error":return $j.error(e);default:return e}},untransform:({_visit:e,...t})=>t});var zaa=S.objectWithoutOptionalProperties({id:S.string().optional(),name:Ua.optional(),url:S.string(),rootPathParameters:S.list(hJi),servicePathParameters:S.list(hJi),endpointPathParameters:S.list(hJi),serviceHeaders:S.list(qbn),endpointHeaders:S.list(qbn),queryParameters:S.list(Taa),request:osu.optional(),response:lsu}).extend(Jn);var fsu=S.objectWithoutOptionalProperties({codeSamples:S.list(rsu).optional(),example:zaa.optional()});var dsu=S.objectWithoutOptionalProperties({example:zaa});var psu=S.objectWithoutOptionalProperties({namespace:S.string()});var _su=S.objectWithoutOptionalProperties({csharp:psu.optional()});var Naa=S.objectWithoutOptionalProperties({filepath:S.string(),packageName:S.string().optional(),options:_su.optional()});var hsu=S.objectWithoutOptionalProperties({file:Naa,name:Ua});var ysu=S.objectWithoutOptionalProperties({service:hsu});var Faa=S.union("type",{http:S.object({}),grpc:ysu}).transform({transform:e=>{switch(e.type){case"http":return BEe.http();case"grpc":return BEe.grpc(e);default:return e}},untransform:({_visit:e,...t})=>t});var bsu=S.enum_(["UNARY","CLIENT_STREAM","SERVER_STREAM","BIDIRECTIONAL_STREAM"]);var vsu=S.objectWithoutOptionalProperties({methodType:bsu.optional()});var gsu=S.union("type",{proto:vsu,openapi:S.object({}),openrpc:S.object({})}).transform({transform:e=>{switch(e.type){case"proto":return yW.proto(e);case"openapi":return yW.openapi();case"openrpc":return yW.openrpc();default:return e}},untransform:({_visit:e,...t})=>t});var Osu=S.objectWithoutOptionalProperties({disabled:S.boolean().optional()});var msu=S.undiscriminatedUnion([Osu]);var Asu=S.objectWithoutOptionalProperties({id:lUi,name:Puu,displayName:S.string().optional(),method:juu,headers:S.list(hF),responseHeaders:S.list(hF).optional(),baseUrl:Zve.optional(),v2BaseUrls:S.list(Zve).optional(),basePath:NEe.optional(),path:NEe,fullPath:NEe,pathParameters:S.list(f8t),allPathParameters:S.list(f8t),queryParameters:S.list(aJi),requestBody:Saa.optional(),v2RequestBodies:quu.optional(),sdkRequest:Nuu.optional(),response:_Ji.optional(),v2Responses:Huu.optional(),errors:Juu,auth:S.boolean(),security:S.list($uu).optional(),idempotent:S.boolean(),pagination:kuu.optional(),userSpecifiedExamples:S.list(fsu),autogeneratedExamples:S.list(dsu),v2Examples:Wou.optional(),transport:Faa.optional(),source:gsu.optional(),audiences:S.list(taa).optional(),retries:msu.optional(),apiPlayground:S.boolean().optional()}).extend(D1);var Psu=S.objectWithoutOptionalProperties({});var jsu=S.objectWithoutOptionalProperties({});var Qaa=S.objectWithoutOptionalProperties({json:Psu.optional(),proto:jsu.optional()});var wsu=S.objectWithoutOptionalProperties({availability:jYt.optional(),name:muu,displayName:S.string().optional(),basePath:NEe,endpoints:S.list(Asu),headers:S.list(hF),pathParameters:S.list(f8t),encoding:Qaa.optional(),transport:Faa.optional(),audiences:S.list(taa).optional()});var oGc={};Yt(oGc,{ApiDefinitionSource:()=>Kcu,ApiDefinitionSourceId:()=>xcu,ApiVersionScheme:()=>Ssu,ErrorDiscriminationByPropertyStrategy:()=>Rcu,ErrorDiscriminationStrategy:()=>zcu,ExampleStyle:()=>Wcu,GenerationMetadata:()=>nlu,HeaderApiVersionScheme:()=>Esu,IntermediateRepresentation:()=>ddh,Package:()=>xaa,PackageNavigationConfig:()=>qcu,PlatformHeaders:()=>Fcu,ProtoSource:()=>Hcu,ReadmeConfig:()=>Gcu,ReadmeCustomSection:()=>Vcu,SdkConfig:()=>Qcu,ServiceTypeReferenceInfo:()=>Lcu,SourceConfig:()=>Jcu,Subpackage:()=>Tcu,UserAgent:()=>Ncu});var fUi=S.objectWithoutOptionalProperties({name:Yc}).extend(D1);var Uaa=S.objectWithoutOptionalProperties({default:fUi.optional(),values:S.list(fUi)});var Esu=S.objectWithoutOptionalProperties({header:hF,value:Uaa});var Ssu=S.union("type",{header:Esu}).transform({transform:e=>{switch(e.type){case"header":return tJi.header(e);default:return e}},untransform:({_visit:e,...t})=>t});var Msu=S.enum_(["ENUM","OBJECT","UNION","UNDISCRIMINATED_UNION"]);var Dsu=S.objectWithoutOptionalProperties({name:iE,shape:Msu});var Bsu=S.enum_(["INTEGER","LONG","UINT","UINT_64","FLOAT","DOUBLE","BOOLEAN","STRING","DATE","DATE_TIME","UUID","BASE_64","BIG_INTEGER"]);var Isu=S.objectWithoutOptionalProperties({min:S.number().optional(),max:S.number().optional(),exclusiveMin:S.boolean().optional(),exclusiveMax:S.boolean().optional(),multipleOf:S.number().optional()});var Csu=S.objectWithoutOptionalProperties({default:S.number().optional(),validation:Isu.optional()});var qsu=S.objectWithoutOptionalProperties({min:S.number().optional(),max:S.number().optional(),exclusiveMin:S.boolean().optional(),exclusiveMax:S.boolean().optional(),multipleOf:S.number().optional()});var Tsu=S.objectWithoutOptionalProperties({default:S.number().optional(),validation:qsu.optional()});var Rsu=S.objectWithoutOptionalProperties({min:S.number().optional(),max:S.number().optional(),exclusiveMin:S.boolean().optional(),exclusiveMax:S.boolean().optional(),multipleOf:S.number().optional()});var zsu=S.objectWithoutOptionalProperties({default:S.number().optional(),validation:Rsu.optional()});var Nsu=S.objectWithoutOptionalProperties({min:S.number().optional(),max:S.number().optional(),exclusiveMin:S.boolean().optional(),exclusiveMax:S.boolean().optional(),multipleOf:S.number().optional()});var Fsu=S.objectWithoutOptionalProperties({default:S.number().optional(),validation:Nsu.optional()});var Qsu=S.objectWithoutOptionalProperties({min:S.number().optional(),max:S.number().optional(),exclusiveMin:S.boolean().optional(),exclusiveMax:S.boolean().optional(),multipleOf:S.number().optional()});var Usu=S.objectWithoutOptionalProperties({default:S.number().optional(),validation:Qsu.optional()});var Lsu=S.objectWithoutOptionalProperties({min:S.number().optional(),max:S.number().optional(),exclusiveMin:S.boolean().optional(),exclusiveMax:S.boolean().optional(),multipleOf:S.number().optional()});var Vsu=S.objectWithoutOptionalProperties({default:S.number().optional(),validation:Lsu.optional()});var Wsu=S.objectWithoutOptionalProperties({default:S.boolean().optional()});var Gsu=S.objectWithoutOptionalProperties({format:S.string().optional(),pattern:S.string().optional(),minLength:S.number().optional(),maxLength:S.number().optional()});var xsu=S.objectWithoutOptionalProperties({default:S.string().optional(),validation:Gsu.optional()});var Hsu=S.objectWithoutOptionalProperties({});var Ksu=S.objectWithoutOptionalProperties({});var Jsu=S.objectWithoutOptionalProperties({});var $su=S.objectWithoutOptionalProperties({});var Ysu=S.objectWithoutOptionalProperties({default:S.string().optional()});var Xsu=S.union("type",{integer:Csu,long:Tsu,uint:zsu,uint64:Fsu,float:Usu,double:Vsu,boolean:Wsu,string:xsu,date:Hsu,dateTime:Ksu,uuid:Jsu,base64:$su,bigInteger:Ysu}).transform({transform:e=>{switch(e.type){case"integer":return vn.integer(e);case"long":return vn.long(e);case"uint":return vn.uint(e);case"uint64":return vn.uint64(e);case"float":return vn.float(e);case"double":return vn.double(e);case"boolean":return vn.boolean(e);case"string":return vn.string(e);case"date":return vn.date(e);case"dateTime":return vn.dateTime(e);case"uuid":return vn.uuid(e);case"base64":return vn.base64(e);case"bigInteger":return vn.bigInteger(e);default:return e}},untransform:({_visit:e,...t})=>t});var Laa=S.objectWithoutOptionalProperties({v1:Bsu,v2:Xsu.optional()});var Zsu=S.union(S.discriminant("type","_type"),{container:S.object({container:S.lazy(()=>Vaa)}),named:Dsu,primitive:S.object({primitive:Laa}),unknown:S.object({})}).transform({transform:e=>{switch(e.type){case"container":return dL.container(e.container);case"named":return dL.named(e);case"primitive":return dL.primitive(e.primitive);case"unknown":return dL.unknown();default:return e}},untransform:({_visit:e,...t})=>t});var ksu=S.objectWithoutOptionalProperties({aliasOf:S.lazy(()=>Ss),resolvedType:Zsu});var ecu=S.objectWithoutOptionalProperties({extends:S.list(iE),properties:S.list(dx),extendedProperties:S.list(dx).optional(),extraProperties:S.property("extra-properties",S.boolean())});var tcu=S.objectWithoutOptionalProperties({name:Yc,type:S.lazy(()=>Ss)});var rcu=S.union(S.discriminant("propertiesType","_type"),{samePropertiesAsObject:iE,singleProperty:tcu,noProperties:S.object({})}).transform({transform:e=>{switch(e.propertiesType){case"samePropertiesAsObject":return cF.samePropertiesAsObject(e);case"singleProperty":return cF.singleProperty(e);case"noProperties":return cF.noProperties();default:return e}},untransform:({_visit:e,...t})=>t});var icu=S.objectWithoutOptionalProperties({discriminantValue:Yc,shape:rcu,displayName:S.string().optional(),availability:jYt.optional()}).extend(Jn);var ncu=S.objectWithoutOptionalProperties({discriminant:Yc,extends:S.list(iE),types:S.list(icu),baseProperties:S.list(dx)});var acu=S.objectWithoutOptionalProperties({type:S.lazy(()=>Ss)}).extend(Jn);var ocu=S.objectWithoutOptionalProperties({members:S.list(acu)});var ucu=S.union(S.discriminant("type","_type"),{alias:ksu,enum:Uaa,object:ecu,union:ncu,undiscriminatedUnion:ocu}).transform({transform:e=>{switch(e.type){case"alias":return Al.alias(e);case"enum":return Al.enum(e);case"object":return Al.object(e);case"union":return Al.union(e);case"undiscriminatedUnion":return Al.undiscriminatedUnion(e);default:return e}},untransform:({_visit:e,...t})=>t});var F7a=S.objectWithoutOptionalProperties({name:Ua.optional(),shape:S.lazy(()=>Waa)}).extend(wYt).extend(Jn);var scu=S.union("type",{any:S.object({}),api:S.object({}),boolValue:S.object({}),bytesValue:S.object({}),doubleValue:S.object({}),duration:S.object({}),empty:S.object({}),enum:S.object({}),enumValue:S.object({}),field:S.object({}),fieldCardinality:S.object({}),fieldKind:S.object({}),fieldMask:S.object({}),floatValue:S.object({}),int32Value:S.object({}),int64Value:S.object({}),listValue:S.object({}),method:S.object({}),mixin:S.object({}),nullValue:S.object({}),option:S.object({}),sourceContext:S.object({}),stringValue:S.object({}),struct:S.object({}),syntax:S.object({}),timestamp:S.object({}),type:S.object({}),uint32Value:S.object({}),uint64Value:S.object({}),value:S.object({})}).transform({transform:e=>{switch(e.type){case"any":return bn.any();case"api":return bn.api();case"boolValue":return bn.boolValue();case"bytesValue":return bn.bytesValue();case"doubleValue":return bn.doubleValue();case"duration":return bn.duration();case"empty":return bn.empty();case"enum":return bn.enum();case"enumValue":return bn.enumValue();case"field":return bn.field();case"fieldCardinality":return bn.fieldCardinality();case"fieldKind":return bn.fieldKind();case"fieldMask":return bn.fieldMask();case"floatValue":return bn.floatValue();case"int32Value":return bn.int32Value();case"int64Value":return bn.int64Value();case"listValue":return bn.listValue();case"method":return bn.method();case"mixin":return bn.mixin();case"nullValue":return bn.nullValue();case"option":return bn.option();case"sourceContext":return bn.sourceContext();case"stringValue":return bn.stringValue();case"struct":return bn.struct();case"syntax":return bn.syntax();case"timestamp":return bn.timestamp();case"type":return bn.type();case"uint32Value":return bn.uint32Value();case"uint64Value":return bn.uint64Value();case"value":return bn.value();default:return e}},untransform:({_visit:e,...t})=>t});var ccu=S.objectWithoutOptionalProperties({file:Naa,name:Ua});var lcu=S.union("type",{wellKnown:S.object({value:scu}),userDefined:ccu}).transform({transform:e=>{switch(e.type){case"wellKnown":return _y.wellKnown(e.value);case"userDefined":return _y.userDefined(e);default:return e}},untransform:({_visit:e,...t})=>t});var fcu=S.union("type",{proto:S.object({value:lcu})}).transform({transform:e=>{switch(e.type){case"proto":return cUi.proto(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var dcu=S.objectWithoutOptionalProperties({name:iE,shape:ucu,autogeneratedExamples:S.list(F7a),userProvidedExamples:S.list(F7a),v2Examples:pF.optional(),referencedTypes:S.set(_L),encoding:Qaa.optional(),source:fcu.optional(),inline:S.boolean().optional()}).extend(D1);var pcu=Ua;var _cu=S.enum_(["GET","POST"]);var hcu=S.objectWithoutOptionalProperties({name:Yc,valueType:S.lazy(()=>Ss)}).extend(uJi);var ycu=S.objectWithoutOptionalProperties({name:Ua,extends:S.list(iE),properties:S.list(hcu)});var bcu=S.objectWithoutOptionalProperties({payloadType:S.lazy(()=>Ss)}).extend(Jn);var vcu=S.union("type",{inlinedPayload:ycu,reference:bcu}).transform({transform:e=>{switch(e.type){case"inlinedPayload":return fF.inlinedPayload(e);case"reference":return fF.reference(e);default:return e}},untransform:({_visit:e,...t})=>t});var gcu=S.objectWithoutOptionalProperties({name:Ua.optional(),payload:S.lazyObject(()=>bf)}).extend(Jn);var Ocu=S.objectWithoutOptionalProperties({id:fau,name:pcu,displayName:S.string().optional(),method:_cu,headers:S.list(hF),payload:vcu,fileUploadPayload:waa.optional(),responses:S.list(_Ji).optional(),examples:S.list(gcu).optional(),v2Examples:Kou.optional()}).extend(D1);var mcu=S.list(Ocu);var Acu=Ua;var Gaa=S.string();var Pcu=S.enum_(["client","server"]);var jcu=S.objectWithoutOptionalProperties({name:Yc,valueType:S.lazy(()=>Ss)}).extend(uJi);var wcu=S.objectWithoutOptionalProperties({name:Ua,extends:S.list(iE),properties:S.list(jcu)});var Ecu=S.objectWithoutOptionalProperties({bodyType:S.lazy(()=>Ss)}).extend(Jn);var Scu=S.union("type",{inlinedBody:wcu,reference:Ecu}).transform({transform:e=>{switch(e.type){case"inlinedBody":return pL.inlinedBody(e);case"reference":return pL.reference(e);default:return e}},untransform:({_visit:e,...t})=>t});var Mcu=S.objectWithoutOptionalProperties({type:Gaa,displayName:S.string().optional(),methodName:S.string().optional(),origin:Pcu,body:Scu}).extend(D1);var Dcu=S.union("type",{inlinedBody:Raa,reference:S.lazyObject(()=>bf)}).transform({transform:e=>{switch(e.type){case"inlinedBody":return Xve.inlinedBody(e);case"reference":return Xve.reference(e);default:return e}},untransform:({_visit:e,...t})=>t});var Bcu=S.objectWithoutOptionalProperties({type:Gaa,body:Dcu});var Icu=S.objectWithoutOptionalProperties({name:Ua.optional(),url:S.string(),pathParameters:S.list(hJi),headers:S.list(qbn),queryParameters:S.list(Taa),messages:S.list(Bcu)}).extend(Jn);var Ccu=S.objectWithoutOptionalProperties({name:Acu,displayName:S.string().optional(),baseUrl:Zve.optional(),path:NEe,auth:S.boolean(),headers:S.list(hF),queryParameters:S.list(aJi),pathParameters:S.list(f8t),messages:S.list(Mcu),examples:S.list(Icu),v2Examples:Hou.optional()}).extend(D1);var qcu=S.objectWithoutOptionalProperties({pointsTo:PYt});var xaa=S.objectWithoutOptionalProperties({fernFilepath:REe,service:AYt.optional(),types:S.list(_L),errors:S.list(cJi),webhooks:aaa.optional(),websocket:oaa.optional(),subpackages:S.list(PYt),hasEndpointsInTree:S.boolean(),navigationConfig:qcu.optional()}).extend(Jn);var Tcu=S.objectWithoutOptionalProperties({name:Ua,displayName:sJi.optional()}).extend(xaa);var Rcu=S.objectWithoutOptionalProperties({discriminant:Yc,contentProperty:Yc});var zcu=S.union("type",{statusCode:S.object({}),property:Rcu}).transform({transform:e=>{switch(e.type){case"statusCode":return Yve.statusCode();case"property":return Yve.property(e);default:return e}},untransform:({_visit:e,...t})=>t});var Ncu=S.objectWithoutOptionalProperties({header:S.stringLiteral("User-Agent"),value:S.string()});var Fcu=S.objectWithoutOptionalProperties({language:S.string(),sdkName:S.string(),sdkVersion:S.string(),userAgent:Ncu.optional()});var Qcu=S.objectWithoutOptionalProperties({isAuthMandatory:S.boolean(),hasStreamingEndpoints:S.boolean(),hasPaginatedEndpoints:S.boolean(),hasFileDownloadEndpoints:S.boolean(),platformHeaders:Fcu});var Ucu=S.objectWithoutOptionalProperties({id:Aaa,name:Ua,type:S.lazy(()=>Ss)}).extend(Jn);var Lcu=S.objectWithoutOptionalProperties({typesReferencedOnlyByService:S.record(AYt,S.list(_L)),sharedTypes:S.list(_L)});var Vcu=S.objectWithoutOptionalProperties({title:S.string(),language:qaa,content:S.string()});var Wcu=S.enum_(["minimal","comprehensive"]);var Gcu=S.objectWithoutOptionalProperties({defaultEndpoint:lUi.optional(),bannerLink:S.string().optional(),introduction:S.string().optional(),apiReferenceLink:S.string().optional(),apiName:S.string().optional(),disabledFeatures:S.list(T7a).optional(),whiteLabel:S.boolean().optional(),features:S.record(T7a,S.list(lUi)).optional(),customSections:S.list(Vcu).optional(),exampleStyle:Wcu.optional()});var xcu=S.string();var Hcu=S.objectWithoutOptionalProperties({id:xcu,protoRootUrl:S.string()});var Kcu=S.union("type",{proto:Hcu,openapi:S.object({})}).transform({transform:e=>{switch(e.type){case"proto":return uY.proto(e);case"openapi":return uY.openapi();default:return e}},untransform:({_visit:e,...t})=>t});var Jcu=S.objectWithoutOptionalProperties({sources:S.list(Kcu)});var $cu=S.objectWithoutOptionalProperties({apiKey:S.string(),workspaceId:S.string(),collectionId:S.string().optional()});var Ycu=S.objectWithoutOptionalProperties({version:S.string().optional(),packageName:S.string().optional(),tokenEnvironmentVariable:S.string()});var Xcu=S.objectWithoutOptionalProperties({coordinate:S.string().optional(),version:S.string().optional(),usernameEnvironmentVariable:S.string(),passwordEnvironmentVariable:S.string(),mavenUrlEnvironmentVariable:S.string()});var Zcu=S.objectWithoutOptionalProperties({version:S.string().optional(),packageName:S.string().optional()});var kcu=S.objectWithoutOptionalProperties({version:S.string().optional(),packageName:S.string().optional()});var yJi=S.union("type",{postman:$cu,npm:Ycu,maven:Xcu,pypi:Zcu,crates:kcu}).transform({transform:e=>{switch(e.type){case"postman":return pC.postman(e);case"npm":return pC.npm(e);case"maven":return pC.maven(e);case"pypi":return pC.pypi(e);case"crates":return pC.crates(e);default:return e}},untransform:({_visit:e,...t})=>t});var elu=S.objectWithoutOptionalProperties({owner:S.string(),repo:S.string(),uri:S.string().optional(),token:S.string().optional(),mode:S.stringLiteral("pull-request").optional(),branch:S.string().optional(),target:yJi});var tlu=S.objectWithoutOptionalProperties({target:yJi});var rlu=S.objectWithoutOptionalProperties({generateFullProject:S.boolean(),publishTarget:yJi.optional()});var ilu=S.union("type",{github:elu,direct:tlu,filesystem:rlu}).transform({transform:e=>{switch(e.type){case"github":return OYt.github(e);case"direct":return OYt.direct(e);case"filesystem":return OYt.filesystem(e);default:return e}},untransform:({_visit:e,...t})=>t});var nlu=S.objectWithoutOptionalProperties({cliVersion:S.string(),generatorName:S.string(),generatorVersion:S.string(),generatorConfig:S.unknown().optional()});var ddh=S.objectWithoutOptionalProperties({fdrApiDefinitionId:S.string().optional(),apiVersion:Ssu.optional(),apiName:Ua,apiDisplayName:S.string().optional(),apiDocs:S.string().optional(),auth:cau,headers:S.list(hF),idempotencyHeaders:S.list(hF),types:S.record(_L,dcu),services:S.record(AYt,wsu),webhookGroups:S.record(aaa,mcu),websocketChannels:S.record(oaa,Ccu).optional(),errors:S.record(cJi,Iou),subpackages:S.record(PYt,Tcu),rootPackage:xaa,constants:dau,environments:Dou.optional(),basePath:NEe.optional(),pathParameters:S.list(f8t),errorDiscriminationStrategy:zcu,sdkConfig:Qcu,variables:S.list(Ucu),serviceTypeReferenceInfo:Lcu,readmeConfig:Gcu.optional(),sourceConfig:Jcu.optional(),publishConfig:ilu.optional(),dynamic:vou.optional(),selfHosted:S.boolean().optional(),audiences:S.list(Gnu).optional(),generationMetadata:nlu.optional(),apiPlayground:S.boolean().optional()});var uGc={};Yt(uGc,{CsharpProtobufFileOptions:()=>psu,ProtobufFile:()=>Naa,ProtobufFileOptions:()=>_su,ProtobufMethodType:()=>bsu,ProtobufService:()=>hsu,ProtobufType:()=>lcu,UserDefinedProtobufType:()=>ccu,WellKnownProtobufType:()=>scu});var sGc={};Yt(sGc,{CratesPublishTarget:()=>kcu,DirectPublish:()=>tlu,Filesystem:()=>rlu,GithubPublish:()=>elu,MavenPublishTarget:()=>Xcu,NpmPublishTarget:()=>Ycu,PostmanPublishTarget:()=>$cu,PublishTarget:()=>yJi,PublishingConfig:()=>ilu,PypiPublishTarget:()=>Zcu});var cGc={};Yt(cGc,{AliasTypeDeclaration:()=>ksu,Base64Type:()=>$su,BigIntegerType:()=>Ysu,BooleanType:()=>Wsu,ContainerType:()=>Vaa,DateTimeType:()=>Ksu,DateType:()=>Hsu,DeclaredTypeName:()=>iE,DoubleType:()=>Vsu,DoubleValidationRules:()=>Lsu,Encoding:()=>Qaa,EnumTypeDeclaration:()=>Uaa,EnumTypeReference:()=>pdh,EnumValue:()=>fUi,ExampleAliasType:()=>llu,ExampleContainer:()=>Olu,ExampleDatetime:()=>glu,ExampleEnumType:()=>clu,ExampleExtraObjectProperty:()=>plu,ExampleKeyValuePair:()=>Mlu,ExampleListContainer:()=>Plu,ExampleLiteralContainer:()=>Alu,ExampleMapContainer:()=>Slu,ExampleNamedType:()=>mlu,ExampleNullableContainer:()=>Elu,ExampleObjectProperty:()=>Kaa,ExampleObjectType:()=>Haa,ExampleObjectTypeWithTypeId:()=>blu,ExampleOptionalContainer:()=>wlu,ExamplePrimitive:()=>Jaa,ExampleSetContainer:()=>jlu,ExampleSingleUnionType:()=>hlu,ExampleSingleUnionTypeProperties:()=>ylu,ExampleType:()=>F7a,ExampleTypeReference:()=>bf,ExampleTypeReferenceShape:()=>vlu,ExampleTypeShape:()=>Waa,ExampleUndiscriminatedUnionType:()=>dlu,ExampleUnionBaseProperty:()=>_lu,ExampleUnionType:()=>flu,FloatType:()=>Usu,FloatValidationRules:()=>Qsu,IntegerType:()=>Csu,IntegerValidationRules:()=>Isu,JsonEncoding:()=>Psu,Literal:()=>ulu,LongType:()=>Tsu,LongValidationRules:()=>qsu,MapType:()=>slu,NamedType:()=>olu,NamedTypeDefault:()=>alu,ObjectProperty:()=>dx,ObjectPropertyAccess:()=>oJi,ObjectTypeDeclaration:()=>ecu,PrimitiveType:()=>Laa,PrimitiveTypeV1:()=>Bsu,PrimitiveTypeV2:()=>Xsu,ProtoEncoding:()=>jsu,ResolvedNamedType:()=>Dsu,ResolvedTypeReference:()=>Zsu,ShapeType:()=>Msu,SingleUnionType:()=>icu,SingleUnionTypeProperties:()=>rcu,SingleUnionTypeProperty:()=>tcu,Source:()=>fcu,StringType:()=>xsu,StringValidationRules:()=>Gsu,Type:()=>ucu,TypeDeclaration:()=>dcu,TypeReference:()=>Ss,Uint64Type:()=>Fsu,Uint64ValidationRules:()=>Nsu,UintType:()=>zsu,UintValidationRules:()=>Rsu,UndiscriminatedUnionMember:()=>acu,UndiscriminatedUnionTypeDeclaration:()=>ocu,UnionTypeDeclaration:()=>ncu,UuidType:()=>Jsu});var alu=S.union("type",{enum:fUi}).transform({transform:e=>{switch(e.type){case"enum":return Xna.enum(e);default:return e}},untransform:({_visit:e,...t})=>t});var olu=S.objectWithoutOptionalProperties({typeId:_L,fernFilepath:REe,name:Ua,displayName:sJi.optional(),default:alu.optional(),inline:S.boolean().optional()});var Ss=S.union(S.discriminant("type","_type"),{container:S.object({container:S.lazy(()=>Vaa)}),named:olu,primitive:S.object({primitive:Laa}),unknown:S.object({})}).transform({transform:e=>{switch(e.type){case"container":return ii.container(e.container);case"named":return ii.named(e);case"primitive":return ii.primitive(e.primitive);case"unknown":return ii.unknown();default:return e}},untransform:({_visit:e,...t})=>t});var pdh=S.objectWithoutOptionalProperties({default:fUi.optional(),name:iE});var ulu=S.union("type",{string:S.object({string:S.string()}),boolean:S.object({boolean:S.boolean()})}).transform({transform:e=>{switch(e.type){case"string":return lF.string(e.string);case"boolean":return lF.boolean(e.boolean);default:return e}},untransform:({_visit:e,...t})=>t});var Vaa=S.union(S.discriminant("type","_type"),{list:S.object({list:S.lazy(()=>Ss)}),map:S.lazyObject(()=>slu),nullable:S.object({nullable:S.lazy(()=>Ss)}),optional:S.object({optional:S.lazy(()=>Ss)}),set:S.object({set:S.lazy(()=>Ss)}),literal:S.object({literal:ulu})}).transform({transform:e=>{switch(e.type){case"list":return Es.list(e.list);case"map":return Es.map(e);case"nullable":return Es.nullable(e.nullable);case"optional":return Es.optional(e.optional);case"set":return Es.set(e.set);case"literal":return Es.literal(e.literal);default:return e}},untransform:({_visit:e,...t})=>t});var slu=S.objectWithoutOptionalProperties({keyType:S.lazy(()=>Ss),valueType:S.lazy(()=>Ss)});var clu=S.objectWithoutOptionalProperties({value:Yc});var Waa=S.union("type",{alias:S.lazyObject(()=>llu),enum:clu,object:S.lazyObject(()=>Haa),union:S.lazyObject(()=>flu),undiscriminatedUnion:S.lazyObject(()=>dlu)}).transform({transform:e=>{switch(e.type){case"alias":return hy.alias(e);case"enum":return hy.enum(e);case"object":return hy.object(e);case"union":return hy.union(e);case"undiscriminatedUnion":return hy.undiscriminatedUnion(e);default:return e}},untransform:({_visit:e,...t})=>t});var llu=S.objectWithoutOptionalProperties({value:S.lazyObject(()=>bf)});var Haa=S.objectWithoutOptionalProperties({properties:S.list(S.lazyObject(()=>Kaa)),extraProperties:S.list(S.lazyObject(()=>plu)).optional()});var Kaa=S.objectWithoutOptionalProperties({name:Yc,value:S.lazyObject(()=>bf),propertyAccess:oJi.optional(),originalTypeDeclaration:iE});var plu=S.objectWithoutOptionalProperties({name:Yc,value:S.lazyObject(()=>bf)});var flu=S.objectWithoutOptionalProperties({discriminant:Yc,singleUnionType:S.lazyObject(()=>hlu),extendProperties:S.list(S.lazyObject(()=>Kaa)).optional(),baseProperties:S.list(S.lazyObject(()=>_lu)).optional()});var _lu=S.objectWithoutOptionalProperties({name:Yc,value:S.lazyObject(()=>bf)});var dlu=S.objectWithoutOptionalProperties({index:S.number(),singleUnionType:S.lazyObject(()=>bf)});var hlu=S.objectWithoutOptionalProperties({wireDiscriminantValue:Yc,shape:S.lazy(()=>ylu)});var ylu=S.union("type",{samePropertiesAsObject:S.lazyObject(()=>blu),singleProperty:S.lazyObject(()=>bf),noProperties:S.object({})}).transform({transform:e=>{switch(e.type){case"samePropertiesAsObject":return _C.samePropertiesAsObject(e);case"singleProperty":return _C.singleProperty(e);case"noProperties":return _C.noProperties();default:return e}},untransform:({_visit:e,...t})=>t});var bf=S.objectWithoutOptionalProperties({shape:S.lazy(()=>vlu)}).extend(wYt);var glu=S.objectWithoutOptionalProperties({datetime:S.date(),raw:S.string().optional()});var Jaa=S.union("type",{integer:S.object({integer:S.number()}),long:S.object({long:S.number()}),uint:S.object({uint:S.number()}),uint64:S.object({uint64:S.number()}),float:S.object({float:S.number()}),double:S.object({double:S.number()}),boolean:S.object({boolean:S.boolean()}),string:S.object({string:lau}),date:S.object({date:S.string()}),datetime:glu,uuid:S.object({uuid:S.string()}),base64:S.object({base64:S.string()}),bigInteger:S.object({bigInteger:S.string()})}).transform({transform:e=>{switch(e.type){case"integer":return Rn.integer(e.integer);case"long":return Rn.long(e.long);case"uint":return Rn.uint(e.uint);case"uint64":return Rn.uint64(e.uint64);case"float":return Rn.float(e.float);case"double":return Rn.double(e.double);case"boolean":return Rn.boolean(e.boolean);case"string":return Rn.string(e.string);case"date":return Rn.date(e.date);case"datetime":return Rn.datetime(e);case"uuid":return Rn.uuid(e.uuid);case"base64":return Rn.base64(e.base64);case"bigInteger":return Rn.bigInteger(e.bigInteger);default:return e}},untransform:({_visit:e,...t})=>t});var vlu=S.union("type",{primitive:S.object({primitive:Jaa}),container:S.object({container:S.lazy(()=>Olu)}),unknown:S.object({unknown:S.unknown()}),named:S.lazyObject(()=>mlu)}).transform({transform:e=>{switch(e.type){case"primitive":return Tu.primitive(e.primitive);case"container":return Tu.container(e.container);case"unknown":return Tu.unknown(e.unknown);case"named":return Tu.named(e);default:return e}},untransform:({_visit:e,...t})=>t});var Alu=S.objectWithoutOptionalProperties({literal:Jaa});var Olu=S.union("type",{list:S.lazyObject(()=>Plu),set:S.lazyObject(()=>jlu),optional:S.lazyObject(()=>wlu),nullable:S.lazyObject(()=>Elu),map:S.lazyObject(()=>Slu),literal:Alu}).transform({transform:e=>{switch(e.type){case"list":return Up.list(e);case"set":return Up.set(e);case"optional":return Up.optional(e);case"nullable":return Up.nullable(e);case"map":return Up.map(e);case"literal":return Up.literal(e);default:return e}},untransform:({_visit:e,...t})=>t});var Plu=S.objectWithoutOptionalProperties({list:S.list(S.lazyObject(()=>bf)),itemType:S.lazy(()=>Ss)});var jlu=S.objectWithoutOptionalProperties({set:S.list(S.lazyObject(()=>bf)),itemType:S.lazy(()=>Ss)});var wlu=S.objectWithoutOptionalProperties({optional:S.lazyObject(()=>bf).optional(),valueType:S.lazy(()=>Ss)});var Elu=S.objectWithoutOptionalProperties({nullable:S.lazyObject(()=>bf).optional(),valueType:S.lazy(()=>Ss)});var Slu=S.objectWithoutOptionalProperties({map:S.list(S.lazyObject(()=>Mlu)),keyType:S.lazy(()=>Ss),valueType:S.lazy(()=>Ss)});var Mlu=S.objectWithoutOptionalProperties({key:S.lazyObject(()=>bf),value:S.lazyObject(()=>bf)});var mlu=S.objectWithoutOptionalProperties({typeName:iE,shape:S.lazy(()=>Waa)});var blu=S.objectWithoutOptionalProperties({typeId:_L,object:S.lazyObject(()=>Haa)});var lGc={};Yt(lGc,{VariableDeclaration:()=>Ucu,VariableId:()=>Aaa});var fGc={};Yt(fGc,{ExampleWebhookCall:()=>gcu,InlinedWebhookPayload:()=>ycu,InlinedWebhookPayloadProperty:()=>hcu,Webhook:()=>Ocu,WebhookGroup:()=>mcu,WebhookHttpMethod:()=>_cu,WebhookName:()=>pcu,WebhookPayload:()=>vcu,WebhookPayloadReference:()=>bcu});var dGc={};Yt(dGc,{ExampleWebSocketMessage:()=>Bcu,ExampleWebSocketMessageBody:()=>Dcu,ExampleWebSocketSession:()=>Icu,InlinedWebSocketMessageBody:()=>wcu,InlinedWebSocketMessageBodyProperty:()=>jcu,WebSocketChannel:()=>Ccu,WebSocketMessage:()=>Mcu,WebSocketMessageBody:()=>Scu,WebSocketMessageBodyReference:()=>Ecu,WebSocketMessageId:()=>Gaa,WebSocketMessageOrigin:()=>Pcu,WebSocketName:()=>Acu});var cI={};Yt(cI,{AvailabilityStatusSchema:()=>hdh,FernDefinitionError:()=>V7a,FernDefinitionTimeoutError:()=>W7a,FormDataBodyEncodingStyle:()=>wdh,HttpMethodSchema:()=>jdh,ObjectPropertyAccess:()=>Mdh,StreamFormat:()=>Edh,SupportedSdkLanguageSchema:()=>Odh,WebSocketOrigin:()=>qdh,WebhookMethodSchema:()=>Cdh,auth:()=>_dh,availability:()=>_Gc,commons:()=>ydh,encoding:()=>bdh,environments:()=>vdh,errors:()=>gdh,examples:()=>hGc,file:()=>mdh,pagination:()=>Adh,products:()=>Pdh,serialization:()=>VGc,service:()=>yGc,source:()=>Sdh,types:()=>bGc,validation:()=>Ddh,variables:()=>Bdh,versioning:()=>Idh,webhooks:()=>vGc,websocket:()=>gGc});var _dh={};var _Gc={};Yt(_Gc,{AvailabilityStatusSchema:()=>hdh});var hdh={InDevelopment:"in-development",PreRelease:"pre-release",Deprecated:"deprecated",GenerallyAvailable:"generally-available"};var ydh={};var bdh={};var vdh={};var gdh={};var hGc={};Yt(hGc,{SupportedSdkLanguageSchema:()=>Odh});var Odh={Curl:"curl",Python:"python",Javascript:"javascript",Typescript:"typescript",Go:"go",Ruby:"ruby",Csharp:"csharp",Java:"java",Js:"js",Node:"node",Ts:"ts",Nodets:"nodets",Golang:"golang",Dotnet:"dotnet",Jvm:"jvm",Csharp2:"c#"};var mdh={};var Adh={};var Pdh={};var yGc={};Yt(yGc,{FormDataBodyEncodingStyle:()=>wdh,HttpMethodSchema:()=>jdh,StreamFormat:()=>Edh});var jdh={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD"};var wdh={Json:"json",Exploded:"exploded",Form:"form"};var Edh={Sse:"sse",Json:"json"};var Sdh={};var bGc={};Yt(bGc,{ObjectPropertyAccess:()=>Mdh});var Mdh={ReadOnly:"read-only",WriteOnly:"write-only"};var Ddh={};var Bdh={};var Idh={};var vGc={};Yt(vGc,{WebhookMethodSchema:()=>Cdh});var Cdh={Post:"POST",Get:"GET"};var gGc={};Yt(gGc,{WebSocketOrigin:()=>qdh});var qdh={Client:"client",Server:"server"};var VGc={};Yt(VGc,{AliasSchema:()=>Kfu,AnyAuthItem:()=>qlu,AnyAuthSchemesSchema:()=>Tlu,ApiAuthSchema:()=>Nlu,AuthSchemeDeclarationSchema:()=>klu,AuthSchemeKey:()=>Zaa,AuthSchemeReferenceSchema:()=>eoa,AuthScope:()=>kaa,AuthVariable:()=>Rbn,AvailabilitySchema:()=>tfu,AvailabilityStatusSchema:()=>roa,AvailabilityUnionSchema:()=>rfu,BaseTypeDeclarationSchema:()=>UEe,BaseTypeReferenceSchema:()=>ooa,BasicAuthSchemeSchema:()=>Hlu,BearerAuthSchemeSchema:()=>Zlu,CasingOverridesSchema:()=>Cfu,CursorPaginationSchema:()=>vdu,CustomPaginationSchema:()=>Odu,DeclarationSchema:()=>BYt,DeclarationWithNameSchema:()=>uph,DeclarationWithoutDocsSchema:()=>ufu,DefinitionFileSchema:()=>Ndu,DiscriminatedUnionSchema:()=>Wfu,EncodingSchema:()=>ioa,EndpointSecuritySchema:()=>zlu,EndpointSecuritySchemaDetails:()=>Rlu,EnumSchema:()=>Rfu,EnumValue:()=>Tfu,EnumValueSchema:()=>qfu,EnvironmentSchema:()=>ffu,ErrorDeclarationSchema:()=>_fu,ErrorDiscriminationSchema:()=>Gdu,ExampleBodyResponseSchema:()=>bfu,ExampleCodeSampleSchema:()=>wfu,ExampleCodeSampleSchemaLanguage:()=>jfu,ExampleCodeSampleSchemaSdk:()=>Pfu,ExampleEndpointCallArraySchema:()=>sph,ExampleEndpointCallSchema:()=>aoa,ExampleResponseSchema:()=>mfu,ExampleSseEventSchema:()=>gfu,ExampleSseResponseSchema:()=>Ofu,ExampleStreamResponseSchema:()=>vfu,ExampleTypeReferenceSchema:()=>RR,ExampleTypeSchema:()=>noa,ExampleTypeValueSchema:()=>pfu,ExampleWebSocketMessage:()=>hfu,ExampleWebSocketSession:()=>yfu,ExampleWebhookCallSchema:()=>Efu,Export:()=>Udu,ExportDetailed:()=>Qdu,FormDataBodyEncodingStyle:()=>adu,GrpcTransport:()=>$fu,HeaderAuthSchemeSchema:()=>xlu,HttpEndpointAuth:()=>edu,HttpEndpointSchema:()=>jdu,HttpEndpointSecurity:()=>kfu,HttpEndpointSecurityItem:()=>Zfu,HttpHeaderSchema:()=>LEe,HttpInlineFileRequestBodyPropertySchema:()=>odu,HttpInlineRequestBodyPropertySchema:()=>udu,HttpInlineRequestBodySchema:()=>sdu,HttpMethodSchema:()=>Yfu,HttpPathParameterSchema:()=>IYt,HttpQueryParameterSchema:()=>soa,HttpReferencedRequestBodySchema:()=>ndu,HttpRequest:()=>fdu,HttpRequestBodySchema:()=>cdu,HttpRequestSchema:()=>ldu,HttpResponseSchema:()=>coa,HttpResponseSchemaDetailed:()=>ddu,HttpResponseStreamSchema:()=>loa,HttpResponseStreamSchemaDetailed:()=>_du,HttpServiceSchema:()=>wdu,InferredAuthenticatedRequestHeader:()=>Jlu,InferredBearerAuthSchema:()=>Xlu,InferredGetTokenEndpointSchema:()=>Ylu,InferredGetTokenEndpointSchemaObject:()=>$lu,MultipleBaseUrlsEnvironmentSchema:()=>lfu,Navigation:()=>Fdu,NumberValidationSchema:()=>afu,OAuthAccessTokenRequestPropertiesSchema:()=>Flu,OAuthAccessTokenResponsePropertiesSchema:()=>Qlu,OAuthGetTokenEndpointSchema:()=>Ulu,OAuthRefreshTokenEndpointSchema:()=>Wlu,OAuthRefreshTokenRequestPropertiesSchema:()=>Llu,OAuthRefreshTokenResponsePropertiesSchema:()=>Vlu,OAuthSchemeSchema:()=>Glu,ObjectExtendsSchema:()=>FEe,ObjectPropertyAccess:()=>Sfu,ObjectPropertySchema:()=>OJi,ObjectPropertyWithAccessSchema:()=>Mfu,ObjectSchema:()=>Ifu,OffsetPaginationSchema:()=>gdu,OpenApiSourceSchema:()=>Dfu,PackageMarkerFileSchema:()=>cph,Pagination:()=>mdu,PaginationSchema:()=>foa,ProductDeclarationHeaderObjectSchema:()=>kdu,ProductDeclarationHeaderSchema:()=>epu,ProductDeclarationSchema:()=>tpu,ProductValue:()=>Zdu,ProductValueDetailed:()=>Xdu,PropertyBasedErrorDiscrimination:()=>Vdu,ProtobufSourceSchema:()=>Bfu,ProtobufTypeSchema:()=>sfu,QueryParameterTypeReferenceDetailed:()=>tdu,ResponseError:()=>ydu,ResponseErrorWithDocsSchema:()=>hdu,ResponseErrorsSchema:()=>bdu,RetriesConfiguration:()=>Pdu,RetriesDisabledSchema:()=>Adu,RootApiFileSchema:()=>lph,ServiceTransport:()=>uoa,SingleBaseUrlEnvironmentSchema:()=>cfu,SingleUndiscriminatedUnionTypeDetailedSchema:()=>Gfu,SingleUndiscriminatedUnionTypeSchema:()=>xfu,SingleUnionTypeDetailedSchema:()=>Lfu,SingleUnionTypeKey:()=>Ufu,SingleUnionTypeKeySchema:()=>Qfu,SingleUnionTypeSchema:()=>Vfu,SourceSchema:()=>mJi,StatusCodeBasedErrorDiscrimination:()=>Wdu,StreamFormat:()=>pdu,StringValidationSchema:()=>nfu,SupportedSdkLanguageSchema:()=>Afu,TokenBearerAuthSchema:()=>Klu,TypeDeclarationSchema:()=>Jfu,TypeReferenceDeclarationWithEnvOverride:()=>idu,TypeReferenceDeclarationWithEnvOverrideSchema:()=>rdu,TypeReferenceDeclarationWithName:()=>QEe,TypeReferenceDeclarationWithNameSchema:()=>fph,TypeReferenceDetailedSchema:()=>Ffu,TypeReferenceSchema:()=>dUi,UndiscriminatedUnionSchema:()=>Hfu,UnionDiscriminant:()=>Nfu,UnionDiscriminantSchema:()=>zfu,ValidationSchema:()=>gJi,VariableDeclarationDetailed:()=>xdu,VariableDeclarationSchema:()=>Hdu,VariableReferenceSchema:()=>Xfu,VersionDeclarationHeaderObjectSchema:()=>$du,VersionDeclarationHeaderSchema:()=>Ydu,VersionDeclarationSchema:()=>doa,VersionValue:()=>Jdu,VersionValueDetailed:()=>Kdu,WebSocketChannelInlinedMessageSchema:()=>qdu,WebSocketChannelMessageBodySchema:()=>Tdu,WebSocketChannelMessageSchema:()=>Rdu,WebSocketChannelReferencedMessageSchema:()=>Cdu,WebSocketChannelSchema:()=>zdu,WebSocketOrigin:()=>Idu,WebhookInlinedPayloadSchema:()=>Mdu,WebhookMethodSchema:()=>Edu,WebhookPayloadSchema:()=>Ddu,WebhookReferencedPayloadSchema:()=>Sdu,WebhookSchema:()=>Bdu,WithAudiences:()=>vF,WithAuthSchema:()=>efu,WithAvailability:()=>PW,WithDisplayName:()=>bF,WithDocsSchema:()=>La,WithEnvironmentVariable:()=>toa,WithEnvironmentsSchema:()=>dfu,WithHeadersSchema:()=>Ldu,WithMethodName:()=>ifu,WithName:()=>rv,WithValidation:()=>ofu,auth:()=>jGc,availability:()=>wGc,commons:()=>EGc,encoding:()=>SGc,environments:()=>MGc,errors:()=>DGc,examples:()=>BGc,file:()=>IGc,pagination:()=>CGc,products:()=>qGc,service:()=>TGc,source:()=>RGc,types:()=>zGc,validation:()=>NGc,variables:()=>FGc,versioning:()=>QGc,webhooks:()=>UGc,websocket:()=>LGc});var jGc={};Yt(jGc,{AnyAuthItem:()=>qlu,AnyAuthSchemesSchema:()=>Tlu,ApiAuthSchema:()=>Nlu,AuthSchemeDeclarationSchema:()=>klu,AuthSchemeKey:()=>Zaa,AuthSchemeReferenceSchema:()=>eoa,AuthScope:()=>kaa,AuthVariable:()=>Rbn,BasicAuthSchemeSchema:()=>Hlu,BearerAuthSchemeSchema:()=>Zlu,EndpointSecuritySchema:()=>zlu,EndpointSecuritySchemaDetails:()=>Rlu,HeaderAuthSchemeSchema:()=>xlu,InferredAuthenticatedRequestHeader:()=>Jlu,InferredBearerAuthSchema:()=>Xlu,InferredGetTokenEndpointSchema:()=>Ylu,InferredGetTokenEndpointSchemaObject:()=>$lu,OAuthAccessTokenRequestPropertiesSchema:()=>Flu,OAuthAccessTokenResponsePropertiesSchema:()=>Qlu,OAuthGetTokenEndpointSchema:()=>Ulu,OAuthRefreshTokenEndpointSchema:()=>Wlu,OAuthRefreshTokenRequestPropertiesSchema:()=>Llu,OAuthRefreshTokenResponsePropertiesSchema:()=>Vlu,OAuthSchemeSchema:()=>Glu,TokenBearerAuthSchema:()=>Klu,WithAuthSchema:()=>efu,WithEnvironmentVariable:()=>toa});var ie={};Yt(ie,{JsonError:()=>$aa,ParseError:()=>Yaa,any:()=>Jdh,bigint:()=>Rdh,boolean:()=>$dh,booleanLiteral:()=>Kdh,date:()=>zdh,discriminant:()=>nph,enum_:()=>Blu,getObjectLikeUtils:()=>d8t,getObjectUtils:()=>Tbn,getSchemaUtils:()=>XP,isProperty:()=>vJi,lazy:()=>Ndh,lazyObject:()=>Gdh,list:()=>Clu,number:()=>Ydh,object:()=>Ilu,objectWithoutOptionalProperties:()=>Wdh,optional:()=>OGc,property:()=>Qdh,record:()=>eph,set:()=>tph,string:()=>Xdh,stringLiteral:()=>Hdh,transform:()=>mGc,undiscriminatedUnion:()=>iph,union:()=>oph,unknown:()=>Zdh,withParsedProperties:()=>PGc});var Qh={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 wA(e,t){return`Expected ${t}. Received ${$LD(e)}.`}function $LD(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 yF(e){return{...e,json:Tdh(e.json),parse:Tdh(e.parse)}}function Tdh(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(`
1467
1467
  `)),{ok:!0,value:t}):i}}function Dlu(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var $aa=class e extends Error{errors;constructor(t){super(t.map(Dlu).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var Yaa=class e extends Error{errors;constructor(t){super(t.map(Dlu).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function XP(e){return{optional:()=>OGc(e),transform:t=>mGc(e,t),parseOrThrow:(t,r)=>{let i=e.parse(t,r);if(i.ok)return i.value;throw new Yaa(i.errors)},jsonOrThrow:(t,r)=>{let i=e.json(t,r);if(i.ok)return i.value;throw new $aa(i.errors)}}}function OGc(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:()=>Qh.OPTIONAL};return{...t,...XP(t)}}function mGc(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,...XP(r)}}function Rdh(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:wA(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:wA(t,"bigint")}]},getType:()=>Qh.BIGINT};return{...yF(e),...XP(e)}}var YLD=/^([+-]?\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 zdh(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:wA(t,"string")}]}:YLD.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:wA(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:wA(t,"Date object")}]},getType:()=>Qh.DATE};return{...yF(e),...XP(e)}}function AW(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{...yF(r),...XP(r)}}}function Blu(e){let t=new Set(e);return AW(Qh.ENUM,(i,{allowUnrecognizedEnumValues:n,breadcrumbsPrefix:a=[]}={})=>typeof i!="string"?{ok:!1,errors:[{path:a,message:wA(i,"string")}]}:!t.has(i)&&!n?{ok:!1,errors:[{path:a,message:wA(i,"enum")}]}:{ok:!0,value:i})()}function Ndh(e){let t=AGc(e);return{...t,...XP(t)}}function AGc(e){return{parse:(t,r)=>Xaa(e).parse(t,r),json:(t,r)=>Xaa(e).json(t,r),getType:()=>Xaa(e).getType()}}function Xaa(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function Q7a(e){return Object.entries(e)}function U7a(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 L7a(e){return Object.keys(e)}function Fdh(e,t){let r=[],i=[];for(let n of e)t(n)?r.push(n):i.push(n);return[r,i]}function d8t(e){return{withParsedProperties:t=>PGc(e,t)}}function PGc(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:wA(i,"object")}]};let a=new Set(Object.keys(t)),o=U7a(i,Object.keys(i).filter(c=>!a.has(c)));return e.json(o,n)},getType:()=>e.getType()};return{...r,...XP(r),...d8t(r)}}function Qdh(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function vJi(e){return e.isProperty}function Ilu(e){let t={_getRawProperties:()=>Object.entries(e).map(([r,i])=>vJi(i)?i.rawKey:r),_getParsedProperties:()=>L7a(e),parse:(r,i)=>{let n={},a=[];for(let[o,c]of Q7a(e)){let d=vJi(c)?c.rawKey:o,s=vJi(c)?c.valueSchema:c,u={rawKey:d,parsedKey:o,valueSchema:s};n[d]=u,Vdh(s)&&a.push(d)}return Udh({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 Q7a(e)){let c=vJi(o)?o.valueSchema:o;Vdh(c)&&n.push(a)}return Udh({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:()=>Qh.OBJECT};return{...yF(t),...XP(t),...d8t(t),...Tbn(t)}}function Udh({value:e,requiredKeys:t,getProperty:r,unrecognizedObjectKeys:i="fail",skipValidation:n=!1,breadcrumbsPrefix:a=[]}){if(!bJi(e))return{ok:!1,errors:[{path:a,message:wA(e,"object")}]};let o=new Set(t),c=[],d={};for(let[s,u]of Object.entries(e)){let l=r(s);if(l!=null){o.delete(s);let p=l.transform(u);p.ok?d[l.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 Tbn(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(i,n)=>Ldh({extensionKeys:t._getRawProperties(),value:i,transformBase:a=>e.parse(a,n),transformExtension:a=>t.parse(a,n)}),json:(i,n)=>Ldh({extensionKeys:t._getParsedProperties(),value:i,transformBase:a=>e.json(a,n),transformExtension:a=>t.json(a,n)}),getType:()=>Qh.OBJECT};return{...r,...XP(r),...d8t(r),...Tbn(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:()=>Qh.OBJECT};return{...t,...XP(t),...d8t(t),...Tbn(t)}}}}function Ldh({extensionKeys:e,value:t,transformBase:r,transformExtension:i}){let n=new Set(e),[a,o]=Fdh(L7a(t),s=>n.has(s)),c=r(U7a(t,o)),d=i(U7a(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 Vdh(e){return!XLD(e)}function XLD(e){switch(e.getType()){case Qh.ANY:case Qh.UNKNOWN:case Qh.OPTIONAL:return!0;default:return!1}}function Wdh(e){return Ilu(e)}function Gdh(e){let t={...AGc(e),_getRawProperties:()=>Xaa(e)._getRawProperties(),_getParsedProperties:()=>Xaa(e)._getParsedProperties()};return{...t,...XP(t),...d8t(t),...Tbn(t)}}function Clu(e){let t={parse:(r,i)=>xdh(r,(n,a)=>e.parse(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),json:(r,i)=>xdh(r,(n,a)=>e.json(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),getType:()=>Qh.LIST};return{...yF(t),...XP(t)}}function xdh(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:wA(e,"list"),path:[]}]}}function Hdh(e){return AW(Qh.STRING_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:wA(r,`"${e}"`)}]})()}function Kdh(e){return AW(Qh.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:wA(r,`${e.toString()}`)}]})()}var Jdh=AW(Qh.ANY,e=>({ok:!0,value:e}));var $dh=AW(Qh.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:wA(e,"boolean")}]});var Ydh=AW(Qh.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:wA(e,"number")}]});var Xdh=AW(Qh.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:wA(e,"string")}]});var Zdh=AW(Qh.UNKNOWN,e=>({ok:!0,value:e}));function eph(e,t){let r={parse:(i,n)=>kdh({value:i,isKeyNumeric:e.getType()===Qh.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)=>kdh({value:i,isKeyNumeric:e.getType()===Qh.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:()=>Qh.RECORD};return{...yF(r),...XP(r)}}function kdh({value:e,isKeyNumeric:t,transformKey:r,transformValue:i,breadcrumbsPrefix:n=[]}){return bJi(e)?Q7a(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),l=i(c,s);if(d.ok&&u.ok&&l.ok)return{ok:!0,value:{...d.value,[u.value]:l.value}};let p=[];return d.ok||p.push(...d.errors),u.ok||p.push(...u.errors),l.ok||p.push(...l.errors),{ok:!1,errors:p}},{ok:!0,value:{}}):{ok:!1,errors:[{path:n,message:wA(e,"object")}]}}function tph(e){let t=Clu(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:wA(i,"Set")}]},getType:()=>Qh.SET};return{...yF(r),...XP(r)}}function iph(e){let t={parse:(r,i)=>rph((n,a)=>n.parse(r,a),e,i),json:(r,i)=>rph((n,a)=>n.json(r,a),e,i),getType:()=>Qh.UNDISCRIMINATED_UNION};return{...yF(t),...XP(t)}}function rph(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 nph(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}function oph(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,i=typeof e=="string"?e:e.parsedDiscriminant,n=Blu(L7a(t)),a={parse:(o,c)=>aph({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)=>aph({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:()=>Qh.UNION};return{...yF(a),...XP(a),...d8t(a)}}function aph({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:wA(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 l=n(u.value);if(l==null)return a?{ok:!0,value:{[r]:u.value,...s}}:{ok:!1,errors:[{path:[...c,t],message:"Unexpected discriminant value"}]};let p=o(s,l);return p.ok?{ok:!0,value:{[r]:d,...p.value}}:p}var Zaa=ie.string();var kaa=ie.string();var La=ie.object({docs:ie.string().optional()});var eoa=ie.object({scheme:ie.string()}).extend(La);var qlu=ie.undiscriminatedUnion([ie.string(),eoa]);var Tlu=ie.object({any:ie.list(qlu)}).extend(La);var Rlu=ie.object({});var zlu=ie.object({"endpoint-security":Rlu}).extend(La);var Nlu=ie.undiscriminatedUnion([ie.string(),eoa,Tlu,zlu]);var Flu=ie.object({"client-id":ie.string().optional(),"client-secret":ie.string().optional(),scopes:ie.string().optional()});var Qlu=ie.object({"access-token":ie.string().optional(),"expires-in":ie.string().optional(),"refresh-token":ie.string().optional()});var Ulu=ie.object({endpoint:ie.string(),"request-properties":Flu.optional(),"response-properties":Qlu.optional()});var Llu=ie.object({"refresh-token":ie.string()});var Vlu=ie.object({"access-token":ie.string().optional(),"expires-in":ie.string().optional(),"refresh-token":ie.string().optional()});var Wlu=ie.object({endpoint:ie.string(),"request-properties":Llu.optional(),"response-properties":Vlu.optional()});var Glu=ie.object({scheme:ie.stringLiteral("oauth"),type:ie.stringLiteral("client-credentials"),scopes:ie.list(kaa).optional(),"client-id-env":ie.string().optional(),"client-secret-env":ie.string().optional(),"token-prefix":ie.string().optional(),"token-header":ie.string().optional(),"get-token":Ulu,"refresh-token":Wlu.optional()}).extend(La);var toa=ie.object({env:ie.string().optional()});var rv=ie.object({name:ie.string().optional()});var xlu=ie.object({header:ie.string(),type:ie.string().optional(),prefix:ie.string().optional()}).extend(toa).extend(rv).extend(La);var Rbn=ie.object({}).extend(toa).extend(rv);var Hlu=ie.object({scheme:ie.stringLiteral("basic"),username:Rbn.optional(),password:Rbn.optional()}).extend(La);var Klu=ie.object({scheme:ie.stringLiteral("bearer"),token:Rbn.optional()}).extend(La);var Jlu=ie.object({"response-property":ie.string(),"header-name":ie.string(),"value-prefix":ie.string().optional()});var $lu=ie.object({endpoint:ie.string(),"expiry-response-property":ie.string().optional(),"authenticated-request-headers":ie.list(Jlu).optional()});var Ylu=ie.undiscriminatedUnion([ie.string(),$lu]);var Xlu=ie.object({scheme:ie.stringLiteral("bearer"),"get-token":Ylu}).extend(La);var Zlu=ie.undiscriminatedUnion([Klu,Xlu]);var klu=ie.undiscriminatedUnion([Glu,xlu,Hlu,Zlu]);var efu=ie.object({auth:Nlu.optional(),"auth-schemes":ie.record(Zaa,klu).optional()});var wGc={};Yt(wGc,{AvailabilitySchema:()=>tfu,AvailabilityStatusSchema:()=>roa,AvailabilityUnionSchema:()=>rfu});var roa=ie.enum_(["in-development","pre-release","deprecated","generally-available"]);var tfu=ie.object({status:roa,message:ie.string().optional()});var rfu=ie.undiscriminatedUnion([roa,tfu]);var EGc={};Yt(EGc,{DeclarationSchema:()=>BYt,DeclarationWithNameSchema:()=>uph,DeclarationWithoutDocsSchema:()=>ufu,WithAudiences:()=>vF,WithAvailability:()=>PW,WithDisplayName:()=>bF,WithDocsSchema:()=>La,WithMethodName:()=>ifu,WithName:()=>rv,WithValidation:()=>ofu});var PW=ie.object({availability:rfu.optional()});var bF=ie.object({"display-name":ie.string().optional()});var ifu=ie.object({"method-name":ie.string().optional()});var nfu=ie.object({minLength:ie.number().optional(),maxLength:ie.number().optional(),pattern:ie.string().optional(),format:ie.string().optional()});var afu=ie.object({min:ie.number().optional(),max:ie.number().optional(),exclusiveMin:ie.boolean().optional(),exclusiveMax:ie.boolean().optional(),multipleOf:ie.number().optional()});var gJi=ie.undiscriminatedUnion([nfu,afu]);var ofu=ie.object({validation:gJi.optional()});var vF=ie.object({audiences:ie.list(ie.string()).optional()});var BYt=ie.object({}).extend(La).extend(PW).extend(vF);var ufu=ie.object({}).extend(PW).extend(vF);var uph=ie.object({}).extend(BYt).extend(rv);var SGc={};Yt(SGc,{EncodingSchema:()=>ioa,ProtobufTypeSchema:()=>sfu});var sfu=ie.object({type:ie.string()});var ioa=ie.object({proto:sfu.optional()});var MGc={};Yt(MGc,{EnvironmentSchema:()=>ffu,MultipleBaseUrlsEnvironmentSchema:()=>lfu,SingleBaseUrlEnvironmentSchema:()=>cfu,WithEnvironmentsSchema:()=>dfu});var cfu=ie.object({url:ie.string()}).extend(vF).extend(La);var lfu=ie.object({urls:ie.record(ie.string(),ie.string())}).extend(vF).extend(La);var ffu=ie.undiscriminatedUnion([ie.string(),cfu,lfu]);var dfu=ie.object({"default-url":ie.string().optional(),"default-environment":ie.string().optional(),environments:ie.record(ie.string(),ffu).optional()});var DGc={};Yt(DGc,{ErrorDeclarationSchema:()=>_fu});var pfu=ie.unknown();var noa=ie.object({value:pfu}).extend(rv).extend(La);var _fu=ie.object({"status-code":ie.number(),type:ie.string().optional(),examples:ie.list(noa).optional()}).extend(La);var BGc={};Yt(BGc,{ExampleBodyResponseSchema:()=>bfu,ExampleCodeSampleSchema:()=>wfu,ExampleCodeSampleSchemaLanguage:()=>jfu,ExampleCodeSampleSchemaSdk:()=>Pfu,ExampleEndpointCallArraySchema:()=>sph,ExampleEndpointCallSchema:()=>aoa,ExampleResponseSchema:()=>mfu,ExampleSseEventSchema:()=>gfu,ExampleSseResponseSchema:()=>Ofu,ExampleStreamResponseSchema:()=>vfu,ExampleTypeReferenceSchema:()=>RR,ExampleTypeSchema:()=>noa,ExampleTypeValueSchema:()=>pfu,ExampleWebSocketMessage:()=>hfu,ExampleWebSocketSession:()=>yfu,ExampleWebhookCallSchema:()=>Efu,SupportedSdkLanguageSchema:()=>Afu});var RR=ie.unknown();var hfu=ie.object({type:ie.string(),body:ie.unknown()});var yfu=ie.object({"path-parameters":ie.record(ie.string(),RR).optional(),"query-parameters":ie.record(ie.string(),RR).optional(),headers:ie.record(ie.string(),RR).optional(),messages:ie.list(hfu)}).extend(rv).extend(La);var bfu=ie.object({error:ie.string().optional(),body:RR.optional()});var vfu=ie.object({stream:ie.list(RR)});var gfu=ie.object({event:ie.string(),data:RR.optional()});var Ofu=ie.object({stream:ie.list(gfu)});var mfu=ie.undiscriminatedUnion([bfu,vfu,Ofu]);var Afu=ie.enum_(["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm","c#"]);var Pfu=ie.object({sdk:Afu,code:ie.string()}).extend(La).extend(rv);var jfu=ie.object({language:ie.string(),code:ie.string(),install:ie.string().optional()}).extend(La).extend(rv);var wfu=ie.undiscriminatedUnion([Pfu,jfu]);var aoa=ie.object({id:ie.string().optional(),"path-parameters":ie.record(ie.string(),RR).optional(),"query-parameters":ie.record(ie.string(),RR).optional(),headers:ie.record(ie.string(),RR).optional(),request:RR.optional(),response:mfu.optional(),"code-samples":ie.list(wfu).optional()}).extend(rv).extend(La);var sph=ie.list(aoa);var Efu=ie.object({id:ie.string().optional(),payload:RR}).extend(rv).extend(La);var IGc={};Yt(IGc,{DefinitionFileSchema:()=>Ndu,ErrorDiscriminationSchema:()=>Gdu,Export:()=>Udu,ExportDetailed:()=>Qdu,Navigation:()=>Fdu,PackageMarkerFileSchema:()=>cph,PropertyBasedErrorDiscrimination:()=>Vdu,RootApiFileSchema:()=>lph,StatusCodeBasedErrorDiscrimination:()=>Wdu,WithHeadersSchema:()=>Ldu});var FEe=ie.undiscriminatedUnion([ie.string(),ie.list(ie.string())]);var Sfu=ie.enum_(["read-only","write-only"]);var ooa=ie.object({default:ie.unknown().optional(),encoding:ioa.optional(),validation:gJi.optional()}).extend(La).extend(PW);var QEe=ie.object({type:ie.string()}).extend(ooa).extend(rv).extend(vF);var Mfu=ie.object({access:Sfu.optional()}).extend(QEe);var OJi=ie.undiscriminatedUnion([ie.string(),Mfu]);var Dfu=ie.object({openapi:ie.string()});var Bfu=ie.object({proto:ie.string()});var mJi=ie.undiscriminatedUnion([Dfu,Bfu]);var UEe=ie.object({examples:ie.list(noa).optional(),encoding:ioa.optional(),source:mJi.optional(),inline:ie.boolean().optional()}).extend(La).extend(PW).extend(vF);var Ifu=ie.object({extends:FEe.optional(),properties:ie.record(ie.string(),OJi).optional(),"extra-properties":ie.boolean().optional()}).extend(UEe);var Cfu=ie.object({camel:ie.string().optional(),snake:ie.string().optional(),pascal:ie.string().optional(),"screaming-snake":ie.string().optional()});var qfu=ie.object({value:ie.string(),casing:Cfu.optional()}).extend(La).extend(rv);var Tfu=ie.undiscriminatedUnion([ie.string(),qfu]);var Rfu=ie.object({default:ie.string().optional(),enum:ie.list(Tfu)}).extend(UEe);var zfu=ie.object({value:ie.string()}).extend(rv);var Nfu=ie.undiscriminatedUnion([ie.string(),zfu]);var Ffu=ie.object({type:ie.string()}).extend(ooa).extend(rv).extend(vF);var dUi=ie.undiscriminatedUnion([ie.string(),Ffu]);var Qfu=ie.object({value:ie.string()}).extend(rv);var Ufu=ie.undiscriminatedUnion([ie.string(),Qfu]);var Lfu=ie.object({type:ie.string().optional(),key:Ufu.optional()}).extend(La).extend(rv).extend(PW).extend(bF);var Vfu=ie.undiscriminatedUnion([ie.string(),Lfu]);var Wfu=ie.object({discriminant:Nfu.optional(),extends:FEe.optional(),"base-properties":ie.record(ie.string(),dUi).optional(),union:ie.record(ie.string(),Vfu)}).extend(UEe);var Gfu=ie.object({type:ie.string()}).extend(La).extend(bF).extend(ofu);var xfu=ie.undiscriminatedUnion([ie.string(),Gfu]);var Hfu=ie.object({discriminated:ie.booleanLiteral(!1),union:ie.list(xfu)}).extend(UEe);var Kfu=ie.object({type:ie.string(),validation:gJi.optional()}).extend(UEe);var Jfu=ie.undiscriminatedUnion([ie.string(),Ifu,Rfu,Wfu,Hfu,Kfu]);var $fu=ie.object({"service-name":ie.string()});var uoa=ie.object({grpc:$fu.optional()});var Yfu=ie.enum_(["GET","POST","PUT","PATCH","DELETE","HEAD"]);var Xfu=ie.object({variable:ie.string()}).extend(PW).extend(La);var IYt=ie.undiscriminatedUnion([dUi,Xfu]);var Zfu=ie.record(Zaa,ie.list(kaa));var kfu=ie.list(Zfu);var edu=ie.undiscriminatedUnion([ie.boolean(),kfu]);var tdu=ie.object({"allow-multiple":ie.boolean().optional()}).extend(QEe);var soa=ie.undiscriminatedUnion([ie.string(),tdu]);var rdu=ie.object({env:ie.string().optional()}).extend(QEe);var idu=ie.undiscriminatedUnion([ie.string(),rdu]);var LEe=idu;var ndu=ie.object({type:ie.string()}).extend(La);var adu=ie.enum_(["json","exploded","form"]);var odu=ie.object({style:adu.optional(),"content-type":ie.string().optional()}).extend(QEe);var udu=ie.undiscriminatedUnion([ie.string(),odu]);var sdu=ie.object({extends:FEe.optional(),"extra-properties":ie.boolean().optional(),properties:ie.record(ie.string(),udu).optional()});var cdu=ie.undiscriminatedUnion([ie.string(),ndu,sdu]);var ldu=ie.object({"content-type":ie.string().optional(),"path-parameters":ie.record(ie.string(),IYt).optional(),"query-parameters":ie.record(ie.string(),soa).optional(),headers:ie.record(ie.string(),LEe).optional(),body:cdu.optional()}).extend(rv).extend(La);var fdu=ie.undiscriminatedUnion([ie.string(),ldu]);var ddu=ie.object({type:ie.string().optional(),property:ie.string().optional(),"status-code":ie.number().optional()}).extend(La);var coa=ie.undiscriminatedUnion([ie.string(),ddu]);var pdu=ie.enum_(["sse","json"]);var _du=ie.object({type:ie.string(),format:pdu.optional(),terminator:ie.string().optional()}).extend(La);var loa=ie.undiscriminatedUnion([ie.string(),_du]);var hdu=ie.object({error:ie.string()}).extend(La);var ydu=ie.undiscriminatedUnion([ie.string(),hdu]);var bdu=ie.list(ydu);var vdu=ie.object({cursor:ie.string(),next_cursor:ie.string(),results:ie.string()});var gdu=ie.object({offset:ie.string(),results:ie.string(),step:ie.string().optional(),"has-next-page":ie.string().optional()});var Odu=ie.object({type:ie.stringLiteral("custom"),results:ie.string()});var foa=ie.undiscriminatedUnion([vdu,gdu,Odu]);var mdu=ie.undiscriminatedUnion([foa,ie.boolean()]);var Adu=ie.object({disabled:ie.boolean().optional()});var Pdu=ie.undiscriminatedUnion([Adu]);var jdu=ie.object({method:Yfu.optional(),"base-path":ie.string().optional(),path:ie.string(),url:ie.string().optional(),"path-parameters":ie.record(ie.string(),IYt).optional(),auth:edu.optional(),idempotent:ie.boolean().optional(),"stream-condition":ie.string().optional(),request:fdu.optional(),response:coa.optional(),"response-stream":loa.optional(),errors:bdu.optional(),examples:ie.list(aoa).optional(),pagination:mdu.optional(),transport:uoa.optional(),source:mJi.optional(),retries:Pdu.optional()}).extend(bF).extend(BYt);var wdu=ie.object({auth:ie.boolean(),url:ie.string().optional(),"base-path":ie.string(),"path-parameters":ie.record(ie.string(),dUi).optional(),idempotent:ie.boolean().optional(),headers:ie.record(ie.string(),dUi).optional(),transport:uoa.optional(),source:mJi.optional(),endpoints:ie.record(ie.string(),jdu)}).extend(ufu).extend(bF);var Edu=ie.enum_(["POST","GET"]);var Sdu=ie.object({type:ie.string()}).extend(La);var Mdu=ie.object({name:ie.string(),extends:FEe.optional(),properties:ie.record(ie.string(),OJi).optional()});var Ddu=ie.undiscriminatedUnion([ie.string(),Sdu,Mdu]);var Bdu=ie.object({method:Edu,headers:ie.record(ie.string(),LEe).optional(),payload:Ddu,response:coa.optional(),"response-stream":loa.optional(),examples:ie.list(Efu).optional()}).extend(PW).extend(vF).extend(La).extend(bF);var Idu=ie.enum_(["client","server"]);var Cdu=ie.object({type:ie.string()}).extend(La);var qdu=ie.object({name:ie.string(),extends:FEe.optional(),properties:ie.record(ie.string(),OJi).optional()});var Tdu=ie.undiscriminatedUnion([ie.string(),Cdu,qdu]);var Rdu=ie.object({origin:Idu,body:Tdu}).extend(BYt).extend(bF).extend(ifu);var zdu=ie.object({auth:ie.boolean(),url:ie.string().optional(),path:ie.string(),headers:ie.record(ie.string(),LEe).optional(),"path-parameters":ie.record(ie.string(),IYt).optional(),"query-parameters":ie.record(ie.string(),soa).optional(),messages:ie.record(ie.string(),Rdu).optional(),examples:ie.list(yfu).optional()}).extend(BYt).extend(bF);var Ndu=ie.object({imports:ie.record(ie.string(),ie.string()).optional(),types:ie.record(ie.string(),Jfu).optional(),service:wdu.optional(),errors:ie.record(ie.string(),_fu).optional(),webhooks:ie.record(ie.string(),Bdu).optional(),channel:zdu.optional()}).extend(La);var Fdu=ie.undiscriminatedUnion([ie.string(),ie.list(ie.string())]);var Qdu=ie.object({dependency:ie.string(),url:ie.string().optional()});var Udu=ie.undiscriminatedUnion([ie.string(),Qdu]);var cph=ie.object({navigation:Fdu.optional(),export:Udu.optional()}).extend(Ndu);var Ldu=ie.object({headers:ie.record(ie.string(),LEe).optional()});var Vdu=ie.object({strategy:ie.stringLiteral("property"),"property-name":ie.string()});var Wdu=ie.object({strategy:ie.stringLiteral("status-code")});var Gdu=ie.undiscriminatedUnion([Vdu,Wdu]);var xdu=ie.object({type:ie.string()}).extend(La);var Hdu=ie.undiscriminatedUnion([ie.string(),xdu]);var Kdu=ie.object({value:ie.string()}).extend(La).extend(rv);var Jdu=ie.undiscriminatedUnion([ie.string(),Kdu]);var $du=ie.object({name:ie.string().optional(),env:ie.string().optional(),value:ie.string()});var Ydu=ie.undiscriminatedUnion([ie.string(),$du]);var doa=ie.object({default:ie.string().optional(),values:ie.list(Jdu),header:Ydu});var Xdu=ie.object({value:ie.string(),versions:doa.optional()}).extend(La).extend(rv);var Zdu=ie.undiscriminatedUnion([ie.string(),Xdu]);var kdu=ie.object({name:ie.string().optional(),env:ie.string().optional(),value:ie.string()});var epu=ie.undiscriminatedUnion([ie.string(),kdu]);var tpu=ie.object({default:ie.string().optional(),values:ie.list(Zdu),header:epu});var lph=ie.object({name:ie.string(),imports:ie.record(ie.string(),ie.string()).optional(),"error-discrimination":Gdu.optional(),audiences:ie.list(ie.string()).optional(),errors:ie.list(ie.string()).optional(),"base-path":ie.string().optional(),"path-parameters":ie.record(ie.string(),IYt).optional(),"idempotency-headers":ie.record(ie.string(),LEe).optional(),variables:ie.record(ie.string(),Hdu).optional(),pagination:foa.optional(),product:tpu.optional(),version:doa.optional()}).extend(La).extend(bF).extend(dfu).extend(efu).extend(Ldu);var CGc={};Yt(CGc,{CursorPaginationSchema:()=>vdu,CustomPaginationSchema:()=>Odu,OffsetPaginationSchema:()=>gdu,PaginationSchema:()=>foa});var qGc={};Yt(qGc,{ProductDeclarationHeaderObjectSchema:()=>kdu,ProductDeclarationHeaderSchema:()=>epu,ProductDeclarationSchema:()=>tpu,ProductValue:()=>Zdu,ProductValueDetailed:()=>Xdu});var TGc={};Yt(TGc,{FormDataBodyEncodingStyle:()=>adu,GrpcTransport:()=>$fu,HttpEndpointAuth:()=>edu,HttpEndpointSchema:()=>jdu,HttpEndpointSecurity:()=>kfu,HttpEndpointSecurityItem:()=>Zfu,HttpHeaderSchema:()=>LEe,HttpInlineFileRequestBodyPropertySchema:()=>odu,HttpInlineRequestBodyPropertySchema:()=>udu,HttpInlineRequestBodySchema:()=>sdu,HttpMethodSchema:()=>Yfu,HttpPathParameterSchema:()=>IYt,HttpQueryParameterSchema:()=>soa,HttpReferencedRequestBodySchema:()=>ndu,HttpRequest:()=>fdu,HttpRequestBodySchema:()=>cdu,HttpRequestSchema:()=>ldu,HttpResponseSchema:()=>coa,HttpResponseSchemaDetailed:()=>ddu,HttpResponseStreamSchema:()=>loa,HttpResponseStreamSchemaDetailed:()=>_du,HttpServiceSchema:()=>wdu,Pagination:()=>mdu,QueryParameterTypeReferenceDetailed:()=>tdu,ResponseError:()=>ydu,ResponseErrorWithDocsSchema:()=>hdu,ResponseErrorsSchema:()=>bdu,RetriesConfiguration:()=>Pdu,RetriesDisabledSchema:()=>Adu,ServiceTransport:()=>uoa,StreamFormat:()=>pdu,TypeReferenceDeclarationWithEnvOverride:()=>idu,TypeReferenceDeclarationWithEnvOverrideSchema:()=>rdu});var RGc={};Yt(RGc,{OpenApiSourceSchema:()=>Dfu,ProtobufSourceSchema:()=>Bfu,SourceSchema:()=>mJi});var zGc={};Yt(zGc,{AliasSchema:()=>Kfu,BaseTypeDeclarationSchema:()=>UEe,BaseTypeReferenceSchema:()=>ooa,CasingOverridesSchema:()=>Cfu,DiscriminatedUnionSchema:()=>Wfu,EnumSchema:()=>Rfu,EnumValue:()=>Tfu,EnumValueSchema:()=>qfu,ObjectExtendsSchema:()=>FEe,ObjectPropertyAccess:()=>Sfu,ObjectPropertySchema:()=>OJi,ObjectPropertyWithAccessSchema:()=>Mfu,ObjectSchema:()=>Ifu,SingleUndiscriminatedUnionTypeDetailedSchema:()=>Gfu,SingleUndiscriminatedUnionTypeSchema:()=>xfu,SingleUnionTypeDetailedSchema:()=>Lfu,SingleUnionTypeKey:()=>Ufu,SingleUnionTypeKeySchema:()=>Qfu,SingleUnionTypeSchema:()=>Vfu,TypeDeclarationSchema:()=>Jfu,TypeReferenceDeclarationWithName:()=>QEe,TypeReferenceDeclarationWithNameSchema:()=>fph,TypeReferenceDetailedSchema:()=>Ffu,TypeReferenceSchema:()=>dUi,UndiscriminatedUnionSchema:()=>Hfu,UnionDiscriminant:()=>Nfu,UnionDiscriminantSchema:()=>zfu});var fph=ie.undiscriminatedUnion([ie.string(),QEe]);var NGc={};Yt(NGc,{NumberValidationSchema:()=>afu,StringValidationSchema:()=>nfu,ValidationSchema:()=>gJi});var FGc={};Yt(FGc,{VariableDeclarationDetailed:()=>xdu,VariableDeclarationSchema:()=>Hdu,VariableReferenceSchema:()=>Xfu});var QGc={};Yt(QGc,{VersionDeclarationHeaderObjectSchema:()=>$du,VersionDeclarationHeaderSchema:()=>Ydu,VersionDeclarationSchema:()=>doa,VersionValue:()=>Jdu,VersionValueDetailed:()=>Kdu});var UGc={};Yt(UGc,{WebhookInlinedPayloadSchema:()=>Mdu,WebhookMethodSchema:()=>Edu,WebhookPayloadSchema:()=>Ddu,WebhookReferencedPayloadSchema:()=>Sdu,WebhookSchema:()=>Bdu});var LGc={};Yt(LGc,{WebSocketChannelInlinedMessageSchema:()=>qdu,WebSocketChannelMessageBodySchema:()=>Tdu,WebSocketChannelMessageSchema:()=>Rdu,WebSocketChannelReferencedMessageSchema:()=>Cdu,WebSocketChannelSchema:()=>zdu,WebSocketOrigin:()=>Idu});var V7a=class e extends Error{statusCode;body;constructor({message:t,statusCode:r,body:i}){super(ZLD({message:t,statusCode:r,body:i})),Object.setPrototypeOf(this,e.prototype),r!=null&&(this.statusCode=r),i!==void 0&&(this.body=i)}};function ZLD({message:e,statusCode:t,body:r}){let i=[];return e!=null&&i.push(e),t!=null&&i.push(`Status code: ${t.toString()}`),r!=null&&i.push(`Body: ${JSON.stringify(r,void 0,2)}`),i.join(`
1468
- `)}var W7a=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}};function WGc(e){return e.scheme==="oauth"}var kLD={optional:"optional",nullable:"nullable",set:"set",list:"list",map:"map",literal:"literal"},dph=new Set(Object.values(kLD));function ED(e){let t=e.match(/([\w.]+)<([\w,\s]+)>/);if(t?.[0]!=null&&t[1]!=null&&t[2]!=null&&!dph.has(t[1].trim()))return{name:t[1].trim(),arguments:t[2].split(",").map(r=>r.trim())}}function VEe(e){return ED(e)!=null}function GGc(e){if(e.request!=null)return typeof e.request=="string"?e.request:e.request.body}var zbn=class{REFERENCE_REGEX=/^(GET|POST|PUT|DELETE|PATCH|HEAD)\s(\/\S*)$/;validate(t){return this.REFERENCE_REGEX.test(t)?{type:"valid"}:{type:"invalid"}}tryParse(t){if(this.validate(t).type==="invalid")return;let i=t.match(this.REFERENCE_REGEX);if(!(i==null||i[1]==null||i[2]==null))return{method:i[1],path:i[2]}}};function fw(e){return typeof e=="string"?!1:e?.extends!=null||e?.properties!=null}function CYt(e){return e?e.proto!=null:!1}var eVD="text";function AJi(e){return e===eVD}var px={integer:"integer",long:"long",uint:"uint",uint64:"uint64",float:"float",double:"double",boolean:"boolean",string:"string",datetime:"datetime",base64:"base64",uuid:"uuid",date:"date",bigint:"bigint",unknown:"unknown"};var sY={MAP:/^map<\s*([^,]*)\s*,\s*(.*)\s*>$/,LIST:/^list<\s*(.*)\s*>$/,SET:/^set<\s*(.*)\s*>$/,OPTIONAL:/^optional<\s*(.*)\s*>$/,NULLABLE:/^nullable<\s*(.*)\s*>$/,LITERAL:/^literal<\s*(?:"(.*)"|(true|false))\s*>$/};function Nbn({type:e,_default:t,validation:r,visitor:i}){switch(e){case px.integer:{let u=r??void 0;return i.primitive({v1:ku.Integer,v2:vn.integer({default:t??void 0,validation:u!=null?{min:u.min,max:u.max,exclusiveMin:u.exclusiveMin,exclusiveMax:u.exclusiveMax,multipleOf:u.multipleOf}:void 0})})}case px.double:{let u=r??void 0;return i.primitive({v1:ku.Double,v2:vn.double({default:t??void 0,validation:u!=null?{min:u.min,max:u.max,exclusiveMin:u.exclusiveMin,exclusiveMax:u.exclusiveMax,multipleOf:u.multipleOf}:void 0})})}case px.string:{let u=r??void 0;return i.primitive({v1:ku.String,v2:vn.string({default:t??void 0,validation:u!=null?{format:u.format,pattern:u.pattern,minLength:u.minLength,maxLength:u.maxLength}:void 0})})}case px.float:return i.primitive({v1:ku.Float,v2:void 0});case px.long:{let u=r??void 0;return i.primitive({v1:ku.Long,v2:vn.long({default:t??void 0,validation:u!=null?{min:u.min,max:u.max,exclusiveMin:u.exclusiveMin,exclusiveMax:u.exclusiveMax,multipleOf:u.multipleOf}:void 0})})}case px.boolean:return i.primitive({v1:ku.Boolean,v2:vn.boolean({default:t??void 0})});case px.datetime:return i.primitive({v1:ku.DateTime,v2:void 0});case px.date:return i.primitive({v1:ku.Date,v2:void 0});case px.uuid:return i.primitive({v1:ku.Uuid,v2:void 0});case px.base64:return i.primitive({v1:ku.Base64,v2:void 0});case px.bigint:return i.primitive({v1:ku.BigInteger,v2:vn.bigInteger({default:t??void 0})});case px.uint:return i.primitive({v1:ku.Uint,v2:void 0});case px.uint64:return i.primitive({v1:ku.Uint64,v2:void 0});case px.unknown:return i.unknown()}let n=e.match(sY.MAP);if(n?.[1]!=null&&n[2]!=null)return i.map({keyType:n[1],valueType:n[2]});let a=e.match(sY.LIST);if(a?.[1]!=null)return i.list(a[1]);let o=e.match(sY.SET);if(o?.[1]!=null)return i.set(o[1]);let c=e.match(sY.OPTIONAL);if(c?.[1]!=null)return i.optional(c[1]);let d=e.match(sY.NULLABLE);if(d?.[1]!=null)return i.nullable(d[1]);let s=e.match(sY.LITERAL);if(s?.[1]!=null)return i.literal(lF.string(s[1]));if(s?.[2]!=null){let u=s[2];switch(u){case"false":return i.literal(lF.boolean(!1));case"true":return i.literal(lF.boolean(!0));default:throw new Error(`Unsupported literal value: ${u}`)}}return i.named(e)}var pph="bytes";function WEe(e){if(e===pph)return{isOptional:!1};if(e.match(sY.OPTIONAL)?.[1]===pph)return{isOptional:!0}}function G7a(e){let t=typeof e=="string"?e:typeof e.body=="string"?e.body:void 0;if(t!=null)return WEe(t)}function xGc({input:e,typeName:t}){for(let r of e.arguments)if(typeof r=="string"){if(r===t)return!0}else if(xGc({input:r,typeName:t}))return!0;return!1}function _ph(e){return xGc({input:e,typeName:"file"})}function hph(e){let t=0,r=0;function i(){for(;t<e.length&&/\s/.test(e[t]);)t++;if(t>=e.length)return;let a="";for(;t<e.length&&e[t]!=="<"&&e[t]!==","&&e[t]!==">";)a+=e[t++];if(a.trim()){for(;t<e.length&&/\s/.test(e[t]);)t++;if(t<e.length&&e[t]==="<"){if(t++,r++,r>128)throw new Error("Internal error; Exceeded maximum recursion depth while parsing generics.");let o={name:a.trim(),arguments:[]};for(;t<e.length&&e[t]!==">";){for(;t<e.length&&/[\s,]/.test(e[t]);)t++;if(t<e.length&&e[t]!==">"){let c=i();c&&o.arguments.push(c)}}if(t<e.length&&e[t]===">")t++,r--;else throw new Error("Malformed input: missing closing '>' for generic arguments.");return o}else return a.trim()}}let n=i();if(typeof n=="object")return n}var HGc="file";function yph(e){return e.match(sY.LIST)?.[1]===HGc}function cY(e){if(e===HGc)return{isOptional:!1,isArray:!1};let t=e.match(sY.OPTIONAL);if(t?.[1]!==void 0){if(t[1]===HGc)return{isOptional:!0,isArray:!1};if(yph(t[1]))return{isOptional:!0,isArray:!0}}if(yph(e))return{isOptional:!1,isArray:!0}}function tVD(e){return typeof e=="string"?!1:tm.parse(e["content-type"])?.isMultiPartFormData()??!1?!0:e.body==null?!1:!!(fw(e.body)&&Object.values(e.body.properties??[]).some(iVD))}function Fbn(e){if(!(!tVD(e)||e.body==null)&&e.name!=null&&e.body!=null&&fw(e.body))return rVD(e.name,e.body)}function rVD(e,t){let r=Object.entries(t.properties??[]).reduce((i,[n,a])=>{let o=typeof a!="string"?a.docs:void 0,c=typeof a!="string"?a["content-type"]:void 0,d=typeof a!="string"?a.style:void 0,s=cY(typeof a=="string"?a:a.type);return s!=null?i.push({isFile:!0,key:n,docs:o,isOptional:s.isOptional,isArray:s.isArray,contentType:c,style:d}):i.push({isFile:!1,key:n,propertyType:a,docs:o,contentType:c,style:d}),i},[]);return t["extra-properties"],{name:e,extends:t.extends,properties:r}}function iVD(e){let t=typeof e=="string"?e:e.type;if(t==="file")return!0;if(!t.includes("file"))return!1;let r=hph(t);return r==null?!1:_ph(r)}var bph="text";function Qbn(e){if(e===bph)return{isOptional:!1};if(e.match(sY.OPTIONAL)?.[1]===bph)return{isOptional:!0}}function hC({type:e,_default:t,validation:r,visitor:i}){return Nbn({type:e,_default:t,validation:r,visitor:{primitive:i.primitive,map:({keyType:n,valueType:a})=>i.map({keyType:hC({type:n,_default:void 0,validation:void 0,visitor:i}),valueType:hC({type:a,_default:void 0,validation:void 0,visitor:i})}),list:n=>i.list(hC({type:n,_default:void 0,validation:void 0,visitor:i})),set:n=>i.set(hC({type:n,_default:void 0,validation:void 0,visitor:i})),optional:n=>i.optional(hC({type:n,_default:t,validation:r,visitor:i})),nullable:n=>i.nullable(hC({type:n,_default:t,validation:r,visitor:i})),literal:i.literal,named:i.named,unknown:i.unknown}})}function KGc(e,t){if(nVD(e))return t.sdk(e);if(aVD(e))return t.language(e);vt(e)}function nVD(e){return e.sdk!=null}function aVD(e){return e.language!=null}function vph(e){return e["response-stream"]!=null&&(typeof e["response-stream"]=="string"||e["response-stream"].format==null||e["response-stream"].format==="json")}function gph(e){return e["response-stream"]!=null&&typeof e["response-stream"]!="string"&&e["response-stream"].format==="sse"}function Ubn(e,t,r){return oVD(e,t)?r.stream(t):uVD(e,t)?r.events(t):r.body(t)}function oVD(e,t){return t.stream!==void 0&&vph(e)}function uVD(e,t){return t.stream!==void 0&&gph(e)}function Lbn(e,t){if(Oph(e))return t.single(e);if(mph(e))return t.any(e);if(sVD(e))return t.endpointSecurity(e);vt(e)}function Oph(e){return typeof e=="string"||e.scheme!=null}function mph(e){let[t,...r]=Object.keys(e);return t==="any"&&r.length===0}function sVD(e){let[t,...r]=Object.keys(e);return t==="endpoint-security"&&r.length===0}function x7a(e,t){if(Aph(e))return t.header(e);switch(e.scheme){case"basic":return t.basic(e);case"bearer":return"get-token"in e?t.inferredBearer(e):t.tokenBearer(e);case"oauth":return t.oauth(e);default:vt(e)}}function Aph(e){return e.header!=null}function qYt(e,t){if(Pph(e))return t.singleBaseUrl(e);if(kve(e))return t.multipleBaseUrls(e);vt(e)}function Pph(e){return typeof e=="string"||"url"in e}function kve(e){return typeof e!="string"&&"urls"in e}function poa(e){return typeof e=="string"?e.startsWith("$"):"variable"in e}function yC(e,t){if(PJi(e))return t.alias(e);if(jJi(e))return t.discriminatedUnion(e);if(iv(e))return t.object(e);if(_oa(e))return t.undiscriminatedUnion(e);if(p8t(e))return t.enum(e);vt(e)}function PJi(e){return typeof e=="string"||e.type!=null}function iv(e){return e.extends!=null||e.properties!=null}function jJi(e){return e.union!=null&&e.discriminated==null}function _oa(e){let t=e;return t.union!=null&&t.discriminated!=null}function p8t(e){return e.enum!=null}function JGc({rawApiFileSchema:e,casingsGenerator:t}){if(e.auth==null)return{docs:void 0,requirement:qR.All,schemes:[]};let r=typeof e.auth!="string"?e.auth.docs:void 0;return Lbn(e.auth,{single:i=>{let n=jph({reference:i,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t});return{docs:r,requirement:qR.All,schemes:[n]}},any:({any:i})=>({docs:r,requirement:qR.Any,schemes:i.map(n=>jph({reference:n,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t}))}),endpointSecurity:()=>({docs:r,requirement:qR.EndpointSecurity,schemes:[]})})}function jph({reference:e,authSchemeDeclarations:t,casingsGenerator:r}){let i=(a,o)=>{let c=t?.[a];if(c==null)throw new Error("Unknown auth scheme: "+a);return x7a(c,{header:d=>PA.header({key:a,docs:o,name:r.generateNameAndWireValue({name:d.name??a,wireValue:d.header}),valueType:ii.primitive({v1:ku.String,v2:vn.string({default:void 0,validation:void 0})}),prefix:d.prefix,headerEnvVar:d.env}),basic:d=>wph({key:a,casingsGenerator:r,docs:o,rawScheme:d}),tokenBearer:d=>rpu({key:a,casingsGenerator:r,docs:o,rawScheme:d}),inferredBearer(d){return rpu({key:a,casingsGenerator:r,docs:o,rawScheme:void 0})},oauth:d=>rpu({key:a,casingsGenerator:r,docs:o,rawScheme:void 0})})},n=typeof e=="string"?e:e.scheme;switch(n){case"bearer":case"oauth":return rpu({key:n,casingsGenerator:r,docs:void 0,rawScheme:void 0});case"basic":return wph({key:n,casingsGenerator:r,docs:void 0,rawScheme:void 0});default:return i(n,typeof e!="string"?e.docs:void 0)}}function rpu({key:e,casingsGenerator:t,docs:r,rawScheme:i}){return PA.bearer({key:e,docs:r,token:t.generateName(i?.token?.name??"token"),tokenEnvVar:i?.token?.env})}function wph({key:e,casingsGenerator:t,docs:r,rawScheme:i}){return PA.basic({key:e,docs:r,username:t.generateName(i?.username?.name??"username"),usernameEnvVar:i?.username?.env,password:t.generateName(i?.password?.name??"password"),passwordEnvVar:i?.password?.env})}function DM(e){let t=lVD(e),{value:r,done:i}=$Gc(t,"{");return i?{head:r,parts:[]}:{head:r,parts:[...cVD(t)]}}function*cVD(e){let t;do{let{value:r}=$Gc(e,"}"),i=$Gc(e,"{");t=i.done,yield{pathParameter:r,tail:i.value}}while(!t)}function*lVD(e){for(let t of e)yield t}function $Gc(e,t){let r="",i=e.next();for(;i.done!==!0&&i.value!==t;)r+=i.value,i=e.next();return{value:r,done:i.done??!1}}function H7a({rawApiFileSchema:{"default-environment":e,environments:t},casingsGenerator:r}){if(t==null)return;let i=Object.values(t)[0];if(i!=null)return{environmentsConfig:{defaultEnvironment:e??void 0,environments:qYt(i,{singleBaseUrl:()=>SM.singleBaseUrl(fVD({environments:t,casingsGenerator:r})),multipleBaseUrls:n=>SM.multipleBaseUrls(dVD({baseUrls:Object.keys(n.urls),environments:t,casingsGenerator:r}))})},audiences:{...Object.fromEntries(Object.entries(t).map(([n,a])=>[n,qYt(a,{singleBaseUrl:o=>[...typeof o=="string"?[]:o.audiences??[]],multipleBaseUrls:o=>[...o.audiences??[]]})]))}}}function fVD({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,i])=>qYt(i,{singleBaseUrl:n=>({docs:typeof n=="string"?void 0:n.docs,id:r,name:t.generateName(r),url:Eph(typeof n=="string"?n:n.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function dVD({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(i=>({id:i,name:r.generateName(i)})),environments:Object.entries(t).map(([i,n])=>qYt(n,{multipleBaseUrls:a=>({docs:a.docs,id:i,name:r.generateName(i),urls:nn(a.urls,o=>Eph(o))}),singleBaseUrl:()=>{throw new Error(`Environment ${i} does not have multiple base URLs`)}}))}}function Eph(e){return e.endsWith("/")?e.slice(0,-1):e}function wJi(e){let t=2166136261;function r(n,a){if(typeof n=="object"&&n!=null){if(a>64){i("[MaxDepthExceeded]");return}if(Array.isArray(n)){i("[");for(let o=0;o<n.length;o++)o>0&&i(","),r(n[o],a+1);i("]")}else i("{"),Object.keys(n).sort().forEach((c,d)=>{d>0&&i(","),i(c),i(":"),r(n[c],a+1)}),i("}")}else i(String(n))}function i(n){for(let a=0;a<n.length;a++){let o=n.charCodeAt(a);t^=o,t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24),t>>>=0}}return r(e,0),t.toString(16)}function TYt({typeReference:e,typeDeclarations:t}){if(e.type==="container"&&e.container.type==="optional")return!0;if(e.type==="named"){let r=t?.[e.typeId];if(r?.shape.type==="alias"&&r?.shape.resolvedType.type==="container"&&r?.shape.resolvedType.container.type==="optional")return!0}return!1}function Sph({fieldName:e,containerType:t,maxDepth:r,currentDepth:i,typeDeclarations:n,skipOptionalProperties:a}){if(i>=r)return RYt({containerType:t});switch(t.type){case"list":{let o=EA({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return o.type==="failure"?RYt({containerType:t}):{type:"success",example:Up.list({list:[o.example,o.example],itemType:t.list}),jsonExample:[o.jsonExample,o.jsonExample]}}case"literal":return{type:"success",example:Up.literal({literal:t.literal._visit({boolean:o=>Rn.boolean(o),string:o=>Rn.string({original:o}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:t.literal._visit({boolean:o=>o,string:o=>o,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":{if(a)return RYt({containerType:t});let o=EA({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return o.type==="failure"?RYt({containerType:t}):{type:"success",example:Up.optional({optional:o.example,valueType:t.optional}),jsonExample:o.jsonExample}}case"nullable":{if(a)return RYt({containerType:t});let o=EA({fieldName:e,typeReference:t.nullable,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return o.type==="failure"?RYt({containerType:t}):{type:"success",example:Up.nullable({nullable:o.example,valueType:t.nullable}),jsonExample:o.jsonExample}}case"set":{let o=EA({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return o.type==="failure"?RYt({containerType:t}):{type:"success",example:Up.set({set:[o.example],itemType:t.set}),jsonExample:[o.jsonExample]}}case"map":{let o=EA({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a}),c=EA({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return o.type==="failure"||c.type==="failure"?RYt({containerType:t}):{type:"success",example:Up.map({map:[{key:o.example,value:c.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[o.jsonExample]:c.jsonExample}}}default:vt(t)}}function RYt({containerType:e}){switch(e.type){case"list":return{type:"success",example:Up.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:Up.literal({literal:e.literal._visit({boolean:t=>Rn.boolean(t),string:t=>Rn.string({original:t}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:e.literal._visit({boolean:t=>t,string:t=>t,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":return{type:"success",example:Up.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"nullable":return{type:"success",example:Up.nullable({nullable:void 0,valueType:e.nullable}),jsonExample:void 0};case"set":return{type:"success",example:Up.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:Up.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:vt(e)}}function Dph({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":return bVD({fieldName:e,default_:pVD(t.v2),validation:_VD(t.v2)});case"BASE_64":return{type:"success",example:Rn.base64(xn.BASE64),jsonExample:xn.BASE64};case"BOOLEAN":return{type:"success",example:Rn.boolean(xn.BOOLEAN),jsonExample:xn.BOOLEAN};case"DATE":return{type:"success",example:Rn.date(xn.DATE),jsonExample:xn.DATE};case"DATE_TIME":return{type:"success",example:Rn.datetime({datetime:new Date(xn.DATE_TIME),raw:xn.DATE_TIME}),jsonExample:xn.DATE_TIME};case"DOUBLE":return vVD({fieldName:e,validation:hVD(t.v2)});case"FLOAT":return{type:"success",example:Rn.float(xn.FLOAT),jsonExample:xn.FLOAT};case"INTEGER":return gVD({fieldName:e,validation:yVD(t.v2)});case"UINT_64":return{type:"success",example:Rn.uint64(xn.INT64),jsonExample:xn.INT64};case"UINT":return{type:"success",example:Rn.uint(xn.UINT),jsonExample:xn.UINT};case"BIG_INTEGER":return{type:"success",example:Rn.bigInteger(xn.INT64.toString()),jsonExample:`${xn.INT64}`};case"LONG":return{type:"success",example:Rn.long(xn.INT64),jsonExample:xn.INT64};case"UUID":return{type:"success",example:Rn.uuid(xn.UUID),jsonExample:xn.UUID};default:vt(t.v1)}}function pVD(e){if(e?.type==="string")return e.default}function _VD(e){if(e?.type==="string")return e.validation}function hVD(e){if(e?.type==="double")return e.validation}function yVD(e){if(e?.type==="integer")return e.validation}function Mph(e){if(e<=xn.SAMPLE_STRINGS.length){let t=xn.SAMPLE_STRINGS[e-1];if(t)return t;throw new Error(`Unexpected undefined value in SAMPLE_STRINGS at index ${e-1}`)}return xn.SAMPLE_STRINGS[xn.SAMPLE_STRINGS.length-1]+".".repeat(e-xn.SAMPLE_STRINGS.length)}function bVD({fieldName:e,default_:t,validation:r}){if(t!=null)return{type:"success",example:Rn.string({original:t}),jsonExample:t};if(r){let n=r.minLength,a=r.maxLength;if(n){let o=Mph(n);return{type:"success",example:Rn.string({original:o}),jsonExample:o}}else if(a!=null&&a<10){let o=Mph(a);return{type:"success",example:Rn.string({original:o}),jsonExample:o}}}let i=e??xn.STRING;return{type:"success",example:Rn.string({original:i}),jsonExample:i}}function vVD({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:Rn.double(r),jsonExample:r};if(i)return{type:"success",example:Rn.double(i),jsonExample:i}}return{type:"success",example:Rn.double(xn.DOUBLE),jsonExample:xn.DOUBLE}}function gVD({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:Rn.integer(r),jsonExample:r};if(i)return{type:"success",example:Rn.integer(i),jsonExample:i}}return{type:"success",example:Rn.integer(xn.INT),jsonExample:xn.INT}}function OVD(e,t){if(e.type==="primitive"||e.type==="container"&&e.container.type==="literal")return!0;if(e.type==="named"){let r=t[e.typeId];if(r!=null&&r.shape.type==="enum")return!0}return!1}function Vbn({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let o=EA({fieldName:e,typeDeclarations:t,typeReference:r.shape.aliasOf,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(o.type==="failure")return o;let{example:c,jsonExample:d}=o;return{type:"success",example:hy.alias({value:c}),jsonExample:d}}case"enum":{let o=r.shape.values[0];return o==null?{type:"failure",message:"No enum values present"}:{type:"success",example:hy.enum({value:o.name}),jsonExample:o.name.wireValue}}case"object":{let o={},c=[];if((r.shape.extendedProperties==null||r.shape.extendedProperties.length===0)&&r.shape.extends!=null)for(let l of r.shape.extends){let p=t[l.typeId];if(p==null)continue;let _=Vbn({fieldName:e,typeDeclaration:p,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});_!=null&&_.type==="success"&&_.example.type==="object"&&(Object.assign(o,_.jsonExample),c.push(..._.example.properties))}let d=mVD({fieldName:e,typeDeclaration:r,objectTypeDeclaration:r.shape,typeDeclarations:t,currentDepth:n,maxDepth:i,skipOptionalProperties:a});if(d.type==="failure")return d;let{example:s,jsonExample:u}=d;return{type:"success",example:hy.object({properties:[...c,...s.properties],extraProperties:s.extraProperties}),jsonExample:Object.assign({},o,u)}}case"undiscriminatedUnion":{let o=r.shape.members;if(o.every(s=>OVD(s.type,t))){let s=o.findIndex(u=>{if(u.type.type==="container"&&u.type.container.type==="literal")return!0;if(u.type.type==="named"){let l=t[u.type.typeId];if(l!=null&&l.shape.type==="enum")return l.shape.values.length>0}return!1});if(s!==-1){let u=o[s];if(u!=null){let l=EA({fieldName:e,typeReference:u.type,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});if(l.type==="success"){let{example:p,jsonExample:_}=l;return{type:"success",example:hy.undiscriminatedUnion({index:s,singleUnionType:p}),jsonExample:_}}}}}let d=0;for(let s of o){let u=EA({fieldName:e,typeReference:s.type,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});if(u.type==="failure"){++d;continue}let{example:l,jsonExample:p}=u;return{type:"success",example:hy.undiscriminatedUnion({index:d,singleUnionType:l}),jsonExample:p}}break}case"union":{let o=r.shape.discriminant,c={};if(r.shape.baseProperties!=null)for(let u of r.shape.baseProperties){let l=EA({fieldName:u.name.wireValue,typeReference:u.valueType,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});l.type==="success"&&(c[u.name.wireValue]=l.jsonExample)}let d=r.shape.baseProperties.map(u=>{let l=EA({fieldName:u.name.wireValue,typeReference:u.valueType,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});if(l.type==="failure")throw new Error(`Failed to generate example for union base property ${u.name.wireValue}`);let{example:p}=l;return{name:u.name,value:p}}),s=r.shape.extends.flatMap(u=>{let l=t[u.typeId];if(l==null)throw new Error(`Failed to find extended type declaration with id ${u.typeId}`);let p=Vbn({fieldName:e,typeDeclaration:l,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});if(p==null||p.type==="failure")throw new Error(`Failed to generate example for extended type declaration ${l.name.typeId}`);if(p.example.type!=="object")throw new Error(`Extended type declaration ${l.name.typeId} is not an object`);return p.example.properties});for(let u of r.shape.types){let l=u.shape._visit({noProperties:()=>({type:"success",example:hy.union({discriminant:o,singleUnionType:{wireDiscriminantValue:u.discriminantValue,shape:_C.noProperties()},baseProperties:d,extendProperties:s}),jsonExample:{[o.wireValue]:u.discriminantValue.wireValue,...c}}),samePropertiesAsObject:p=>{let _=t[p.typeId];if(_==null)return{type:"failure",message:`Failed to find type declaration with id ${p.typeId}`};let h=Vbn({currentDepth:n,maxDepth:i,fieldName:e,typeDeclaration:_,typeDeclarations:t,skipOptionalProperties:a});if(h==null)return{type:"failure",message:"Failed to generate example for type reference"};if(h.type==="failure")return h;let{example:y,jsonExample:b}=h;return{type:"success",example:hy.union({discriminant:o,singleUnionType:{wireDiscriminantValue:u.discriminantValue,shape:_C.samePropertiesAsObject({typeId:_.name.typeId,object:y.type==="object"?y:{properties:[],extraProperties:void 0}})},baseProperties:d,extendProperties:s}),jsonExample:{[o.wireValue]:u.discriminantValue.wireValue,...typeof b=="object"?b:{},...c}}},singleProperty:p=>{let _=EA({currentDepth:n+1,maxDepth:i,fieldName:e,typeReference:p.type,typeDeclarations:t,skipOptionalProperties:a});if(_.type==="failure")return _;let{example:h,jsonExample:y}=_;return{type:"success",example:hy.union({discriminant:o,singleUnionType:{wireDiscriminantValue:u.discriminantValue,shape:_C.singleProperty(h)},baseProperties:d,extendProperties:s}),jsonExample:{[o.wireValue]:u.discriminantValue.wireValue,[p.name.wireValue]:y,...c}}},_other:()=>{throw new Error("Encountered unknown union type")}});if(l.type!=="failure")return l}}}return{type:"failure",message:"Failed to generate example for type reference"}}function mVD({fieldName:e,typeDeclaration:t,objectTypeDeclaration:r,typeDeclarations:i,maxDepth:n,currentDepth:a,skipOptionalProperties:o}){let c={},d=[];for(let s of[...r.properties??[],...r.extendedProperties??[]]){let u=EA({fieldName:s.name.wireValue,typeReference:s.valueType,typeDeclarations:i,currentDepth:a+1,maxDepth:n,skipOptionalProperties:o});if(u.type==="failure"&&!TYt({typeDeclarations:i,typeReference:s.valueType}))return{type:"failure",message:`Failed to generate required property ${s.name.wireValue} b/c ${u.message}`};if(u.type==="failure")continue;let{example:l,jsonExample:p}=u;d.push({name:s.name,originalTypeDeclaration:t.name,value:l,propertyAccess:s.propertyAccess}),c[s.name.wireValue]=p}return{type:"success",example:hy.object({properties:d,extraProperties:void 0}),jsonExample:c}}function EA({fieldName:e,typeReference:t,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){if(n>i)return{type:"failure",message:`Exceeded max depth of ${i}`};switch(t.type){case"named":{let o=r[t.typeId];if(o==null)return{type:"failure",message:`Failed to find type declaration with id ${t.typeId}`};let c=Vbn({fieldName:e,typeDeclaration:o,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(c==null)return{type:"failure",message:"Failed to generate example for type declaration"};if(c.type==="failure")return c;let{example:d,jsonExample:s}=c;return{type:"success",example:{jsonExample:s,shape:Tu.named({shape:d,typeName:o.name})},jsonExample:s}}case"container":{let o=Sph({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(o.type==="failure"){let{example:s,jsonExample:u}=RYt({containerType:t.container});return{type:"success",example:{jsonExample:u,shape:Tu.container(s)},jsonExample:u}}let{example:c,jsonExample:d}=o;return{type:"success",example:{jsonExample:d,shape:Tu.container(c)},jsonExample:d}}case"primitive":{let{jsonExample:o,example:c}=Dph({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:o,shape:Tu.primitive(c)},jsonExample:o}}case"unknown":{let o={key:"value"};return{type:"success",example:{jsonExample:o,shape:Tu.unknown(o)},jsonExample:o}}}}function Wbn(e,t){let r=[];for(let i of e){let n=EA({fieldName:i.name.originalName,currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,value:n.example})}return{type:"success",example:r,jsonExample:void 0}}function hoa(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&TYt({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=EA({fieldName:i.name.name.originalName,currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,value:n.example})}return{type:"success",example:r,jsonExample:void 0}}function ipu(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&TYt({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=EA({fieldName:i.name.name.originalName,currentDepth:0,maxDepth:t.maxDepth??10,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,shape:i.allowMultiple?TR.exploded():TR.single(),value:n.example})}return{type:"success",example:r,jsonExample:void 0}}var YGc=ii.primitive({v1:ku.String,v2:vn.string({default:void 0,validation:void 0})});function yoa({ir:e,endpoint:t,service:r,typeDeclarations:i,skipOptionalRequestProperties:n,generationResponse:a}){let o={name:void 0,endpointHeaders:[],endpointPathParameters:[],queryParameters:[],servicePathParameters:[],serviceHeaders:[],rootPathParameters:[],request:void 0,response:$j.ok(cw.body(void 0)),docs:void 0},c=Wbn(t.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(c.type==="failure")return c;o.endpointPathParameters=c.example;let d=Wbn(r.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(d.type==="failure")return d;o.servicePathParameters=d.example;let s=Wbn(e.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(s.type==="failure")return s;o.rootPathParameters=s.example;let u=ipu(t.queryParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:10});if(u.type==="failure")return u;o.queryParameters=u.example;let l=hoa(t.headers,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(l.type==="failure")return l;o.endpointHeaders=l.example;let p=hoa(r.headers,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(p.type==="failure")return p;if(o.serviceHeaders=p.example,t.requestBody!=null)switch(t.requestBody.type){case"bytes":return{type:"failure",message:"Bytes request unsupported"};case"fileUpload":return{type:"failure",message:"File upload unsupported"};case"inlinedRequestBody":{let _={},h=[];if(t.requestBody.extends!=null)for(let y of t.requestBody.extends){let b=i[y.typeId];if(b==null)throw new Error(`Failed to find extended type declaration with id ${y.typeId}`);let v=Vbn({typeDeclaration:b,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});v!=null&&v.type==="success"&&Object.assign(_,v.jsonExample)}for(let y of[...t.requestBody.properties??[],...t.requestBody.extendedProperties??[]]){let b=EA({fieldName:y.name.wireValue,typeReference:y.valueType,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});if(b.type==="failure"&&!TYt({typeDeclarations:i,typeReference:y.valueType}))return{type:"failure",message:`Failed to generate required property ${y.name.wireValue} b/c ${b.message}`};if(b.type==="failure")continue;let{example:v,jsonExample:g}=b;h.push({name:y.name,originalTypeDeclaration:void 0,value:v}),_[y.name.wireValue]=g}o.request=vW.inlinedRequestBody({jsonExample:_,properties:h,extraProperties:void 0});break}case"reference":{let _=EA({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:n});if(_.type==="failure")return _;let{example:h}=_;o.request=vW.reference(h);break}default:vt(t.requestBody)}if(a.type==="success"&&t.response?.body!=null)switch(t.response.body.type){case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":{let _=EA({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.responseBodyType,skipOptionalProperties:!1});if(_.type==="failure")return _;let{example:h,jsonExample:y}=_;o.response=$j.ok(cw.body({...h,jsonExample:y}));break}case"streamParameter":{let _;switch(t.response.body.nonStreamResponse.type){case"bytes":return{type:"failure",message:"Bytes unsupported"};case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":_=EA({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.nonStreamResponse.value.responseBodyType,skipOptionalProperties:!1});break;case"text":_=EA({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:YGc,skipOptionalProperties:!1});break;default:vt(t.response.body.nonStreamResponse)}if(_.type==="failure")return _;let{example:h,jsonExample:y}=_;o.response=$j.ok(cw.body({...h,jsonExample:y}));break}case"streaming":{let _;switch(t.response.body.value.type){case"sse":{if(_=EA({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),_.type==="failure")return _;let{example:h,jsonExample:y}=_;o.response=$j.ok(cw.sse([{data:{...h,jsonExample:y},event:""}]));break}case"json":{if(_=EA({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),_.type==="failure")return _;let{example:h,jsonExample:y}=_;o.response=$j.ok(cw.stream([{...h,jsonExample:y}]));break}case"text":{if(_=EA({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:YGc,skipOptionalProperties:!1}),_.type==="failure")return _;let{example:h,jsonExample:y}=_;o.response=$j.ok(cw.stream([{...h,jsonExample:y}]));break}default:vt(t.response.body.value)}break}case"text":{let _=EA({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:YGc,skipOptionalProperties:!1});if(_.type==="failure")return _;let{example:h,jsonExample:y}=_;o.response=$j.ok(cw.body({...h,jsonExample:y}));break}case"bytes":return{type:"failure",message:"Bytes unsupported"};default:vt(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)o.response=$j.error({body:void 0,error:a.declaration.name});else{let _=EA({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:a.declaration.type,skipOptionalProperties:n});if(_.type==="failure")return _;let{example:h}=_;o.response=$j.error({body:h,error:a.declaration.name})}try{return{type:"success",example:{id:wJi(o),url:AVD(t,o),...o},jsonExample:void 0}}catch(_){return{type:"failure",message:`Parse failure with exceptions ${_}`}}}function AVD(e,t){let r={};[...t.rootPathParameters,...t.servicePathParameters,...t.endpointPathParameters].forEach(n=>{let a=n.value.jsonExample,o=typeof a=="string"?a:JSON.stringify(a);r[n.name.originalName]=o});let i=e.fullPath.head+e.fullPath.parts.map(n=>encodeURIComponent(`${r[n.pathParameter]}`)+n.tail).join("");return i.startsWith("/")||i===""?i:`/${i}`}function XGc({ir:e,channel:t,typeDeclarations:r,skipOptionalRequestProperties:i}){let n={name:void 0,pathParameters:[],headers:[],queryParameters:[],messages:[],docs:void 0},a=Wbn(t.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(a.type==="failure")return a;n.pathParameters.push(...a.example);let o=Wbn(e.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(o.type==="failure")return o;n.pathParameters.push(...o.example);let c=ipu(t.queryParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:10});if(c.type==="failure")return c;n.queryParameters=c.example;let d=hoa(t.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(d.type==="failure")return d;n.headers.push(...d.example);let s=hoa(e.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(s.type==="failure")return s;n.headers.push(...s.example);let l=t.messages.filter(h=>h.origin==="client")[0];if(l!=null){let h=Bph({message:l,typeDeclarations:r,skipOptionalRequestProperties:i});h!=null&&n.messages.push({type:l.type,body:h})}let _=t.messages.filter(h=>h.origin==="server")[0];if(_!=null){let h=Bph({message:_,typeDeclarations:r,skipOptionalRequestProperties:i});h!=null&&n.messages.push({type:_.type,body:h})}return{type:"success",example:{...n,url:PVD(t,n)},jsonExample:void 0}}function Bph({message:e,typeDeclarations:t,skipOptionalRequestProperties:r}){if(e.body.type==="inlinedBody")return;let i=EA({currentDepth:0,maxDepth:10,typeDeclarations:t,typeReference:e.body.bodyType,skipOptionalProperties:r});if(i.type==="success")return Xve.reference(i.example)}function PVD(e,t){let r={};[...t.pathParameters].forEach(n=>{let a=n.value.jsonExample,o=typeof a=="string"?a:JSON.stringify(a);r[n.name.originalName]=o});let i=e.path.head+e.path.parts.map(n=>encodeURIComponent(`${r[n.pathParameter]}`)+n.tail).join("");return i.startsWith("/")||i===""?i:`/${i}`}function boa(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{},i=Object.values(t)[0],n=Object.values(r)[0];return{userExample:i,autoExample:n}}function EJi(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{};return{userExamples:t,autoExamples:r}}function Iph({ir:e,endpoint:t,skipOptionalRequestProperties:r}){let i=e.types,n={pathParameters:{},queryParameters:{},headers:{}};for(let o of t.pathParameters){let{userExample:c,autoExample:d}=boa(o.v2Examples);c!==void 0?n.pathParameters[o.name.originalName]=c:d!==void 0&&(n.pathParameters[o.name.originalName]=d)}for(let o of t.queryParameters){let{userExample:c,autoExample:d}=boa(o.v2Examples);if(c!==void 0)n.queryParameters[o.name.name.originalName]=c;else if(d!==void 0){if(r&&TYt({typeReference:o.valueType,typeDeclarations:i}))continue;n.queryParameters[o.name.name.originalName]=d}}let a=[...t.headers,...e.headers,...e.idempotencyHeaders];for(let o of a){let{userExample:c,autoExample:d}=boa(o.v2Examples);if(c!==void 0)n.headers[o.name.wireValue]=c;else if(d!==void 0){if(r&&TYt({typeReference:o.valueType,typeDeclarations:i}))continue;n.headers[o.name.wireValue]=d}}return n}function Cph({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let{pathParameters:i,queryParameters:n,headers:a}=Iph({endpoint:e,ir:t,skipOptionalRequestProperties:r}),o={},c={},d={endpoint:{method:e.method,path:jVD(e)},baseUrl:void 0,environment:e.baseUrl,auth:void 0,pathParameters:i,queryParameters:n,headers:a,requestBody:void 0,docs:void 0};if(e.requestBody!=null)switch(e.requestBody.type){case"bytes":break;case"fileUpload":{let{userExamples:s,autoExamples:u}=EJi(e.requestBody.v2Examples);for(let[l,p]of Object.entries(s))o[l]={...d,requestBody:p};for(let[l,p]of Object.entries(u))c[l]={...d,requestBody:p};break}case"inlinedRequestBody":{let{userExamples:s,autoExamples:u}=EJi(e.requestBody.v2Examples);for(let[l,p]of Object.entries(s))o[l]={...d,requestBody:p};for(let[l,p]of Object.entries(u))c[l]={...d,requestBody:p};break}case"reference":{let{userExamples:s,autoExamples:u}=EJi(e.requestBody.v2Examples);for(let[l,p]of Object.entries(s))o[l]={...d,requestBody:p};for(let[l,p]of Object.entries(u))c[l]={...d,requestBody:p};break}default:vt(e.requestBody)}return{userRequestExamples:o,autoRequestExamples:c,baseExample:d}}function jVD(e){let t={};[...e.pathParameters,...e.allPathParameters].forEach(i=>{let{userExample:n,autoExample:a}=boa(i.v2Examples),o=n??a,c;o==null?c=i.name.originalName:c=typeof o=="string"?o:JSON.stringify(o),t[i.name.originalName]=c});let r=e.fullPath.head+e.fullPath.parts.map(i=>encodeURIComponent(`${t[i.pathParameter]}`)+i.tail).join("");return r.startsWith("/")||r===""?r:`/${r}`}function npu({endpoint:e,responseObject:t}){let r=t!==void 0?t:e.response,i={},n={},a={statusCode:r?.statusCode,body:void 0,docs:void 0};if(r==null)return{userResponseExamples:{},autoResponseExamples:{},baseExample:a};if(r.body==null)return e.source?.type==="openrpc"?{userResponseExamples:{},autoResponseExamples:{},baseExample:{...a,body:S1.json(K7a(null))}}:{userResponseExamples:{},autoResponseExamples:{},baseExample:a};switch(r.body.type){case"bytes":break;case"fileDownload":break;case"text":{let o=r.body,{userExamples:c,autoExamples:d}=EJi(o.v2Examples);for(let[s,u]of Object.entries(c)){let l=e.source?.type==="openrpc"?K7a(u):u;i[s]={...a,body:S1.json(l)}}for(let[s,u]of Object.entries(d)){let l=e.source?.type==="openrpc"?K7a(u):u;n[s]={...a,body:S1.json(l)}}break}case"json":{let o=r.body.value;if(o.type==="response"){let{userExamples:c,autoExamples:d}=EJi(o.v2Examples);for(let[s,u]of Object.entries(c)){let l=e.source?.type==="openrpc"?K7a(u):u;i[s]={...a,body:S1.json(l)}}for(let[s,u]of Object.entries(d)){let l=e.source?.type==="openrpc"?K7a(u):u;n[s]={...a,body:S1.json(l)}}}break}case"streaming":{let o=r.body.value;if(o.type==="json"){let{userExamples:c,autoExamples:d}=EJi(o.v2Examples);for(let[s,u]of Object.entries(c))i[s]={...a,body:S1.stream([u])};for(let[s,u]of Object.entries(d))n[s]={...a,body:S1.stream([u])}}break}case"streamParameter":break;default:vt(r.body)}return{userResponseExamples:i,autoResponseExamples:n,baseExample:a}}function K7a(e,t=1){return{id:t,jsonrpc:"2.0",result:e}}var voa=(e,t,r)=>{let i;return e===t?i=`${e}`:i=`${e}_${t}`,r&&(i=`${i}_${r}`),i},wVD=({exampleStore:e,key:t,example:r})=>e.has(t)?!1:(e.set(t,r),!0);function apu({key:e,displayName:t,request:r,response:i,exampleStore:n,userOrAutoStore:a}){if(!n.has(e)){let o={displayName:t,request:r,response:i,codeSamples:void 0};return a[e]=o,wVD({exampleStore:n,key:e,example:o}),!0}return!1}function qph({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let i={},n={},a=new Map,{userRequestExamples:o,autoRequestExamples:c,baseExample:d}=Cph({endpoint:e,ir:t,skipOptionalRequestProperties:r}),s=Object.keys(o)[0],u=Object.values(o)[0],l=Object.keys(c)[0],p=Object.values(c)[0],_=EVD({endpoint:e,userRequestExamples:o,baseRequestExample:d,firstUserRequestName:s,firstUserRequestExample:u,firstAutoRequestName:l,firstAutoRequestExample:p,userResults:i,autoResults:n,exampleStore:a});if(SVD({endpoint:e,userRequestExamples:o,requestExamplesUsed:_,userResults:i,exampleStore:a}),Object.keys(i).length===0&&Object.keys(n).length===0){let{baseExample:h}=npu({endpoint:e}),y=voa(l??"base","base",void 0);apu({key:y,displayName:l??"base",request:p??d,response:h,exampleStore:a,userOrAutoStore:n})}return{userFullExamples:i,autoFullExamples:n}}function EVD({endpoint:e,userRequestExamples:t,baseRequestExample:r,firstUserRequestName:i,firstUserRequestExample:n,firstAutoRequestName:a,firstAutoRequestExample:o,userResults:c,autoResults:d,exampleStore:s}){let u=e.v2Responses?.responses??[e.response],l=new Set;for(let p of u){let _=!1,{userResponseExamples:h,autoResponseExamples:y,baseExample:b}=npu({endpoint:e,responseObject:p}),v=Object.keys(y)[0],g=Object.values(y)[0];for(let[m,O]of Object.entries(h)){let A,j;t[m]?(j=t[m],l.add(m),A=voa(m,m,p?.statusCode)):o&&a?(j=o,A=voa(a,m,p?.statusCode)):(j=r,A=voa("base",m,p?.statusCode)),apu({key:A,displayName:m,request:j,response:O,exampleStore:s,userOrAutoStore:c})&&(_=!0)}if(!_){let m=ou(`${e.name.originalName}_example`);i&&n&&l.add(i);let O=voa(i??a??"base",v??"base",p?.statusCode);apu({key:O,displayName:i??a??m,request:n??o??r,response:g??b,exampleStore:s,userOrAutoStore:d})&&(_=!0)}}return l}function SVD({endpoint:e,userRequestExamples:t,requestExamplesUsed:r,userResults:i,exampleStore:n}){let{userResponseExamples:a,autoResponseExamples:o,baseExample:c}=npu({endpoint:e}),d=Object.values(a)[0],s=Object.keys(a)[0],u=Object.keys(o)[0],l=Object.values(o)[0],p=Object.entries(t).filter(([_])=>!r.has(_));for(let[_,h]of p){let y=voa(_,s??u??"base",d?d.statusCode:l?l.statusCode:c.statusCode);apu({key:y,displayName:_,request:h,response:d??l??c,exampleStore:n,userOrAutoStore:i})}}function J7a({ir:e,exampleGeneration:t}){let r={disabled:t.disabled,includeOptionalRequestPropertyExamples:t.includeOptionalRequestPropertyExamples??!1,skipAutogenerationIfManualExamplesExist:t.skipAutogenerationIfManualExamplesExist??!1,skipErrorAutogenerationIfManualErrorExamplesExist:t.skipErrorAutogenerationIfManualErrorExamplesExist??!1};for(let[i,n]of Object.entries(e.services))for(let a of n.endpoints){let o=[];if(a.userSpecifiedExamples.length===0||r.skipAutogenerationIfManualExamplesExist===!1){let c=yoa({ir:e,service:n,endpoint:a,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples,generationResponse:{type:"success"}});c.type==="success"&&o.push({example:c.example})}if(a.userSpecifiedExamples.filter(c=>c.example?.response.type==="error").length===0||r.skipErrorAutogenerationIfManualErrorExamplesExist===!1)for(let c of a.errors){let d=e.errors[c.error.errorId];if(!d)continue;let s=yoa({ir:e,service:n,endpoint:a,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples,generationResponse:{type:"error",declaration:d}});s.type==="success"&&o.push({example:s.example})}a.autogeneratedExamples=o}for(let[i,n]of Object.entries(e.websocketChannels??{})){if(n.examples.length>0&&r.skipAutogenerationIfManualExamplesExist===!0)continue;let a=XGc({ir:e,channel:n,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples});if(a.type==="failure")continue;let{example:o}=a;n.examples=[...n.examples,o]}return e}function ZGc({ir:e,exampleGeneration:t}){let r={disabled:t.disabled,includeOptionalRequestPropertyExamples:t.includeOptionalRequestPropertyExamples??!1,skipAutogenerationIfManualExamplesExist:t.skipAutogenerationIfManualExamplesExist??!1,skipErrorAutogenerationIfManualErrorExamplesExist:t.skipErrorAutogenerationIfManualErrorExamplesExist??!1};for(let[i,n]of Object.entries(e.services))for(let a of n.endpoints){a.v2Examples==null&&(a.v2Examples={userSpecifiedExamples:{},autogeneratedExamples:{}});let{userFullExamples:o,autoFullExamples:c}=qph({endpoint:a,ir:e,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples});if(Object.keys(a.v2Examples.userSpecifiedExamples).length>0){if(Object.values(a.v2Examples.userSpecifiedExamples).some(s=>s.request!=null||s.response!=null))continue;let d=Object.values(a.v2Examples.userSpecifiedExamples).filter(s=>s!=null).flatMap(s=>s.codeSamples??[]);for(let[s,u]of Object.entries(c))c[s]={...u,codeSamples:d};for(let[s,u]of Object.entries(o))o[s]={...u,codeSamples:d}}a.v2Examples.autogeneratedExamples=c,a.v2Examples.userSpecifiedExamples=o}for(let[i,n]of Object.entries(e.websocketChannels??{})){if(n.examples.length>0&&r.skipAutogenerationIfManualExamplesExist===!0)continue;let a=XGc({ir:e,channel:n,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples});if(a.type==="failure")continue;let{example:o}=a;n.examples=[...n.examples,o]}return e}function Rph({filteredIr:e,singleUnionTypeProperties:t}){return t._visit({samePropertiesAsObject:r=>{let i=e.hasTypeId(r.typeId)?{...r,object:{...r.object,properties:r.object.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:SD({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)}}:void 0;return i!==void 0?_C.samePropertiesAsObject(i):void 0},singleProperty:r=>{let i=SD({filteredIr:e,exampleTypeReference:r});return i!==void 0?_C.singleProperty(i):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function SD({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:i=>({...t,shape:Tu.container(Up.list({...i,list:i.list.map(n=>SD({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),set:i=>({...t,shape:Tu.container(Up.set({...i,set:i.set.map(n=>SD({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),optional:i=>{let n=i.optional!=null?SD({filteredIr:e,exampleTypeReference:i.optional}):void 0;return n!=null?{...t,shape:Tu.container(Up.optional({optional:n,valueType:i.valueType}))}:void 0},nullable:i=>{let n=i.nullable!=null?SD({filteredIr:e,exampleTypeReference:i.nullable}):void 0;return n!=null?{...t,shape:Tu.container(Up.nullable({nullable:n,valueType:i.valueType}))}:void 0},map:i=>({...t,shape:Tu.container(Up.map({...i,map:i.map.map(n=>{let a=SD({filteredIr:e,exampleTypeReference:n.key}),o=SD({filteredIr:e,exampleTypeReference:n.value});return a!==void 0&&o!==void 0?{key:a,value:o}:void 0}).filter(n=>n!==void 0)}))}),literal:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}}),named:r=>e.hasTypeId(r.typeName.typeId)?r.shape._visit({alias:i=>{let n=SD({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...t,shape:Tu.named({...r,shape:hy.alias({...i,value:n})})}:void 0},enum:i=>({...t,shape:Tu.named({...r,shape:hy.enum(i)})}),object:i=>({...t,shape:Tu.named({...r,shape:hy.object({...i,properties:i.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:SD({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})})}),union:i=>{let n=Rph({filteredIr:e,singleUnionTypeProperties:i.singleUnionType.shape});return n!==void 0?{...t,shape:Tu.named({...r,shape:hy.union({...i,singleUnionType:{...i.singleUnionType,shape:n}})})}:void 0},undiscriminatedUnion:i=>{let n=SD({filteredIr:e,exampleTypeReference:i.singleUnionType});return n!==void 0?{...t,shape:Tu.named({...r,shape:hy.undiscriminatedUnion({...i,singleUnionType:n})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function kGc({filteredIr:e,pathParameters:t}){return t.map(r=>{let i=SD({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function MVD({filteredIr:e,queryParameters:t}){return t.map(r=>{let i=SD({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function Tph({filteredIr:e,headers:t}){return t.map(r=>{let i=SD({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function DVD({filteredIr:e,requestBody:t}){return t._visit({inlinedRequestBody:r=>({...t,properties:r.properties.filter(i=>i.originalTypeDeclaration?e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue):!0).map(i=>{let n=SD({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...i,value:n}:void 0}).filter(i=>i!==void 0)}),reference:r=>{let i=SD({filteredIr:e,exampleTypeReference:r});return i!==void 0?vW.reference(i):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function BVD({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:i=>$j.ok(cw.body(i!=null?SD({filteredIr:e,exampleTypeReference:i}):void 0)),stream:i=>$j.ok(cw.stream(i.map(n=>SD({filteredIr:e,exampleTypeReference:n})).filter(us))),sse:i=>$j.ok(cw.sse(i.map(({event:n,data:a})=>{let o=SD({filteredIr:e,exampleTypeReference:a});return o!==void 0?{event:n,data:o}:void 0}).filter(us))),_other:({type:i})=>{throw new Error(`Received unknown type for OK example: ${i}`)}}),error:({error:r,body:i})=>$j.error({error:r,body:i!=null?SD({filteredIr:e,exampleTypeReference:i}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function exc({filteredIr:e,example:t}){return{...t,rootPathParameters:kGc({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:kGc({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:kGc({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:Tph({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:Tph({filteredIr:e,headers:t.endpointHeaders}),queryParameters:MVD({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?DVD({filteredIr:e,requestBody:t.request}):void 0,response:BVD({filteredIr:e,response:t.response})}}function zph({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let i=SD({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...t,shape:hy.alias({...r,value:i})}:void 0},enum:()=>t,object:r=>({...t,shape:hy.object({...r,properties:r.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:SD({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})}),union:r=>{let i=Rph({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return i!==void 0?{...t,shape:hy.union({...r,singleUnionType:{...r.singleUnionType,shape:i}})}:void 0},undiscriminatedUnion:r=>{let i=SD({filteredIr:e,exampleTypeReference:r.singleUnionType});return i!==void 0?{...t,shape:hy.undiscriminatedUnion({...r,singleUnionType:i})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function txc(e,t){if(t==null)return e;let r=Bfn(e.types,c=>t.hasType(c)),i=Object.fromEntries(Object.entries(r).map(([c,d])=>{let s=[];if(d.userProvidedExamples=d.userProvidedExamples.map(u=>zph({filteredIr:t,exampleType:u})).filter(u=>u!==void 0),d.shape.type==="object"){for(let u of d.shape.properties)t.hasProperty(c,u.name.wireValue)&&s.push(u);return[c,{...d,shape:Al.object({...d.shape,properties:s})}]}return[c,d]})),n=Object.fromEntries(Object.entries(e.webhookGroups).map(([c,d])=>{let s=d.filter(u=>t.hasWebhook(u)).map(u=>{let l=u.id;return u.payload.type==="inlinedPayload"&&l!=null&&(u.payload={...u.payload,properties:u.payload.properties.filter(p=>t.hasWebhookPayloadProperty(l,p.name.wireValue))}),u});return[c,s]})),a=e.websocketChannels!=null?Object.fromEntries(Object.entries(e.websocketChannels).filter(([c])=>t.hasChannel(c)).map(([c,d])=>[c,{...d}])):{},o=e.environments;if(o){switch(o.environments.type){case"singleBaseUrl":{o.environments.environments=o.environments.environments.filter(c=>t.hasEnvironmentId(c.id));break}case"multipleBaseUrls":{o.environments.environments=o.environments.environments.filter(c=>t.hasEnvironmentId(c.id));break}}o.defaultEnvironment&&(t.hasEnvironmentId(o.defaultEnvironment)||(o.defaultEnvironment=void 0))}return{...e,environments:o,types:i,errors:Bfn(e.errors,c=>t.hasError(c)),services:nn(Bfn(e.services,c=>t.hasService(c)),c=>({...c,endpoints:c.endpoints.filter(d=>t.hasEndpoint(d)).map(d=>(d.autogeneratedExamples=d.autogeneratedExamples.map(s=>({...s,example:exc({filteredIr:t,example:s.example})})),d.userSpecifiedExamples=d.userSpecifiedExamples.map(s=>({...s,example:s.example!=null?exc({filteredIr:t,example:s.example}):void 0})),d.queryParameters.length>0&&(d.queryParameters=d.queryParameters.filter(s=>t.hasQueryParameter(d.id,s.name.wireValue))),d.requestBody?.type==="inlinedRequestBody"?{...d,requestBody:{...d.requestBody,properties:d.requestBody.properties.filter(s=>t.hasRequestProperty(d.id,s.name.wireValue))}}:d))})),websocketChannels:a,webhookGroups:n,serviceTypeReferenceInfo:IVD(e.serviceTypeReferenceInfo,t)}}function IVD(e,t){if(t==null)return e;let r={};return Object.entries(e.typesReferencedOnlyByService).forEach(([i,n])=>{t.hasServiceId(i)&&(r[i]=n.filter(a=>t.hasTypeId(a)))}),{sharedTypes:e.sharedTypes.filter(i=>t.hasTypeId(i)),typesReferencedOnlyByService:r}}function Gbn(e){let t={};for(let[r,i]of Object.entries(e))if(typeof i!="string")for(let n of i.audiences??[])t[n]==null&&(t[n]=new Set),t[n]?.add(r);return t}function ege(e){return e.allParts.map(t=>t.originalName).join("/")}var Lp={generateTypeId:e=>`type_${ege(e.fernFilepath)}:${e.name.originalName}`,generateErrorId:e=>`error_${ege(e.fernFilepath)}:${e.name.originalName}`,generateServiceId:e=>`service_${ege(e.fernFilepath)}`,generateServiceIdFromFernFilepath:e=>`service_${ege(e)}`,generateSubpackageId:e=>`subpackage_${ege(e)}`,generateEndpointId:(e,t)=>{let r=ege(e.fernFilepath),i=t.name.originalName;return`endpoint_${r}.${i}`},generateWebhookGroupId:e=>`webhooks_${ege(e)}`,generateWebhookId:(e,t)=>`webhooks_${ege(e)}.${t}`,generateWebSocketChannelId:e=>`channel_${ege(e)}`};function goa(e){return e.type!=null}var opu=class{environments=new Set;types=new Set;properties;errors=new Set;services=new Set;endpoints=new Set;requestProperties;queryParameters;webhooks=new Set;webhookPayloadProperties;channels=new Set;subpackages=new Set;constructor({types:t,properties:r,errors:i,environments:n,services:a,endpoints:o,webhooks:c,subpackages:d,queryParameters:s,requestProperties:u,webhookPayloadProperties:l,channels:p}){this.environments=n,this.types=t,this.properties=r,this.errors=i,this.services=a,this.endpoints=o,this.webhooks=c,this.webhookPayloadProperties=l,this.subpackages=d,this.requestProperties=u,this.queryParameters=s,this.channels=p}hasTypeId(t){return this.types.has(t)}hasErrorId(t){return this.errors.has(t)}hasServiceId(t){return this.services.has(t)}hasSubpackageId(t){return this.subpackages.has(t)}hasType(t){let r=Lp.generateTypeId(t.name);return this.types.has(r)}hasProperty(t,r){let i=this.properties[t];return i==null?!0:i.has(r)}hasError(t){let r=Lp.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=Lp.generateServiceId(t.name);return this.services.has(r)}hasEnvironmentId(t){return this.environments.has(t)}hasEndpoint(t){return this.endpoints.has(t.id)}hasRequestProperty(t,r){let i=this.requestProperties[t];return i==null?!0:i.has(r)}hasQueryParameter(t,r){let i=this.queryParameters[t];return i==null?!0:i.has(r)}hasSubpackage(t){return this.subpackages.has(t)}hasWebhook(t){return t.id?this.webhooks.has(t.id):!0}hasChannel(t){return t?this.channels.has(t):!0}hasWebhookPayloadProperty(t,r){let i=this.webhookPayloadProperties[t];return i==null?!0:i.has(r)}};var xbn=class{types={};properties={};queryParameters={};requestProperties={};webhookProperties={};errors={};endpoints={};webhooks={};channels={};audiences;typesReferencedByService={};environmentsNeededForAudience=new Set;typesNeededForAudience=new Set;servicesNeededForAudience=new Set;endpointsNeededForAudience=new Set;webhooksNeededForAudience=new Set;channelsNeededForAudience=new Set;subpackagesNeededForAudience=new Set;constructor(t){this.audiences=CVD(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:i,descendantTypeIdsByAudience:n,propertiesByAudience:a}){let o=Lp.generateTypeId(t),c={typeId:o,allDescendants:r,descendantsByAudience:n,referencedSubpackages:i};this.types[o]=c,this.typesReferencedByService[o]==null&&(this.typesReferencedByService[o]=new Set),this.properties[o]={typeId:o,propertiesByAudience:a}}markTypeForAudiences(t,r){let i=Lp.generateTypeId(t);this.hasAudience(r)&&(this.typesNeededForAudience.add(i),this.addSubpackages(t.fernFilepath),this.types[i]?.referencedSubpackages.forEach(n=>{this.addSubpackages(n)}))}markEnvironmentForAudiences(t,r,i){t&&(this.hasAudience(r)||i)&&this.environmentsNeededForAudience.add(t.id)}getTypesReferencedByService(){for(let t of Object.values(this.endpoints))for(let r of t.referencedTypes)this.markTypeForService(r,t.serviceId);return this.typesReferencedByService}addError(t){let r=Lp.generateErrorId(t.name),i=new Set,n=new Set;t.type!=null&&BM(t.type,i,n);let a={errorId:r,referencedTypes:i,referencedSubpackages:n};this.errors[r]=a}addEndpoint(t,r,i){let n=Lp.generateServiceId(t.name),a=r.id,o=new Set,c=new Set,d=new Set;for(let s of[...t.headers,...r.headers])BM(s.valueType,o,d);for(let s of[...t.pathParameters,...r.pathParameters])BM(s.valueType,o,d);for(let s of r.queryParameters)BM(s.valueType,o,d);if(i!=null&&i.request!=null&&typeof i.request!="string"){let s=Gbn(i.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:s}}r.requestBody!=null&&Nm._visit(r.requestBody,{inlinedRequestBody:s=>{for(let u of s.extends)upu(u,o,d);for(let u of s.properties)BM(u.valueType,o,d);if(i!=null&&typeof i.request=="object"&&typeof i.request.body=="object"&&fw(i.request.body)){let u=Gbn(i.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:u}}},reference:({requestBodyType:s})=>{BM(s,o,d)},fileUpload:({properties:s})=>{for(let u of s)M1._visit(u,{file:It,bodyProperty:({valueType:l})=>{BM(l,o,d)},_other:()=>{throw new Error("Unknown FileUploadRequestProperty: "+u.type)}})},bytes:()=>{},_other:()=>{throw new Error("Unknown HttpRequestBody: "+r.requestBody?.type)}}),r.response?.body!=null&&Ed._visit(r.response.body,{fileDownload:It,json:s=>{BM(s.responseBodyType,o,d)},streaming:s=>{s._visit({sse:u=>BM(u.payload,o,d),json:u=>BM(u.payload,o,d),text:It,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.type)}})},streamParameter:s=>{s.streamResponse._visit({sse:u=>BM(u.payload,o,d),json:u=>BM(u.payload,o,d),text:It,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.streamResponse.type)}}),s.nonStreamResponse.type==="json"&&BM(s.nonStreamResponse.value.responseBodyType,o,d)},text:It,bytes:It,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(s=>{c.add(Lp.generateErrorId(s.error)),d.add(s.error.fernFilepath)}),this.endpoints[a]={endpointId:a,serviceId:n,referencedTypes:o,referencedErrors:c,referencedSubpackages:d}}markEndpointForAudience(t,r,i){if(this.hasAudience(i)){let n=Lp.generateServiceId(t);this.servicesNeededForAudience.add(n),r.forEach(a=>{let o=a.id;this.endpointsNeededForAudience.add(o),this.endpoints[o]?.referencedSubpackages.forEach(c=>{this.addSubpackages(c)})}),this.servicesNeededForAudience.add(n),this.addSubpackages(t.fernFilepath)}}getFilteredSubpackages(){return this.subpackagesNeededForAudience}getFilteredServices(){return this.servicesNeededForAudience}getFilteredEndpoints(){return this.endpointsNeededForAudience}getFilteredChannels(){return this.channelsNeededForAudience}getFilteredWebhooks(){return this.webhooksNeededForAudience}addWebhook(t,r,i){let n=r.id;if(n==null)return;let a=new Set,o=new Set;r.payload!=null&&fF._visit(r.payload,{inlinedPayload:c=>{for(let d of c.extends)upu(d,a,o);for(let d of c.properties)BM(d.valueType,a,o);if(i?.payload!=null&&typeof i.payload=="object"&&!goa(i.payload)){let d=Gbn(i.payload.properties??{});this.webhookProperties[n]={webhookId:n,propertiesByAudience:d}}},reference:({payloadType:c})=>{BM(c,a,o)},_other:()=>{throw new Error("Unknown WebhookPayload: "+r.payload?.type)}}),o.add(t),this.webhooks[n]={webhookId:n,referencedTypes:a,referencedSubpackages:o}}markWebhookForAudiences(t,r,i){let n=r.id;n!=null&&this.hasAudience(i)&&(this.webhooksNeededForAudience.add(n),this.addSubpackages(t))}addChannel(t,r,i,n){if(r==null)return;let a=new Set,o=new Set;for(let c of i.messages)pL._visit(c.body,{reference:({bodyType:d})=>{BM(d,a,o)},inlinedBody:d=>{for(let s of d.extends)upu(s,a,o);for(let s of d.properties)BM(s.valueType,a,o)},_other:()=>{}});for(let c of i.queryParameters)BM(c.valueType,a,o);o.add(t),this.channels[r]={channelId:r,referencedTypes:a,referencedSubpackages:o}}markChannelForAudiences(t,r,i){r!=null&&this.hasAudience(i)&&(this.channelsNeededForAudience.add(r),this.addSubpackages(t))}build(){let t=new Set,r=new Set;for(let c of this.endpointsNeededForAudience.keys()){let d=this.getEndpointNode(c);for(let s of d.referencedErrors){if(r.has(s))continue;r.add(s);let u=this.getErrorNode(s);this.addReferencedTypes(t,u.referencedTypes)}this.addReferencedTypes(t,d.referencedTypes)}this.addReferencedTypes(t,this.typesNeededForAudience);for(let c of this.webhooksNeededForAudience.keys()){let d=this.getWebhookNode(c);this.addReferencedTypes(t,d.referencedTypes)}for(let c of this.channelsNeededForAudience.keys()){let d=this.getChannelNode(c);this.addReferencedTypes(t,d.referencedTypes)}let i={},n={},a={},o={};if(this.audiences.type==="filtered"){for(let[c,d]of Object.entries(this.properties)){if(!t.has(c))continue;let s=new Set;for(let u of this.audiences.audiences){let l=d.propertiesByAudience[u];l?.forEach(p=>{s.add(p)})}s.size>0&&(i[c]=s),i[c]=s.size>0?s:void 0}for(let[c,d]of Object.entries(this.requestProperties)){if(!this.endpointsNeededForAudience.has(c))continue;let s=new Set;for(let u of this.audiences.audiences){let l=d.propertiesByAudience[u];l?.forEach(p=>{s.add(p)})}n[c]=s.size>0?s:void 0}for(let[c,d]of Object.entries(this.queryParameters)){if(!this.endpointsNeededForAudience.has(c))continue;let s=new Set;for(let u of this.audiences.audiences){let l=d.parametersByAudience[u];l?.forEach(p=>{s.add(p)})}a[c]=s.size>0?s:void 0}for(let[c,d]of Object.entries(this.webhookProperties)){if(!this.webhooksNeededForAudience.has(c))continue;let s=new Set;for(let u of this.audiences.audiences){let l=d.propertiesByAudience[u];l?.forEach(p=>{s.add(p)})}o[c]=s.size>0?s:void 0}}return new opu({types:t,properties:i,errors:r,requestProperties:n,queryParameters:a,environments:this.environmentsNeededForAudience,services:this.servicesNeededForAudience,endpoints:this.endpointsNeededForAudience,webhooks:this.webhooksNeededForAudience,webhookPayloadProperties:o,subpackages:this.subpackagesNeededForAudience,channels:this.channelsNeededForAudience})}markTypeForService(t,r){let i=this.typesReferencedByService[t]??=new Set;if(i.has(r))return;i.add(r);let n=this.getTypeNode(t);for(let a of n.allDescendants)this.markTypeForService(a,r)}addReferencedTypes(t,r){for(let i of r){if(t.has(i))continue;t.add(i);let n=this.getTypeNode(i);if(this.audiences.type==="filtered")for(let a of this.audiences.audiences){let o=n.descendantsByAudience[a];if(o!=null)o.forEach(c=>{t.add(c)});else{n.allDescendants.forEach(c=>{t.add(c)});break}}else n.allDescendants.forEach(a=>{t.add(a)})}}getTypeNode(t){let r=this.types[t];if(r==null)throw new Error(`Failed to find type node with id ${t}`);return r}getErrorNode(t){let r=this.errors[t];if(r==null)throw new Error(`Failed to find error node with id ${t}`);return r}getEndpointNode(t){let r=this.endpoints[t];if(r==null)throw new Error(`Failed to find endpoint node with id ${t}`);return r}getWebhookNode(t){let r=this.webhooks[t];if(r==null)throw new Error(`Failed to find webhook node with id ${t}`);return r}getChannelNode(t){let r=this.channels[t];if(r==null)throw new Error(`Failed to find channel node with id ${t}`);return r}hasNoAudiences(){return this.audiences.type==="none"}hasAudience(t){let r=this.audiences;switch(r.type){case"none":return!0;case"filtered":return t.some(i=>r.audiences.has(i));default:vt(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let i={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(Lp.generateSubpackageId(i))}}};function CVD(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:vt(e)}}function BM(e,t,r){ii._visit(e,{container:i=>{qVD(i,t,r)},named:i=>{upu(i,t,r)},primitive:It,unknown:It,_other:It})}function upu(e,t,r){t.add(Lp.generateTypeId(e)),r.add(e.fernFilepath)}function qVD(e,t,r){Es._visit(e,{list:i=>{BM(i,t,r)},map:i=>{BM(i.keyType,t,r),BM(i.valueType,t,r)},optional:i=>{BM(i,t,r)},nullable:i=>{BM(i,t,r)},set:i=>{BM(i,t,r)},literal:It,_other:It})}var TVD=[Ar.AvailabilityStatus.GeneralAvailability];function pUi(e){return e!==void 0&&!TVD.includes(e.status)}var rxc=class{errors;constructor(){this.errors=[]}add(t){this.errors.push({message:t})}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}},$7a=class{errors;constructor(){this.errors=new rxc}async check({from:t,to:r}){let i=this.toInternalIr(t),n=this.toInternalIr(r),a=wJi(i),o=wJi(n);if(a===o)return{bump:"no_change",isBreaking:!1,errors:[]};let c=this.checkBreaking({from:i,to:n});return{bump:c.isBreaking?"major":"minor",isBreaking:c.isBreaking,errors:c.errors}}toInternalIr(t){return{types:t.types,errors:t.errors,services:t.services}}checkBreaking({from:t,to:r}){this.checkTypeBreakingChanges({from:t.types,to:r.types}),this.checkErrorsBreakingChanges({from:t.errors,to:r.errors}),this.checkServicesBreakingChanges({from:t.services,to:r.services});let i=this.errors.hasErrors();return{bump:i?"major":"minor",isBreaking:i,errors:this.errors.getErrors()}}checkTypeBreakingChanges({from:t,to:r}){for(let[i,n]of Object.entries(t)){if(pUi(n.availability))continue;let a=r[i];if(!a){this.errors.add(`Type "${i}" was removed.`);continue}if(pUi(a.availability)){this.errors.add(`Type "${i}" was moved from stable to unstable availability status.`);continue}this.areTypeDeclarationsCompatible({from:n,to:a})||this.errors.add(`Type "${i}" has an incompatible change.`)}}checkErrorsBreakingChanges({from:t,to:r}){for(let[i,n]of Object.entries(t)){let a=Object.values(r).find(o=>o.name.errorId===n.name.errorId);if(!a){this.errors.add(`Error "${n.name.errorId}" with status code "${n.statusCode}" was removed.`);continue}this.checkErrorBreakingChanges({from:n,to:a})}}checkErrorBreakingChanges({from:t,to:r}){if(t.type!=null){if(r.type==null){this.errors.add(`Error "${t.name.errorId}" with status code "${t.statusCode}" had its type removed.`);return}this.areTypeReferencesCompatible({from:t.type,to:r.type})||this.errors.add(`Error "${t.name.errorId}" type reference changed.`)}this.areDeclaredErrorNamesCompatible({from:t.name,to:r.name})||this.errors.add(`Error "${t.name.errorId}" name changed.`),this.areNameAndWireValuesCompatible({from:t.discriminantValue,to:r.discriminantValue})||this.errors.add(`Error "${t.name.errorId}" discriminant value changed.`)}checkServicesBreakingChanges({from:t,to:r}){for(let[i,n]of Object.entries(t)){if(pUi(n.availability)||(n.endpoints?.every(o=>pUi(o.availability))??!1))continue;let a=r[i];if(!a){this.errors.add(`Service "${i}" was removed.`);continue}if(pUi(a.availability)){this.errors.add(`Service "${i}" was moved from stable to unstable availability status.`);continue}this.checkServiceBreakingChanges({id:i,from:n,to:a})}}checkServiceBreakingChanges({id:t,from:r,to:i}){this.checkHeadersBreakingChanges({id:t,from:r.headers,to:i.headers}),this.checkEndpointsBreakingChanges({id:t,from:r,to:i})}checkEndpointsBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.endpoints.map(o=>[o.id,o])),a=Object.fromEntries(i.endpoints.map(o=>[o.id,o]));for(let[o,c]of Object.entries(n)){if(pUi(c.availability))continue;let d=a[o];if(!d){this.errors.add(`Endpoint "${o}" was removed.`);continue}if(pUi(d.availability)){this.errors.add(`Endpoint "${o}" was moved from stable to unstable availability status.`);continue}this.checkEndpointBreakingChanges({id:o,from:c,to:d})}}checkEndpointBreakingChanges({id:t,from:r,to:i}){this.checkHttpMethodsBreakingChanges({id:t,from:r.method,to:i.method}),this.checkHttpPathsBreakingChanges({id:t,from:r.fullPath,to:i.fullPath}),this.checkPathParametersBreakingChanges({id:t,from:r.pathParameters,to:i.pathParameters}),this.checkQueryParametersBreakingChanges({id:t,from:r.queryParameters,to:i.queryParameters}),this.checkHeadersBreakingChanges({id:t,from:r.headers,to:i.headers}),r.requestBody!=null&&(i.requestBody!=null?this.checkHttpRequestBodiesCompatible({id:t,from:r.requestBody,to:i.requestBody}):this.errors.add(`Request body was removed from endpoint "${r.id}".`)),r.response!=null&&(i.response!=null?this.checkHttpResponseBreakingChanges({id:t,from:r.response,to:i.response}):this.errors.add(`Response was removed from endpoint "${r.id}".`)),(r.pagination!=null&&i.pagination==null||r.pagination==null&&i.pagination!=null)&&this.errors.add(`Pagination was ${r.pagination!=null?"added":"removed"} from endpoint "${r.id}".`)}checkPathParametersBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.map(o=>[o.name.originalName,o])),a=Object.fromEntries(i.map(o=>[o.name.originalName,o]));for(let[o,c]of Object.entries(n)){let d=a[o];if(!d){this.errors.add(`Path parameter "${o}" was removed from endpoint "${t}".`);continue}this.areTypeReferencesCompatible({from:c.valueType,to:d.valueType})||this.errors.add(`Path parameter "${o}" type changed in endpoint "${t}".`)}}checkQueryParametersBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.map(o=>[o.name.wireValue,o])),a=Object.fromEntries(i.map(o=>[o.name.wireValue,o]));this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(n).map(([o,c])=>[o,c.valueType])),to:Object.fromEntries(Object.entries(a).map(([o,c])=>[o,c.valueType]))});for(let[o,c]of Object.entries(n)){let d=a[o];if(!d){this.errors.add(`Query parameter "${o}" was removed from endpoint "${t}".`);continue}this.areTypeReferencesCompatible({from:c.valueType,to:d.valueType})||this.errors.add(`Query parameter "${o}" type changed in endpoint "${t}".`),c.allowMultiple!==d.allowMultiple&&this.errors.add(`Query parameter "${o}" allow-multiple values changed in endpoint "${t}".`)}}checkHeadersBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.map(o=>[o.name.wireValue,o])),a=Object.fromEntries(i.map(o=>[o.name.wireValue,o]));this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(n).map(([o,c])=>[o,c.valueType])),to:Object.fromEntries(Object.entries(a).map(([o,c])=>[o,c.valueType]))});for(let[o,c]of Object.entries(n)){let d=a[o];if(!d){this.errors.add(`Header "${o}" was removed from ${t}.`);continue}this.areTypeReferencesCompatible({from:c.valueType,to:d.valueType})||this.errors.add(`Header "${o}" type changed in ${t}.`)}}checkHttpMethodsBreakingChanges({id:t,from:r,to:i}){r!==i&&this.errors.add(`HTTP method changed in ${t}.`)}checkHttpPathsBreakingChanges({id:t,from:r,to:i}){this.areHttpPathsCompatible({from:r,to:i})||this.errors.add(`HTTP path changed in ${t}.`)}areHttpPathsCompatible({from:t,to:r}){if(t.head!==r.head||t.parts.length!==r.parts.length)return!1;for(let i=0;i<t.parts.length;i++){let n=t.parts[i];if(n==null)return!1;let a=r.parts[i];if(a==null||n.pathParameter!==a.pathParameter||n.tail!==a.tail)return!1}return!0}checkHttpRequestBodiesCompatible({id:t,from:r,to:i}){switch(r.type){case"inlinedRequestBody":if(i.type==="inlinedRequestBody"&&this.areInlinedRequestBodiesCompatible({from:r,to:i}))return;break;case"reference":if(i.type==="reference"&&this.areReferenceRequestBodiesCompatible({from:r,to:i}))return;break;case"fileUpload":if(i.type==="fileUpload"&&this.areFileUploadRequestBodiesCompatible({from:r,to:i}))return;break;case"bytes":if(i.type==="bytes")return;break;default:vt(r)}this.errors.add(`Request body type changed from "${r.type}" to "${i.type}" in endpoint "${t}".`)}areInlinedRequestBodiesCompatible({from:t,to:r}){let i=this.getInlinedRequestBody(t),n=this.getInlinedRequestBody(r);return this.checkForNewInlinedRequestBodyProperties({from:i,to:n}),Object.entries(i).every(([a,o])=>{let c=n[a];return c?this.areTypeReferencesCompatible({from:o,to:c}):(this.errors.add(`Request body property "${a}" was removed.`),!1)})}areReferenceRequestBodiesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.requestBodyType,to:r.requestBodyType})}areFileUploadRequestBodiesCompatible({from:t,to:r}){let i=this.getFileUploadRequest(t.properties),n=this.getFileUploadRequest(r.properties);this.checkForNewFileUploadRequestProperties({from:i,to:n});for(let[a,o]of Object.entries(i)){let c=n[a];if(!c)return this.errors.add(`File upload property "${a}" was removed.`),!1;if(o==="file"&&c!=="file")return this.errors.add(`File upload property "${a}" type changed.`),!1;if(o==="fileArray"&&c!=="fileArray")return this.errors.add(`File upload property "${a}" type changed.`),!1;if(o!=="file"&&o!=="fileArray"&&c!=="file"&&c!=="fileArray"&&!this.areTypeReferencesCompatible({from:o,to:c}))return this.errors.add(`File upload property "${a}" type changed.`),!1}return!0}checkHttpResponseBreakingChanges({id:t,from:r,to:i}){if(r.statusCode!==i.statusCode&&this.errors.add(`Response status code changed from "${r.statusCode}" to "${i.statusCode}".`),!(r.body==null&&i.body==null)){if(r.body==null||i.body==null){this.errors.add(`Response body was ${r.body==null?"added":"removed"}.`);return}switch(r.body.type){case"json":if(i.body.type==="json"){this.areJsonResponsesCompatible({from:r.body.value,to:i.body.value});return}break;case"fileDownload":if(i.body.type==="fileDownload")return;break;case"text":if(i.body.type==="text")return;break;case"bytes":if(i.body.type==="bytes")return;break;case"streaming":if(i.body.type==="streaming"){this.areStreamingResponsesCompatible({from:r.body.value,to:i.body.value});return}break;case"streamParameter":if(i.body.type==="streamParameter"){this.areStreamingResponsesCompatible({from:r.body.streamResponse,to:i.body.streamResponse});return}break;default:vt(r.body)}this.errors.add(`HTTP response type "${r.body.type}" defined for endpoint "${t}" is not compatible with type "${i.body.type}".`)}}areJsonResponsesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.responseBodyType,to:r.responseBodyType})}areStreamingResponsesCompatible({from:t,to:r}){switch(t.type){case"json":if(r.type==="json")return this.areTypeReferencesCompatible({from:t.payload,to:r.payload});break;case"sse":if(r.type==="sse")return this.areTypeReferencesCompatible({from:t.payload,to:r.payload});break;case"text":if(r.type==="text")return!0;break;default:vt(t)}return this.errors.add(`Streaming response type "${t.type}" is not compatible with type "${r.type}".`),!1}areTypeDeclarationsCompatible({from:t,to:r}){return pUi(t.availability)?!0:this.areDeclaredTypeNamesCompatible({from:t.name,to:r.name})&&this.areTypeShapesCompatible({from:t.shape,to:r.shape})}areTypeShapesCompatible({from:t,to:r}){switch(t.type){case"alias":if(r.type==="alias")return this.areAliasTypesCompatible({from:t,to:r});break;case"enum":if(r.type==="enum")return this.areEnumTypesCompatible({from:t,to:r});break;case"object":if(r.type==="object")return this.areObjectTypesCompatible({from:t,to:r});break;case"union":if(r.type==="union")return this.areUnionTypesCompatible({from:t,to:r});break;case"undiscriminatedUnion":if(r.type==="undiscriminatedUnion")return this.areUndiscriminatedUnionTypesCompatible({from:t,to:r});break;default:vt(t)}return this.errors.add(`Type "${t.type}" is not compatible with type "${r.type}".`),!1}areAliasTypesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.aliasOf,to:r.aliasOf})}areEnumTypesCompatible({from:t,to:r}){let i=Object.fromEntries(t.values.map(a=>[a.name.wireValue,a])),n=Object.fromEntries(r.values.map(a=>[a.name.wireValue,a]));return Object.keys(i).length!==Object.keys(n).length?!1:Object.values(i).every(a=>{let o=n[a.name.wireValue];return o?this.areNameAndWireValuesCompatible({from:a.name,to:o.name}):(this.errors.add(`Enum value "${a.name.wireValue}" was removed.`),!1)})}areObjectTypesCompatible({from:t,to:r}){let i=Object.fromEntries([...t.properties.map(a=>[a.name.wireValue,a]),...t.extendedProperties?.map(a=>[a.name.wireValue,a])??[]]),n=Object.fromEntries([...r.properties.map(a=>[a.name.wireValue,a]),...r.extendedProperties?.map(a=>[a.name.wireValue,a])??[]]);return this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(i).map(([a,o])=>[a,o.valueType])),to:Object.fromEntries(Object.entries(n).map(([a,o])=>[a,o.valueType]))}),Object.values(i).every(a=>{let o=n[a.name.wireValue];return o?this.areObjectPropertiesCompatible({from:a,to:o}):(this.errors.add(`Object property "${a.name.wireValue}" was removed.`),!1)})}areObjectPropertiesCompatible({from:t,to:r}){return this.areNameAndWireValuesCompatible({from:t.name,to:r.name})&&this.areTypeReferencesCompatible({from:t.valueType,to:r.valueType})}areUnionTypesCompatible({from:t,to:r}){if(!this.areNameAndWireValuesCompatible({from:t.discriminant,to:r.discriminant}))return this.errors.add(`Union type with discriminant value "${t.discriminant.wireValue}" changed.`),!1;let i=new Set(t.extends.map(s=>this.getKeyForDeclaration(s))),n=new Set(r.extends.map(s=>this.getKeyForDeclaration(s)));for(let s of i)if(!n.has(s))return this.errors.add(`Extended type "${s}" was removed.`),!1;let a=Object.fromEntries(t.baseProperties.map(s=>[s.name.wireValue,s])),o=Object.fromEntries(r.baseProperties.map(s=>[s.name.wireValue,s]));for(let s of Object.values(a)){let u=o[s.name.wireValue];if(!u)return this.errors.add(`Union type with discriminant value "${s.name.wireValue}" no longer has a property named "${s.name.wireValue}".`),!1;if(!this.areObjectPropertiesCompatible({from:s,to:u}))return!1}this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(a).map(([s,u])=>[s,u.valueType])),to:Object.fromEntries(Object.entries(o).map(([s,u])=>[s,u.valueType]))});let c=Object.fromEntries(t.types.map(s=>[s.discriminantValue.wireValue,s])),d=Object.fromEntries(r.types.map(s=>[s.discriminantValue.wireValue,s]));return Object.values(c).every(s=>{let u=d[s.discriminantValue.wireValue];return u?this.areSingleUnionTypesCompatible({from:s.shape,to:u.shape}):(this.errors.add(`Union type for discriminant value "${s.discriminantValue.wireValue}" was removed.`),!1)})}areSingleUnionTypesCompatible({from:t,to:r}){switch(t.propertiesType){case"samePropertiesAsObject":if(r.propertiesType==="samePropertiesAsObject")return this.areDeclaredTypeNamesCompatible({from:t,to:r});break;case"singleProperty":if(r.propertiesType==="singleProperty")return this.areNameAndWireValuesCompatible({from:t.name,to:r.name})&&this.areTypeReferencesCompatible({from:t.type,to:r.type});break;case"noProperties":if(r.propertiesType==="noProperties")return!0;break;default:vt(t)}return this.errors.add(`Single union type of style "${t.propertiesType}" is not compatible with style "${r.propertiesType}".`),!1}areUndiscriminatedUnionTypesCompatible({from:t,to:r}){return t.members.every((i,n)=>{let a=r.members[n];return a?this.areTypeReferencesCompatible({from:i.type,to:a.type}):(this.errors.add(`Undiscriminated union member at index ${n} was removed.`),!1)})}checkForNewRequiredTypeReferences({from:t,to:r}){for(let[i,n]of Object.entries(r))t[i]||(n.type!=="container"||n.container.type!=="optional")&&this.errors.add(`Required property "${i}" was added.`)}checkForNewFileUploadRequestProperties({from:t,to:r}){for(let[i,n]of Object.entries(r))t[i]||n==="file"||n==="fileArray"||(n.type!=="container"||n.container.type!=="optional")&&this.errors.add(`Required property "${i}" was added.`)}checkForNewInlinedRequestBodyProperties({from:t,to:r}){for(let[i,n]of Object.entries(r))t[i]||(n.type!=="container"||n.container.type!=="optional")&&this.errors.add(`Required property "${i}" was added.`)}areTypeReferencesCompatible({from:t,to:r}){switch(t.type){case"primitive":if(r.type==="primitive")return this.arePrimitiveTypesCompatible({from:t,to:r});break;case"container":if(r.type==="container")return this.areContainerTypesCompatible({from:t.container,to:r.container});break;case"named":if(r.type==="named")return this.areNamedTypesCompatible({from:t,to:r});break;case"unknown":if(r.type==="unknown")return!0;break;default:vt(t)}return this.errors.add(`TypeReference "${t.type}" is not compatible with type "${r.type}".`),!1}arePrimitiveTypesCompatible({from:t,to:r}){return t.primitive.v1===r.primitive.v1}areContainerTypesCompatible({from:t,to:r}){switch(t.type){case"list":if(r.type==="list")return this.areTypeReferencesCompatible({from:t.list,to:r.list});break;case"set":if(r.type==="set")return this.areTypeReferencesCompatible({from:t.set,to:r.set});break;case"map":if(r.type==="map")return this.areTypeReferencesCompatible({from:t.keyType,to:r.keyType})&&this.areTypeReferencesCompatible({from:t.valueType,to:r.valueType});break;case"optional":if(r.type==="optional")return this.areTypeReferencesCompatible({from:t.optional,to:r.optional});break;case"nullable":if(r.type==="nullable")return this.areTypeReferencesCompatible({from:t.nullable,to:r.nullable});break;case"literal":if(r.type==="literal")return this.areLiteralsCompatible({from:t.literal,to:r.literal});break;default:vt(t)}return this.errors.add(`Container type "${t.type}" is not compatible with type "${r.type}".`),!1}areNamedTypesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&this.areFernFilepathsCompatible({from:t.fernFilepath,to:r.fernFilepath})}areDeclaredTypeNamesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&this.areFernFilepathsCompatible({from:t.fernFilepath,to:r.fernFilepath})}areDeclaredErrorNamesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&this.areFernFilepathsCompatible({from:t.fernFilepath,to:r.fernFilepath})}areNameAndWireValuesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&t.wireValue===r.wireValue}areLiteralsCompatible({from:t,to:r}){switch(t.type){case"boolean":if(r.type==="boolean")return t.boolean===r.boolean;break;case"string":if(r.type==="string")return t.string===r.string;break;default:vt(t)}return!1}areFernFilepathsCompatible({from:t,to:r}){return t.allParts.length!==r.allParts.length?!1:t.allParts.every((i,n)=>{let a=r.allParts[n];return a==null?!1:this.areNamesCompatible({from:i,to:a})})}areNamesCompatible({from:t,to:r}){return t.originalName===r.originalName}getInlinedRequestBody(t){let r={};for(let i of[...t.extendedProperties??[],...t.properties])r[i.name.wireValue]=i.valueType;return r}getFileUploadRequest(t){let r={};for(let i of t)switch(i.type){case"file":r[i.value.key.wireValue]="file";break;case"bodyProperty":r[i.name.wireValue]=i.valueType;break;default:vt(i)}return r}getKeyForDeclaration({name:t,fernFilepath:r}){return`${r.allParts.map(n=>n.camelCase.unsafeName).join(".")}.${t.pascalCase.unsafeName}`}};function Hbn(e,t,r){let{environments:i,changedBaseUrlIds1:n,changedBaseUrlIds2:a}=zVD(e.environments,t.environments,r),{services:o,websocketChannels:c}=NVD(e,t,n,a);return{apiName:e.apiName,basePath:e.basePath,selfHosted:e.selfHosted&&t.selfHosted,apiDisplayName:e.apiDisplayName??t.apiDisplayName,apiDocs:e.apiDocs??t.apiDocs,auth:{requirement:e.auth?.requirement??t.auth?.requirement,schemes:t.auth?.schemes?.length!=null&&t.auth.schemes.length>(e.auth?.schemes?.length??0)?t.auth.schemes:e.auth?.schemes??[],docs:e.auth?.docs??t.auth?.docs},headers:[...e.headers??[],...t.headers??[]],environments:i,types:{...e.types??{},...t.types??{}},constants:{...e.constants??{},...t.constants??{}},errors:{...e.errors??{},...t.errors??{}},services:o,webhookGroups:{...e.webhookGroups??{},...t.webhookGroups??{}},subpackages:RVD(e.subpackages,t.subpackages),websocketChannels:c,rootPackage:{service:e.rootPackage.service??t.rootPackage.service,types:[...e.rootPackage.types??[],...t.rootPackage.types??[]],errors:[...e.rootPackage.errors??[],...t.rootPackage.errors??[]],subpackages:[...e.rootPackage.subpackages??[],...(t.rootPackage.subpackages??[]).filter(d=>!e.rootPackage.subpackages?.includes(d))],fernFilepath:e.rootPackage.fernFilepath??t.rootPackage.fernFilepath,webhooks:e.rootPackage.webhooks??t.rootPackage.webhooks,websocket:e.rootPackage.websocket??t.rootPackage.websocket,hasEndpointsInTree:e.rootPackage.hasEndpointsInTree||t.rootPackage.hasEndpointsInTree,navigationConfig:e.rootPackage.navigationConfig??t.rootPackage.navigationConfig,docs:e.rootPackage.docs??t.rootPackage.docs},fdrApiDefinitionId:e.fdrApiDefinitionId??t.fdrApiDefinitionId,apiVersion:e.apiVersion??t.apiVersion,idempotencyHeaders:[...e.idempotencyHeaders??[],...t.idempotencyHeaders??[]],pathParameters:[...e.pathParameters??[],...t.pathParameters??[]],errorDiscriminationStrategy:e.errorDiscriminationStrategy??t.errorDiscriminationStrategy,variables:[...e.variables??[],...t.variables??[]],serviceTypeReferenceInfo:e.serviceTypeReferenceInfo??t.serviceTypeReferenceInfo,readmeConfig:e.readmeConfig??t.readmeConfig,sourceConfig:e.sourceConfig??t.sourceConfig,publishConfig:e.publishConfig??t.publishConfig,dynamic:e.dynamic??t.dynamic,sdkConfig:e.sdkConfig??t.sdkConfig,audiences:[...e.audiences??[],...t.audiences??[]],generationMetadata:e.generationMetadata??t.generationMetadata,apiPlayground:e.apiPlayground??t.apiPlayground}}function RVD(e,t){let r=e;for(let[i,n]of Object.entries(t))r[i]==null?r[i]=n:r[i]={name:n.name,displayName:n.displayName,fernFilepath:n.fernFilepath,hasEndpointsInTree:r[i].hasEndpointsInTree||n.hasEndpointsInTree,navigationConfig:r[i].navigationConfig??n.navigationConfig,docs:r[i].docs??n.docs,service:r[i].service??n.service,subpackages:[...r[i].subpackages??[],...(n.subpackages??[]).filter(a=>!r[i]?.subpackages?.includes(a))],webhooks:r[i].webhooks??n.webhooks,websocket:r[i].websocket??n.websocket,errors:[...r[i].errors??[],...n.errors??[]],types:[...r[i].types??[],...n.types??[]]};return r}function zVD(e,t,r){if(e==null&&t==null)return{environments:void 0,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(t==null)return{environments:e,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(e==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(JSON.stringify(e)===JSON.stringify(t))return{environments:e,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let i=Nph(e),n=Nph(t);if(i&&n&&e.environments.type==="singleBaseUrl"&&t.environments.type==="singleBaseUrl")return{environments:{defaultEnvironment:e.defaultEnvironment??t.defaultEnvironment,environments:SM.singleBaseUrl({environments:[...e.environments.environments,...t.environments.environments]})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let a=i?t.defaultEnvironment:e.defaultEnvironment,o=e.environments,c=t.environments;if(o.type==="singleBaseUrl"&&c.type==="singleBaseUrl"){let d=i?c:o,s=i?o:c,u={},{deconflictedEnvironments2:l,changedBaseUrlIds2:p}=FVD(d,s,r);if(d.environments[0]==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let _="Base",h=r.generateName("Base");return d.environments.forEach(y=>{u[y.id]=_}),{environments:{defaultEnvironment:a,environments:SM.multipleBaseUrls({baseUrls:[{id:_,name:h},...l.environments.map(y=>({id:y.id,name:y.name}))],environments:d.environments.map(y=>({id:y.id,name:y.name,urls:{[_]:y.url,...Object.fromEntries(l.environments.map(b=>[b.id,b.url]))},docs:void 0}))})},changedBaseUrlIds1:i?p:u,changedBaseUrlIds2:i?u:p}}if(o.type==="multipleBaseUrls"&&c.type==="singleBaseUrl"||o.type==="singleBaseUrl"&&c.type==="multipleBaseUrls"){let d=o.type==="singleBaseUrl"?o:c,s=o.type==="multipleBaseUrls"?o:c,{deconflictedEnvironments1:u,changedBaseUrlIds1:l}=QVD(d,s,r);return{environments:{defaultEnvironment:a,environments:SM.multipleBaseUrls({baseUrls:[...s.baseUrls,...u.environments.map(p=>({id:p.id,name:p.name}))],environments:s.environments.map(p=>({...p,urls:{...p.urls,...Object.fromEntries(u.environments.map(_=>[_.id,_.url]))}}))})},changedBaseUrlIds1:o.type==="singleBaseUrl"?l:void 0,changedBaseUrlIds2:o.type==="singleBaseUrl"?void 0:l}}if(o.type==="multipleBaseUrls"&&c.type==="multipleBaseUrls"){let{deconflictedEnvironments:d,changedBaseUrlIds:s}=UVD(o,c,r);return{environments:{defaultEnvironment:a,environments:SM.multipleBaseUrls({baseUrls:[...o.baseUrls,...d.baseUrls],environments:o.environments.flatMap(u=>d.environments.map(l=>({...u,urls:{...u.urls,...l.urls}})))})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:s}}return{environments:e??t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0}}function NVD(e,t,r,i){if(r!=null)for(let[o,c]of Object.entries(r)){for(let d of Object.values(e.services))for(let s of Object.values(d.endpoints))s.baseUrl==o&&(s.baseUrl=c),s.v2BaseUrls?.includes(o)&&(s.v2BaseUrls=s.v2BaseUrls.map(u=>u===o?c:u));for(let d of Object.values(e.websocketChannels??{}))d.baseUrl==o&&(d.baseUrl=c)}if(i!=null)for(let[o,c]of Object.entries(i)){for(let d of Object.values(t.services))for(let s of Object.values(d.endpoints))s.baseUrl==o&&(s.baseUrl=c),s.v2BaseUrls?.includes(o)&&(s.v2BaseUrls=s.v2BaseUrls.map(u=>u===o?c:u));for(let d of Object.values(t.websocketChannels??{}))d.baseUrl==o&&(d.baseUrl=c)}let n=e.services;for(let[o,c]of Object.entries(t.services))n[o]==null?n[o]=c:n[o]={availability:c.availability,name:c.name,displayName:c.displayName,basePath:c.basePath,endpoints:[...n[o].endpoints??[],...c.endpoints],pathParameters:[...n[o].pathParameters??[],...c.pathParameters??[]],headers:[...n[o].headers??[],...c.headers??[]],encoding:c.encoding,transport:c.transport,audiences:[...n[o].audiences??[],...c.audiences??[]]};let a={...e.websocketChannels??{},...t.websocketChannels??{}};return{services:n,websocketChannels:a}}function FVD(e,t,r){let i={},n=new Set(e.environments.map(s=>s.id)),a=new Set(e.environments.map(s=>s.name)),o=new Map(e.environments.map(s=>[s.url,s.id])),c=t.environments.filter(s=>{let u=o.get(s.url);return u!=null?(i[s.id]=u,!1):!0}).map(s=>{if(n.has(s.id)||a.has(s.name)){let u=ixc(s.id,n);return i[s.id]=u,{...s,id:u,name:r.generateName(u)}}return s});return{deconflictedEnvironments2:SM.singleBaseUrl({environments:c}),changedBaseUrlIds2:i}}function QVD(e,t,r){let i={},n=new Set(t.baseUrls.map(d=>d.id)),a=new Set(t.baseUrls.map(d=>d.name)),o=e.environments.map(d=>{if(n.has(d.id)||a.has(d.name)){let s=ixc(d.id,n);return i[d.id]=s,{...d,id:s,name:r.generateName(s)}}return d});return{deconflictedEnvironments1:SM.singleBaseUrl({environments:o}),changedBaseUrlIds1:i}}function UVD(e,t,r){let i={},n=new Set(e.baseUrls.map(s=>s.id)),a=new Set(e.baseUrls.map(s=>s.name)),o=t.baseUrls.map(s=>{if(n.has(s.id)||a.has(s.name)){let u=ixc(s.id,n);return i[s.id]=u,{...s,id:u,name:r.generateName(u)}}return s}),c=t.environments.map(s=>({...s,urls:Object.fromEntries(Object.entries(s.urls).map(([u,l])=>[i[u]??u,l]))}));return{deconflictedEnvironments:SM.multipleBaseUrls({baseUrls:o,environments:c}),changedBaseUrlIds:i}}function Nph(e){return e.environments.type==="singleBaseUrl"?e.environments.environments.some(t=>t.url&&(t.url.startsWith("ws://")||t.url.startsWith("wss://"))):e.environments.type==="multipleBaseUrls"?e.environments.environments.some(t=>Object.values(t.urls).some(r=>r&&(r.startsWith("ws://")||r.startsWith("wss://")))):!1}function ixc(e,t){let r=e,i=1;for(;t.has(r);)r=`${e}-${i}`,i++;return r}var Oa=class e{breadcrumbs=[];context;static STRING=Ar.TypeReference.primitive({v1:"STRING",v2:Ar.PrimitiveTypeV2.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=Ar.TypeReference.container(Ar.ContainerType.optional(e.STRING));constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r}};var Qph=require("fs/promises");var nxc=class{_map;_path;_lastScalar;_fragments;_count;constructor(){this._map={},this._path=[],this._lastScalar="",this._fragments=[],this._count=0}get map(){return this._map}resolveNode(t,r){if(t.path==="."&&(r="."),!this._map[r]){let{line:i,position:n,lineStart:a}=t;this._map[r]={line:i,position:n,lineStart:a}}t.children&&t.children.length>0&&t.children.forEach(i=>{this.resolveNode(i,(r==="."?"":r)+"."+i.path)})}iterFragments(t,r){for(let i=this._fragments.length-1;i>=0;i--){if(!this._fragments[i].path.startsWith(t)||this._fragments[i].path===t)continue;let n=this._fragments.pop();r(n)}}handleState(t,r){if(t==="close"){let i=r.result,n=r.kind,a=this._path.join(".");if(n==="scalar"){this._path.pop(),this._lastScalar=`${i}`;let{line:o,position:c,lineStart:d}=r;this._path.length===0?this._map["."+i]={line:o,position:c,lineStart:d}:this._fragments.push({path:this._path.join(".")+"."+i,line:o,position:c,lineStart:d})}else if(n==="mapping"){let o={path:a,children:[],line:0,position:0,lineStart:0},c=0;this.iterFragments(a,d=>{c++,!((!d.children||d.children.length===0)&&c%2===1)&&(this._path.length===1?this.resolveNode(d,d.path):(o.children.push({...d,path:d.path.slice(a.length+1)}),o.line=d.line,o.position=d.position,o.lineStart=d.lineStart))}),o.children&&o.children.length>0&&this._fragments.push(o),this._path.pop()}else if(n==="sequence"){let o={path:a,children:[],line:0,position:0,lineStart:0},c=new Set,d=i.length;this.iterFragments(a,s=>{c.has(s.position)||(d--,c.add(s.position),this._path.length===1?this.resolveNode(s,`${a}.${d}`):(o.children.push({...s,path:d.toString()}),o.line=s.line,o.position=s.position,o.lineStart=s.lineStart))}),o.children&&o.children.length>0&&this._fragments.push(o),this._path.pop()}else this._path.pop()}if(t==="open"){if(this._count===0){let{line:i,position:n,lineStart:a}=r;this._map["."]={line:i,position:n,lineStart:a}}this._path.push(this._lastScalar),this._count++}}listen(){return this.handleState.bind(this)}lookup(t){let r=t instanceof Array?t.map(n=>`${n}`).join("."):`${t}`;r.startsWith(".")||(r="."+r),r.startsWith("..")&&(r=r.slice(1)),r=r.replace(/\[/g,".").replace(/\]/g,"");let i=this._map[r];if(i)return{line:i.line+1,column:i.position-i.lineStart+1,position:i.position}}},Fph=nxc;var zR;(function(e){e.WARNING="warning",e.ERROR="error"})(zR||(zR={}));var GEe=class{errors=[];logger;breadcrumbToLineNumberMapper;relativeFilepathToSpec;constructor({logger:t,relativeFilepathToSpec:r}){this.logger=t,this.relativeFilepathToSpec=r,r&&(this.breadcrumbToLineNumberMapper=new axc({logger:t,relativePathToFile:He.of(r)}))}collect(t){this.errors.push(t)}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}dedupe(){let t=[],r=new Set,i=0;for(let n of this.errors){let a=n.path?n.path.join("->"):"",o=`${n.message}|${n.level||zR.WARNING}|${a}`;r.has(o)?i++:(r.add(o),t.push(n))}return this.errors=t,i}getErrorStats(){this.dedupe();let t=0,r=0;for(let i of this.errors)i.level===zR.ERROR?t++:(i.level===zR.WARNING||i.level===void 0)&&r++;return{numErrors:t,numWarnings:r}}async logErrors({logWarnings:t}){this.dedupe();for(let r of this.errors){let i=r.level??zR.WARNING;if(!(i===zR.WARNING&&!t))switch(i){case zR.ERROR:if(this.logger.log(Ou.Debug,r.message),r.path&&r.path.length>0){let n=await this.breadcrumbToLineNumberMapper?.getSourceLocation(r.path),a=n?`${this.relativeFilepathToSpec}:${n.line}:${n.column}`:r.path.join(" -> ");this.logger.log(Ou.Debug,` - at location (${a})`)}break;case zR.WARNING:if(this.logger.log(Ou.Warn,r.message),r.path&&r.path.length>0){let n=await this.breadcrumbToLineNumberMapper?.getSourceLocation(r.path),a=n?`${this.relativeFilepathToSpec}:${n.line}:${n.column}`:r.path.join(" -> ");this.logger.log(Ou.Warn,` - at location (${a})`)}r.resolution&&this.logger.log(Ou.Warn,` - resolution: ${r.resolution}`);break}}}},axc=class{logger;relativePathToFile;map=new Fph;initialized=!1;constructor({relativePathToFile:t,logger:r}){this.relativePathToFile=t,this.logger=r}async initialize(){if(!this.initialized)try{let t=await(0,Qph.readFile)(this.relativePathToFile,"utf-8");qi.load(t,{listener:this.map.listen()}),this.initialized=!0}catch(t){this.logger.log(Ou.Warn,`Failed to initialize line number mapping for ${this.relativePathToFile}: ${JSON.stringify(t)}`)}}async getSourceLocation(t){return this.initialized||await this.initialize(),this.map.lookup(t)}};var bC=class e{args;spec;settings;errorCollector;logger;generationLanguage;smartCasing;casingsGenerator;namespace;exampleGenerationArgs;authOverrides;environmentOverrides;globalHeaderOverrides;enableUniqueErrorsPerEndpoint;generateV1Examples;documentBaseDir;constructor(t){this.args=t,this.spec=t.spec,this.settings=t.settings,this.errorCollector=t.errorCollector,this.logger=t.logger,this.generationLanguage=t.generationLanguage,this.smartCasing=t.smartCasing,this.namespace=t.namespace,this.casingsGenerator=lx({generationLanguage:t.generationLanguage,keywords:void 0,smartCasing:t.smartCasing}),this.exampleGenerationArgs=t.exampleGenerationArgs,this.authOverrides=t.authOverrides,this.environmentOverrides=t.environmentOverrides,this.globalHeaderOverrides=t.globalHeaderOverrides,this.enableUniqueErrorsPerEndpoint=t.enableUniqueErrorsPerEndpoint,this.generateV1Examples=t.generateV1Examples,this.documentBaseDir=t.documentBaseDir}static BREADCRUMBS_TO_IGNORE=["properties","allOf","anyOf"];convertBreadcrumbsToName(t){let r=t.filter((n,a)=>!(/^\d+$/.test(n)||e.BREADCRUMBS_TO_IGNORE.includes(n)||a===0&&n==="components"||a===1&&n==="schemas"||t[0]==="paths"&&(a===0||a===1&&["get","post","put","delete","patch"].includes(n)||a===2&&t[1]!=null&&["get","post","put","delete","patch"].includes(t[1])&&n==="parameters"))),i=ou(r.join("_"));return i.charAt(0).toUpperCase()+i.slice(1)}createFernFilepath(t={}){let r=this.namespace!=null?[this.casingsGenerator.generateName(this.namespace)]:[],i=t.name!=null?this.casingsGenerator.generateName(t.name):void 0;return{allParts:i?[...r,i]:r,packagePath:r,file:i}}resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:i}){let n=this.spec,a=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(o=>o.replace(/~1/g,"/"));for(let o of a){if(typeof n!="object"||n==null)return i||this.errorCollector.collect({level:zR.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1};n=n[o]}return n==null?(i||this.errorCollector.collect({level:zR.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1}):{resolved:!0,value:n}}getErrorMessageForMissingRef({reference:t}){let r=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/");return r.length>=3&&r[0]==="components"&&r[1]==="schemas"?`Schema ${r[2]} does not exist`:`${t.$ref} does not exist`}async resolveMaybeExternalReference(t){let r=this.spec,i,n=!1,a=null,o;if(this.isExternalReference(t.$ref)){n=!0;let s=t.$ref.split("#"),u=s[0];if(i=s[1],!u)return{resolved:!1};o=u;let l=await fetch(u);if(!l.ok)return{resolved:!1};try{let p=await l.text();try{a=JSON.parse(p),r=a}catch{a=qi.load(p),r=a}if(r==null)return{resolved:!1}}catch{return{resolved:!1}}if(!i)return{resolved:!0,value:r}}let c=i??t.$ref;if(c==null||typeof c!="string")return{resolved:!1};let d=c.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(s=>s.replace(/~1/g,"/"));for(let s of d){if(typeof r!="object"||r==null)return{resolved:!1};r=r[s]}if(r==null)return{resolved:!1};if(n&&typeof r=="object"&&r!==null){let s=new Set;s.add(t.$ref),r=await this.resolveNestedExternalReferences(r,a,s,o)}return{resolved:!0,value:r}}async resolveNestedExternalReferences(t,r,i,n){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){let o=[];for(let c of t)o.push(await this.resolveNestedExternalReferences(c,r,i,n));return o}if(this.isReferenceObject(t)){let o=t.$ref;if(this.isExternalReference(o)){if(i.has(o))return t;i.add(o);let c=await this.resolveMaybeExternalReference({$ref:o});if(i.delete(o),c.resolved)return c.value}else{let c=`${n}${o}`;if(i.has(c))return t;i.add(c);let d=r,s=o.substring(2).split("/").map(u=>u.replace(/~1/g,"/").replace(/~0/g,"~"));for(let u of s){if(typeof d!="object"||d===null)return t;d=d[u]}if(d!=null){let u=await this.resolveNestedExternalReferences(d,r,i,n);return i.delete(o),u}i.delete(o)}return t}let a={};for(let[o,c]of Object.entries(t))typeof c=="object"&&c!==null?a[o]=await this.resolveNestedExternalReferences(c,r,i,n):a[o]=c;return a}getExamplesFromSchema({schema:t,breadcrumbs:r}){if(t==null)return[];let i=t.example!=null?[t.example]:[];return t.examples!=null&&(Array.isArray(t.examples)?i.push(...t.examples):this.errorCollector.collect({message:"Received non-array schema examples",path:r})),i}getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:r,defaultExampleName:i}){if(t==null)return[];let n=[];if(t.example!=null){let a=this.generateUniqueName({prefix:i??`${r.join("_")}_example`,existingNames:[]});n.push([a,t.example])}return t.examples!=null&&n.push(...Object.entries(t.examples)),n}resolveMaybeReference({schemaOrReference:t,breadcrumbs:r,skipErrorCollector:i}){if(this.isReferenceObject(t)){let n=this.resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:i});return n.resolved?n.value:void 0}return t}resolveExample(t){if(!this.isReferenceObject(t))return t;let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}resolveExampleWithValue(t){if(!this.isReferenceObject(t))return this.returnExampleValue(t);let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}returnExampleValue(t){return this.isExampleWithValue(t)?t.value:t}getPropertyAccess(t){let r=t;for(;this.isReferenceObject(r);){let a=this.resolveReference({reference:r});if(!a.resolved)return;r=a.value}let{readOnly:i,writeOnly:n}=this.getReadOnlyWriteOnlyFromSchema(r);if(!(i&&n)){if(i)return mYt.ReadOnly;if(n)return mYt.WriteOnly}}getReadOnlyWriteOnlyFromSchema(t){if(t.allOf&&t.allOf.length>0){let r=!0,i=!0;for(let n of t.allOf){let a=n;if(this.isReferenceObject(n)){let c=this.resolveReference({reference:n});if(!c.resolved)continue;a=c.value}let o=this.getReadOnlyWriteOnlyFromSchema(a);r=r&&o.readOnly,i=i&&o.writeOnly}return{readOnly:r,writeOnly:i}}else return{readOnly:!!t.readOnly,writeOnly:!!t.writeOnly}}getAudiences({operation:t,breadcrumbs:r}){let n=new NR.AudienceExtension({operation:t,breadcrumbs:r,context:this}).convert();if(n!=null)return n.audiences}getAvailability({node:t,breadcrumbs:r}){for(;this.isReferenceObject(t);){let a=this.resolveReference({reference:t});if(!a.resolved)return;t=a.value}let n=new NR.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(n!=null)return{status:n,message:void 0};if(t.deprecated===!0)return{status:E1.Deprecated,message:void 0}}getTypeIdFromSchemaReference(t){let r=t.$ref.match(/\/schemas\/(.+)$/);if(!(!r||!r[1]))return r[1]}createNamedTypeReference(t,r){return ii.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(t),typeId:t,displayName:r,default:void 0,inline:!1})}typeReferenceToDeclaredTypeName(t){if(t.type!=="named")return;let r=t.typeId;return{typeId:r,fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(r),displayName:t.displayName}}removeSchemaFromInlinedTypes({id:t,inlinedTypes:r}){return Object.fromEntries(Object.entries(r).filter(([i])=>i!==t))}static maybeTrimPrefix(t,r){return t.startsWith(r)?t.slice(r.length):t}generateUniqueName({prefix:t,existingNames:r}){if(!r.includes(t))return t;let i=0;for(;r.includes(`${t}_${i}`);)i++;return`${t}_${i}`}isReferenceObject(t){return typeof t=="object"&&t!==null&&"$ref"in t}isExternalReference(t){return typeof t=="string"&&(t.startsWith("http://")||t.startsWith("https://"))}isReferenceObjectWithIdentifier(t){return this.isReferenceObject(t)&&("title"in t||"name"in t||"messageId"in t||"summary"in t)}isExampleWithSummary(t){return typeof t=="object"&&t!=null&&"summary"in t}isExampleWithValue(t){return typeof t=="object"&&t!=null&&"value"in t}isOptional(t){return t.type==="container"&&t.container.type==="optional"}isNullable(t){return t.type==="container"&&t.container.type==="nullable"}isList(t){return t.type==="container"&&t.container.type==="list"}isFile(t){return t.type==="primitive"&&t.primitive.v2?.type==="string"&&t.primitive.v2.validation?.format==="binary"}getAsString(t){if(typeof t=="string")return t}getAsInteger(t){if(typeof t=="number"&&Number.isInteger(t))return t}getAsNumber(t){if(typeof t=="number")return t}getAsBoolean(t){if(typeof t=="boolean")return t}getAsArray(t){if(Array.isArray(t))return t}getAsObject(t){if(typeof t=="object"&&t!==null&&!Array.isArray(t))return t}getGroup({groupParts:t,namespace:r}){let i=[];return r!=null&&i.push(r),i.push(...t??[]),i}isObjectSchemaType(t){return t.type==="object"||t.properties!=null}};var fl=class{breadcrumbs;context;constructor(t){this.breadcrumbs=t.breadcrumbs,this.context=t.context}getExtensionValue(t,r){if(typeof t!="object"||t==null)return;let i=t[this.key];if(i!=null)return i;if(r!=null)return t[r]}};var NR={};Yt(NR,{AudienceExtension:()=>spu,FernAvailabilityExtension:()=>cpu,FernEnumExtension:()=>lpu,FernIgnoreExtension:()=>Kbn,FernOptionalExtension:()=>fpu,FernTypeExtension:()=>hpu,FernTypeNameExtension:()=>ypu,SdkGroupNameExtension:()=>dpu,SdkMethodNameExtension:()=>ppu,ServerFromOperationNameExtension:()=>_pu});var spu=class extends fl{operation;key="x-fern-audiences";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(i=>typeof i=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{audiences:r}}};var cpu=class extends fl{node;key="x-fern-availability";constructor({breadcrumbs:t,node:r,context:i}){super({breadcrumbs:t,context:i}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t==null||typeof t!="string")return;switch(t.toUpperCase().replace(/[-_\s]/g,"_")){case"IN_DEVELOPMENT":return E1.InDevelopment;case"PRE_RELEASE":case"BETA":return E1.PreRelease;case"GENERAL_AVAILABILITY":case"GA":return E1.GeneralAvailability;case"DEPRECATED":return E1.Deprecated;default:return}}};var LVD=Qt.object({snake:Qt.string().optional(),camel:Qt.string().optional(),screamingSnake:Qt.string().optional(),pascal:Qt.string().optional()}),VVD=Qt.object({description:Qt.string().optional(),name:Qt.string().optional(),casing:LVD.optional()}),Uph=Qt.record(VVD);var lpu=class extends fl{schema;key="x-fern-enum";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t==null)return;let r=Uph.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-enum extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data}};var Kbn=class extends fl{operation;key="x-fern-ignore";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-ignore",path:this.breadcrumbs});return}return t}}};var fpu=class extends fl{parameter;key="x-fern-optional";constructor({breadcrumbs:t,parameter:r,context:i}){super({breadcrumbs:t,context:i}),this.parameter=r}convert(){let t=this.getExtensionValue(this.parameter);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-optional",path:this.breadcrumbs});return}return t}}};var dpu=class extends fl{operation;key="x-fern-sdk-group-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(i=>typeof i=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{groups:r}}};var ppu=class extends fl{operation;key="x-fern-sdk-method-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null&&typeof t=="string")return{methodName:t}}};var _pu=class extends fl{operation;key="x-fern-server-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation,"x-name");if(!(t==null||typeof t!="string"))return t}};var hpu=class extends fl{schema;key="x-fern-type";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t!=null&&typeof t=="string")return t}};var ypu=class extends fl{schema;key="x-fern-type-name";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(typeof t=="string")return t}};var _8t=class extends Oa{ir;audiences;irGraph;constructor({breadcrumbs:t=[],context:r,audiences:i}){super({breadcrumbs:t,context:r}),this.audiences=i,this.irGraph=new xbn(i),this.ir={auth:{docs:void 0,requirement:Ar.AuthSchemesRequirement.All,schemes:[]},selfHosted:!1,types:{},services:{},errors:{},webhookGroups:{},websocketChannels:void 0,headers:[],idempotencyHeaders:[],apiVersion:void 0,apiDisplayName:void 0,apiDocs:void 0,basePath:void 0,pathParameters:[],errorDiscriminationStrategy:Ar.ErrorDiscriminationStrategy.statusCode(),variables:[],serviceTypeReferenceInfo:{sharedTypes:[],typesReferencedOnlyByService:{}},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0,environments:void 0,fdrApiDefinitionId:void 0,rootPackage:this.createPackage(),subpackages:{},sdkConfig:{hasFileDownloadEndpoints:!1,hasPaginatedEndpoints:!1,hasStreamingEndpoints:!1,isAuthMandatory:!0,platformHeaders:{language:"",sdkName:"",sdkVersion:"",userAgent:void 0}},audiences:void 0,generationMetadata:void 0,apiPlayground:void 0}}removeXFernIgnores({document:t,breadcrumbs:r=[]}){return Array.isArray(t)?t.filter((i,n)=>!new Kbn({breadcrumbs:[...r,String(n)],operation:i,context:this.context}).convert()).map((i,n)=>this.removeXFernIgnores({document:i,breadcrumbs:[...r,String(n)]})):t!=null&&typeof t=="object"?Object.fromEntries(Object.entries(t).filter(([i,n])=>!new Kbn({breadcrumbs:[...r,i],operation:n,context:this.context}).convert()).map(([i,n])=>[i,this.removeXFernIgnores({document:n,breadcrumbs:[...r,i]})])):t}finalizeIr(){let t={...this.ir,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})},audiences:this.audiences.type==="select"?this.audiences.audiences:void 0};this.irGraph.hasNoAudiences()||(t=this.filterIrForAudiences(t));let r=this.context.exampleGenerationArgs,i=ZGc({ir:t,exampleGeneration:r});if(this.context.generateV1Examples){let n=J7a({ir:t,exampleGeneration:r});return{...t,...n,...i}}return{...t,...i}}filterIrForAudiences(t){let r=this.irGraph.getFilteredEndpoints(),i=this.irGraph.getFilteredChannels(),n=this.irGraph.getFilteredWebhooks();for(let a of Object.values(t.services)){let o=[];for(let c of a.endpoints)r.has(c.id)&&o.push(c);a.endpoints=o}return t.websocketChannels=Object.fromEntries(Object.entries(t.websocketChannels??{}).filter(([a])=>i.has(a))),t.webhookGroups=Object.fromEntries(Object.entries(t.webhookGroups).map(([a,o])=>{let c=o.filter(d=>d.id!=null&&n.has(d.id));return[a,c]})),t}async resolveAllExternalRefs({spec:t}){let r=[t];for(;r.length>0;){let i=r.shift();i!=null&&(Array.isArray(i)?await this.resolveExternalRefsInArray(i,r):typeof i=="object"&&await this.resolveExternalRefsInObject(i,r))}return t}async resolveExternalRefsInArray(t,r){for(let i=0;i<t.length;i++)t[i]=await this.resolveReferenceChain(t[i],r)}async resolveExternalRefsInObject(t,r){for(let[i,n]of Object.entries(t))t[i]=await this.resolveReferenceChain(n,r)}async resolveReferenceChain(t,r){let i=t;if(!this.context.isReferenceObject(i))return r.push(i),t;for(;this.context.isReferenceObject(i);){let n=this.context.isExternalReference(i.$ref),a=await this.context.resolveMaybeExternalReference(i);if(a.resolved){if(i=a.value,n)return i}else return t}return t}shouldAddServerToCollectedServers({server:t,currentServers:r,specType:i="openapi"}){return i==="openapi"?!r.some(n=>n.url===t.url&&"x-fern-server-name"in n&&"x-fern-server-name"in t&&n["x-fern-server-name"]===t["x-fern-server-name"]):!r.some(n=>n.url===t.url&&"name"in n&&"name"in t&&n.name===t.name)}addEndpointToIr({endpoint:t,audiences:r,endpointGroup:i,endpointGroupDisplayName:n,serviceName:a}){let o=this.context.getGroup({groupParts:i,namespace:this.context.namespace}),c=this.getOrCreatePackage({group:i}),d=[...o].map(l=>this.context.casingsGenerator.generateName(l)),s=d[d.length-1];c.service==null&&(c.service=a??`service_${o.map(l=>ou(l)).join("/")}`),this.ir.services[c.service]==null&&(this.ir.services[c.service]=this.createNewService({allParts:d,finalpart:s,endpointGroupDisplayName:n})),this.ir.services[c.service]?.endpoints.push(t);let u=this.ir.services[c.service];u!=null&&(this.irGraph.addEndpoint(u,t),this.irGraph.markEndpointForAudience(u.name,[t],r))}addWebhookToIr({webhook:t,operationId:r,audiences:i,group:n}){let a=n?.join(".")??r,o=this.getOrCreatePackage({group:n});this.ir.webhookGroups[a]==null&&(this.ir.webhookGroups[a]=[]),this.ir.webhookGroups[a].push(t),o.webhooks=a;let c=this.context.createFernFilepath();this.irGraph.addWebhook(c,t),i!=null&&this.irGraph.markWebhookForAudiences(c,t,i)}addWebsocketChannelToIr({websocketChannel:t,channelPath:r,audiences:i,websocketGroup:n}){let a=ou(n?.join(".")),o=ou(r),c=this.context.namespace?`${ou(this.context.namespace)}/`:"",d=a?`channel_${c}${a}`:`channel_${c}${o}`,s=n?this.getOrCreatePackage({group:n}):this.getOrCreatePackage({group:[o]});this.ir.websocketChannels={...this.ir.websocketChannels,[d]:t},d!==""?s.websocket==null&&(s.websocket=d):this.ir.rootPackage.websocket="";let u=this.context.createFernFilepath();this.irGraph.addChannel(u,d,t),i!=null&&this.irGraph.markChannelForAudiences(u,d,i)}addAuthToIR(t){this.ir.auth=t}addErrorsToIr(t){this.ir.errors=t;for(let r of Object.values(t))this.irGraph.addError(r)}addGlobalHeadersToIr(t){this.ir.headers=t}addEnvironmentsToIr({environmentConfig:t,audiences:r}){if(this.ir.environments=t,r!=null)for(let[i,n]of Object.entries(t??{}))r[i]!=null&&this.irGraph.markEnvironmentForAudiences(n,r[i])}addTypeToRootPackage(t){this.ir.rootPackage.types.push(t)}addSchemaOutputToIr(t,r){let{convertedSchema:i,inlinedTypes:n}=r,o=Object.keys(n).some(c=>c===t)?`${t}Wrapper`:t;this.addTypeToPackage(o),this.addTypesToIr({...n,[o]:i})}addTypeToPackage(t){let r=this.context.getGroup({groupParts:[],namespace:this.context.namespace});this.getOrCreatePackage({group:r}).types.push(t)}addTypesToIr(t){Object.assign(this.ir.types,Object.fromEntries(Object.entries(t).map(([r,i])=>[r,i.typeDeclaration])));for(let r of Object.values(t))this.irGraph.addType({declaredTypeName:r.typeDeclaration.name,descendantTypeIds:r.typeDeclaration.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:r.propertiesByAudience,descendantFilepaths:new Set}),this.irGraph.markTypeForAudiences(r.typeDeclaration.name,r.audiences)}updateEndpointsWithDefaultUrl(t){if(t!=null)for(let r of Object.values(this.ir.services))for(let i of r.endpoints)i.baseUrl==null&&(i.baseUrl=t)}createNewService({allParts:t,finalpart:r,endpointGroupDisplayName:i}){return{name:{fernFilepath:{allParts:t,packagePath:t.slice(0,-1),file:r}},displayName:i,basePath:DM(""),headers:[],pathParameters:[],availability:void 0,endpoints:[],transport:void 0,encoding:void 0,audiences:void 0}}createPackage(t={}){return{fernFilepath:this.context.createFernFilepath(t),service:void 0,types:[],errors:[],subpackages:[],docs:void 0,webhooks:void 0,websocket:void 0,hasEndpointsInTree:!1,navigationConfig:void 0}}getOrCreatePackage({group:t}){let r=[];if(this.context.namespace!=null&&r.push(this.context.namespace),r.push(...(t??[]).map(n=>ou(n))),r.length==0)return this.ir.rootPackage;let i=this.ir.rootPackage;for(let n=0;n<r.length;n++){let a=r[n]??"",c=`subpackage_${r.slice(0,n+1).join("/")}`;this.ir.subpackages[c]==null&&(this.ir.subpackages[c]={name:this.context.casingsGenerator.generateName(a),displayName:void 0,...this.createPackage({name:a})});let d=this.ir.subpackages[c];i.subpackages.includes(c)||i.subpackages.push(c),i=d}return i}};var Fm={};Yt(Fm,{AbstractConverters:()=>uxc,ExampleConverter:()=>gF,SchemaConverters:()=>oxc,ServersConverter:()=>tge});var uxc={};Yt(uxc,{AbstractMediaTypeObjectConverter:()=>gpu,AbstractParameterConverter:()=>Opu});var WVD=/^literal<\s*(?:"(.*)"|(true|false))\s*>$/;function GVD(e){return e.type==="array"||e.properties||e.oneOf||e.anyOf||e.allOf||e.additionalProperties?!1:!!(e.type==="string"||e.type==="number"||e.type==="integer"||e.type==="boolean"||e.const!==void 0||Array.isArray(e.enum)&&e.enum.length>0)}function Lph(e){if(e.const!==void 0)return e.const;if(Array.isArray(e.enum)&&e.enum.length>0)return e.enum[0]}var gF=class e extends Oa{MAX_DEPTH=12;EXAMPLE_STRING=xn.STRING;EXAMPLE_NUMBER=xn.DOUBLE;EXAMPLE_BOOLEAN=xn.BOOLEAN;EXAMPLE_INTEGER=xn.INT;EXAMPLE_DATE=xn.DATE;EXAMPLE_DATE_TIME=xn.DATE_TIME;schema;example;depth;exampleGenerationStrategy;generateOptionalProperties;seenRefs;constructor({breadcrumbs:t,context:r,schema:i,example:n,depth:a=0,exampleGenerationStrategy:o,generateOptionalProperties:c=!1,seenRefs:d=new Set}){super({breadcrumbs:t,context:r}),this.example=n,this.schema=i,this.depth=a,this.exampleGenerationStrategy=o,this.generateOptionalProperties=c,this.seenRefs=d}convert(){if(this.depth>this.MAX_DEPTH)return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:typeof this.example<"u"?this.example:{},errors:[]};if(this.context.isReferenceObject(this.schema)){let i=this.schema.$ref;if(this.seenRefs.has(i))return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}}let t=this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(t==null)return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:"Schema is not resolvable",path:this.breadcrumbs}]};if(typeof t!="object")return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Schema should be an object: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]};if("nullable"in t&&t.nullable===!0&&this.example===null)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let r=this.maybeConvertLiteralFernType(t);return r??(Array.isArray(t.type)?this.convertSchemaTypeArray({resolvedSchema:t}):t.type=="null"?this.convertNull():t.type=="boolean"?this.convertBoolean():t.enum!=null?this.convertEnum(t):t.type=="number"?this.convertNumber():t.type=="string"?this.convertString():t.type=="integer"?this.convertInteger():t.type=="array"?this.convertArray({resolvedSchema:t}):"oneOf"in t&&t.oneOf!=null?this.convertOneOf({resolvedSchema:t}):"anyOf"in t&&t.anyOf!=null?this.convertAnyOf({resolvedSchema:t}):t.type=="object"||t.properties!=null||t.allOf!=null?this.convertObject({resolvedSchema:t}):typeof t=="object"&&Object.keys(t).length===0?{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Unsupported schema type: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]})}convertNull(){let t=this.example===null;return t?{isValid:t,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Example is not null: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertBoolean(){let t=typeof this.example=="boolean";if(t)return{isValid:t,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.default:this.schema.default,i=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.const:this.schema.const;return typeof r=="boolean"||typeof i=="boolean"?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:i??r,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_BOOLEAN,errors:[{message:`Example is not a boolean: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertEnum(t){let r=t.enum?.includes(this.example)??!1;if(r)return{isValid:r,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let i=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return i!==void 0&&t.enum?.includes(i)?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:i,errors:[]}:{isValid:r,coerced:!1,usedProvidedExample:!1,validExample:t.enum?.[0],errors:[{message:`Example is not one of the allowed enum values: ${JSON.stringify(t.enum,null,2)}`,path:this.breadcrumbs}]}}convertNumber(){if(typeof this.example=="number")return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let t=Number(this.example);if(!isNaN(t))return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):this.schema,i=r?.default;return typeof i=="number"?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:i,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.adjustNumberToConstraints(this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_NUMBER,r),errors:[{message:`Example is not a number: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}adjustNumberToConstraints(t,r){if(r==null)return this.context.logger.debug("[ExampleConverter.adjustNumberToConstraints] Schema object is null, returning original number","number:",t.toString()),t;let{minimum:i,maximum:n,exclusiveMinimum:a,exclusiveMaximum:o}=r,c;a!=null?typeof a=="boolean"?c=i!=null?i+Math.max(Number.EPSILON,Math.abs(i)*1e-10):void 0:c=a+Math.max(Number.EPSILON,Math.abs(a)*1e-10):i!=null&&(c=i);let d;return o!=null?typeof o=="boolean"?d=n!=null?n-Math.max(Number.EPSILON,Math.abs(n)*Number.EPSILON):void 0:d=o-Math.max(Number.EPSILON,Math.abs(o)*Number.EPSILON):n!=null&&(d=n),c!==void 0&&d!==void 0?(t<c||t>d)&&(t=c+(d-c)/2):c!==void 0&&t<c?t=c+Math.abs(c*.1):d!==void 0&&t>d&&(t=d-Math.abs(d*.1)),Number(Number(t).toPrecision(3))}convertString(){if(typeof this.example=="string")return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};if(typeof this.example!="object"&&!Array.isArray(this.example)&&this.example!=null)return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:String(this.example),errors:[]};let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;if(typeof t=="string")return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):this.schema,i=r?.format==="date"?this.EXAMPLE_DATE:r?.format==="date-time"?this.EXAMPLE_DATE_TIME:this.EXAMPLE_STRING;return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??i,errors:[{message:`Example cannot be converted to string: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertInteger(){if(typeof this.example=="number"&&Number.isInteger(this.example))return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};if(typeof this.example=="string"){let r=Number(this.example);if(!isNaN(r)&&Number.isInteger(r))return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:r,errors:[]}}let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return typeof t=="number"&&Number.isInteger(t)?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:t,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_INTEGER,errors:[{message:`Example is not an integer: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertArray({resolvedSchema:t}){if(t.type!="array")return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};t.items==null&&(t.items={type:"string"});let r=this.example==null,i=this.example??t.example,a=(Array.isArray(i)?i:[i]).map(d=>new e({breadcrumbs:[...this.breadcrumbs,"items"],context:this.context,schema:t.items,example:d,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),o=a.every(d=>d?.isValid??!1)&&!r,c=!r&&a.some(d=>d.usedProvidedExample);return{isValid:o,coerced:!1,usedProvidedExample:c,validExample:a.map(d=>d.validExample),errors:o?[]:a.flatMap(d=>d.errors)}}convertObject({resolvedSchema:t}){if(t.type=="object"&&t.properties==null&&t.allOf==null)return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example??{},errors:[]};let r=typeof this.example!="object"||this.example==null?{}:this.example,i=Object.entries(t.properties??{}).map(([l,p])=>{if(typeof p!="object")return{key:l,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if(this.isDeprecatedProperty(p)&&!this.isRequiredProperty({key:l,resolvedSchema:t}))return{key:l,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("readOnly"in p&&p.readOnly===!0&&"writeOnly"in p&&p.writeOnly===!0)return{key:l,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("readOnly"in p&&p.readOnly===!0&&this.exampleGenerationStrategy==="request")return{key:l,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("writeOnly"in p&&p.writeOnly===!0&&this.exampleGenerationStrategy==="response")return{key:l,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};let _=!(l in r)||!("nullable"in p)&&r[l]==null||"nullable"in p&&p.nullable===!0&&r[l]===void 0,h=!t.required?.includes(l);if(_&&h){if(this.example===void 0&&this.generateOptionalProperties){let y=this.maybeResolveSchemaExample(p),b=new e({breadcrumbs:[...this.breadcrumbs,l],context:this.context,schema:p,example:y,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()});return{key:l,result:b.convert()}}return{key:l,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}}}else{let y=r[l],b=y!==void 0?y:this.maybeResolveSchemaExample(p),g=new e({breadcrumbs:[...this.breadcrumbs,l],context:this.context,schema:p,example:b,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();return{key:l,result:g}}}),n=(t.allOf??[]).map((l,p)=>new e({breadcrumbs:[...this.breadcrumbs,`allOf[${p}]`],context:this.context,schema:{...t,...l,allOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),a=i.every(l=>l.result.isValid)&&n.every(l=>l.isValid),o=this.example!==void 0&&(i.some(({result:l})=>l.usedProvidedExample)||n.some(l=>l.usedProvidedExample)),c=Object.fromEntries(i.map(({key:l,result:p})=>[l,p.validExample]).filter(([l,p])=>p!==void 0));for(let l of n)if(typeof l.validExample=="object"&&l.validExample!==null){let p=l.validExample;c={...c,...Object.fromEntries(Object.entries(p).filter(([_,h])=>h!==void 0))}}let d=[],s=new Set(Object.keys(t.properties??{})),u=Object.keys(r).filter(l=>!s.has(l));u.length>0&&(t.additionalProperties===!1?u.forEach(l=>{let p=[...this.breadcrumbs,l].join("."),_={message:`Found unexpected property '${l}' in example. This property does not exist in the schema${p?` at path: ${p}`:""}`,path:[...this.breadcrumbs,l]};d.push({key:l,result:{isValid:!1,coerced:!1,usedProvidedExample:!0,validExample:void 0,errors:[_]}})}):u.forEach(l=>{let p=[...this.breadcrumbs,l].join("."),_={message:`Additional property ${l} is not allowed`,path:[...this.breadcrumbs,l]};d.push({key:l,result:{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:void 0,errors:[_]}})}));for(let{key:l,result:p}of d)p.validExample!==void 0&&c[l]===void 0&&(c[l]=p.validExample);if(Object.keys(c).length===0){let l=n.find(p=>p.validExample!==void 0&&(typeof p.validExample!="object"||p.validExample===null));l&&(c=l.validExample)}return{isValid:a,coerced:!1,usedProvidedExample:o,validExample:c,errors:[...i.flatMap(({result:l})=>l.errors),...n.flatMap(l=>l.errors),...d.flatMap(({result:l})=>l.errors)]}}convertSchemaTypeArray({resolvedSchema:t}){if(!Array.isArray(t.type))return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};if(t.type.length===1)return new e({breadcrumbs:this.breadcrumbs,context:this.context,schema:{...t,type:t.type[0]},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();let r=t.type.map((c,d)=>new e({breadcrumbs:[...this.breadcrumbs,`type[${d}]`],context:this.context,schema:{...t,type:c},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),i=r.some(c=>c?.isValid??!1),a=r.find(c=>c.isValid)?.validExample??r[0]?.validExample??null,o=r.some(c=>c.usedProvidedExample);return{isValid:i,coerced:!1,usedProvidedExample:o,validExample:a,errors:i?[]:r.flatMap(c=>c?.errors??[])}}convertUnion({resolvedSchema:t,unionType:r}){let i=r==="oneOf"?t.oneOf:t.anyOf;if(!(r in t)||i==null)return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};let n=this.example??this.maybeResolveSchemaExample(t);if(this.example===void 0){let p=[];for(let h of i){if(!h)continue;let y=this.context.resolveMaybeReference({schemaOrReference:h,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});y&&p.push(y)}if(p.length>0&&p.every(h=>GVD(h))){let h=p.findIndex(y=>Lph(y)!==void 0);if(h!==-1){let y=i[h],b=p[h];if(y&&b){let v=Lph(b),m=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${h}]`],context:this.context,schema:r==="oneOf"?{...t,...y,oneOf:void 0}:y,example:v,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(m.isValid)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:m.validExample,errors:[]}}}}}let a=[],o=null,c=null;for(let p=0;p<i.length;p++){let _=i[p];if(!_)continue;let h=r==="oneOf"?{...t,..._,oneOf:void 0}:_,y=n??this.maybeResolveSchemaExample(h),v=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${p}]`],context:this.context,schema:h,example:y,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(v.isValid&&!v.coerced&&v.usedProvidedExample)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:v.validExample,errors:[]};if(v.isValid&&!v.coerced)return{isValid:!0,coerced:!1,usedProvidedExample:v.usedProvidedExample,validExample:v.validExample,errors:[]};a.push(v),v.isValid&&v.usedProvidedExample&&c===null&&(c=v),v.isValid&&o===null&&(o=v)}let d=c??o,s=d!==null,u=d?.validExample??a[0]?.validExample,l=d?.usedProvidedExample??!1;return{isValid:s,coerced:!1,usedProvidedExample:l,validExample:u,errors:s?[]:a.flatMap(p=>p.errors)}}convertOneOf({resolvedSchema:t}){return this.convertUnion({resolvedSchema:t,unionType:"oneOf"})}convertAnyOf({resolvedSchema:t}){return this.convertUnion({resolvedSchema:t,unionType:"anyOf"})}getMaybeUpdatedSeenRefs(){let t=new Set(this.seenRefs);return this.context.isReferenceObject(this.schema)&&t.add(this.schema.$ref),t}maybeResolveSchemaExample(t){if("example"in t)return t.example;if("examples"in t){let i=t.examples;if(Array.isArray(i)&&i.length>0)return i[0];if(i!=null&&typeof i=="object")return Object.values(i)[0]}let r=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(r!=null){if("example"in r)return r.example;if("examples"in r){let i=r.examples;return Array.isArray(i)&&i.length>0?i[0]:Object.values(i??{})[0]}}}maybeConvertLiteralFernType(t){let r=t["x-fern-type"];if(typeof r!="string")return;let i=r.match(WVD);if(i!=null){if(i[1]!=null)return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:i[1],errors:[]};if(i[2]!=null)return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:i[2]==="true",errors:[]}}}isDeprecatedProperty(t){return t!=null&&"availability"in t&&t.availability==="deprecated"}isRequiredProperty({key:t,resolvedSchema:r}){return r.required?.includes(t)??!1}};var oxc={};Yt(oxc,{ArraySchemaConverter:()=>Poa,EnumSchemaConverter:()=>Ooa,ObjectSchemaConverter:()=>moa,OneOfSchemaConverter:()=>Jbn,PrimitiveSchemaConverter:()=>Aoa,SchemaConverter:()=>SJi,SchemaOrReferenceConverter:()=>jW});function Vph(e){return hC({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return ii.primitive({v1:"BASE_64",v2:vn.base64({})});case"BOOLEAN":return ii.primitive({v1:"BOOLEAN",v2:vn.boolean({default:void 0})});case"DATE":return ii.primitive({v1:"DATE",v2:vn.date({})});case"DATE_TIME":return ii.primitive({v1:"DATE_TIME",v2:vn.dateTime({})});case"FLOAT":return ii.primitive({v1:"FLOAT",v2:vn.float({default:void 0,validation:void 0})});case"DOUBLE":return ii.primitive({v1:"DOUBLE",v2:vn.double({default:void 0,validation:void 0})});case"UINT":return ii.primitive({v1:"UINT",v2:vn.uint({default:void 0,validation:void 0})});case"UINT_64":return ii.primitive({v1:"UINT_64",v2:vn.uint64({default:void 0,validation:void 0})});case"INTEGER":return ii.primitive({v1:"INTEGER",v2:vn.integer({default:void 0,validation:void 0})});case"LONG":return ii.primitive({v1:"LONG",v2:vn.long({default:void 0,validation:void 0})});case"STRING":return ii.primitive({v1:"STRING",v2:vn.string({default:void 0,validation:void 0})});case"UUID":return ii.primitive({v1:"UUID",v2:vn.uuid({})});case"BIG_INTEGER":return ii.primitive({v1:"BIG_INTEGER",v2:vn.bigInteger({default:void 0})});default:return}},unknown:()=>ii.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return ii.container(Es.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return ii.container(Es.list(t))},optional:t=>{if(t!=null)return ii.container(Es.optional(t))},nullable:t=>{if(t!=null)return ii.container(Es.nullable(t))},set:t=>{if(t!=null)return ii.container(Es.set(t))},literal:t=>ii.container(Es.literal(t._visit({string:r=>lF.string(r),boolean:r=>lF.boolean(r),_other:()=>{throw new Error("Unexpected literal type")}}))),named:()=>{}}})}var Ooa=class extends Oa{schema;maybeFernEnum;constructor({context:t,breadcrumbs:r,schema:i,maybeFernEnum:n}){super({context:t,breadcrumbs:r}),this.schema=i,this.maybeFernEnum=n}convert(){if(!this.schema.enum)return;let r=this.schema.enum.filter(n=>typeof n=="string"||typeof n=="number").map(n=>{let a=n.toString(),o=this.maybeFernEnum?.[a],c=o?.name??a;return{name:this.context.casingsGenerator.generateNameAndWireValue({name:c,wireValue:a}),docs:o?.description,availability:void 0,casing:o?.casing}});if(r.length===0){this.context.errorCollector.collect({message:`Received enum schema with no valid values: ${JSON.stringify(this.schema)}`,path:this.breadcrumbs});return}let i=this.context.getAsString(this.schema.default);return{type:Al.enum({default:i!=null?r.find(n=>n.name.wireValue===i):void 0,values:r})}}};var bpu=class extends Oa{schemaOrReferenceOrBoolean;constructor({context:t,breadcrumbs:r,schemaOrReferenceOrBoolean:i}){super({context:t,breadcrumbs:r}),this.schemaOrReferenceOrBoolean=i}convert(){let t=this.tryConvertUnknownMap();if(t!=null)return t;let r=this.tryConvertTypedMap();if(r!=null)return r}tryConvertUnknownMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean"){let t=ii.container(Es.map({keyType:Oa.STRING,valueType:ii.unknown()}));return{type:Al.alias({aliasOf:t,resolvedType:t}),referencedTypes:new Set,inlinedTypes:{}}}}tryConvertTypedMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean")return;let r=new jW({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schemaOrReferenceOrBoolean}).convert();if(r!=null){let i=ii.container(Es.map({keyType:Oa.STRING,valueType:r.type})),n=new Set;for(let a of r.schema?.typeDeclaration.referencedTypes??[])n.add(a);for(let a of Object.keys(r.inlinedTypes))n.add(a);return{type:Al.alias({aliasOf:i,resolvedType:i}),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}};function Y7a({properties:e,required:t,breadcrumbs:r,context:i,errorCollector:n}){let a=[],o={},c={},d=new Set;for(let[s,u]of Object.entries(e??{})){let l=[...r,"properties",s];if(typeof u!="object"){n.collect({message:`Schema property ${s} should be an object`,path:l});continue}let p=xVD(r,u,i)??i.convertBreadcrumbsToName(l),_="nullable"in u?u.nullable:!1,y=new jW({context:i,breadcrumbs:l,schemaOrReference:u,schemaIdOverride:p,wrapAsOptional:!t.includes(s),wrapAsNullable:_}).convert();if(y!=null){a.push({name:i.casingsGenerator.generateNameAndWireValue({name:s,wireValue:s}),valueType:y.type,docs:u.description,availability:y.availability,propertyAccess:i.getPropertyAccess(u),v2Examples:y.schema?.typeDeclaration?.v2Examples??{userSpecifiedExamples:{},autogeneratedExamples:{}}}),o={...o,...y.inlinedTypes},y.schema?.typeDeclaration.referencedTypes!=null&&y.schema.typeDeclaration.referencedTypes.forEach(b=>{d.add(b)});for(let b of y.schema?.audiences??[])c[b]==null&&(c[b]=new Set),c[b].add(s)}}for(let s of Object.keys(o))d.add(s);return{convertedProperties:a,propertiesByAudience:c,inlinedTypesFromProperties:o,referencedTypes:d}}function xVD(e,t,r){return r.isReferenceObject(t)?void 0:new NR.FernTypeNameExtension({breadcrumbs:e,schema:t,context:r}).convert()}var moa=class extends Oa{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){let t=typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties;if(!this.schema.properties&&!this.schema.allOf)return{type:Al.object({properties:[],extends:[],extendedProperties:[],extraProperties:t}),propertiesByAudience:{},inlinedTypes:{},referencedTypes:new Set};let{convertedProperties:r,inlinedTypesFromProperties:i,referencedTypes:n,propertiesByAudience:a}=Y7a({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector}),o=[],c=n,d=this.schema.required!=null&&this.schema.required.length>0,s=i,u=a;for(let[l,p]of(this.schema.allOf??[]).entries()){let _=[...this.breadcrumbs,"allOf",l.toString()],h;if(this.context.isReferenceObject(p)){let m=this.context.resolveMaybeReference({schemaOrReference:p,breadcrumbs:_});if(m==null){this.context.logger.debug?.(`[ObjectSchemaConverter] allOf[${l}] reference could not be resolved. Skipping: ${JSON.stringify(p)}`);continue}if(h=m,typeof h.additionalProperties=="boolean"&&h.additionalProperties&&(t=!0),!d||Object.keys(h.properties??{}).every(O=>!this.schema.required?.includes(O))){this.addTypeReferenceToExtends({reference:p,breadcrumbs:_,extends_:o,referencedTypes:c});continue}}else h=p;typeof h.additionalProperties=="boolean"&&h.additionalProperties&&(t=!0);let{convertedProperties:y,inlinedTypesFromProperties:b,referencedTypes:v,propertiesByAudience:g}=Y7a({properties:h.properties??{},required:[...this.schema.required??[],...h.required??[]],breadcrumbs:_,context:this.context,errorCollector:this.context.errorCollector});r.push(...y),s={...s,...b},u={...u,...g},v.forEach(m=>{c.add(m)})}for(let l of Object.keys(s))c.add(l);return{type:Al.object({properties:r,extends:o.map(l=>this.context.typeReferenceToDeclaredTypeName(l)).filter(us),extendedProperties:[],extraProperties:t}),propertiesByAudience:u,referencedTypes:c,inlinedTypes:s}}addTypeReferenceToExtends({reference:t,breadcrumbs:r,extends_:i,referencedTypes:n}){let a=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:r});a.ok&&i.push(a.reference);let o=this.context.getTypeIdFromSchemaReference(t);o!=null&&n.add(o)}};var vpu=class extends fl{node;key="x-fern-discriminated";constructor({breadcrumbs:t,node:r,context:i}){super({breadcrumbs:t,context:i}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t!=null&&typeof t=="boolean")return t}};var Jbn=class extends Oa{schema;id;constructor({context:t,breadcrumbs:r,schema:i,id:n,inlinedTypes:a}){super({context:t,breadcrumbs:r}),this.schema=i,this.id=n}convert(){return this.shouldConvertAsNullableSchemaOrReference()?this.convertAsNullableSchemaOrReference():new vpu({context:this.context,breadcrumbs:this.breadcrumbs,node:this.schema}).convert()===!1?this.convertAsUndiscriminatedUnion():this.schema.discriminator!=null&&!this.unionVariantsContainLiteral({discriminantProperty:this.schema.discriminator.propertyName})?this.convertAsDiscriminatedUnion():this.convertAsUndiscriminatedUnion()}unionVariantsContainLiteral({discriminantProperty:t}){for(let[r,i]of Object.entries(this.schema.discriminator?.mapping??{})){let n=this.context.resolveReference({reference:{$ref:i},breadcrumbs:this.breadcrumbs});if(n.resolved&&!Object.keys(n.value.properties??{}).includes(t))return!1}return!0}convertAsDiscriminatedUnion(){if(this.schema.discriminator==null)return;let t=[],r=new Set,i={};for(let[d,s]of Object.entries(this.schema.discriminator.mapping??{})){let u=new jW({context:this.context,schemaOrReference:{$ref:s},breadcrumbs:[...this.breadcrumbs,"discriminator","mapping",d]}),l=this.context.getTypeIdFromSchemaReference({$ref:s});l!=null&&r.add(l);let p=u.convert();if(p?.type!=null&&l!=null){for(let h of Object.keys(p?.inlinedTypes??{}))r.add(h);for(let h of p.schema?.typeDeclaration.referencedTypes??[])r.add(h);let _=this.context.casingsGenerator.generateNameAndWireValue({name:d,wireValue:d});t.push({docs:void 0,discriminantValue:_,availability:p.availability,displayName:d,shape:cF.samePropertiesAsObject({typeId:l,name:this.context.casingsGenerator.generateName(l),fernFilepath:{allParts:[],packagePath:[],file:void 0},displayName:d})}),i={...i,...p.inlinedTypes}}}let{convertedProperties:n,referencedTypes:a,inlinedTypesFromProperties:o}=Y7a({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector});r=new Set([...r,...a]);let c=[];for(let[d,s]of(this.schema.allOf??[]).entries()){let u=[...this.breadcrumbs,"allOf",d.toString()];if(this.context.isReferenceObject(s)){let l=this.context.convertReferenceToTypeReference({reference:s,breadcrumbs:u});if(l.ok){let _=this.context.typeReferenceToDeclaredTypeName(l.reference);_!=null&&c.push(_)}let p=this.context.getTypeIdFromSchemaReference(s);p!=null&&r.add(p);continue}}for(let d of Object.keys({...i,...o}))r.add(d);return{type:Al.union({baseProperties:n,discriminant:this.context.casingsGenerator.generateNameAndWireValue({name:this.schema.discriminator.propertyName,wireValue:this.schema.discriminator.propertyName}),extends:c,types:t}),referencedTypes:r,inlinedTypes:{...i,...o}}}convertAsUndiscriminatedUnion(){if(!this.schema.oneOf&&!this.schema.anyOf||this.schema.anyOf?.length===0&&this.schema.oneOf?.length===0)return;let t=[],r=new Set,i={},n=[...this.schema.oneOf??[],...this.schema.anyOf??[]].filter(a=>!this.context.isReferenceObject(a));for(let[a,o]of[...(this.schema.oneOf??[]).entries(),...(this.schema.anyOf??[]).entries()]){if(this.context.isReferenceObject(o)){let p;if(this.context.isReferenceObjectWithIdentifier(o))p=this.context.convertReferenceToTypeReference({reference:o,displayNameOverride:o.summary??o.title??o.name??o.messageId,displayNameOverrideSource:"reference_identifier"});else if(this.getDiscriminatorKeyForRef(o)!=null){let h=this.getDiscriminatorKeyForRef(o);p=this.context.convertReferenceToTypeReference({reference:o,displayNameOverride:h,displayNameOverrideSource:"discriminator_key"})}else p=this.context.convertReferenceToTypeReference({reference:o,displayNameOverride:o.$ref.split("/").pop(),displayNameOverrideSource:"schema_identifier"});p.ok&&t.push({type:p.reference,docs:o.description});let _=this.context.getTypeIdFromSchemaReference(o);_!=null&&r.add(_);continue}let c=this.extendSubSchema(o),d=this.context.convertBreadcrumbsToName([`${this.id}_${a}`]),s=o.title,l=new SJi({context:this.context,id:d,nameOverride:s,breadcrumbs:[...this.breadcrumbs,`oneOf[${a}]`],schema:c??o}).convert();if(l!=null){let p=l.convertedSchema.typeDeclaration.shape;p.type==="alias"&&this.typeReferenceIsWrappedPrimitive(p.aliasOf)?t.push({type:p.aliasOf,docs:o.description}):p.type==="object"&&p.properties.length===0&&p.extends.length===0?t.push({type:ii.container(Es.map({keyType:Oa.STRING,valueType:ii.unknown()})),docs:o.description}):(t.push({type:this.context.createNamedTypeReference(d,s),docs:o.description}),i={...i,...l.inlinedTypes,[d]:l.convertedSchema}),l.convertedSchema.typeDeclaration.referencedTypes.forEach(_=>{r.add(_)})}}return{type:Al.undiscriminatedUnion({members:t}),referencedTypes:r,inlinedTypes:i}}shouldConvertAsNullableSchemaOrReference(){return this.schema.oneOf!=null?this.schema.oneOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):this.schema.anyOf!=null?this.schema.anyOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):!1}removeNullFromOneOfOrAnyOf(){let t=this.schema.oneOf??this.schema.anyOf,r=this.schema.oneOf!=null?"oneOf":"anyOf";if(t==null)return;let i=t.filter(n=>!("type"in n&&n.type==="null"));if(i.length===0){this.context.errorCollector.collect({message:`Received ${r} schema with no valid non-null types`,path:this.breadcrumbs});return}return i.length===1?{...this.schema,[r]:void 0,...i[0]}:{...this.schema,[r]:i}}convertAsNullableSchemaOrReference(){let t=this.removeNullFromOneOfOrAnyOf();if(t==null)return;let i=new jW({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(i==null)return;let n=this.wrapInNullable(i.type);return{type:Al.alias({aliasOf:n,resolvedType:n}),referencedTypes:i.schema?.typeDeclaration.referencedTypes??new Set,inlinedTypes:i.inlinedTypes}}typeReferenceIsWrappedPrimitive(t){switch(t.type){case"container":return this.containerTypeIsWrappedPrimitive(t.container);case"named":return!1;case"primitive":return!0;case"unknown":return!0;default:return!1}}containerTypeIsWrappedPrimitive(t){switch(t.type){case"list":return this.typeReferenceIsWrappedPrimitive(t.list);case"map":return this.typeReferenceIsWrappedPrimitive(t.keyType)&&this.typeReferenceIsWrappedPrimitive(t.valueType);case"nullable":return this.typeReferenceIsWrappedPrimitive(t.nullable);case"optional":return this.typeReferenceIsWrappedPrimitive(t.optional);case"set":return this.typeReferenceIsWrappedPrimitive(t.set);case"literal":return!0;default:return!1}}wrapInNullable(t){return ii.container(Es.nullable(t))}mergeIntoObjectSchema(t,r){return{...t,properties:{...r,...t.properties??{}}}}extendSubSchema(t){if(Object.entries(this.schema.properties??{}).length===0)return t;if(t.type==="object")return this.mergeIntoObjectSchema(t,this.schema.properties??{});this.context.isObjectSchemaType(t)||this.context.errorCollector.collect({message:"Received additional object properties for oneOf/anyOf that are not objects",path:this.breadcrumbs})}getDiscriminatorKeyForRef(t){return Object.entries(this.schema.discriminator?.mapping??{}).find(([r,i])=>i===t.$ref)?.[0]}};var Aoa=class extends Oa{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){switch(this.schema.type){case"string":{let t=this.context.getAsString(this.schema.const);if(t!=null)return ii.container(Es.literal(lF.string(t)));if(this.context.settings.typeDatesAsStrings===!1){if(this.schema.format==="date")return ii.primitive({v1:ku.Date,v2:vn.date({})});if(this.schema.format==="date-time")return ii.primitive({v1:ku.DateTime,v2:vn.dateTime({})})}return ii.primitive({v1:"STRING",v2:vn.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":switch(this.schema.format){case"double":return ii.primitive({v1:"DOUBLE",v2:vn.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return ii.primitive({v1:"FLOAT",v2:vn.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return ii.primitive({v1:"INTEGER",v2:vn.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return ii.primitive({v1:"LONG",v2:vn.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return ii.primitive({v1:"UINT",v2:vn.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return ii.primitive({v1:"UINT_64",v2:vn.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return ii.primitive({v1:"DOUBLE",v2:vn.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"integer":switch(this.schema.format){case"double":return ii.primitive({v1:"DOUBLE",v2:vn.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return ii.primitive({v1:"FLOAT",v2:vn.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return ii.primitive({v1:"INTEGER",v2:vn.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return ii.primitive({v1:"LONG",v2:vn.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return ii.primitive({v1:"UINT",v2:vn.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return ii.primitive({v1:"UINT_64",v2:vn.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return ii.primitive({v1:"INTEGER",v2:vn.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"boolean":{let t=this.context.getAsBoolean(this.schema.const);return t!=null?ii.container(Es.literal(lF.boolean(t))):ii.primitive({v1:"BOOLEAN",v2:vn.boolean({default:this.schema.default})})}default:return}}getNumberValidation(t){let r=t.minimum,i=t.maximum,n,a;return typeof t.exclusiveMinimum=="boolean"?n=t.exclusiveMinimum:typeof t.exclusiveMinimum=="number"&&(r=t.exclusiveMinimum,n=!0),typeof t.exclusiveMaximum=="boolean"?a=t.exclusiveMaximum:typeof t.exclusiveMaximum=="number"&&(i=t.exclusiveMaximum,a=!0),{max:i,min:r,exclusiveMax:a,exclusiveMin:n,multipleOf:t.multipleOf}}getStringValidation(t){return{minLength:t.minLength,maxLength:t.maxLength,pattern:t.pattern,format:t.format}}};var HVD=["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],SJi=class e extends Oa{schema;id;inlined;audiences;nameOverride;constructor({context:t,breadcrumbs:r,schema:i,id:n,inlined:a=!1,nameOverride:o}){super({context:t,breadcrumbs:r}),this.schema=i,this.id=n,this.inlined=a,this.nameOverride=o,this.audiences=this.context.getAudiences({operation:this.schema,breadcrumbs:this.breadcrumbs})??[]}convert(){let t=this.tryConvertFernTypeDeclaration();if(t!=null)return t;let r=this.tryConvertEnumSchema();if(r!=null)return r;let i=this.tryConvertSingularAllOfSchema();if(i!=null)return i;let n=this.tryConvertPrimitiveSchema();if(n!=null)return n;let a=this.tryConvertArraySchema();if(a!=null)return a;let o=this.tryConvertTypeArraySchema();if(o!=null)return o;let c=this.tryConvertOneOfAnyOfSchema();if(c!=null)return c;let d=this.tryConvertMapSchema();if(d!=null)return d;let s=this.tryConvertDiscriminatorMappingSchema();if(s!=null)return s;let u=this.tryConvertObjectAllOfSchema();if(u!=null)return u;let l=this.tryConvertUntypedSchema();if(l!=null)return l;this.context.errorCollector.collect({message:`Failed to convert schema object: ${JSON.stringify(this.schema,null,2)}`,path:this.breadcrumbs})}tryConvertEnumSchema(){if(!this.schema.enum?.length)return;let r=new NR.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),n=new Ooa({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,maybeFernEnum:r}).convert();if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:n.type,referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertSingularAllOfSchema(){if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&this.schema.allOf?.length===1&&this.schema.allOf[0]!=null){let r=this.context.resolveMaybeReference({schemaOrReference:this.schema.allOf[0],breadcrumbs:this.breadcrumbs});if(r!=null){let n=new e({context:this.context,breadcrumbs:[...this.breadcrumbs,"allOf","0"],schema:r,id:this.id,inlined:!0}).convert();if(n?.convertedSchema.typeDeclaration?.shape.type!=="object")return n}}if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&Array.isArray(this.schema.allOf)&&this.schema.allOf.length>=1){let r={};for(let n of this.schema.allOf??[]){if(this.context.isReferenceObject(n))return;r=d$n(r,n,(a,o)=>{if(o===n)return a;if(Array.isArray(a)&&Array.isArray(o))return[...a,...o]})}return new e({context:this.context,breadcrumbs:this.breadcrumbs,schema:r,id:this.id,inlined:!0}).convert()}}tryConvertPrimitiveSchema(){let r=new Aoa({context:this.context,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Al.alias({aliasOf:r,resolvedType:r}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertArraySchema(){if(this.schema.type==="array"){let r=new Poa({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Al.alias({aliasOf:r.typeReference,resolvedType:r.typeReference}),referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertTypeArraySchema(){if(Array.isArray(this.schema.type)&&this.schema.type.length>0)return this.schema.type.length===1?this.schema.type=this.schema.type[0]:(this.schema.oneOf=this.schema.type.map(t=>({type:t})),this.schema.type=void 0),this.convert()}tryConvertOneOfAnyOfSchema(){if(this.schema.oneOf!=null||this.schema.anyOf!=null){let r=new Jbn({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,inlinedTypes:{}}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertMapSchema(){if((typeof this.schema.additionalProperties=="object"||typeof this.schema.additionalProperties=="boolean")&&this.schema.additionalProperties!=null&&!this.schema.properties&&!this.schema.allOf){if(typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties===!1)return;let r=new bpu({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReferenceOrBoolean:this.schema.additionalProperties}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertDiscriminatorMappingSchema(){if(this.schema.discriminator?.mapping!=null&&Object.keys(this.schema.discriminator.mapping).length>0&&this.schema.oneOf==null&&this.schema.anyOf==null){let t={...this.schema,oneOf:Object.values(this.schema.discriminator.mapping).map(n=>({$ref:n}))},i=new Jbn({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:t,inlinedTypes:{}}).convert();if(i!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:i.type,referencedTypes:i.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:i.inlinedTypes}}}tryConvertObjectAllOfSchema(){if(this.schema.type==="object"||this.schema.properties!=null||this.schema.allOf!=null){let r=new moa({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:r.propertiesByAudience},inlinedTypes:r.inlinedTypes}}}tryConvertUntypedSchema(){if(this.isUntypedSchema())return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Al.alias({aliasOf:ii.unknown(),resolvedType:ii.unknown()}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertFernTypeDeclaration(){let r=new NR.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r==null)return;let i=Vph(r);if(i!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Al.alias({aliasOf:i,resolvedType:i}),referencedTypes:new Set,omitV2Examples:!0}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}createTypeDeclaration({shape:t,referencedTypes:r,omitV2Examples:i}){return{name:this.convertDeclaredTypeName(),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs}),docs:this.schema.description,referencedTypes:r,source:void 0,inline:this.inlined,v2Examples:i?void 0:this.convertSchemaExamples()}}convertDeclaredTypeName(){return{typeId:this.id,fernFilepath:this.context.createFernFilepath(),name:this.context.casingsGenerator.generateName(this.id),displayName:this.nameOverride}}schemaOnlyHasAllowedKeys(t){let r=[...HVD,...t];return Object.keys(this.schema).every(n=>r.includes(n))}isUntypedSchema(){return!!(this.schema&&typeof this.schema=="object"&&!("oneOf"in this.schema)&&!("anyOf"in this.schema)&&!("allOf"in this.schema)&&!("items"in this.schema)&&!("properties"in this.schema))}convertSchemaExamples(){let t={userSpecifiedExamples:{},autogeneratedExamples:{}},r=this.context.getExamplesFromSchema({schema:this.schema,breadcrumbs:this.breadcrumbs});if(r.length===0){let i=this.generateOrValidateExample({example:void 0,ignoreErrors:!0});return t.autogeneratedExamples={[`${this.id}_example_autogenerated`]:i},t}return t.userSpecifiedExamples=this.convertUserSpecifiedExamples(r),t}convertUserSpecifiedExamples(t){let r={};for(let[i,n]of t.entries()){let a=this.context.resolveExample(n),o=this.generateOrValidateExample({example:a});r[`${this.id}_example_${i}`]=o}return r}generateOrValidateExample({example:t,ignoreErrors:r}){let i=new gF({breadcrumbs:this.breadcrumbs,context:this.context,schema:this.schema,example:t}),{validExample:n,errors:a}=i.convert();return r||a.forEach(o=>{this.context.errorCollector.collect({message:o.message,path:o.path})}),n}};var jW=class extends Oa{schemaOrReference;schemaIdOverride;wrapAsOptional;wrapAsNullable;constructor({context:t,breadcrumbs:r,schemaOrReference:i,schemaIdOverride:n,wrapAsOptional:a=!1,wrapAsNullable:o=!1}){super({context:t,breadcrumbs:r}),this.schemaOrReference=i,this.schemaIdOverride=n,this.wrapAsOptional=a,this.wrapAsNullable=o}convert(){let t=this.maybeConvertReferenceObject({schemaOrReference:this.schemaOrReference});if(t!=null)return t;let r=this.maybeConvertSingularAllOfReferenceObject();return r??this.convertSchemaObject({schema:this.schemaOrReference})}maybeConvertReferenceObject({schemaOrReference:t}){if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:r.inlinedTypes??{}}}}maybeConvertSingularAllOfReferenceObject(){if(this.context.isReferenceObject(this.schemaOrReference)||this.schemaOrReference.allOf==null||this.schemaOrReference.allOf.length!==1)return;let t=this.schemaOrReference.allOf[0];if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:{}}}}convertSchemaObject({schema:t}){let r=this.schemaIdOverride??this.context.convertBreadcrumbsToName(this.breadcrumbs),i=new SJi({context:this.context,breadcrumbs:this.breadcrumbs,schema:t,id:r}),n=this.context.getAvailability({node:t,breadcrumbs:this.breadcrumbs}),a=i.convert();if(a!=null){let o=a.convertedSchema.typeDeclaration.shape;return o.type==="alias"?{type:this.wrapTypeReference(o.aliasOf),schema:a.convertedSchema,inlinedTypes:a.inlinedTypes,availability:n}:{type:this.wrapTypeReference(this.context.createNamedTypeReference(r)),schema:a.convertedSchema,inlinedTypes:{...a.inlinedTypes,[r]:a.convertedSchema},availability:n}}}wrapTypeReference(t){return this.wrapAsOptional&&this.wrapAsNullable?this.wrapInOptional(this.wrapInNullable(t)):this.wrapAsOptional?this.wrapInOptional(t):this.wrapAsNullable?this.wrapInNullable(t):t}wrapInOptional(t){return ii.container(Es.optional(t))}wrapInNullable(t){return ii.container(Es.nullable(t))}};var Poa=class e extends Oa{static LIST_UNKNOWN=ii.container(Es.list(ii.unknown()));schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){if(this.schema.items!=null){Array.isArray(this.schema.items)&&(this.schema.items={oneOf:this.schema.items});let r=new jW({context:this.context,breadcrumbs:[...this.breadcrumbs,"items"],schemaOrReference:this.schema.items}).convert();if(r!=null){let i=new Set;for(let n of r.schema?.typeDeclaration.referencedTypes??[])i.add(n);return r.inlinedTypes!=null&&Object.values(r.inlinedTypes).forEach(n=>{n.typeDeclaration.referencedTypes.forEach(a=>{i.add(a)})}),{typeReference:ii.container(Es.list(r.type)),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var gpu=class extends Oa{group;method;constructor({context:t,breadcrumbs:r,group:i,method:n}){super({context:t,breadcrumbs:r}),this.group=i,this.method=n}parseMediaTypeObject({mediaTypeObject:t,resolveSchema:r,contentType:i,schemaId:n}){if(t.schema==null)return;if(r){let d=this.context.resolveMaybeReference({schemaOrReference:t.schema,breadcrumbs:[...this.breadcrumbs,"content",i]});if(d==null)return;t.schema=d}let o=new jW({context:this.context,breadcrumbs:[...this.breadcrumbs,"content",i,"schema"],schemaOrReference:t.schema,schemaIdOverride:n}).convert();if(o==null)return;let c=t.examples!=null?Object.fromEntries(Object.entries(t.examples).map(([d,s])=>{if(this.context.isReferenceObject(s)){let u=this.context.resolveReference({reference:s,breadcrumbs:[...this.breadcrumbs,"content",i,"examples"],skipErrorCollector:!0});return u.resolved?[d,u.value.value??u.value]:null}return[d,s.value??s]}).filter(d=>d!=null)):void 0;return{...o,examples:c}}parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:r}){let n=new jW({context:this.context,breadcrumbs:[...this.breadcrumbs],schemaOrReference:t,schemaIdOverride:r}).convert();if(n!=null)return{...n,examples:void 0}}convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:r,exampleGenerationStrategy:i}){let n={userSpecifiedExamples:{},autogeneratedExamples:{}},a=t?.schema,o=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_example`});for(let[c,d]of o){let s=this.context.resolveExampleWithValue(d),u=this.context.isExampleWithSummary(d)?d.summary:c;s!=null&&(a!=null?n.userSpecifiedExamples[u]=this.generateOrValidateExample({schema:a,example:s,exampleGenerationStrategy:i}):n.userSpecifiedExamples[u]=s)}if(Object.keys(n.userSpecifiedExamples).length===0&&a!=null){let c=ou(`${[...this.group,this.method].join("_")}_example`);n.autogeneratedExamples[c]=this.generateOrValidateExample({schema:a,example:void 0,ignoreErrors:!0,generateOptionalProperties:r,exampleGenerationStrategy:i})}return n}generateOrValidateExample({schema:t,example:r,ignoreErrors:i,generateOptionalProperties:n,exampleGenerationStrategy:a}){let o=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(o==null)return;let c=this.context.getExamplesFromSchema({schema:o,breadcrumbs:this.breadcrumbs}),d=new gF({breadcrumbs:this.breadcrumbs,context:this.context,schema:o,example:r??c[0],generateOptionalProperties:n??!1,exampleGenerationStrategy:a}),{validExample:s,errors:u}=d.convert();return i||u.forEach(l=>{this.context.errorCollector.collect({message:l.message,path:l.path})}),s}};var Opu=class extends Oa{parameter;constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r}),this.parameter=i}convertToOutput({schema:t,typeReference:r,inlinedTypes:i}){let n=this.context.getAvailability({node:this.parameter,breadcrumbs:this.breadcrumbs}),a=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs}),o=this.getParameterSchemaWithExampleOverride({schema:a});switch(this.parameter.in){case"query":return{type:"query",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??Oa.OPTIONAL_STRING,allowMultiple:this.parameter.explode??!1,v2Examples:this.convertParameterExamples({schema:o??t}),availability:n,explode:this.getExplodeForQueryParameter()},inlinedTypes:i};case"header":return{type:"header",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??Oa.OPTIONAL_STRING,env:void 0,v2Examples:this.convertParameterExamples({schema:o??t}),availability:n},inlinedTypes:i};case"path":return{type:"path",parameter:{name:this.context.casingsGenerator.generateName(this.parameter.name),docs:this.parameter.description,valueType:r??Oa.STRING,location:"ENDPOINT",variable:void 0,v2Examples:this.convertParameterExamples({schema:o??t}),explode:this.getExplodeForPathParameter()},inlinedTypes:i};default:return}}getParameterSchemaWithExampleOverride({schema:t}){if(t!=null)return t.type==="string"&&t.example==null?{...t,example:this.parameter.name}:t}convertParameterExamples({schema:t}){let r={userSpecifiedExamples:{},autogeneratedExamples:{}},i=this.parameter.example,n=this.parameter.examples;for(let[a,o]of Object.entries(n??{})){let c=this.context.resolveExampleWithValue(o);c!=null&&(r.userSpecifiedExamples[a]=this.generateOrValidateExample({schema:t,example:c}))}if(i!=null){let a=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(r.userSpecifiedExamples)});r.userSpecifiedExamples[a]=this.generateOrValidateExample({schema:t,example:i})}if(Object.keys(r.userSpecifiedExamples).length===0){let a=`${this.parameter.name}_example`;r.autogeneratedExamples[a]=this.generateOrValidateExample({schema:t,example:void 0,ignoreErrors:!0})}return r}generateOrValidateExample({schema:t,ignoreErrors:r,example:i}){let n=new gF({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:i}),{validExample:a,errors:o}=n.convert();return r||o.forEach(c=>{this.context.errorCollector.collect({message:c.message,path:c.path})}),a}getExplodeForQueryParameter(){let t=this.parameter.style??"form",r=this.parameter.explode;if(r!==void 0)return t==="form"?r===!0?void 0:r:r===!1?void 0:r}getExplodeForPathParameter(){let t=this.parameter.explode;if(t!==void 0)return t===!1?void 0:t}};var mpu=class extends fl{server;key="x-fern-server-name";constructor({breadcrumbs:t,server:r,context:i}){super({breadcrumbs:t,context:i}),this.server=r}convert(){let t=this.getExtensionValue(this.server,"x-name");if(!(t==null||typeof t!="string"))return t}};var Wph="Base",tge=class e extends Oa{servers;endpointLevelServers;constructor({breadcrumbs:t,context:r,servers:i,endpointLevelServers:n}){super({breadcrumbs:t,context:r}),this.servers=i,this.endpointLevelServers=n}convert(){if(this.servers==null||this.servers.length===0||this.servers[0]==null)return;if(this.endpointLevelServers!=null&&this.endpointLevelServers.length>0){let r=this.getDefaultBaseUrlName(),i={id:r,name:this.context.casingsGenerator.generateName(r)},n=this.endpointLevelServers.map(c=>{let d=e.getServerName({server:c,context:this.context});return{id:d,name:this.context.casingsGenerator.generateName(d)}}).filter((c,d,s)=>s.findIndex(u=>u.id===c.id)===d),a=[i,...n],o=this.servers.map(c=>{let d=e.getServerName({server:c,context:this.context}),s=this.endpointLevelServers?.map(u=>[e.getServerName({server:u,context:this.context}),this.getServerUrl(u)]);return{id:d,name:this.context.casingsGenerator.generateName(d),urls:{[r]:this.getServerUrl(c),...Object.fromEntries(s??[])},docs:c.description}});return{value:{defaultEnvironment:o[0]?.id,environments:SM.multipleBaseUrls({baseUrls:a,environments:o})},defaultUrl:i.id}}let t=this.withExplodedServers(this.servers).map(r=>{let i=e.getServerName({server:r,context:this.context});return{id:i,name:this.context.casingsGenerator.generateName(i),url:this.maybeRemoveTrailingSlashIfNotEmpty(this.getServerUrl(r)),docs:r.description}}).filter(us);return{value:{defaultEnvironment:t[0]?.id,environments:SM.singleBaseUrl({environments:t})},defaultUrl:t[0]?.id}}static getServerExtensionName({server:t,context:r}){return new mpu({breadcrumbs:[],server:t,context:r}).convert()}static getServerName({server:t,context:r}){return t.name!=null?t.name:e.getServerExtensionName({server:t,context:r})??t.description??t.url}getServerUrl(t){if(t.variables==null)return t.url;let r=t.url;for(let[i,n]of Object.entries(t.variables))n.default!=null&&(r=r.replace(`{${i}}`,encodeURIComponent(n.default)));return r}withExplodedServers(t){return t.flatMap(r=>{if(r.variables==null)return[r];let i=Object.entries(r.variables).filter(([c,d])=>d.enum!=null&&d.enum.length>0);if(i.length===0)return[r];let n=i[0];if(n==null)return[r];let[a,o]=n;return o.enum==null?[r]:o.enum.map(c=>{let d=r.url.replace(`{${a}}`,encodeURIComponent(c)),s={};for(let[l,p]of Object.entries(r.variables??{}))l!==a&&(s[l]=p);let u={...r,url:d,variables:Object.keys(s).length>0?s:void 0,"x-fern-server-name":r.description?`${r.description}_${c}`:`${c}`,description:r.description};return this.withExplodedServers([u])[0]})}).filter(us)}getDefaultBaseUrlName(){return this.servers==null||this.servers.length===0||this.servers[0]==null?Wph:e.getServerExtensionName({server:this.servers[0],context:this.context})??Wph}maybeRemoveTrailingSlashIfNotEmpty(t){return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}};var $bn=class{context;constructor({context:t}){this.context=t}validateExample({example:t,schema:r,breadcrumbs:i,exampleGenerationStrategy:n}){return new gF({breadcrumbs:i,context:this.context,schema:r,example:t,depth:0,exampleGenerationStrategy:n,generateOptionalProperties:!1}).convert()}validateEndpointExample({exampleToValidate:t}){let r=[],i=[],n=!0,a=!1,o,c=[t.endpointPath,t.method];if(t.requestExample!==void 0&&t.requestSchema!==void 0){let s=this.validateExample({example:t.requestExample,schema:t.requestSchema,breadcrumbs:[...c,"request"],exampleGenerationStrategy:"request"});if(!s.isValid){n=!1;let u=t.exampleSource==="human"?zR.WARNING:zR.ERROR;r.push(...s.errors.map(l=>({...l,level:u,message:`Invalid request example: ${l.message}`})))}s.coerced&&(a=!0,i.push({level:zR.WARNING,message:"Request example was coerced to match schema",path:[...c,"request"]})),o={request:s.validExample}}let d=this.getResponseSchemaForValidation(t);if(t.responseExample!==void 0&&d!==void 0){let s=this.validateExample({example:t.responseExample,schema:d,breadcrumbs:[...c,"response"],exampleGenerationStrategy:"response"});if(!s.isValid){n=!1;let u=t.exampleSource==="human"?zR.WARNING:zR.ERROR;r.push(...s.errors.map(l=>({...l,level:u,message:`Invalid response example: ${l.message}`})))}s.coerced&&(a=!0,i.push({level:zR.WARNING,message:"Response example was coerced to match schema",path:[...c,"response"]})),o={...typeof o=="object"&&o!==null?o:{},response:s.validExample}}return{isValid:n,errors:r,warnings:i,endpointPath:t.endpointPath,method:t.method,exampleSource:t.exampleSource,exampleName:t.exampleName,validExample:o,coerced:a}}getResponseSchemaForValidation(t){let{responseStatusCode:r,responseSchemas:i,responseSchema:n}=t;return i&&Object.keys(i).length>0?r&&i[r]?i[r]:i[200]??i[201]:n}validateAiExamples({aiExamples:t,spec:r}){let i=[],n=[];for(let a of t){let{requestSchema:o,responseSchema:c,responseSchemas:d}=this.getSchemasForEndpoint({spec:r,endpointPath:a.endpointPath,method:a.method}),s={endpointPath:a.endpointPath,method:a.method,exampleSource:"ai",requestExample:a.request?.body,responseExample:a.response?.body,requestSchema:o,responseSchema:c,responseSchemas:d},u=this.validateEndpointExample({exampleToValidate:s}),l=this.hasUnexpectedProperties({requestExample:a.request?.body,responseExample:a.response?.body,requestSchema:o,responseSchema:c}),p=u.errors.length>0||u.warnings.length>0;!u.isValid||p||l?n.push({example:a,validationResult:u}):i.push(a)}return{validExamples:i,invalidExamples:n}}hasUnexpectedProperties({requestExample:t,responseExample:r,requestSchema:i,responseSchema:n}){return!!(t&&i&&this.exampleHasUnexpectedProperties(t,i)||r&&n&&this.exampleHasUnexpectedProperties(r,n))}exampleHasUnexpectedProperties(t,r){if(!t||typeof t!="object"||t===null)return!1;let i=this.context.resolveMaybeReference({schemaOrReference:r,breadcrumbs:[],skipErrorCollector:!0});if(!i||!i.properties)return!1;let n=t,a=new Set(Object.keys(i.properties));return Object.keys(n).some(c=>!a.has(c))}validateHumanExamples({spec:t}){let r=[],i=0,n=0,a=0,o=[],c=[];if(!t.paths)return{endpoints:r,totalExamples:i,validExamples:n,invalidExamples:a,hasInvalidHumanExamples:!1,hasInvalidAiExamples:!1,invalidHumanExamples:o,invalidAiExamples:c};for(let[d,s]of Object.entries(t.paths)){if(!s)continue;let u=["get","post","put","delete","patch","options","head","trace"];for(let l of u){let p=s[l];if(!p)continue;let _=[],{requestSchema:h,responseSchema:y,responseSchemas:b}=this.getSchemasForOperation({operation:p}),v=this.extractExamplesFromOperation({operation:p,path:d,method:l});for(let g of v){i++;let m={endpointPath:d,method:l,exampleName:g.name,exampleSource:g.source,requestExample:g.request,responseExample:g.response,requestSchema:h,responseSchema:y,responseStatusCode:g.statusCode,responseSchemas:b},O=this.validateEndpointExample({exampleToValidate:m});_.push(O),O.isValid?n++:(a++,g.source==="human"?o.push(O):g.source==="ai"&&c.push(O))}_.length>0&&r.push({endpointPath:d,method:l,results:_,hasInvalidExamples:_.some(g=>!g.isValid),invalidExampleCount:_.filter(g=>!g.isValid).length})}}return{endpoints:r,totalExamples:i,validExamples:n,invalidExamples:a,hasInvalidHumanExamples:o.length>0,hasInvalidAiExamples:c.length>0,invalidHumanExamples:o,invalidAiExamples:c}}getSchemasForEndpoint({spec:t,endpointPath:r,method:i}){let n=t.paths?.[r];if(!n)return{responseSchemas:{}};let a=n[i.toLowerCase()];return!a||typeof a!="object"||!("responses"in a)?{responseSchemas:{}}:this.getSchemasForOperation({operation:a})}getSchemasForOperation({operation:t}){let r,i,n={};if(t.requestBody&&!this.context.isReferenceObject(t.requestBody)){let o=t.requestBody.content?.["application/json"];o?.schema&&(r=o.schema)}if(t.responses){for(let[a,o]of Object.entries(t.responses)){if(!o||this.context.isReferenceObject(o))continue;let d=o.content?.["application/json"];d?.schema&&(n[a]=d.schema)}i=n[200]??n[201]}return{requestSchema:r,responseSchema:i,responseSchemas:n}}extractExamplesFromOperation({operation:t,path:r,method:i}){let n=[];if(t.requestBody&&!this.context.isReferenceObject(t.requestBody)){let c=t.requestBody.content?.["application/json"];if(c?.example!==void 0&&n.push({name:`${i}_${r}_request_example`,source:"openapi",request:c.example}),c?.examples)for(let[d,s]of Object.entries(c.examples)){let u=this.context.isReferenceObject(s)?this.context.resolveExample(s):s;u&&typeof u=="object"&&"value"in u&&n.push({name:d,source:"human",request:u.value})}}if(t.responses)for(let[o,c]of Object.entries(t.responses)){if(!c||this.context.isReferenceObject(c))continue;let s=c.content?.["application/json"];if(s?.example!==void 0){let u=n.find(l=>l.request!==void 0&&l.response===void 0);u?(u.response=s.example,u.statusCode=o):n.push({name:`${i}_${r}_response_${o}_example`,source:"openapi",response:s.example,statusCode:o})}if(s?.examples)for(let[u,l]of Object.entries(s.examples)){let p=this.context.isReferenceObject(l)?this.context.resolveExample(l):l;if(p&&typeof p=="object"&&"value"in p){let _=n.find(h=>h.name===u);_?(_.response=p.value,_.statusCode=o):n.push({name:u,source:"human",response:p.value,statusCode:o})}}}let a=t["x-fern-examples"];if(Array.isArray(a)){for(let o of a)if(typeof o=="object"&&o!==null){let c=o;n.push({name:c.name,source:"human",request:c.request?.body,response:c.response?.body})}}return n}};var Apu={400:"BadRequestError",401:"UnauthorizedError",402:"PaymentRequiredError",403:"ForbiddenError",404:"NotFoundError",405:"MethodNotAllowedError",406:"NotAcceptableError",407:"ProxyAuthenticationRequiredError",408:"RequestTimeoutError",409:"ConflictError",410:"GoneError",411:"LengthRequiredError",412:"PreconditionFailedError",413:"ContentTooLargeError",414:"URITooLongError",415:"UnsupportedMediaTypeError",416:"RangeNotSatisfiableError",417:"ExpectationFailedError",418:"ImATeapotError",419:"AuthenticationTimeoutError",420:"MethodFailureError",421:"MisdirectedRequestError",422:"UnprocessableEntityError",423:"LockedError",424:"FailedDependencyError",425:"TooEarlyError",426:"UpgradeRequiredError",428:"PreconditionError",429:"TooManyRequestsError",430:"RequestHeaderFieldsTooLargeError",431:"RequestHeaderFieldsTooLargeError",444:"NoResponseError",449:"RetryWithError",450:"BlockedByWindowsParentalControlsError",451:"UnavailableForLegalReasonsError",498:"InvalidTokenError",499:"ClientClosedRequestError",500:"InternalServerError",501:"NotImplementedError",502:"BadGatewayError",503:"ServiceUnavailableError",504:"GatewayTimeoutError",505:"HTTPVersionNotSupportedError",506:"VariantAlsoNegotiatesError",507:"InsufficientStorageError",508:"LoopDetectedError",509:"BandwidthLimitExceededError",510:"NotExtendedError",511:"NetworkAuthenticationRequiredError"},KVD=new Set(Object.values(Apu));var joa=class{enabled=!0;write(t,...r){this.enabled&&process.stderr.write(`[${t}] ${r.join(" ")}
1468
+ `)}var W7a=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}};function WGc(e){return e.scheme==="oauth"}var kLD={optional:"optional",nullable:"nullable",set:"set",list:"list",map:"map",literal:"literal"},dph=new Set(Object.values(kLD));function ED(e){let t=e.match(/([\w.]+)<([\w,\s]+)>/);if(t?.[0]!=null&&t[1]!=null&&t[2]!=null&&!dph.has(t[1].trim()))return{name:t[1].trim(),arguments:t[2].split(",").map(r=>r.trim())}}function VEe(e){return ED(e)!=null}function GGc(e){if(e.request!=null)return typeof e.request=="string"?e.request:e.request.body}var zbn=class{REFERENCE_REGEX=/^(GET|POST|PUT|DELETE|PATCH|HEAD)\s(\/\S*)$/;validate(t){return this.REFERENCE_REGEX.test(t)?{type:"valid"}:{type:"invalid"}}tryParse(t){if(this.validate(t).type==="invalid")return;let i=t.match(this.REFERENCE_REGEX);if(!(i==null||i[1]==null||i[2]==null))return{method:i[1],path:i[2]}}};function fw(e){return typeof e=="string"?!1:e?.extends!=null||e?.properties!=null}function CYt(e){return e?e.proto!=null:!1}var eVD="text";function AJi(e){return e===eVD}var px={integer:"integer",long:"long",uint:"uint",uint64:"uint64",float:"float",double:"double",boolean:"boolean",string:"string",datetime:"datetime",base64:"base64",uuid:"uuid",date:"date",bigint:"bigint",unknown:"unknown"};var sY={MAP:/^map<\s*([^,]*)\s*,\s*(.*)\s*>$/,LIST:/^list<\s*(.*)\s*>$/,SET:/^set<\s*(.*)\s*>$/,OPTIONAL:/^optional<\s*(.*)\s*>$/,NULLABLE:/^nullable<\s*(.*)\s*>$/,LITERAL:/^literal<\s*(?:"(.*)"|(true|false))\s*>$/};function Nbn({type:e,_default:t,validation:r,visitor:i}){switch(e){case px.integer:{let u=r??void 0;return i.primitive({v1:ku.Integer,v2:vn.integer({default:t??void 0,validation:u!=null?{min:u.min,max:u.max,exclusiveMin:u.exclusiveMin,exclusiveMax:u.exclusiveMax,multipleOf:u.multipleOf}:void 0})})}case px.double:{let u=r??void 0;return i.primitive({v1:ku.Double,v2:vn.double({default:t??void 0,validation:u!=null?{min:u.min,max:u.max,exclusiveMin:u.exclusiveMin,exclusiveMax:u.exclusiveMax,multipleOf:u.multipleOf}:void 0})})}case px.string:{let u=r??void 0;return i.primitive({v1:ku.String,v2:vn.string({default:t??void 0,validation:u!=null?{format:u.format,pattern:u.pattern,minLength:u.minLength,maxLength:u.maxLength}:void 0})})}case px.float:return i.primitive({v1:ku.Float,v2:void 0});case px.long:{let u=r??void 0;return i.primitive({v1:ku.Long,v2:vn.long({default:t??void 0,validation:u!=null?{min:u.min,max:u.max,exclusiveMin:u.exclusiveMin,exclusiveMax:u.exclusiveMax,multipleOf:u.multipleOf}:void 0})})}case px.boolean:return i.primitive({v1:ku.Boolean,v2:vn.boolean({default:t??void 0})});case px.datetime:return i.primitive({v1:ku.DateTime,v2:void 0});case px.date:return i.primitive({v1:ku.Date,v2:void 0});case px.uuid:return i.primitive({v1:ku.Uuid,v2:void 0});case px.base64:return i.primitive({v1:ku.Base64,v2:void 0});case px.bigint:return i.primitive({v1:ku.BigInteger,v2:vn.bigInteger({default:t??void 0})});case px.uint:return i.primitive({v1:ku.Uint,v2:void 0});case px.uint64:return i.primitive({v1:ku.Uint64,v2:void 0});case px.unknown:return i.unknown()}let n=e.match(sY.MAP);if(n?.[1]!=null&&n[2]!=null)return i.map({keyType:n[1],valueType:n[2]});let a=e.match(sY.LIST);if(a?.[1]!=null)return i.list(a[1]);let o=e.match(sY.SET);if(o?.[1]!=null)return i.set(o[1]);let c=e.match(sY.OPTIONAL);if(c?.[1]!=null)return i.optional(c[1]);let d=e.match(sY.NULLABLE);if(d?.[1]!=null)return i.nullable(d[1]);let s=e.match(sY.LITERAL);if(s?.[1]!=null)return i.literal(lF.string(s[1]));if(s?.[2]!=null){let u=s[2];switch(u){case"false":return i.literal(lF.boolean(!1));case"true":return i.literal(lF.boolean(!0));default:throw new Error(`Unsupported literal value: ${u}`)}}return i.named(e)}var pph="bytes";function WEe(e){if(e===pph)return{isOptional:!1};if(e.match(sY.OPTIONAL)?.[1]===pph)return{isOptional:!0}}function G7a(e){let t=typeof e=="string"?e:typeof e.body=="string"?e.body:void 0;if(t!=null)return WEe(t)}function xGc({input:e,typeName:t}){for(let r of e.arguments)if(typeof r=="string"){if(r===t)return!0}else if(xGc({input:r,typeName:t}))return!0;return!1}function _ph(e){return xGc({input:e,typeName:"file"})}function hph(e){let t=0,r=0;function i(){for(;t<e.length&&/\s/.test(e[t]);)t++;if(t>=e.length)return;let a="";for(;t<e.length&&e[t]!=="<"&&e[t]!==","&&e[t]!==">";)a+=e[t++];if(a.trim()){for(;t<e.length&&/\s/.test(e[t]);)t++;if(t<e.length&&e[t]==="<"){if(t++,r++,r>128)throw new Error("Internal error; Exceeded maximum recursion depth while parsing generics.");let o={name:a.trim(),arguments:[]};for(;t<e.length&&e[t]!==">";){for(;t<e.length&&/[\s,]/.test(e[t]);)t++;if(t<e.length&&e[t]!==">"){let c=i();c&&o.arguments.push(c)}}if(t<e.length&&e[t]===">")t++,r--;else throw new Error("Malformed input: missing closing '>' for generic arguments.");return o}else return a.trim()}}let n=i();if(typeof n=="object")return n}var HGc="file";function yph(e){return e.match(sY.LIST)?.[1]===HGc}function cY(e){if(e===HGc)return{isOptional:!1,isArray:!1};let t=e.match(sY.OPTIONAL);if(t?.[1]!==void 0){if(t[1]===HGc)return{isOptional:!0,isArray:!1};if(yph(t[1]))return{isOptional:!0,isArray:!0}}if(yph(e))return{isOptional:!1,isArray:!0}}function tVD(e){return typeof e=="string"?!1:tm.parse(e["content-type"])?.isMultiPartFormData()??!1?!0:e.body==null?!1:!!(fw(e.body)&&Object.values(e.body.properties??[]).some(iVD))}function Fbn(e){if(!(!tVD(e)||e.body==null)&&e.name!=null&&e.body!=null&&fw(e.body))return rVD(e.name,e.body)}function rVD(e,t){let r=Object.entries(t.properties??[]).reduce((i,[n,a])=>{let o=typeof a!="string"?a.docs:void 0,c=typeof a!="string"?a["content-type"]:void 0,d=typeof a!="string"?a.style:void 0,s=cY(typeof a=="string"?a:a.type);return s!=null?i.push({isFile:!0,key:n,docs:o,isOptional:s.isOptional,isArray:s.isArray,contentType:c,style:d}):i.push({isFile:!1,key:n,propertyType:a,docs:o,contentType:c,style:d}),i},[]);return t["extra-properties"],{name:e,extends:t.extends,properties:r}}function iVD(e){let t=typeof e=="string"?e:e.type;if(t==="file")return!0;if(!t.includes("file"))return!1;let r=hph(t);return r==null?!1:_ph(r)}var bph="text";function Qbn(e){if(e===bph)return{isOptional:!1};if(e.match(sY.OPTIONAL)?.[1]===bph)return{isOptional:!0}}function hC({type:e,_default:t,validation:r,visitor:i}){return Nbn({type:e,_default:t,validation:r,visitor:{primitive:i.primitive,map:({keyType:n,valueType:a})=>i.map({keyType:hC({type:n,_default:void 0,validation:void 0,visitor:i}),valueType:hC({type:a,_default:void 0,validation:void 0,visitor:i})}),list:n=>i.list(hC({type:n,_default:void 0,validation:void 0,visitor:i})),set:n=>i.set(hC({type:n,_default:void 0,validation:void 0,visitor:i})),optional:n=>i.optional(hC({type:n,_default:t,validation:r,visitor:i})),nullable:n=>i.nullable(hC({type:n,_default:t,validation:r,visitor:i})),literal:i.literal,named:i.named,unknown:i.unknown}})}function KGc(e,t){if(nVD(e))return t.sdk(e);if(aVD(e))return t.language(e);vt(e)}function nVD(e){return e.sdk!=null}function aVD(e){return e.language!=null}function vph(e){return e["response-stream"]!=null&&(typeof e["response-stream"]=="string"||e["response-stream"].format==null||e["response-stream"].format==="json")}function gph(e){return e["response-stream"]!=null&&typeof e["response-stream"]!="string"&&e["response-stream"].format==="sse"}function Ubn(e,t,r){return oVD(e,t)?r.stream(t):uVD(e,t)?r.events(t):r.body(t)}function oVD(e,t){return t.stream!==void 0&&vph(e)}function uVD(e,t){return t.stream!==void 0&&gph(e)}function Lbn(e,t){if(Oph(e))return t.single(e);if(mph(e))return t.any(e);if(sVD(e))return t.endpointSecurity(e);vt(e)}function Oph(e){return typeof e=="string"||e.scheme!=null}function mph(e){let[t,...r]=Object.keys(e);return t==="any"&&r.length===0}function sVD(e){let[t,...r]=Object.keys(e);return t==="endpoint-security"&&r.length===0}function x7a(e,t){if(Aph(e))return t.header(e);switch(e.scheme){case"basic":return t.basic(e);case"bearer":return"get-token"in e?t.inferredBearer(e):t.tokenBearer(e);case"oauth":return t.oauth(e);default:vt(e)}}function Aph(e){return e.header!=null}function qYt(e,t){if(Pph(e))return t.singleBaseUrl(e);if(kve(e))return t.multipleBaseUrls(e);vt(e)}function Pph(e){return typeof e=="string"||"url"in e}function kve(e){return typeof e!="string"&&"urls"in e}function poa(e){return typeof e=="string"?e.startsWith("$"):"variable"in e}function yC(e,t){if(PJi(e))return t.alias(e);if(jJi(e))return t.discriminatedUnion(e);if(iv(e))return t.object(e);if(_oa(e))return t.undiscriminatedUnion(e);if(p8t(e))return t.enum(e);vt(e)}function PJi(e){return typeof e=="string"||e.type!=null}function iv(e){return e.extends!=null||e.properties!=null}function jJi(e){return e.union!=null&&e.discriminated==null}function _oa(e){let t=e;return t.union!=null&&t.discriminated!=null}function p8t(e){return e.enum!=null}function JGc({rawApiFileSchema:e,casingsGenerator:t}){if(e.auth==null)return{docs:void 0,requirement:qR.All,schemes:[]};let r=typeof e.auth!="string"?e.auth.docs:void 0;return Lbn(e.auth,{single:i=>{let n=jph({reference:i,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t});return{docs:r,requirement:qR.All,schemes:[n]}},any:({any:i})=>({docs:r,requirement:qR.Any,schemes:i.map(n=>jph({reference:n,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t}))}),endpointSecurity:()=>({docs:r,requirement:qR.EndpointSecurity,schemes:[]})})}function jph({reference:e,authSchemeDeclarations:t,casingsGenerator:r}){let i=(a,o)=>{let c=t?.[a];if(c==null)throw new Error("Unknown auth scheme: "+a);return x7a(c,{header:d=>PA.header({key:a,docs:o,name:r.generateNameAndWireValue({name:d.name??a,wireValue:d.header}),valueType:ii.primitive({v1:ku.String,v2:vn.string({default:void 0,validation:void 0})}),prefix:d.prefix,headerEnvVar:d.env}),basic:d=>wph({key:a,casingsGenerator:r,docs:o,rawScheme:d}),tokenBearer:d=>rpu({key:a,casingsGenerator:r,docs:o,rawScheme:d}),inferredBearer(d){return rpu({key:a,casingsGenerator:r,docs:o,rawScheme:void 0})},oauth:d=>rpu({key:a,casingsGenerator:r,docs:o,rawScheme:void 0})})},n=typeof e=="string"?e:e.scheme;switch(n){case"bearer":case"oauth":return rpu({key:n,casingsGenerator:r,docs:void 0,rawScheme:void 0});case"basic":return wph({key:n,casingsGenerator:r,docs:void 0,rawScheme:void 0});default:return i(n,typeof e!="string"?e.docs:void 0)}}function rpu({key:e,casingsGenerator:t,docs:r,rawScheme:i}){return PA.bearer({key:e,docs:r,token:t.generateName(i?.token?.name??"token"),tokenEnvVar:i?.token?.env})}function wph({key:e,casingsGenerator:t,docs:r,rawScheme:i}){return PA.basic({key:e,docs:r,username:t.generateName(i?.username?.name??"username"),usernameEnvVar:i?.username?.env,password:t.generateName(i?.password?.name??"password"),passwordEnvVar:i?.password?.env})}function DM(e){let t=lVD(e),{value:r,done:i}=$Gc(t,"{");return i?{head:r,parts:[]}:{head:r,parts:[...cVD(t)]}}function*cVD(e){let t;do{let{value:r}=$Gc(e,"}"),i=$Gc(e,"{");t=i.done,yield{pathParameter:r,tail:i.value}}while(!t)}function*lVD(e){for(let t of e)yield t}function $Gc(e,t){let r="",i=e.next();for(;i.done!==!0&&i.value!==t;)r+=i.value,i=e.next();return{value:r,done:i.done??!1}}function H7a({rawApiFileSchema:{"default-environment":e,environments:t},casingsGenerator:r}){if(t==null)return;let i=Object.values(t)[0];if(i!=null)return{environmentsConfig:{defaultEnvironment:e??void 0,environments:qYt(i,{singleBaseUrl:()=>SM.singleBaseUrl(fVD({environments:t,casingsGenerator:r})),multipleBaseUrls:n=>SM.multipleBaseUrls(dVD({baseUrls:Object.keys(n.urls),environments:t,casingsGenerator:r}))})},audiences:{...Object.fromEntries(Object.entries(t).map(([n,a])=>[n,qYt(a,{singleBaseUrl:o=>[...typeof o=="string"?[]:o.audiences??[]],multipleBaseUrls:o=>[...o.audiences??[]]})]))}}}function fVD({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,i])=>qYt(i,{singleBaseUrl:n=>({docs:typeof n=="string"?void 0:n.docs,id:r,name:t.generateName(r),url:Eph(typeof n=="string"?n:n.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function dVD({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(i=>({id:i,name:r.generateName(i)})),environments:Object.entries(t).map(([i,n])=>qYt(n,{multipleBaseUrls:a=>({docs:a.docs,id:i,name:r.generateName(i),urls:nn(a.urls,o=>Eph(o))}),singleBaseUrl:()=>{throw new Error(`Environment ${i} does not have multiple base URLs`)}}))}}function Eph(e){return e.endsWith("/")?e.slice(0,-1):e}function wJi(e){let t=2166136261;function r(n,a){if(typeof n=="object"&&n!=null){if(a>64){i("[MaxDepthExceeded]");return}if(Array.isArray(n)){i("[");for(let o=0;o<n.length;o++)o>0&&i(","),r(n[o],a+1);i("]")}else i("{"),Object.keys(n).sort().forEach((c,d)=>{d>0&&i(","),i(c),i(":"),r(n[c],a+1)}),i("}")}else i(String(n))}function i(n){for(let a=0;a<n.length;a++){let o=n.charCodeAt(a);t^=o,t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24),t>>>=0}}return r(e,0),t.toString(16)}function TYt({typeReference:e,typeDeclarations:t}){if(e.type==="container"&&e.container.type==="optional")return!0;if(e.type==="named"){let r=t?.[e.typeId];if(r?.shape.type==="alias"&&r?.shape.resolvedType.type==="container"&&r?.shape.resolvedType.container.type==="optional")return!0}return!1}function Sph({fieldName:e,containerType:t,maxDepth:r,currentDepth:i,typeDeclarations:n,skipOptionalProperties:a}){if(i>=r)return RYt({containerType:t});switch(t.type){case"list":{let o=EA({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return o.type==="failure"?RYt({containerType:t}):{type:"success",example:Up.list({list:[o.example,o.example],itemType:t.list}),jsonExample:[o.jsonExample,o.jsonExample]}}case"literal":return{type:"success",example:Up.literal({literal:t.literal._visit({boolean:o=>Rn.boolean(o),string:o=>Rn.string({original:o}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:t.literal._visit({boolean:o=>o,string:o=>o,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":{if(a)return RYt({containerType:t});let o=EA({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return o.type==="failure"?RYt({containerType:t}):{type:"success",example:Up.optional({optional:o.example,valueType:t.optional}),jsonExample:o.jsonExample}}case"nullable":{if(a)return RYt({containerType:t});let o=EA({fieldName:e,typeReference:t.nullable,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return o.type==="failure"?RYt({containerType:t}):{type:"success",example:Up.nullable({nullable:o.example,valueType:t.nullable}),jsonExample:o.jsonExample}}case"set":{let o=EA({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return o.type==="failure"?RYt({containerType:t}):{type:"success",example:Up.set({set:[o.example],itemType:t.set}),jsonExample:[o.jsonExample]}}case"map":{let o=EA({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a}),c=EA({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return o.type==="failure"||c.type==="failure"?RYt({containerType:t}):{type:"success",example:Up.map({map:[{key:o.example,value:c.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[o.jsonExample]:c.jsonExample}}}default:vt(t)}}function RYt({containerType:e}){switch(e.type){case"list":return{type:"success",example:Up.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:Up.literal({literal:e.literal._visit({boolean:t=>Rn.boolean(t),string:t=>Rn.string({original:t}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:e.literal._visit({boolean:t=>t,string:t=>t,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":return{type:"success",example:Up.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"nullable":return{type:"success",example:Up.nullable({nullable:void 0,valueType:e.nullable}),jsonExample:void 0};case"set":return{type:"success",example:Up.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:Up.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:vt(e)}}function Dph({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":return bVD({fieldName:e,default_:pVD(t.v2),validation:_VD(t.v2)});case"BASE_64":return{type:"success",example:Rn.base64(xn.BASE64),jsonExample:xn.BASE64};case"BOOLEAN":return{type:"success",example:Rn.boolean(xn.BOOLEAN),jsonExample:xn.BOOLEAN};case"DATE":return{type:"success",example:Rn.date(xn.DATE),jsonExample:xn.DATE};case"DATE_TIME":return{type:"success",example:Rn.datetime({datetime:new Date(xn.DATE_TIME),raw:xn.DATE_TIME}),jsonExample:xn.DATE_TIME};case"DOUBLE":return vVD({fieldName:e,validation:hVD(t.v2)});case"FLOAT":return{type:"success",example:Rn.float(xn.FLOAT),jsonExample:xn.FLOAT};case"INTEGER":return gVD({fieldName:e,validation:yVD(t.v2)});case"UINT_64":return{type:"success",example:Rn.uint64(xn.INT64),jsonExample:xn.INT64};case"UINT":return{type:"success",example:Rn.uint(xn.UINT),jsonExample:xn.UINT};case"BIG_INTEGER":return{type:"success",example:Rn.bigInteger(xn.INT64.toString()),jsonExample:`${xn.INT64}`};case"LONG":return{type:"success",example:Rn.long(xn.INT64),jsonExample:xn.INT64};case"UUID":return{type:"success",example:Rn.uuid(xn.UUID),jsonExample:xn.UUID};default:vt(t.v1)}}function pVD(e){if(e?.type==="string")return e.default}function _VD(e){if(e?.type==="string")return e.validation}function hVD(e){if(e?.type==="double")return e.validation}function yVD(e){if(e?.type==="integer")return e.validation}function Mph(e){if(e<=xn.SAMPLE_STRINGS.length){let t=xn.SAMPLE_STRINGS[e-1];if(t)return t;throw new Error(`Unexpected undefined value in SAMPLE_STRINGS at index ${e-1}`)}return xn.SAMPLE_STRINGS[xn.SAMPLE_STRINGS.length-1]+".".repeat(e-xn.SAMPLE_STRINGS.length)}function bVD({fieldName:e,default_:t,validation:r}){if(t!=null)return{type:"success",example:Rn.string({original:t}),jsonExample:t};if(r){let n=r.minLength,a=r.maxLength;if(n){let o=Mph(n);return{type:"success",example:Rn.string({original:o}),jsonExample:o}}else if(a!=null&&a<10){let o=Mph(a);return{type:"success",example:Rn.string({original:o}),jsonExample:o}}}let i=e??xn.STRING;return{type:"success",example:Rn.string({original:i}),jsonExample:i}}function vVD({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:Rn.double(r),jsonExample:r};if(i)return{type:"success",example:Rn.double(i),jsonExample:i}}return{type:"success",example:Rn.double(xn.DOUBLE),jsonExample:xn.DOUBLE}}function gVD({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:Rn.integer(r),jsonExample:r};if(i)return{type:"success",example:Rn.integer(i),jsonExample:i}}return{type:"success",example:Rn.integer(xn.INT),jsonExample:xn.INT}}function OVD(e,t){if(e.type==="primitive"||e.type==="container"&&e.container.type==="literal")return!0;if(e.type==="named"){let r=t[e.typeId];if(r!=null&&r.shape.type==="enum")return!0}return!1}function Vbn({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let o=EA({fieldName:e,typeDeclarations:t,typeReference:r.shape.aliasOf,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(o.type==="failure")return o;let{example:c,jsonExample:d}=o;return{type:"success",example:hy.alias({value:c}),jsonExample:d}}case"enum":{let o=r.shape.values[0];return o==null?{type:"failure",message:"No enum values present"}:{type:"success",example:hy.enum({value:o.name}),jsonExample:o.name.wireValue}}case"object":{let o={},c=[];if((r.shape.extendedProperties==null||r.shape.extendedProperties.length===0)&&r.shape.extends!=null)for(let l of r.shape.extends){let p=t[l.typeId];if(p==null)continue;let _=Vbn({fieldName:e,typeDeclaration:p,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});_!=null&&_.type==="success"&&_.example.type==="object"&&(Object.assign(o,_.jsonExample),c.push(..._.example.properties))}let d=mVD({fieldName:e,typeDeclaration:r,objectTypeDeclaration:r.shape,typeDeclarations:t,currentDepth:n,maxDepth:i,skipOptionalProperties:a});if(d.type==="failure")return d;let{example:s,jsonExample:u}=d;return{type:"success",example:hy.object({properties:[...c,...s.properties],extraProperties:s.extraProperties}),jsonExample:Object.assign({},o,u)}}case"undiscriminatedUnion":{let o=r.shape.members;if(o.every(s=>OVD(s.type,t))){let s=o.findIndex(u=>{if(u.type.type==="container"&&u.type.container.type==="literal")return!0;if(u.type.type==="named"){let l=t[u.type.typeId];if(l!=null&&l.shape.type==="enum")return l.shape.values.length>0}return!1});if(s!==-1){let u=o[s];if(u!=null){let l=EA({fieldName:e,typeReference:u.type,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});if(l.type==="success"){let{example:p,jsonExample:_}=l;return{type:"success",example:hy.undiscriminatedUnion({index:s,singleUnionType:p}),jsonExample:_}}}}}let d=0;for(let s of o){let u=EA({fieldName:e,typeReference:s.type,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});if(u.type==="failure"){++d;continue}let{example:l,jsonExample:p}=u;return{type:"success",example:hy.undiscriminatedUnion({index:d,singleUnionType:l}),jsonExample:p}}break}case"union":{let o=r.shape.discriminant,c={};if(r.shape.baseProperties!=null)for(let u of r.shape.baseProperties){let l=EA({fieldName:u.name.wireValue,typeReference:u.valueType,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});l.type==="success"&&(c[u.name.wireValue]=l.jsonExample)}let d=r.shape.baseProperties.map(u=>{let l=EA({fieldName:u.name.wireValue,typeReference:u.valueType,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});if(l.type==="failure")throw new Error(`Failed to generate example for union base property ${u.name.wireValue}`);let{example:p}=l;return{name:u.name,value:p}}),s=r.shape.extends.flatMap(u=>{let l=t[u.typeId];if(l==null)throw new Error(`Failed to find extended type declaration with id ${u.typeId}`);let p=Vbn({fieldName:e,typeDeclaration:l,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});if(p==null||p.type==="failure")throw new Error(`Failed to generate example for extended type declaration ${l.name.typeId}`);if(p.example.type!=="object")throw new Error(`Extended type declaration ${l.name.typeId} is not an object`);return p.example.properties});for(let u of r.shape.types){let l=u.shape._visit({noProperties:()=>({type:"success",example:hy.union({discriminant:o,singleUnionType:{wireDiscriminantValue:u.discriminantValue,shape:_C.noProperties()},baseProperties:d,extendProperties:s}),jsonExample:{[o.wireValue]:u.discriminantValue.wireValue,...c}}),samePropertiesAsObject:p=>{let _=t[p.typeId];if(_==null)return{type:"failure",message:`Failed to find type declaration with id ${p.typeId}`};let h=Vbn({currentDepth:n,maxDepth:i,fieldName:e,typeDeclaration:_,typeDeclarations:t,skipOptionalProperties:a});if(h==null)return{type:"failure",message:"Failed to generate example for type reference"};if(h.type==="failure")return h;let{example:y,jsonExample:b}=h;return{type:"success",example:hy.union({discriminant:o,singleUnionType:{wireDiscriminantValue:u.discriminantValue,shape:_C.samePropertiesAsObject({typeId:_.name.typeId,object:y.type==="object"?y:{properties:[],extraProperties:void 0}})},baseProperties:d,extendProperties:s}),jsonExample:{[o.wireValue]:u.discriminantValue.wireValue,...typeof b=="object"?b:{},...c}}},singleProperty:p=>{let _=EA({currentDepth:n+1,maxDepth:i,fieldName:e,typeReference:p.type,typeDeclarations:t,skipOptionalProperties:a});if(_.type==="failure")return _;let{example:h,jsonExample:y}=_;return{type:"success",example:hy.union({discriminant:o,singleUnionType:{wireDiscriminantValue:u.discriminantValue,shape:_C.singleProperty(h)},baseProperties:d,extendProperties:s}),jsonExample:{[o.wireValue]:u.discriminantValue.wireValue,[p.name.wireValue]:y,...c}}},_other:()=>{throw new Error("Encountered unknown union type")}});if(l.type!=="failure")return l}}}return{type:"failure",message:"Failed to generate example for type reference"}}function mVD({fieldName:e,typeDeclaration:t,objectTypeDeclaration:r,typeDeclarations:i,maxDepth:n,currentDepth:a,skipOptionalProperties:o}){let c={},d=[];for(let s of[...r.properties??[],...r.extendedProperties??[]]){let u=EA({fieldName:s.name.wireValue,typeReference:s.valueType,typeDeclarations:i,currentDepth:a+1,maxDepth:n,skipOptionalProperties:o});if(u.type==="failure"&&!TYt({typeDeclarations:i,typeReference:s.valueType}))return{type:"failure",message:`Failed to generate required property ${s.name.wireValue} b/c ${u.message}`};if(u.type==="failure")continue;let{example:l,jsonExample:p}=u;d.push({name:s.name,originalTypeDeclaration:t.name,value:l,propertyAccess:s.propertyAccess}),c[s.name.wireValue]=p}return{type:"success",example:hy.object({properties:d,extraProperties:void 0}),jsonExample:c}}function EA({fieldName:e,typeReference:t,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){if(n>i)return{type:"failure",message:`Exceeded max depth of ${i}`};switch(t.type){case"named":{let o=r[t.typeId];if(o==null)return{type:"failure",message:`Failed to find type declaration with id ${t.typeId}`};let c=Vbn({fieldName:e,typeDeclaration:o,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(c==null)return{type:"failure",message:"Failed to generate example for type declaration"};if(c.type==="failure")return c;let{example:d,jsonExample:s}=c;return{type:"success",example:{jsonExample:s,shape:Tu.named({shape:d,typeName:o.name})},jsonExample:s}}case"container":{let o=Sph({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(o.type==="failure"){let{example:s,jsonExample:u}=RYt({containerType:t.container});return{type:"success",example:{jsonExample:u,shape:Tu.container(s)},jsonExample:u}}let{example:c,jsonExample:d}=o;return{type:"success",example:{jsonExample:d,shape:Tu.container(c)},jsonExample:d}}case"primitive":{let{jsonExample:o,example:c}=Dph({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:o,shape:Tu.primitive(c)},jsonExample:o}}case"unknown":{let o={key:"value"};return{type:"success",example:{jsonExample:o,shape:Tu.unknown(o)},jsonExample:o}}}}function Wbn(e,t){let r=[];for(let i of e){let n=EA({fieldName:i.name.originalName,currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,value:n.example})}return{type:"success",example:r,jsonExample:void 0}}function hoa(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&TYt({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=EA({fieldName:i.name.name.originalName,currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,value:n.example})}return{type:"success",example:r,jsonExample:void 0}}function ipu(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&TYt({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=EA({fieldName:i.name.name.originalName,currentDepth:0,maxDepth:t.maxDepth??10,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,shape:i.allowMultiple?TR.exploded():TR.single(),value:n.example})}return{type:"success",example:r,jsonExample:void 0}}var YGc=ii.primitive({v1:ku.String,v2:vn.string({default:void 0,validation:void 0})});function yoa({ir:e,endpoint:t,service:r,typeDeclarations:i,skipOptionalRequestProperties:n,generationResponse:a}){let o={name:void 0,endpointHeaders:[],endpointPathParameters:[],queryParameters:[],servicePathParameters:[],serviceHeaders:[],rootPathParameters:[],request:void 0,response:$j.ok(cw.body(void 0)),docs:void 0},c=Wbn(t.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(c.type==="failure")return c;o.endpointPathParameters=c.example;let d=Wbn(r.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(d.type==="failure")return d;o.servicePathParameters=d.example;let s=Wbn(e.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(s.type==="failure")return s;o.rootPathParameters=s.example;let u=ipu(t.queryParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:10});if(u.type==="failure")return u;o.queryParameters=u.example;let l=hoa(t.headers,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(l.type==="failure")return l;o.endpointHeaders=l.example;let p=hoa(r.headers,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(p.type==="failure")return p;if(o.serviceHeaders=p.example,t.requestBody!=null)switch(t.requestBody.type){case"bytes":return{type:"failure",message:"Bytes request unsupported"};case"fileUpload":return{type:"failure",message:"File upload unsupported"};case"inlinedRequestBody":{let _={},h=[];if(t.requestBody.extends!=null)for(let y of t.requestBody.extends){let b=i[y.typeId];if(b==null)throw new Error(`Failed to find extended type declaration with id ${y.typeId}`);let v=Vbn({typeDeclaration:b,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});v!=null&&v.type==="success"&&Object.assign(_,v.jsonExample)}for(let y of[...t.requestBody.properties??[],...t.requestBody.extendedProperties??[]]){let b=EA({fieldName:y.name.wireValue,typeReference:y.valueType,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});if(b.type==="failure"&&!TYt({typeDeclarations:i,typeReference:y.valueType}))return{type:"failure",message:`Failed to generate required property ${y.name.wireValue} b/c ${b.message}`};if(b.type==="failure")continue;let{example:v,jsonExample:g}=b;h.push({name:y.name,originalTypeDeclaration:void 0,value:v}),_[y.name.wireValue]=g}o.request=vW.inlinedRequestBody({jsonExample:_,properties:h,extraProperties:void 0});break}case"reference":{let _=EA({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:n});if(_.type==="failure")return _;let{example:h}=_;o.request=vW.reference(h);break}default:vt(t.requestBody)}if(a.type==="success"&&t.response?.body!=null)switch(t.response.body.type){case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":{let _=EA({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.responseBodyType,skipOptionalProperties:!1});if(_.type==="failure")return _;let{example:h,jsonExample:y}=_;o.response=$j.ok(cw.body({...h,jsonExample:y}));break}case"streamParameter":{let _;switch(t.response.body.nonStreamResponse.type){case"bytes":return{type:"failure",message:"Bytes unsupported"};case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":_=EA({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.nonStreamResponse.value.responseBodyType,skipOptionalProperties:!1});break;case"text":_=EA({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:YGc,skipOptionalProperties:!1});break;default:vt(t.response.body.nonStreamResponse)}if(_.type==="failure")return _;let{example:h,jsonExample:y}=_;o.response=$j.ok(cw.body({...h,jsonExample:y}));break}case"streaming":{let _;switch(t.response.body.value.type){case"sse":{if(_=EA({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),_.type==="failure")return _;let{example:h,jsonExample:y}=_;o.response=$j.ok(cw.sse([{data:{...h,jsonExample:y},event:""}]));break}case"json":{if(_=EA({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),_.type==="failure")return _;let{example:h,jsonExample:y}=_;o.response=$j.ok(cw.stream([{...h,jsonExample:y}]));break}case"text":{if(_=EA({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:YGc,skipOptionalProperties:!1}),_.type==="failure")return _;let{example:h,jsonExample:y}=_;o.response=$j.ok(cw.stream([{...h,jsonExample:y}]));break}default:vt(t.response.body.value)}break}case"text":{let _=EA({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:YGc,skipOptionalProperties:!1});if(_.type==="failure")return _;let{example:h,jsonExample:y}=_;o.response=$j.ok(cw.body({...h,jsonExample:y}));break}case"bytes":return{type:"failure",message:"Bytes unsupported"};default:vt(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)o.response=$j.error({body:void 0,error:a.declaration.name});else{let _=EA({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:a.declaration.type,skipOptionalProperties:n});if(_.type==="failure")return _;let{example:h}=_;o.response=$j.error({body:h,error:a.declaration.name})}try{return{type:"success",example:{id:wJi(o),url:AVD(t,o),...o},jsonExample:void 0}}catch(_){return{type:"failure",message:`Parse failure with exceptions ${_}`}}}function AVD(e,t){let r={};[...t.rootPathParameters,...t.servicePathParameters,...t.endpointPathParameters].forEach(n=>{let a=n.value.jsonExample,o=typeof a=="string"?a:JSON.stringify(a);r[n.name.originalName]=o});let i=e.fullPath.head+e.fullPath.parts.map(n=>encodeURIComponent(`${r[n.pathParameter]}`)+n.tail).join("");return i.startsWith("/")||i===""?i:`/${i}`}function XGc({ir:e,channel:t,typeDeclarations:r,skipOptionalRequestProperties:i}){let n={name:void 0,pathParameters:[],headers:[],queryParameters:[],messages:[],docs:void 0},a=Wbn(t.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(a.type==="failure")return a;n.pathParameters.push(...a.example);let o=Wbn(e.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(o.type==="failure")return o;n.pathParameters.push(...o.example);let c=ipu(t.queryParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:10});if(c.type==="failure")return c;n.queryParameters=c.example;let d=hoa(t.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(d.type==="failure")return d;n.headers.push(...d.example);let s=hoa(e.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(s.type==="failure")return s;n.headers.push(...s.example);let l=t.messages.filter(h=>h.origin==="client")[0];if(l!=null){let h=Bph({message:l,typeDeclarations:r,skipOptionalRequestProperties:i});h!=null&&n.messages.push({type:l.type,body:h})}let _=t.messages.filter(h=>h.origin==="server")[0];if(_!=null){let h=Bph({message:_,typeDeclarations:r,skipOptionalRequestProperties:i});h!=null&&n.messages.push({type:_.type,body:h})}return{type:"success",example:{...n,url:PVD(t,n)},jsonExample:void 0}}function Bph({message:e,typeDeclarations:t,skipOptionalRequestProperties:r}){if(e.body.type==="inlinedBody")return;let i=EA({currentDepth:0,maxDepth:10,typeDeclarations:t,typeReference:e.body.bodyType,skipOptionalProperties:r});if(i.type==="success")return Xve.reference(i.example)}function PVD(e,t){let r={};[...t.pathParameters].forEach(n=>{let a=n.value.jsonExample,o=typeof a=="string"?a:JSON.stringify(a);r[n.name.originalName]=o});let i=e.path.head+e.path.parts.map(n=>encodeURIComponent(`${r[n.pathParameter]}`)+n.tail).join("");return i.startsWith("/")||i===""?i:`/${i}`}function boa(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{},i=Object.values(t)[0],n=Object.values(r)[0];return{userExample:i,autoExample:n}}function EJi(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{};return{userExamples:t,autoExamples:r}}function Iph({ir:e,endpoint:t,skipOptionalRequestProperties:r}){let i=e.types,n={pathParameters:{},queryParameters:{},headers:{}};for(let o of t.pathParameters){let{userExample:c,autoExample:d}=boa(o.v2Examples);c!==void 0?n.pathParameters[o.name.originalName]=c:d!==void 0&&(n.pathParameters[o.name.originalName]=d)}for(let o of t.queryParameters){let{userExample:c,autoExample:d}=boa(o.v2Examples);if(c!==void 0)n.queryParameters[o.name.name.originalName]=c;else if(d!==void 0){if(r&&TYt({typeReference:o.valueType,typeDeclarations:i}))continue;n.queryParameters[o.name.name.originalName]=d}}let a=[...t.headers,...e.headers,...e.idempotencyHeaders];for(let o of a){let{userExample:c,autoExample:d}=boa(o.v2Examples);if(c!==void 0)n.headers[o.name.wireValue]=c;else if(d!==void 0){if(r&&TYt({typeReference:o.valueType,typeDeclarations:i}))continue;n.headers[o.name.wireValue]=d}}return n}function Cph({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let{pathParameters:i,queryParameters:n,headers:a}=Iph({endpoint:e,ir:t,skipOptionalRequestProperties:r}),o={},c={},d={endpoint:{method:e.method,path:jVD(e)},baseUrl:void 0,environment:e.baseUrl,auth:void 0,pathParameters:i,queryParameters:n,headers:a,requestBody:void 0,docs:void 0};if(e.requestBody!=null)switch(e.requestBody.type){case"bytes":break;case"fileUpload":{let{userExamples:s,autoExamples:u}=EJi(e.requestBody.v2Examples);for(let[l,p]of Object.entries(s))o[l]={...d,requestBody:p};for(let[l,p]of Object.entries(u))c[l]={...d,requestBody:p};break}case"inlinedRequestBody":{let{userExamples:s,autoExamples:u}=EJi(e.requestBody.v2Examples);for(let[l,p]of Object.entries(s))o[l]={...d,requestBody:p};for(let[l,p]of Object.entries(u))c[l]={...d,requestBody:p};break}case"reference":{let{userExamples:s,autoExamples:u}=EJi(e.requestBody.v2Examples);for(let[l,p]of Object.entries(s))o[l]={...d,requestBody:p};for(let[l,p]of Object.entries(u))c[l]={...d,requestBody:p};break}default:vt(e.requestBody)}return{userRequestExamples:o,autoRequestExamples:c,baseExample:d}}function jVD(e){let t={};[...e.pathParameters,...e.allPathParameters].forEach(i=>{let{userExample:n,autoExample:a}=boa(i.v2Examples),o=n??a,c;o==null?c=i.name.originalName:c=typeof o=="string"?o:JSON.stringify(o),t[i.name.originalName]=c});let r=e.fullPath.head+e.fullPath.parts.map(i=>encodeURIComponent(`${t[i.pathParameter]}`)+i.tail).join("");return r.startsWith("/")||r===""?r:`/${r}`}function npu({endpoint:e,responseObject:t}){let r=t!==void 0?t:e.response,i={},n={},a={statusCode:r?.statusCode,body:void 0,docs:void 0};if(r==null)return{userResponseExamples:{},autoResponseExamples:{},baseExample:a};if(r.body==null)return e.source?.type==="openrpc"?{userResponseExamples:{},autoResponseExamples:{},baseExample:{...a,body:S1.json(K7a(null))}}:{userResponseExamples:{},autoResponseExamples:{},baseExample:a};switch(r.body.type){case"bytes":break;case"fileDownload":break;case"text":{let o=r.body,{userExamples:c,autoExamples:d}=EJi(o.v2Examples);for(let[s,u]of Object.entries(c)){let l=e.source?.type==="openrpc"?K7a(u):u;i[s]={...a,body:S1.json(l)}}for(let[s,u]of Object.entries(d)){let l=e.source?.type==="openrpc"?K7a(u):u;n[s]={...a,body:S1.json(l)}}break}case"json":{let o=r.body.value;if(o.type==="response"){let{userExamples:c,autoExamples:d}=EJi(o.v2Examples);for(let[s,u]of Object.entries(c)){let l=e.source?.type==="openrpc"?K7a(u):u;i[s]={...a,body:S1.json(l)}}for(let[s,u]of Object.entries(d)){let l=e.source?.type==="openrpc"?K7a(u):u;n[s]={...a,body:S1.json(l)}}}break}case"streaming":{let o=r.body.value;if(o.type==="json"){let{userExamples:c,autoExamples:d}=EJi(o.v2Examples);for(let[s,u]of Object.entries(c))i[s]={...a,body:S1.stream([u])};for(let[s,u]of Object.entries(d))n[s]={...a,body:S1.stream([u])}}break}case"streamParameter":break;default:vt(r.body)}return{userResponseExamples:i,autoResponseExamples:n,baseExample:a}}function K7a(e,t=1){return{id:t,jsonrpc:"2.0",result:e}}var voa=(e,t,r)=>{let i;return e===t?i=`${e}`:i=`${e}_${t}`,r&&(i=`${i}_${r}`),i},wVD=({exampleStore:e,key:t,example:r})=>e.has(t)?!1:(e.set(t,r),!0);function apu({key:e,displayName:t,request:r,response:i,exampleStore:n,userOrAutoStore:a}){if(!n.has(e)){let o={displayName:t,request:r,response:i,codeSamples:void 0};return a[e]=o,wVD({exampleStore:n,key:e,example:o}),!0}return!1}function qph({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let i={},n={},a=new Map,{userRequestExamples:o,autoRequestExamples:c,baseExample:d}=Cph({endpoint:e,ir:t,skipOptionalRequestProperties:r}),s=Object.keys(o)[0],u=Object.values(o)[0],l=Object.keys(c)[0],p=Object.values(c)[0],_=EVD({endpoint:e,userRequestExamples:o,baseRequestExample:d,firstUserRequestName:s,firstUserRequestExample:u,firstAutoRequestName:l,firstAutoRequestExample:p,userResults:i,autoResults:n,exampleStore:a});if(SVD({endpoint:e,userRequestExamples:o,requestExamplesUsed:_,userResults:i,exampleStore:a}),Object.keys(i).length===0&&Object.keys(n).length===0){let{baseExample:h}=npu({endpoint:e}),y=voa(l??"base","base",void 0);apu({key:y,displayName:l??"base",request:p??d,response:h,exampleStore:a,userOrAutoStore:n})}return{userFullExamples:i,autoFullExamples:n}}function EVD({endpoint:e,userRequestExamples:t,baseRequestExample:r,firstUserRequestName:i,firstUserRequestExample:n,firstAutoRequestName:a,firstAutoRequestExample:o,userResults:c,autoResults:d,exampleStore:s}){let u=e.v2Responses?.responses??[e.response],l=new Set;for(let p of u){let _=!1,{userResponseExamples:h,autoResponseExamples:y,baseExample:b}=npu({endpoint:e,responseObject:p}),v=Object.keys(y)[0],g=Object.values(y)[0];for(let[m,O]of Object.entries(h)){let A,j;t[m]?(j=t[m],l.add(m),A=voa(m,m,p?.statusCode)):o&&a?(j=o,A=voa(a,m,p?.statusCode)):(j=r,A=voa("base",m,p?.statusCode)),apu({key:A,displayName:m,request:j,response:O,exampleStore:s,userOrAutoStore:c})&&(_=!0)}if(!_){let m=ou(`${e.name.originalName}_example`);i&&n&&l.add(i);let O=voa(i??a??"base",v??"base",p?.statusCode);apu({key:O,displayName:i??a??m,request:n??o??r,response:g??b,exampleStore:s,userOrAutoStore:d})&&(_=!0)}}return l}function SVD({endpoint:e,userRequestExamples:t,requestExamplesUsed:r,userResults:i,exampleStore:n}){let{userResponseExamples:a,autoResponseExamples:o,baseExample:c}=npu({endpoint:e}),d=Object.values(a)[0],s=Object.keys(a)[0],u=Object.keys(o)[0],l=Object.values(o)[0],p=Object.entries(t).filter(([_])=>!r.has(_));for(let[_,h]of p){let y=voa(_,s??u??"base",d?d.statusCode:l?l.statusCode:c.statusCode);apu({key:y,displayName:_,request:h,response:d??l??c,exampleStore:n,userOrAutoStore:i})}}function J7a({ir:e,exampleGeneration:t}){let r={disabled:t.disabled,includeOptionalRequestPropertyExamples:t.includeOptionalRequestPropertyExamples??!1,skipAutogenerationIfManualExamplesExist:t.skipAutogenerationIfManualExamplesExist??!1,skipErrorAutogenerationIfManualErrorExamplesExist:t.skipErrorAutogenerationIfManualErrorExamplesExist??!1};for(let[i,n]of Object.entries(e.services))for(let a of n.endpoints){let o=[];if(a.userSpecifiedExamples.length===0||r.skipAutogenerationIfManualExamplesExist===!1){let c=yoa({ir:e,service:n,endpoint:a,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples,generationResponse:{type:"success"}});c.type==="success"&&o.push({example:c.example})}if(a.userSpecifiedExamples.filter(c=>c.example?.response.type==="error").length===0||r.skipErrorAutogenerationIfManualErrorExamplesExist===!1)for(let c of a.errors){let d=e.errors[c.error.errorId];if(!d)continue;let s=yoa({ir:e,service:n,endpoint:a,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples,generationResponse:{type:"error",declaration:d}});s.type==="success"&&o.push({example:s.example})}a.autogeneratedExamples=o}for(let[i,n]of Object.entries(e.websocketChannels??{})){if(n.examples.length>0&&r.skipAutogenerationIfManualExamplesExist===!0)continue;let a=XGc({ir:e,channel:n,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples});if(a.type==="failure")continue;let{example:o}=a;n.examples=[...n.examples,o]}return e}function ZGc({ir:e,exampleGeneration:t}){let r={disabled:t.disabled,includeOptionalRequestPropertyExamples:t.includeOptionalRequestPropertyExamples??!1,skipAutogenerationIfManualExamplesExist:t.skipAutogenerationIfManualExamplesExist??!1,skipErrorAutogenerationIfManualErrorExamplesExist:t.skipErrorAutogenerationIfManualErrorExamplesExist??!1};for(let[i,n]of Object.entries(e.services))for(let a of n.endpoints){a.v2Examples==null&&(a.v2Examples={userSpecifiedExamples:{},autogeneratedExamples:{}});let{userFullExamples:o,autoFullExamples:c}=qph({endpoint:a,ir:e,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples});if(Object.keys(a.v2Examples.userSpecifiedExamples).length>0){if(Object.values(a.v2Examples.userSpecifiedExamples).some(s=>s.request!=null||s.response!=null))continue;let d=Object.values(a.v2Examples.userSpecifiedExamples).filter(s=>s!=null).flatMap(s=>s.codeSamples??[]);for(let[s,u]of Object.entries(c))c[s]={...u,codeSamples:d};for(let[s,u]of Object.entries(o))o[s]={...u,codeSamples:d}}a.v2Examples.autogeneratedExamples=c,a.v2Examples.userSpecifiedExamples=o}for(let[i,n]of Object.entries(e.websocketChannels??{})){if(n.examples.length>0&&r.skipAutogenerationIfManualExamplesExist===!0)continue;let a=XGc({ir:e,channel:n,typeDeclarations:e.types,skipOptionalRequestProperties:!r.includeOptionalRequestPropertyExamples});if(a.type==="failure")continue;let{example:o}=a;n.examples=[...n.examples,o]}return e}function Rph({filteredIr:e,singleUnionTypeProperties:t}){return t._visit({samePropertiesAsObject:r=>{let i=e.hasTypeId(r.typeId)?{...r,object:{...r.object,properties:r.object.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:SD({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)}}:void 0;return i!==void 0?_C.samePropertiesAsObject(i):void 0},singleProperty:r=>{let i=SD({filteredIr:e,exampleTypeReference:r});return i!==void 0?_C.singleProperty(i):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function SD({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:i=>({...t,shape:Tu.container(Up.list({...i,list:i.list.map(n=>SD({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),set:i=>({...t,shape:Tu.container(Up.set({...i,set:i.set.map(n=>SD({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),optional:i=>{let n=i.optional!=null?SD({filteredIr:e,exampleTypeReference:i.optional}):void 0;return n!=null?{...t,shape:Tu.container(Up.optional({optional:n,valueType:i.valueType}))}:void 0},nullable:i=>{let n=i.nullable!=null?SD({filteredIr:e,exampleTypeReference:i.nullable}):void 0;return n!=null?{...t,shape:Tu.container(Up.nullable({nullable:n,valueType:i.valueType}))}:void 0},map:i=>({...t,shape:Tu.container(Up.map({...i,map:i.map.map(n=>{let a=SD({filteredIr:e,exampleTypeReference:n.key}),o=SD({filteredIr:e,exampleTypeReference:n.value});return a!==void 0&&o!==void 0?{key:a,value:o}:void 0}).filter(n=>n!==void 0)}))}),literal:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}}),named:r=>e.hasTypeId(r.typeName.typeId)?r.shape._visit({alias:i=>{let n=SD({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...t,shape:Tu.named({...r,shape:hy.alias({...i,value:n})})}:void 0},enum:i=>({...t,shape:Tu.named({...r,shape:hy.enum(i)})}),object:i=>({...t,shape:Tu.named({...r,shape:hy.object({...i,properties:i.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:SD({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})})}),union:i=>{let n=Rph({filteredIr:e,singleUnionTypeProperties:i.singleUnionType.shape});return n!==void 0?{...t,shape:Tu.named({...r,shape:hy.union({...i,singleUnionType:{...i.singleUnionType,shape:n}})})}:void 0},undiscriminatedUnion:i=>{let n=SD({filteredIr:e,exampleTypeReference:i.singleUnionType});return n!==void 0?{...t,shape:Tu.named({...r,shape:hy.undiscriminatedUnion({...i,singleUnionType:n})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function kGc({filteredIr:e,pathParameters:t}){return t.map(r=>{let i=SD({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function MVD({filteredIr:e,queryParameters:t}){return t.map(r=>{let i=SD({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function Tph({filteredIr:e,headers:t}){return t.map(r=>{let i=SD({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function DVD({filteredIr:e,requestBody:t}){return t._visit({inlinedRequestBody:r=>({...t,properties:r.properties.filter(i=>i.originalTypeDeclaration?e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue):!0).map(i=>{let n=SD({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...i,value:n}:void 0}).filter(i=>i!==void 0)}),reference:r=>{let i=SD({filteredIr:e,exampleTypeReference:r});return i!==void 0?vW.reference(i):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function BVD({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:i=>$j.ok(cw.body(i!=null?SD({filteredIr:e,exampleTypeReference:i}):void 0)),stream:i=>$j.ok(cw.stream(i.map(n=>SD({filteredIr:e,exampleTypeReference:n})).filter(us))),sse:i=>$j.ok(cw.sse(i.map(({event:n,data:a})=>{let o=SD({filteredIr:e,exampleTypeReference:a});return o!==void 0?{event:n,data:o}:void 0}).filter(us))),_other:({type:i})=>{throw new Error(`Received unknown type for OK example: ${i}`)}}),error:({error:r,body:i})=>$j.error({error:r,body:i!=null?SD({filteredIr:e,exampleTypeReference:i}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function exc({filteredIr:e,example:t}){return{...t,rootPathParameters:kGc({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:kGc({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:kGc({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:Tph({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:Tph({filteredIr:e,headers:t.endpointHeaders}),queryParameters:MVD({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?DVD({filteredIr:e,requestBody:t.request}):void 0,response:BVD({filteredIr:e,response:t.response})}}function zph({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let i=SD({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...t,shape:hy.alias({...r,value:i})}:void 0},enum:()=>t,object:r=>({...t,shape:hy.object({...r,properties:r.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:SD({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})}),union:r=>{let i=Rph({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return i!==void 0?{...t,shape:hy.union({...r,singleUnionType:{...r.singleUnionType,shape:i}})}:void 0},undiscriminatedUnion:r=>{let i=SD({filteredIr:e,exampleTypeReference:r.singleUnionType});return i!==void 0?{...t,shape:hy.undiscriminatedUnion({...r,singleUnionType:i})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function txc(e,t){if(t==null)return e;let r=Bfn(e.types,c=>t.hasType(c)),i=Object.fromEntries(Object.entries(r).map(([c,d])=>{let s=[];if(d.userProvidedExamples=d.userProvidedExamples.map(u=>zph({filteredIr:t,exampleType:u})).filter(u=>u!==void 0),d.shape.type==="object"){for(let u of d.shape.properties)t.hasProperty(c,u.name.wireValue)&&s.push(u);return[c,{...d,shape:Al.object({...d.shape,properties:s})}]}return[c,d]})),n=Object.fromEntries(Object.entries(e.webhookGroups).map(([c,d])=>{let s=d.filter(u=>t.hasWebhook(u)).map(u=>{let l=u.id;return u.payload.type==="inlinedPayload"&&l!=null&&(u.payload={...u.payload,properties:u.payload.properties.filter(p=>t.hasWebhookPayloadProperty(l,p.name.wireValue))}),u});return[c,s]})),a=e.websocketChannels!=null?Object.fromEntries(Object.entries(e.websocketChannels).filter(([c])=>t.hasChannel(c)).map(([c,d])=>[c,{...d}])):{},o=e.environments;if(o){switch(o.environments.type){case"singleBaseUrl":{o.environments.environments=o.environments.environments.filter(c=>t.hasEnvironmentId(c.id));break}case"multipleBaseUrls":{o.environments.environments=o.environments.environments.filter(c=>t.hasEnvironmentId(c.id));break}}o.defaultEnvironment&&(t.hasEnvironmentId(o.defaultEnvironment)||(o.defaultEnvironment=void 0))}return{...e,environments:o,types:i,errors:Bfn(e.errors,c=>t.hasError(c)),services:nn(Bfn(e.services,c=>t.hasService(c)),c=>({...c,endpoints:c.endpoints.filter(d=>t.hasEndpoint(d)).map(d=>(d.autogeneratedExamples=d.autogeneratedExamples.map(s=>({...s,example:exc({filteredIr:t,example:s.example})})),d.userSpecifiedExamples=d.userSpecifiedExamples.map(s=>({...s,example:s.example!=null?exc({filteredIr:t,example:s.example}):void 0})),d.queryParameters.length>0&&(d.queryParameters=d.queryParameters.filter(s=>t.hasQueryParameter(d.id,s.name.wireValue))),d.requestBody?.type==="inlinedRequestBody"?{...d,requestBody:{...d.requestBody,properties:d.requestBody.properties.filter(s=>t.hasRequestProperty(d.id,s.name.wireValue))}}:d))})),websocketChannels:a,webhookGroups:n,serviceTypeReferenceInfo:IVD(e.serviceTypeReferenceInfo,t)}}function IVD(e,t){if(t==null)return e;let r={};return Object.entries(e.typesReferencedOnlyByService).forEach(([i,n])=>{t.hasServiceId(i)&&(r[i]=n.filter(a=>t.hasTypeId(a)))}),{sharedTypes:e.sharedTypes.filter(i=>t.hasTypeId(i)),typesReferencedOnlyByService:r}}function Gbn(e){let t={};for(let[r,i]of Object.entries(e))if(typeof i!="string")for(let n of i.audiences??[])t[n]==null&&(t[n]=new Set),t[n]?.add(r);return t}function ege(e){return e.allParts.map(t=>t.originalName).join("/")}var Lp={generateTypeId:e=>`type_${ege(e.fernFilepath)}:${e.name.originalName}`,generateErrorId:e=>`error_${ege(e.fernFilepath)}:${e.name.originalName}`,generateServiceId:e=>`service_${ege(e.fernFilepath)}`,generateServiceIdFromFernFilepath:e=>`service_${ege(e)}`,generateSubpackageId:e=>`subpackage_${ege(e)}`,generateEndpointId:(e,t)=>{let r=ege(e.fernFilepath),i=t.name.originalName;return`endpoint_${r}.${i}`},generateWebhookGroupId:e=>`webhooks_${ege(e)}`,generateWebhookId:(e,t)=>`webhooks_${ege(e)}.${t}`,generateWebSocketChannelId:e=>`channel_${ege(e)}`};function goa(e){return e.type!=null}var opu=class{environments=new Set;types=new Set;properties;errors=new Set;services=new Set;endpoints=new Set;requestProperties;queryParameters;webhooks=new Set;webhookPayloadProperties;channels=new Set;subpackages=new Set;constructor({types:t,properties:r,errors:i,environments:n,services:a,endpoints:o,webhooks:c,subpackages:d,queryParameters:s,requestProperties:u,webhookPayloadProperties:l,channels:p}){this.environments=n,this.types=t,this.properties=r,this.errors=i,this.services=a,this.endpoints=o,this.webhooks=c,this.webhookPayloadProperties=l,this.subpackages=d,this.requestProperties=u,this.queryParameters=s,this.channels=p}hasTypeId(t){return this.types.has(t)}hasErrorId(t){return this.errors.has(t)}hasServiceId(t){return this.services.has(t)}hasSubpackageId(t){return this.subpackages.has(t)}hasType(t){let r=Lp.generateTypeId(t.name);return this.types.has(r)}hasProperty(t,r){let i=this.properties[t];return i==null?!0:i.has(r)}hasError(t){let r=Lp.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=Lp.generateServiceId(t.name);return this.services.has(r)}hasEnvironmentId(t){return this.environments.has(t)}hasEndpoint(t){return this.endpoints.has(t.id)}hasRequestProperty(t,r){let i=this.requestProperties[t];return i==null?!0:i.has(r)}hasQueryParameter(t,r){let i=this.queryParameters[t];return i==null?!0:i.has(r)}hasSubpackage(t){return this.subpackages.has(t)}hasWebhook(t){return t.id?this.webhooks.has(t.id):!0}hasChannel(t){return t?this.channels.has(t):!0}hasWebhookPayloadProperty(t,r){let i=this.webhookPayloadProperties[t];return i==null?!0:i.has(r)}};var xbn=class{types={};properties={};queryParameters={};requestProperties={};webhookProperties={};errors={};endpoints={};webhooks={};channels={};audiences;typesReferencedByService={};environmentsNeededForAudience=new Set;typesNeededForAudience=new Set;servicesNeededForAudience=new Set;endpointsNeededForAudience=new Set;webhooksNeededForAudience=new Set;channelsNeededForAudience=new Set;subpackagesNeededForAudience=new Set;constructor(t){this.audiences=CVD(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:i,descendantTypeIdsByAudience:n,propertiesByAudience:a}){let o=Lp.generateTypeId(t),c={typeId:o,allDescendants:r,descendantsByAudience:n,referencedSubpackages:i};this.types[o]=c,this.typesReferencedByService[o]==null&&(this.typesReferencedByService[o]=new Set),this.properties[o]={typeId:o,propertiesByAudience:a}}markTypeForAudiences(t,r){let i=Lp.generateTypeId(t);this.hasAudience(r)&&(this.typesNeededForAudience.add(i),this.addSubpackages(t.fernFilepath),this.types[i]?.referencedSubpackages.forEach(n=>{this.addSubpackages(n)}))}markEnvironmentForAudiences(t,r,i){t&&(this.hasAudience(r)||i)&&this.environmentsNeededForAudience.add(t.id)}getTypesReferencedByService(){for(let t of Object.values(this.endpoints))for(let r of t.referencedTypes)this.markTypeForService(r,t.serviceId);return this.typesReferencedByService}addError(t){let r=Lp.generateErrorId(t.name),i=new Set,n=new Set;t.type!=null&&BM(t.type,i,n);let a={errorId:r,referencedTypes:i,referencedSubpackages:n};this.errors[r]=a}addEndpoint(t,r,i){let n=Lp.generateServiceId(t.name),a=r.id,o=new Set,c=new Set,d=new Set;for(let s of[...t.headers,...r.headers])BM(s.valueType,o,d);for(let s of[...t.pathParameters,...r.pathParameters])BM(s.valueType,o,d);for(let s of r.queryParameters)BM(s.valueType,o,d);if(i!=null&&i.request!=null&&typeof i.request!="string"){let s=Gbn(i.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:s}}r.requestBody!=null&&Nm._visit(r.requestBody,{inlinedRequestBody:s=>{for(let u of s.extends)upu(u,o,d);for(let u of s.properties)BM(u.valueType,o,d);if(i!=null&&typeof i.request=="object"&&typeof i.request.body=="object"&&fw(i.request.body)){let u=Gbn(i.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:u}}},reference:({requestBodyType:s})=>{BM(s,o,d)},fileUpload:({properties:s})=>{for(let u of s)M1._visit(u,{file:It,bodyProperty:({valueType:l})=>{BM(l,o,d)},_other:()=>{throw new Error("Unknown FileUploadRequestProperty: "+u.type)}})},bytes:()=>{},_other:()=>{throw new Error("Unknown HttpRequestBody: "+r.requestBody?.type)}}),r.response?.body!=null&&Ed._visit(r.response.body,{fileDownload:It,json:s=>{BM(s.responseBodyType,o,d)},streaming:s=>{s._visit({sse:u=>BM(u.payload,o,d),json:u=>BM(u.payload,o,d),text:It,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.type)}})},streamParameter:s=>{s.streamResponse._visit({sse:u=>BM(u.payload,o,d),json:u=>BM(u.payload,o,d),text:It,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.streamResponse.type)}}),s.nonStreamResponse.type==="json"&&BM(s.nonStreamResponse.value.responseBodyType,o,d)},text:It,bytes:It,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(s=>{c.add(Lp.generateErrorId(s.error)),d.add(s.error.fernFilepath)}),this.endpoints[a]={endpointId:a,serviceId:n,referencedTypes:o,referencedErrors:c,referencedSubpackages:d}}markEndpointForAudience(t,r,i){if(this.hasAudience(i)){let n=Lp.generateServiceId(t);this.servicesNeededForAudience.add(n),r.forEach(a=>{let o=a.id;this.endpointsNeededForAudience.add(o),this.endpoints[o]?.referencedSubpackages.forEach(c=>{this.addSubpackages(c)})}),this.servicesNeededForAudience.add(n),this.addSubpackages(t.fernFilepath)}}getFilteredSubpackages(){return this.subpackagesNeededForAudience}getFilteredServices(){return this.servicesNeededForAudience}getFilteredEndpoints(){return this.endpointsNeededForAudience}getFilteredChannels(){return this.channelsNeededForAudience}getFilteredWebhooks(){return this.webhooksNeededForAudience}addWebhook(t,r,i){let n=r.id;if(n==null)return;let a=new Set,o=new Set;r.payload!=null&&fF._visit(r.payload,{inlinedPayload:c=>{for(let d of c.extends)upu(d,a,o);for(let d of c.properties)BM(d.valueType,a,o);if(i?.payload!=null&&typeof i.payload=="object"&&!goa(i.payload)){let d=Gbn(i.payload.properties??{});this.webhookProperties[n]={webhookId:n,propertiesByAudience:d}}},reference:({payloadType:c})=>{BM(c,a,o)},_other:()=>{throw new Error("Unknown WebhookPayload: "+r.payload?.type)}}),o.add(t),this.webhooks[n]={webhookId:n,referencedTypes:a,referencedSubpackages:o}}markWebhookForAudiences(t,r,i){let n=r.id;n!=null&&this.hasAudience(i)&&(this.webhooksNeededForAudience.add(n),this.addSubpackages(t))}addChannel(t,r,i,n){if(r==null)return;let a=new Set,o=new Set;for(let c of i.messages)pL._visit(c.body,{reference:({bodyType:d})=>{BM(d,a,o)},inlinedBody:d=>{for(let s of d.extends)upu(s,a,o);for(let s of d.properties)BM(s.valueType,a,o)},_other:()=>{}});for(let c of i.queryParameters)BM(c.valueType,a,o);o.add(t),this.channels[r]={channelId:r,referencedTypes:a,referencedSubpackages:o}}markChannelForAudiences(t,r,i){r!=null&&this.hasAudience(i)&&(this.channelsNeededForAudience.add(r),this.addSubpackages(t))}build(){let t=new Set,r=new Set;for(let c of this.endpointsNeededForAudience.keys()){let d=this.getEndpointNode(c);for(let s of d.referencedErrors){if(r.has(s))continue;r.add(s);let u=this.getErrorNode(s);this.addReferencedTypes(t,u.referencedTypes)}this.addReferencedTypes(t,d.referencedTypes)}this.addReferencedTypes(t,this.typesNeededForAudience);for(let c of this.webhooksNeededForAudience.keys()){let d=this.getWebhookNode(c);this.addReferencedTypes(t,d.referencedTypes)}for(let c of this.channelsNeededForAudience.keys()){let d=this.getChannelNode(c);this.addReferencedTypes(t,d.referencedTypes)}let i={},n={},a={},o={};if(this.audiences.type==="filtered"){for(let[c,d]of Object.entries(this.properties)){if(!t.has(c))continue;let s=new Set;for(let u of this.audiences.audiences){let l=d.propertiesByAudience[u];l?.forEach(p=>{s.add(p)})}s.size>0&&(i[c]=s),i[c]=s.size>0?s:void 0}for(let[c,d]of Object.entries(this.requestProperties)){if(!this.endpointsNeededForAudience.has(c))continue;let s=new Set;for(let u of this.audiences.audiences){let l=d.propertiesByAudience[u];l?.forEach(p=>{s.add(p)})}n[c]=s.size>0?s:void 0}for(let[c,d]of Object.entries(this.queryParameters)){if(!this.endpointsNeededForAudience.has(c))continue;let s=new Set;for(let u of this.audiences.audiences){let l=d.parametersByAudience[u];l?.forEach(p=>{s.add(p)})}a[c]=s.size>0?s:void 0}for(let[c,d]of Object.entries(this.webhookProperties)){if(!this.webhooksNeededForAudience.has(c))continue;let s=new Set;for(let u of this.audiences.audiences){let l=d.propertiesByAudience[u];l?.forEach(p=>{s.add(p)})}o[c]=s.size>0?s:void 0}}return new opu({types:t,properties:i,errors:r,requestProperties:n,queryParameters:a,environments:this.environmentsNeededForAudience,services:this.servicesNeededForAudience,endpoints:this.endpointsNeededForAudience,webhooks:this.webhooksNeededForAudience,webhookPayloadProperties:o,subpackages:this.subpackagesNeededForAudience,channels:this.channelsNeededForAudience})}markTypeForService(t,r){let i=this.typesReferencedByService[t]??=new Set;if(i.has(r))return;i.add(r);let n=this.getTypeNode(t);for(let a of n.allDescendants)this.markTypeForService(a,r)}addReferencedTypes(t,r){for(let i of r){if(t.has(i))continue;t.add(i);let n=this.getTypeNode(i);if(this.audiences.type==="filtered")for(let a of this.audiences.audiences){let o=n.descendantsByAudience[a];if(o!=null)o.forEach(c=>{t.add(c)});else{n.allDescendants.forEach(c=>{t.add(c)});break}}else n.allDescendants.forEach(a=>{t.add(a)})}}getTypeNode(t){let r=this.types[t];if(r==null)throw new Error(`Failed to find type node with id ${t}`);return r}getErrorNode(t){let r=this.errors[t];if(r==null)throw new Error(`Failed to find error node with id ${t}`);return r}getEndpointNode(t){let r=this.endpoints[t];if(r==null)throw new Error(`Failed to find endpoint node with id ${t}`);return r}getWebhookNode(t){let r=this.webhooks[t];if(r==null)throw new Error(`Failed to find webhook node with id ${t}`);return r}getChannelNode(t){let r=this.channels[t];if(r==null)throw new Error(`Failed to find channel node with id ${t}`);return r}hasNoAudiences(){return this.audiences.type==="none"}hasAudience(t){let r=this.audiences;switch(r.type){case"none":return!0;case"filtered":return t.some(i=>r.audiences.has(i));default:vt(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let i={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(Lp.generateSubpackageId(i))}}};function CVD(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:vt(e)}}function BM(e,t,r){ii._visit(e,{container:i=>{qVD(i,t,r)},named:i=>{upu(i,t,r)},primitive:It,unknown:It,_other:It})}function upu(e,t,r){t.add(Lp.generateTypeId(e)),r.add(e.fernFilepath)}function qVD(e,t,r){Es._visit(e,{list:i=>{BM(i,t,r)},map:i=>{BM(i.keyType,t,r),BM(i.valueType,t,r)},optional:i=>{BM(i,t,r)},nullable:i=>{BM(i,t,r)},set:i=>{BM(i,t,r)},literal:It,_other:It})}var TVD=[Ar.AvailabilityStatus.GeneralAvailability];function pUi(e){return e!==void 0&&!TVD.includes(e.status)}var rxc=class{errors;constructor(){this.errors=[]}add(t){this.errors.push({message:t})}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}},$7a=class{errors;constructor(){this.errors=new rxc}async check({from:t,to:r}){let i=this.toInternalIr(t),n=this.toInternalIr(r),a=wJi(i),o=wJi(n);if(a===o)return{bump:"no_change",isBreaking:!1,errors:[]};let c=this.checkBreaking({from:i,to:n});return{bump:c.isBreaking?"major":"minor",isBreaking:c.isBreaking,errors:c.errors}}toInternalIr(t){return{types:t.types,errors:t.errors,services:t.services}}checkBreaking({from:t,to:r}){this.checkTypeBreakingChanges({from:t.types,to:r.types}),this.checkErrorsBreakingChanges({from:t.errors,to:r.errors}),this.checkServicesBreakingChanges({from:t.services,to:r.services});let i=this.errors.hasErrors();return{bump:i?"major":"minor",isBreaking:i,errors:this.errors.getErrors()}}checkTypeBreakingChanges({from:t,to:r}){for(let[i,n]of Object.entries(t)){if(pUi(n.availability))continue;let a=r[i];if(!a){this.errors.add(`Type "${i}" was removed.`);continue}if(pUi(a.availability)){this.errors.add(`Type "${i}" was moved from stable to unstable availability status.`);continue}this.areTypeDeclarationsCompatible({from:n,to:a})||this.errors.add(`Type "${i}" has an incompatible change.`)}}checkErrorsBreakingChanges({from:t,to:r}){for(let[i,n]of Object.entries(t)){let a=Object.values(r).find(o=>o.name.errorId===n.name.errorId);if(!a){this.errors.add(`Error "${n.name.errorId}" with status code "${n.statusCode}" was removed.`);continue}this.checkErrorBreakingChanges({from:n,to:a})}}checkErrorBreakingChanges({from:t,to:r}){if(t.type!=null){if(r.type==null){this.errors.add(`Error "${t.name.errorId}" with status code "${t.statusCode}" had its type removed.`);return}this.areTypeReferencesCompatible({from:t.type,to:r.type})||this.errors.add(`Error "${t.name.errorId}" type reference changed.`)}this.areDeclaredErrorNamesCompatible({from:t.name,to:r.name})||this.errors.add(`Error "${t.name.errorId}" name changed.`),this.areNameAndWireValuesCompatible({from:t.discriminantValue,to:r.discriminantValue})||this.errors.add(`Error "${t.name.errorId}" discriminant value changed.`)}checkServicesBreakingChanges({from:t,to:r}){for(let[i,n]of Object.entries(t)){if(pUi(n.availability)||(n.endpoints?.every(o=>pUi(o.availability))??!1))continue;let a=r[i];if(!a){this.errors.add(`Service "${i}" was removed.`);continue}if(pUi(a.availability)){this.errors.add(`Service "${i}" was moved from stable to unstable availability status.`);continue}this.checkServiceBreakingChanges({id:i,from:n,to:a})}}checkServiceBreakingChanges({id:t,from:r,to:i}){this.checkHeadersBreakingChanges({id:t,from:r.headers,to:i.headers}),this.checkEndpointsBreakingChanges({id:t,from:r,to:i})}checkEndpointsBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.endpoints.map(o=>[o.id,o])),a=Object.fromEntries(i.endpoints.map(o=>[o.id,o]));for(let[o,c]of Object.entries(n)){if(pUi(c.availability))continue;let d=a[o];if(!d){this.errors.add(`Endpoint "${o}" was removed.`);continue}if(pUi(d.availability)){this.errors.add(`Endpoint "${o}" was moved from stable to unstable availability status.`);continue}this.checkEndpointBreakingChanges({id:o,from:c,to:d})}}checkEndpointBreakingChanges({id:t,from:r,to:i}){this.checkHttpMethodsBreakingChanges({id:t,from:r.method,to:i.method}),this.checkHttpPathsBreakingChanges({id:t,from:r.fullPath,to:i.fullPath}),this.checkPathParametersBreakingChanges({id:t,from:r.pathParameters,to:i.pathParameters}),this.checkQueryParametersBreakingChanges({id:t,from:r.queryParameters,to:i.queryParameters}),this.checkHeadersBreakingChanges({id:t,from:r.headers,to:i.headers}),r.requestBody!=null&&(i.requestBody!=null?this.checkHttpRequestBodiesCompatible({id:t,from:r.requestBody,to:i.requestBody}):this.errors.add(`Request body was removed from endpoint "${r.id}".`)),r.response!=null&&(i.response!=null?this.checkHttpResponseBreakingChanges({id:t,from:r.response,to:i.response}):this.errors.add(`Response was removed from endpoint "${r.id}".`)),(r.pagination!=null&&i.pagination==null||r.pagination==null&&i.pagination!=null)&&this.errors.add(`Pagination was ${r.pagination!=null?"added":"removed"} from endpoint "${r.id}".`)}checkPathParametersBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.map(o=>[o.name.originalName,o])),a=Object.fromEntries(i.map(o=>[o.name.originalName,o]));for(let[o,c]of Object.entries(n)){let d=a[o];if(!d){this.errors.add(`Path parameter "${o}" was removed from endpoint "${t}".`);continue}this.areTypeReferencesCompatible({from:c.valueType,to:d.valueType})||this.errors.add(`Path parameter "${o}" type changed in endpoint "${t}".`)}}checkQueryParametersBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.map(o=>[o.name.wireValue,o])),a=Object.fromEntries(i.map(o=>[o.name.wireValue,o]));this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(n).map(([o,c])=>[o,c.valueType])),to:Object.fromEntries(Object.entries(a).map(([o,c])=>[o,c.valueType]))});for(let[o,c]of Object.entries(n)){let d=a[o];if(!d){this.errors.add(`Query parameter "${o}" was removed from endpoint "${t}".`);continue}this.areTypeReferencesCompatible({from:c.valueType,to:d.valueType})||this.errors.add(`Query parameter "${o}" type changed in endpoint "${t}".`),c.allowMultiple!==d.allowMultiple&&this.errors.add(`Query parameter "${o}" allow-multiple values changed in endpoint "${t}".`)}}checkHeadersBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.map(o=>[o.name.wireValue,o])),a=Object.fromEntries(i.map(o=>[o.name.wireValue,o]));this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(n).map(([o,c])=>[o,c.valueType])),to:Object.fromEntries(Object.entries(a).map(([o,c])=>[o,c.valueType]))});for(let[o,c]of Object.entries(n)){let d=a[o];if(!d){this.errors.add(`Header "${o}" was removed from ${t}.`);continue}this.areTypeReferencesCompatible({from:c.valueType,to:d.valueType})||this.errors.add(`Header "${o}" type changed in ${t}.`)}}checkHttpMethodsBreakingChanges({id:t,from:r,to:i}){r!==i&&this.errors.add(`HTTP method changed in ${t}.`)}checkHttpPathsBreakingChanges({id:t,from:r,to:i}){this.areHttpPathsCompatible({from:r,to:i})||this.errors.add(`HTTP path changed in ${t}.`)}areHttpPathsCompatible({from:t,to:r}){if(t.head!==r.head||t.parts.length!==r.parts.length)return!1;for(let i=0;i<t.parts.length;i++){let n=t.parts[i];if(n==null)return!1;let a=r.parts[i];if(a==null||n.pathParameter!==a.pathParameter||n.tail!==a.tail)return!1}return!0}checkHttpRequestBodiesCompatible({id:t,from:r,to:i}){switch(r.type){case"inlinedRequestBody":if(i.type==="inlinedRequestBody"&&this.areInlinedRequestBodiesCompatible({from:r,to:i}))return;break;case"reference":if(i.type==="reference"&&this.areReferenceRequestBodiesCompatible({from:r,to:i}))return;break;case"fileUpload":if(i.type==="fileUpload"&&this.areFileUploadRequestBodiesCompatible({from:r,to:i}))return;break;case"bytes":if(i.type==="bytes")return;break;default:vt(r)}this.errors.add(`Request body type changed from "${r.type}" to "${i.type}" in endpoint "${t}".`)}areInlinedRequestBodiesCompatible({from:t,to:r}){let i=this.getInlinedRequestBody(t),n=this.getInlinedRequestBody(r);return this.checkForNewInlinedRequestBodyProperties({from:i,to:n}),Object.entries(i).every(([a,o])=>{let c=n[a];return c?this.areTypeReferencesCompatible({from:o,to:c}):(this.errors.add(`Request body property "${a}" was removed.`),!1)})}areReferenceRequestBodiesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.requestBodyType,to:r.requestBodyType})}areFileUploadRequestBodiesCompatible({from:t,to:r}){let i=this.getFileUploadRequest(t.properties),n=this.getFileUploadRequest(r.properties);this.checkForNewFileUploadRequestProperties({from:i,to:n});for(let[a,o]of Object.entries(i)){let c=n[a];if(!c)return this.errors.add(`File upload property "${a}" was removed.`),!1;if(o==="file"&&c!=="file")return this.errors.add(`File upload property "${a}" type changed.`),!1;if(o==="fileArray"&&c!=="fileArray")return this.errors.add(`File upload property "${a}" type changed.`),!1;if(o!=="file"&&o!=="fileArray"&&c!=="file"&&c!=="fileArray"&&!this.areTypeReferencesCompatible({from:o,to:c}))return this.errors.add(`File upload property "${a}" type changed.`),!1}return!0}checkHttpResponseBreakingChanges({id:t,from:r,to:i}){if(r.statusCode!==i.statusCode&&this.errors.add(`Response status code changed from "${r.statusCode}" to "${i.statusCode}".`),!(r.body==null&&i.body==null)){if(r.body==null||i.body==null){this.errors.add(`Response body was ${r.body==null?"added":"removed"}.`);return}switch(r.body.type){case"json":if(i.body.type==="json"){this.areJsonResponsesCompatible({from:r.body.value,to:i.body.value});return}break;case"fileDownload":if(i.body.type==="fileDownload")return;break;case"text":if(i.body.type==="text")return;break;case"bytes":if(i.body.type==="bytes")return;break;case"streaming":if(i.body.type==="streaming"){this.areStreamingResponsesCompatible({from:r.body.value,to:i.body.value});return}break;case"streamParameter":if(i.body.type==="streamParameter"){this.areStreamingResponsesCompatible({from:r.body.streamResponse,to:i.body.streamResponse});return}break;default:vt(r.body)}this.errors.add(`HTTP response type "${r.body.type}" defined for endpoint "${t}" is not compatible with type "${i.body.type}".`)}}areJsonResponsesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.responseBodyType,to:r.responseBodyType})}areStreamingResponsesCompatible({from:t,to:r}){switch(t.type){case"json":if(r.type==="json")return this.areTypeReferencesCompatible({from:t.payload,to:r.payload});break;case"sse":if(r.type==="sse")return this.areTypeReferencesCompatible({from:t.payload,to:r.payload});break;case"text":if(r.type==="text")return!0;break;default:vt(t)}return this.errors.add(`Streaming response type "${t.type}" is not compatible with type "${r.type}".`),!1}areTypeDeclarationsCompatible({from:t,to:r}){return pUi(t.availability)?!0:this.areDeclaredTypeNamesCompatible({from:t.name,to:r.name})&&this.areTypeShapesCompatible({from:t.shape,to:r.shape})}areTypeShapesCompatible({from:t,to:r}){switch(t.type){case"alias":if(r.type==="alias")return this.areAliasTypesCompatible({from:t,to:r});break;case"enum":if(r.type==="enum")return this.areEnumTypesCompatible({from:t,to:r});break;case"object":if(r.type==="object")return this.areObjectTypesCompatible({from:t,to:r});break;case"union":if(r.type==="union")return this.areUnionTypesCompatible({from:t,to:r});break;case"undiscriminatedUnion":if(r.type==="undiscriminatedUnion")return this.areUndiscriminatedUnionTypesCompatible({from:t,to:r});break;default:vt(t)}return this.errors.add(`Type "${t.type}" is not compatible with type "${r.type}".`),!1}areAliasTypesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.aliasOf,to:r.aliasOf})}areEnumTypesCompatible({from:t,to:r}){let i=Object.fromEntries(t.values.map(a=>[a.name.wireValue,a])),n=Object.fromEntries(r.values.map(a=>[a.name.wireValue,a]));return Object.keys(i).length!==Object.keys(n).length?!1:Object.values(i).every(a=>{let o=n[a.name.wireValue];return o?this.areNameAndWireValuesCompatible({from:a.name,to:o.name}):(this.errors.add(`Enum value "${a.name.wireValue}" was removed.`),!1)})}areObjectTypesCompatible({from:t,to:r}){let i=Object.fromEntries([...t.properties.map(a=>[a.name.wireValue,a]),...t.extendedProperties?.map(a=>[a.name.wireValue,a])??[]]),n=Object.fromEntries([...r.properties.map(a=>[a.name.wireValue,a]),...r.extendedProperties?.map(a=>[a.name.wireValue,a])??[]]);return this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(i).map(([a,o])=>[a,o.valueType])),to:Object.fromEntries(Object.entries(n).map(([a,o])=>[a,o.valueType]))}),Object.values(i).every(a=>{let o=n[a.name.wireValue];return o?this.areObjectPropertiesCompatible({from:a,to:o}):(this.errors.add(`Object property "${a.name.wireValue}" was removed.`),!1)})}areObjectPropertiesCompatible({from:t,to:r}){return this.areNameAndWireValuesCompatible({from:t.name,to:r.name})&&this.areTypeReferencesCompatible({from:t.valueType,to:r.valueType})}areUnionTypesCompatible({from:t,to:r}){if(!this.areNameAndWireValuesCompatible({from:t.discriminant,to:r.discriminant}))return this.errors.add(`Union type with discriminant value "${t.discriminant.wireValue}" changed.`),!1;let i=new Set(t.extends.map(s=>this.getKeyForDeclaration(s))),n=new Set(r.extends.map(s=>this.getKeyForDeclaration(s)));for(let s of i)if(!n.has(s))return this.errors.add(`Extended type "${s}" was removed.`),!1;let a=Object.fromEntries(t.baseProperties.map(s=>[s.name.wireValue,s])),o=Object.fromEntries(r.baseProperties.map(s=>[s.name.wireValue,s]));for(let s of Object.values(a)){let u=o[s.name.wireValue];if(!u)return this.errors.add(`Union type with discriminant value "${s.name.wireValue}" no longer has a property named "${s.name.wireValue}".`),!1;if(!this.areObjectPropertiesCompatible({from:s,to:u}))return!1}this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(a).map(([s,u])=>[s,u.valueType])),to:Object.fromEntries(Object.entries(o).map(([s,u])=>[s,u.valueType]))});let c=Object.fromEntries(t.types.map(s=>[s.discriminantValue.wireValue,s])),d=Object.fromEntries(r.types.map(s=>[s.discriminantValue.wireValue,s]));return Object.values(c).every(s=>{let u=d[s.discriminantValue.wireValue];return u?this.areSingleUnionTypesCompatible({from:s.shape,to:u.shape}):(this.errors.add(`Union type for discriminant value "${s.discriminantValue.wireValue}" was removed.`),!1)})}areSingleUnionTypesCompatible({from:t,to:r}){switch(t.propertiesType){case"samePropertiesAsObject":if(r.propertiesType==="samePropertiesAsObject")return this.areDeclaredTypeNamesCompatible({from:t,to:r});break;case"singleProperty":if(r.propertiesType==="singleProperty")return this.areNameAndWireValuesCompatible({from:t.name,to:r.name})&&this.areTypeReferencesCompatible({from:t.type,to:r.type});break;case"noProperties":if(r.propertiesType==="noProperties")return!0;break;default:vt(t)}return this.errors.add(`Single union type of style "${t.propertiesType}" is not compatible with style "${r.propertiesType}".`),!1}areUndiscriminatedUnionTypesCompatible({from:t,to:r}){return t.members.every((i,n)=>{let a=r.members[n];return a?this.areTypeReferencesCompatible({from:i.type,to:a.type}):(this.errors.add(`Undiscriminated union member at index ${n} was removed.`),!1)})}checkForNewRequiredTypeReferences({from:t,to:r}){for(let[i,n]of Object.entries(r))t[i]||(n.type!=="container"||n.container.type!=="optional")&&this.errors.add(`Required property "${i}" was added.`)}checkForNewFileUploadRequestProperties({from:t,to:r}){for(let[i,n]of Object.entries(r))t[i]||n==="file"||n==="fileArray"||(n.type!=="container"||n.container.type!=="optional")&&this.errors.add(`Required property "${i}" was added.`)}checkForNewInlinedRequestBodyProperties({from:t,to:r}){for(let[i,n]of Object.entries(r))t[i]||(n.type!=="container"||n.container.type!=="optional")&&this.errors.add(`Required property "${i}" was added.`)}areTypeReferencesCompatible({from:t,to:r}){switch(t.type){case"primitive":if(r.type==="primitive")return this.arePrimitiveTypesCompatible({from:t,to:r});break;case"container":if(r.type==="container")return this.areContainerTypesCompatible({from:t.container,to:r.container});break;case"named":if(r.type==="named")return this.areNamedTypesCompatible({from:t,to:r});break;case"unknown":if(r.type==="unknown")return!0;break;default:vt(t)}return this.errors.add(`TypeReference "${t.type}" is not compatible with type "${r.type}".`),!1}arePrimitiveTypesCompatible({from:t,to:r}){return t.primitive.v1===r.primitive.v1}areContainerTypesCompatible({from:t,to:r}){switch(t.type){case"list":if(r.type==="list")return this.areTypeReferencesCompatible({from:t.list,to:r.list});break;case"set":if(r.type==="set")return this.areTypeReferencesCompatible({from:t.set,to:r.set});break;case"map":if(r.type==="map")return this.areTypeReferencesCompatible({from:t.keyType,to:r.keyType})&&this.areTypeReferencesCompatible({from:t.valueType,to:r.valueType});break;case"optional":if(r.type==="optional")return this.areTypeReferencesCompatible({from:t.optional,to:r.optional});break;case"nullable":if(r.type==="nullable")return this.areTypeReferencesCompatible({from:t.nullable,to:r.nullable});break;case"literal":if(r.type==="literal")return this.areLiteralsCompatible({from:t.literal,to:r.literal});break;default:vt(t)}return this.errors.add(`Container type "${t.type}" is not compatible with type "${r.type}".`),!1}areNamedTypesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&this.areFernFilepathsCompatible({from:t.fernFilepath,to:r.fernFilepath})}areDeclaredTypeNamesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&this.areFernFilepathsCompatible({from:t.fernFilepath,to:r.fernFilepath})}areDeclaredErrorNamesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&this.areFernFilepathsCompatible({from:t.fernFilepath,to:r.fernFilepath})}areNameAndWireValuesCompatible({from:t,to:r}){return this.areNamesCompatible({from:t.name,to:r.name})&&t.wireValue===r.wireValue}areLiteralsCompatible({from:t,to:r}){switch(t.type){case"boolean":if(r.type==="boolean")return t.boolean===r.boolean;break;case"string":if(r.type==="string")return t.string===r.string;break;default:vt(t)}return!1}areFernFilepathsCompatible({from:t,to:r}){return t.allParts.length!==r.allParts.length?!1:t.allParts.every((i,n)=>{let a=r.allParts[n];return a==null?!1:this.areNamesCompatible({from:i,to:a})})}areNamesCompatible({from:t,to:r}){return t.originalName===r.originalName}getInlinedRequestBody(t){let r={};for(let i of[...t.extendedProperties??[],...t.properties])r[i.name.wireValue]=i.valueType;return r}getFileUploadRequest(t){let r={};for(let i of t)switch(i.type){case"file":r[i.value.key.wireValue]="file";break;case"bodyProperty":r[i.name.wireValue]=i.valueType;break;default:vt(i)}return r}getKeyForDeclaration({name:t,fernFilepath:r}){return`${r.allParts.map(n=>n.camelCase.unsafeName).join(".")}.${t.pascalCase.unsafeName}`}};function Hbn(e,t,r){let{environments:i,changedBaseUrlIds1:n,changedBaseUrlIds2:a}=zVD(e.environments,t.environments,r),{services:o,websocketChannels:c}=NVD(e,t,n,a);return{apiName:e.apiName,basePath:e.basePath,selfHosted:e.selfHosted&&t.selfHosted,apiDisplayName:e.apiDisplayName??t.apiDisplayName,apiDocs:e.apiDocs??t.apiDocs,auth:{requirement:e.auth?.requirement??t.auth?.requirement,schemes:t.auth?.schemes?.length!=null&&t.auth.schemes.length>(e.auth?.schemes?.length??0)?t.auth.schemes:e.auth?.schemes??[],docs:e.auth?.docs??t.auth?.docs},headers:[...e.headers??[],...t.headers??[]],environments:i,types:{...e.types??{},...t.types??{}},constants:{...e.constants??{},...t.constants??{}},errors:{...e.errors??{},...t.errors??{}},services:o,webhookGroups:{...e.webhookGroups??{},...t.webhookGroups??{}},subpackages:RVD(e.subpackages,t.subpackages),websocketChannels:c,rootPackage:{service:e.rootPackage.service??t.rootPackage.service,types:[...e.rootPackage.types??[],...t.rootPackage.types??[]],errors:[...e.rootPackage.errors??[],...t.rootPackage.errors??[]],subpackages:[...e.rootPackage.subpackages??[],...(t.rootPackage.subpackages??[]).filter(d=>!e.rootPackage.subpackages?.includes(d))],fernFilepath:e.rootPackage.fernFilepath??t.rootPackage.fernFilepath,webhooks:e.rootPackage.webhooks??t.rootPackage.webhooks,websocket:e.rootPackage.websocket??t.rootPackage.websocket,hasEndpointsInTree:e.rootPackage.hasEndpointsInTree||t.rootPackage.hasEndpointsInTree,navigationConfig:e.rootPackage.navigationConfig??t.rootPackage.navigationConfig,docs:e.rootPackage.docs??t.rootPackage.docs},fdrApiDefinitionId:e.fdrApiDefinitionId??t.fdrApiDefinitionId,apiVersion:e.apiVersion??t.apiVersion,idempotencyHeaders:[...e.idempotencyHeaders??[],...t.idempotencyHeaders??[]],pathParameters:[...e.pathParameters??[],...t.pathParameters??[]],errorDiscriminationStrategy:e.errorDiscriminationStrategy??t.errorDiscriminationStrategy,variables:[...e.variables??[],...t.variables??[]],serviceTypeReferenceInfo:e.serviceTypeReferenceInfo??t.serviceTypeReferenceInfo,readmeConfig:e.readmeConfig??t.readmeConfig,sourceConfig:e.sourceConfig??t.sourceConfig,publishConfig:e.publishConfig??t.publishConfig,dynamic:e.dynamic??t.dynamic,sdkConfig:e.sdkConfig??t.sdkConfig,audiences:[...e.audiences??[],...t.audiences??[]],generationMetadata:e.generationMetadata??t.generationMetadata,apiPlayground:e.apiPlayground??t.apiPlayground}}function RVD(e,t){let r=e;for(let[i,n]of Object.entries(t))r[i]==null?r[i]=n:r[i]={name:n.name,displayName:n.displayName,fernFilepath:n.fernFilepath,hasEndpointsInTree:r[i].hasEndpointsInTree||n.hasEndpointsInTree,navigationConfig:r[i].navigationConfig??n.navigationConfig,docs:r[i].docs??n.docs,service:r[i].service??n.service,subpackages:[...r[i].subpackages??[],...(n.subpackages??[]).filter(a=>!r[i]?.subpackages?.includes(a))],webhooks:r[i].webhooks??n.webhooks,websocket:r[i].websocket??n.websocket,errors:[...r[i].errors??[],...n.errors??[]],types:[...r[i].types??[],...n.types??[]]};return r}function zVD(e,t,r){if(e==null&&t==null)return{environments:void 0,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(t==null)return{environments:e,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(e==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(JSON.stringify(e)===JSON.stringify(t))return{environments:e,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let i=Nph(e),n=Nph(t);if(i&&n&&e.environments.type==="singleBaseUrl"&&t.environments.type==="singleBaseUrl")return{environments:{defaultEnvironment:e.defaultEnvironment??t.defaultEnvironment,environments:SM.singleBaseUrl({environments:[...e.environments.environments,...t.environments.environments]})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let a=i?t.defaultEnvironment:e.defaultEnvironment,o=e.environments,c=t.environments;if(o.type==="singleBaseUrl"&&c.type==="singleBaseUrl"){let d=i?c:o,s=i?o:c,u={},{deconflictedEnvironments2:l,changedBaseUrlIds2:p}=FVD(d,s,r);if(d.environments[0]==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let _="Base",h=r.generateName("Base");return d.environments.forEach(y=>{u[y.id]=_}),{environments:{defaultEnvironment:a,environments:SM.multipleBaseUrls({baseUrls:[{id:_,name:h},...l.environments.map(y=>({id:y.id,name:y.name}))],environments:d.environments.map(y=>({id:y.id,name:y.name,urls:{[_]:y.url,...Object.fromEntries(l.environments.map(b=>[b.id,b.url]))},docs:void 0}))})},changedBaseUrlIds1:i?p:u,changedBaseUrlIds2:i?u:p}}if(o.type==="multipleBaseUrls"&&c.type==="singleBaseUrl"||o.type==="singleBaseUrl"&&c.type==="multipleBaseUrls"){let d=o.type==="singleBaseUrl"?o:c,s=o.type==="multipleBaseUrls"?o:c,{deconflictedEnvironments1:u,changedBaseUrlIds1:l}=QVD(d,s,r);return{environments:{defaultEnvironment:a,environments:SM.multipleBaseUrls({baseUrls:[...s.baseUrls,...u.environments.map(p=>({id:p.id,name:p.name}))],environments:s.environments.map(p=>({...p,urls:{...p.urls,...Object.fromEntries(u.environments.map(_=>[_.id,_.url]))}}))})},changedBaseUrlIds1:o.type==="singleBaseUrl"?l:void 0,changedBaseUrlIds2:o.type==="singleBaseUrl"?void 0:l}}if(o.type==="multipleBaseUrls"&&c.type==="multipleBaseUrls"){let{deconflictedEnvironments:d,changedBaseUrlIds:s}=UVD(o,c,r);return{environments:{defaultEnvironment:a,environments:SM.multipleBaseUrls({baseUrls:[...o.baseUrls,...d.baseUrls],environments:o.environments.flatMap(u=>d.environments.map(l=>({...u,urls:{...u.urls,...l.urls}})))})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:s}}return{environments:e??t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0}}function NVD(e,t,r,i){if(r!=null)for(let[o,c]of Object.entries(r)){for(let d of Object.values(e.services))for(let s of Object.values(d.endpoints))s.baseUrl==o&&(s.baseUrl=c),s.v2BaseUrls?.includes(o)&&(s.v2BaseUrls=s.v2BaseUrls.map(u=>u===o?c:u));for(let d of Object.values(e.websocketChannels??{}))d.baseUrl==o&&(d.baseUrl=c)}if(i!=null)for(let[o,c]of Object.entries(i)){for(let d of Object.values(t.services))for(let s of Object.values(d.endpoints))s.baseUrl==o&&(s.baseUrl=c),s.v2BaseUrls?.includes(o)&&(s.v2BaseUrls=s.v2BaseUrls.map(u=>u===o?c:u));for(let d of Object.values(t.websocketChannels??{}))d.baseUrl==o&&(d.baseUrl=c)}let n=e.services;for(let[o,c]of Object.entries(t.services))n[o]==null?n[o]=c:n[o]={availability:c.availability,name:c.name,displayName:c.displayName,basePath:c.basePath,endpoints:[...n[o].endpoints??[],...c.endpoints],pathParameters:[...n[o].pathParameters??[],...c.pathParameters??[]],headers:[...n[o].headers??[],...c.headers??[]],encoding:c.encoding,transport:c.transport,audiences:[...n[o].audiences??[],...c.audiences??[]]};let a={...e.websocketChannels??{},...t.websocketChannels??{}};return{services:n,websocketChannels:a}}function FVD(e,t,r){let i={},n=new Set(e.environments.map(s=>s.id)),a=new Set(e.environments.map(s=>s.name)),o=new Map(e.environments.map(s=>[s.url,s.id])),c=t.environments.filter(s=>{let u=o.get(s.url);return u!=null?(i[s.id]=u,!1):!0}).map(s=>{if(n.has(s.id)||a.has(s.name)){let u=ixc(s.id,n);return i[s.id]=u,{...s,id:u,name:r.generateName(u)}}return s});return{deconflictedEnvironments2:SM.singleBaseUrl({environments:c}),changedBaseUrlIds2:i}}function QVD(e,t,r){let i={},n=new Set(t.baseUrls.map(d=>d.id)),a=new Set(t.baseUrls.map(d=>d.name)),o=e.environments.map(d=>{if(n.has(d.id)||a.has(d.name)){let s=ixc(d.id,n);return i[d.id]=s,{...d,id:s,name:r.generateName(s)}}return d});return{deconflictedEnvironments1:SM.singleBaseUrl({environments:o}),changedBaseUrlIds1:i}}function UVD(e,t,r){let i={},n=new Set(e.baseUrls.map(s=>s.id)),a=new Set(e.baseUrls.map(s=>s.name)),o=t.baseUrls.map(s=>{if(n.has(s.id)||a.has(s.name)){let u=ixc(s.id,n);return i[s.id]=u,{...s,id:u,name:r.generateName(u)}}return s}),c=t.environments.map(s=>({...s,urls:Object.fromEntries(Object.entries(s.urls).map(([u,l])=>[i[u]??u,l]))}));return{deconflictedEnvironments:SM.multipleBaseUrls({baseUrls:o,environments:c}),changedBaseUrlIds:i}}function Nph(e){return e.environments.type==="singleBaseUrl"?e.environments.environments.some(t=>t.url&&(t.url.startsWith("ws://")||t.url.startsWith("wss://"))):e.environments.type==="multipleBaseUrls"?e.environments.environments.some(t=>Object.values(t.urls).some(r=>r&&(r.startsWith("ws://")||r.startsWith("wss://")))):!1}function ixc(e,t){let r=e,i=1;for(;t.has(r);)r=`${e}-${i}`,i++;return r}var Oa=class e{breadcrumbs=[];context;static STRING=Ar.TypeReference.primitive({v1:"STRING",v2:Ar.PrimitiveTypeV2.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=Ar.TypeReference.container(Ar.ContainerType.optional(e.STRING));constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r}};var Qph=require("fs/promises");var nxc=class{_map;_path;_lastScalar;_fragments;_count;constructor(){this._map={},this._path=[],this._lastScalar="",this._fragments=[],this._count=0}get map(){return this._map}resolveNode(t,r){if(t.path==="."&&(r="."),!this._map[r]){let{line:i,position:n,lineStart:a}=t;this._map[r]={line:i,position:n,lineStart:a}}t.children&&t.children.length>0&&t.children.forEach(i=>{this.resolveNode(i,(r==="."?"":r)+"."+i.path)})}iterFragments(t,r){for(let i=this._fragments.length-1;i>=0;i--){if(!this._fragments[i].path.startsWith(t)||this._fragments[i].path===t)continue;let n=this._fragments.pop();r(n)}}handleState(t,r){if(t==="close"){let i=r.result,n=r.kind,a=this._path.join(".");if(n==="scalar"){this._path.pop(),this._lastScalar=`${i}`;let{line:o,position:c,lineStart:d}=r;this._path.length===0?this._map["."+i]={line:o,position:c,lineStart:d}:this._fragments.push({path:this._path.join(".")+"."+i,line:o,position:c,lineStart:d})}else if(n==="mapping"){let o={path:a,children:[],line:0,position:0,lineStart:0},c=0;this.iterFragments(a,d=>{c++,!((!d.children||d.children.length===0)&&c%2===1)&&(this._path.length===1?this.resolveNode(d,d.path):(o.children.push({...d,path:d.path.slice(a.length+1)}),o.line=d.line,o.position=d.position,o.lineStart=d.lineStart))}),o.children&&o.children.length>0&&this._fragments.push(o),this._path.pop()}else if(n==="sequence"){let o={path:a,children:[],line:0,position:0,lineStart:0},c=new Set,d=i.length;this.iterFragments(a,s=>{c.has(s.position)||(d--,c.add(s.position),this._path.length===1?this.resolveNode(s,`${a}.${d}`):(o.children.push({...s,path:d.toString()}),o.line=s.line,o.position=s.position,o.lineStart=s.lineStart))}),o.children&&o.children.length>0&&this._fragments.push(o),this._path.pop()}else this._path.pop()}if(t==="open"){if(this._count===0){let{line:i,position:n,lineStart:a}=r;this._map["."]={line:i,position:n,lineStart:a}}this._path.push(this._lastScalar),this._count++}}listen(){return this.handleState.bind(this)}lookup(t){let r=t instanceof Array?t.map(n=>`${n}`).join("."):`${t}`;r.startsWith(".")||(r="."+r),r.startsWith("..")&&(r=r.slice(1)),r=r.replace(/\[/g,".").replace(/\]/g,"");let i=this._map[r];if(i)return{line:i.line+1,column:i.position-i.lineStart+1,position:i.position}}},Fph=nxc;var zR;(function(e){e.WARNING="warning",e.ERROR="error"})(zR||(zR={}));var GEe=class{errors=[];logger;breadcrumbToLineNumberMapper;relativeFilepathToSpec;constructor({logger:t,relativeFilepathToSpec:r}){this.logger=t,this.relativeFilepathToSpec=r,r&&(this.breadcrumbToLineNumberMapper=new axc({logger:t,relativePathToFile:He.of(r)}))}collect(t){this.errors.push(t)}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}dedupe(){let t=[],r=new Set,i=0;for(let n of this.errors){let a=n.path?n.path.join("->"):"",o=`${n.message}|${n.level||zR.WARNING}|${a}`;r.has(o)?i++:(r.add(o),t.push(n))}return this.errors=t,i}getErrorStats(){this.dedupe();let t=0,r=0;for(let i of this.errors)i.level===zR.ERROR?t++:(i.level===zR.WARNING||i.level===void 0)&&r++;return{numErrors:t,numWarnings:r}}async logErrors({logWarnings:t}){this.dedupe();for(let r of this.errors){let i=r.level??zR.WARNING;if(!(i===zR.WARNING&&!t))switch(i){case zR.ERROR:if(this.logger.log(Ou.Debug,r.message),r.path&&r.path.length>0){let n=await this.breadcrumbToLineNumberMapper?.getSourceLocation(r.path),a=n?`${this.relativeFilepathToSpec}:${n.line}:${n.column}`:r.path.join(" -> ");this.logger.log(Ou.Debug,` - at location (${a})`)}break;case zR.WARNING:if(this.logger.log(Ou.Warn,r.message),r.path&&r.path.length>0){let n=await this.breadcrumbToLineNumberMapper?.getSourceLocation(r.path),a=n?`${this.relativeFilepathToSpec}:${n.line}:${n.column}`:r.path.join(" -> ");this.logger.log(Ou.Warn,` - at location (${a})`)}r.resolution&&this.logger.log(Ou.Warn,` - resolution: ${r.resolution}`);break}}}},axc=class{logger;relativePathToFile;map=new Fph;initialized=!1;constructor({relativePathToFile:t,logger:r}){this.relativePathToFile=t,this.logger=r}async initialize(){if(!this.initialized)try{let t=await(0,Qph.readFile)(this.relativePathToFile,"utf-8");qi.load(t,{listener:this.map.listen()}),this.initialized=!0}catch(t){this.logger.log(Ou.Warn,`Failed to initialize line number mapping for ${this.relativePathToFile}: ${JSON.stringify(t)}`)}}async getSourceLocation(t){return this.initialized||await this.initialize(),this.map.lookup(t)}};var bC=class e{args;spec;settings;errorCollector;logger;generationLanguage;smartCasing;casingsGenerator;namespace;exampleGenerationArgs;authOverrides;environmentOverrides;globalHeaderOverrides;enableUniqueErrorsPerEndpoint;generateV1Examples;documentBaseDir;constructor(t){this.args=t,this.spec=t.spec,this.settings=t.settings,this.errorCollector=t.errorCollector,this.logger=t.logger,this.generationLanguage=t.generationLanguage,this.smartCasing=t.smartCasing,this.namespace=t.namespace,this.casingsGenerator=lx({generationLanguage:t.generationLanguage,keywords:void 0,smartCasing:t.smartCasing}),this.exampleGenerationArgs=t.exampleGenerationArgs,this.authOverrides=t.authOverrides,this.environmentOverrides=t.environmentOverrides,this.globalHeaderOverrides=t.globalHeaderOverrides,this.enableUniqueErrorsPerEndpoint=t.enableUniqueErrorsPerEndpoint,this.generateV1Examples=t.generateV1Examples,this.documentBaseDir=t.documentBaseDir}static BREADCRUMBS_TO_IGNORE=["properties","allOf","anyOf"];convertBreadcrumbsToName(t){let r=t.filter((n,a)=>!(/^\d+$/.test(n)||e.BREADCRUMBS_TO_IGNORE.includes(n)||a===0&&n==="components"||a===1&&n==="schemas"||t[0]==="paths"&&(a===0||a===1&&["get","post","put","delete","patch"].includes(n)||a===2&&t[1]!=null&&["get","post","put","delete","patch"].includes(t[1])&&n==="parameters"))),i=ou(r.join("_"));return i.charAt(0).toUpperCase()+i.slice(1)}createFernFilepath(t={}){let r=this.namespace!=null?[this.casingsGenerator.generateName(this.namespace)]:[],i=t.name!=null?this.casingsGenerator.generateName(t.name):void 0;return{allParts:i?[...r,i]:r,packagePath:r,file:i}}resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:i}){let n=this.spec,a=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(o=>o.replace(/~1/g,"/"));for(let o of a){if(typeof n!="object"||n==null)return i||this.errorCollector.collect({level:zR.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1};n=n[o]}return n==null?(i||this.errorCollector.collect({level:zR.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1}):{resolved:!0,value:n}}getErrorMessageForMissingRef({reference:t}){let r=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/");return r.length>=3&&r[0]==="components"&&r[1]==="schemas"?`Schema ${r[2]} does not exist`:`${t.$ref} does not exist`}async resolveMaybeExternalReference(t){let r=this.spec,i,n=!1,a=null,o;if(this.isExternalReference(t.$ref)){n=!0;let s=t.$ref.split("#"),u=s[0];if(i=s[1],!u)return{resolved:!1};o=u;let l=await fetch(u);if(!l.ok)return{resolved:!1};try{let p=await l.text();try{a=JSON.parse(p),r=a}catch{a=qi.load(p),r=a}if(r==null)return{resolved:!1}}catch{return{resolved:!1}}if(!i)return{resolved:!0,value:r}}let c=i??t.$ref;if(c==null||typeof c!="string")return{resolved:!1};let d=c.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(s=>s.replace(/~1/g,"/"));for(let s of d){if(typeof r!="object"||r==null)return{resolved:!1};r=r[s]}if(r==null)return{resolved:!1};if(n&&typeof r=="object"&&r!==null){let s=new Set;s.add(t.$ref),r=await this.resolveNestedExternalReferences(r,a,s,o)}return{resolved:!0,value:r}}async resolveNestedExternalReferences(t,r,i,n){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){let o=[];for(let c of t)o.push(await this.resolveNestedExternalReferences(c,r,i,n));return o}if(this.isReferenceObject(t)){let o=t.$ref;if(this.isExternalReference(o)){if(i.has(o))return t;i.add(o);let c=await this.resolveMaybeExternalReference({$ref:o});if(i.delete(o),c.resolved)return c.value}else{let c=`${n}${o}`;if(i.has(c))return t;i.add(c);let d=r,s=o.substring(2).split("/").map(u=>u.replace(/~1/g,"/").replace(/~0/g,"~"));for(let u of s){if(typeof d!="object"||d===null)return t;d=d[u]}if(d!=null){let u=await this.resolveNestedExternalReferences(d,r,i,n);return i.delete(o),u}i.delete(o)}return t}let a={};for(let[o,c]of Object.entries(t))typeof c=="object"&&c!==null?a[o]=await this.resolveNestedExternalReferences(c,r,i,n):a[o]=c;return a}getExamplesFromSchema({schema:t,breadcrumbs:r}){if(t==null)return[];let i=t.example!=null?[t.example]:[];return t.examples!=null&&(Array.isArray(t.examples)?i.push(...t.examples):this.errorCollector.collect({message:"Received non-array schema examples",path:r})),i}getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:r,defaultExampleName:i}){if(t==null)return[];let n=[];if(t.example!=null){let a=this.generateUniqueName({prefix:i??`${r.join("_")}_example`,existingNames:[]});n.push([a,{value:t.example}])}return t.examples!=null&&n.push(...Object.entries(t.examples)),n}resolveMaybeReference({schemaOrReference:t,breadcrumbs:r,skipErrorCollector:i}){if(this.isReferenceObject(t)){let n=this.resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:i});return n.resolved?n.value:void 0}return t}resolveExampleRecursively({example:t,breadcrumbs:r,maxDepth:i=10}){let n=t,a=0;for(;this.isReferenceObject(n);){if(a>=i){this.errorCollector.collect({message:`Maximum reference depth (${i}) exceeded while resolving example reference`,path:r});return}let o=this.resolveReference({reference:n,breadcrumbs:r,skipErrorCollector:!0});if(!o.resolved)return;n=o.value,a++}return n}resolveExample(t){if(!this.isReferenceObject(t))return t;let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}resolveExampleWithValue(t){if(!this.isReferenceObject(t))return this.returnExampleValue(t);let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}returnExampleValue(t){return this.isExampleWithValue(t)?t.value:t}getPropertyAccess(t){let r=t;for(;this.isReferenceObject(r);){let a=this.resolveReference({reference:r});if(!a.resolved)return;r=a.value}let{readOnly:i,writeOnly:n}=this.getReadOnlyWriteOnlyFromSchema(r);if(!(i&&n)){if(i)return mYt.ReadOnly;if(n)return mYt.WriteOnly}}getReadOnlyWriteOnlyFromSchema(t){if(t.allOf&&t.allOf.length>0){let r=!0,i=!0;for(let n of t.allOf){let a=n;if(this.isReferenceObject(n)){let c=this.resolveReference({reference:n});if(!c.resolved)continue;a=c.value}let o=this.getReadOnlyWriteOnlyFromSchema(a);r=r&&o.readOnly,i=i&&o.writeOnly}return{readOnly:r,writeOnly:i}}else return{readOnly:!!t.readOnly,writeOnly:!!t.writeOnly}}getAudiences({operation:t,breadcrumbs:r}){let n=new NR.AudienceExtension({operation:t,breadcrumbs:r,context:this}).convert();if(n!=null)return n.audiences}getAvailability({node:t,breadcrumbs:r}){for(;this.isReferenceObject(t);){let a=this.resolveReference({reference:t});if(!a.resolved)return;t=a.value}let n=new NR.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(n!=null)return{status:n,message:void 0};if(t.deprecated===!0)return{status:E1.Deprecated,message:void 0}}getTypeIdFromSchemaReference(t){let r=t.$ref.match(/\/schemas\/(.+)$/);if(!(!r||!r[1]))return r[1]}createNamedTypeReference(t,r){return ii.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(t),typeId:t,displayName:r,default:void 0,inline:!1})}typeReferenceToDeclaredTypeName(t){if(t.type!=="named")return;let r=t.typeId;return{typeId:r,fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(r),displayName:t.displayName}}removeSchemaFromInlinedTypes({id:t,inlinedTypes:r}){return Object.fromEntries(Object.entries(r).filter(([i])=>i!==t))}static maybeTrimPrefix(t,r){return t.startsWith(r)?t.slice(r.length):t}generateUniqueName({prefix:t,existingNames:r}){if(!r.includes(t))return t;let i=0;for(;r.includes(`${t}_${i}`);)i++;return`${t}_${i}`}isReferenceObject(t){return typeof t=="object"&&t!==null&&"$ref"in t}isExternalReference(t){return typeof t=="string"&&(t.startsWith("http://")||t.startsWith("https://"))}isReferenceObjectWithIdentifier(t){return this.isReferenceObject(t)&&("title"in t||"name"in t||"messageId"in t||"summary"in t)}isExampleWithSummary(t){return typeof t=="object"&&t!=null&&"summary"in t&&typeof t.summary=="string"&&t.summary.length>0}isExampleWithValue(t){return typeof t=="object"&&t!=null&&"value"in t}isOptional(t){return t.type==="container"&&t.container.type==="optional"}isNullable(t){return t.type==="container"&&t.container.type==="nullable"}isList(t){return t.type==="container"&&t.container.type==="list"}isFile(t){return t.type==="primitive"&&t.primitive.v2?.type==="string"&&t.primitive.v2.validation?.format==="binary"}getAsString(t){if(typeof t=="string")return t}getAsInteger(t){if(typeof t=="number"&&Number.isInteger(t))return t}getAsNumber(t){if(typeof t=="number")return t}getAsBoolean(t){if(typeof t=="boolean")return t}getAsArray(t){if(Array.isArray(t))return t}getAsObject(t){if(typeof t=="object"&&t!==null&&!Array.isArray(t))return t}getGroup({groupParts:t,namespace:r}){let i=[];return r!=null&&i.push(r),i.push(...t??[]),i}isObjectSchemaType(t){return t.type==="object"||t.properties!=null}};var fl=class{breadcrumbs;context;constructor(t){this.breadcrumbs=t.breadcrumbs,this.context=t.context}getExtensionValue(t,r){if(typeof t!="object"||t==null)return;let i=t[this.key];if(i!=null)return i;if(r!=null)return t[r]}};var NR={};Yt(NR,{AudienceExtension:()=>spu,FernAvailabilityExtension:()=>cpu,FernEnumExtension:()=>lpu,FernIgnoreExtension:()=>Kbn,FernOptionalExtension:()=>fpu,FernTypeExtension:()=>hpu,FernTypeNameExtension:()=>ypu,SdkGroupNameExtension:()=>dpu,SdkMethodNameExtension:()=>ppu,ServerFromOperationNameExtension:()=>_pu});var spu=class extends fl{operation;key="x-fern-audiences";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(i=>typeof i=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{audiences:r}}};var cpu=class extends fl{node;key="x-fern-availability";constructor({breadcrumbs:t,node:r,context:i}){super({breadcrumbs:t,context:i}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t==null||typeof t!="string")return;switch(t.toUpperCase().replace(/[-_\s]/g,"_")){case"IN_DEVELOPMENT":return E1.InDevelopment;case"PRE_RELEASE":case"BETA":return E1.PreRelease;case"GENERAL_AVAILABILITY":case"GA":return E1.GeneralAvailability;case"DEPRECATED":return E1.Deprecated;default:return}}};var LVD=Qt.object({snake:Qt.string().optional(),camel:Qt.string().optional(),screamingSnake:Qt.string().optional(),pascal:Qt.string().optional()}),VVD=Qt.object({description:Qt.string().optional(),name:Qt.string().optional(),casing:LVD.optional()}),Uph=Qt.record(VVD);var lpu=class extends fl{schema;key="x-fern-enum";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t==null)return;let r=Uph.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-enum extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data}};var Kbn=class extends fl{operation;key="x-fern-ignore";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-ignore",path:this.breadcrumbs});return}return t}}};var fpu=class extends fl{parameter;key="x-fern-optional";constructor({breadcrumbs:t,parameter:r,context:i}){super({breadcrumbs:t,context:i}),this.parameter=r}convert(){let t=this.getExtensionValue(this.parameter);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-optional",path:this.breadcrumbs});return}return t}}};var dpu=class extends fl{operation;key="x-fern-sdk-group-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(i=>typeof i=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{groups:r}}};var ppu=class extends fl{operation;key="x-fern-sdk-method-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null&&typeof t=="string")return{methodName:t}}};var _pu=class extends fl{operation;key="x-fern-server-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation,"x-name");if(!(t==null||typeof t!="string"))return t}};var hpu=class extends fl{schema;key="x-fern-type";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t!=null&&typeof t=="string")return t}};var ypu=class extends fl{schema;key="x-fern-type-name";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(typeof t=="string")return t}};var _8t=class extends Oa{ir;audiences;irGraph;constructor({breadcrumbs:t=[],context:r,audiences:i}){super({breadcrumbs:t,context:r}),this.audiences=i,this.irGraph=new xbn(i),this.ir={auth:{docs:void 0,requirement:Ar.AuthSchemesRequirement.All,schemes:[]},selfHosted:!1,types:{},services:{},errors:{},webhookGroups:{},websocketChannels:void 0,headers:[],idempotencyHeaders:[],apiVersion:void 0,apiDisplayName:void 0,apiDocs:void 0,basePath:void 0,pathParameters:[],errorDiscriminationStrategy:Ar.ErrorDiscriminationStrategy.statusCode(),variables:[],serviceTypeReferenceInfo:{sharedTypes:[],typesReferencedOnlyByService:{}},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0,environments:void 0,fdrApiDefinitionId:void 0,rootPackage:this.createPackage(),subpackages:{},sdkConfig:{hasFileDownloadEndpoints:!1,hasPaginatedEndpoints:!1,hasStreamingEndpoints:!1,isAuthMandatory:!0,platformHeaders:{language:"",sdkName:"",sdkVersion:"",userAgent:void 0}},audiences:void 0,generationMetadata:void 0,apiPlayground:void 0}}removeXFernIgnores({document:t,breadcrumbs:r=[]}){return Array.isArray(t)?t.filter((i,n)=>!new Kbn({breadcrumbs:[...r,String(n)],operation:i,context:this.context}).convert()).map((i,n)=>this.removeXFernIgnores({document:i,breadcrumbs:[...r,String(n)]})):t!=null&&typeof t=="object"?Object.fromEntries(Object.entries(t).filter(([i,n])=>!new Kbn({breadcrumbs:[...r,i],operation:n,context:this.context}).convert()).map(([i,n])=>[i,this.removeXFernIgnores({document:n,breadcrumbs:[...r,i]})])):t}finalizeIr(){let t={...this.ir,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})},audiences:this.audiences.type==="select"?this.audiences.audiences:void 0};this.irGraph.hasNoAudiences()||(t=this.filterIrForAudiences(t));let r=this.context.exampleGenerationArgs,i=ZGc({ir:t,exampleGeneration:r});if(this.context.generateV1Examples){let n=J7a({ir:t,exampleGeneration:r});return{...t,...n,...i}}return{...t,...i}}filterIrForAudiences(t){let r=this.irGraph.getFilteredEndpoints(),i=this.irGraph.getFilteredChannels(),n=this.irGraph.getFilteredWebhooks();for(let a of Object.values(t.services)){let o=[];for(let c of a.endpoints)r.has(c.id)&&o.push(c);a.endpoints=o}return t.websocketChannels=Object.fromEntries(Object.entries(t.websocketChannels??{}).filter(([a])=>i.has(a))),t.webhookGroups=Object.fromEntries(Object.entries(t.webhookGroups).map(([a,o])=>{let c=o.filter(d=>d.id!=null&&n.has(d.id));return[a,c]})),t}async resolveAllExternalRefs({spec:t}){let r=[t];for(;r.length>0;){let i=r.shift();i!=null&&(Array.isArray(i)?await this.resolveExternalRefsInArray(i,r):typeof i=="object"&&await this.resolveExternalRefsInObject(i,r))}return t}async resolveExternalRefsInArray(t,r){for(let i=0;i<t.length;i++)t[i]=await this.resolveReferenceChain(t[i],r)}async resolveExternalRefsInObject(t,r){for(let[i,n]of Object.entries(t))t[i]=await this.resolveReferenceChain(n,r)}async resolveReferenceChain(t,r){let i=t;if(!this.context.isReferenceObject(i))return r.push(i),t;for(;this.context.isReferenceObject(i);){let n=this.context.isExternalReference(i.$ref),a=await this.context.resolveMaybeExternalReference(i);if(a.resolved){if(i=a.value,n)return i}else return t}return t}shouldAddServerToCollectedServers({server:t,currentServers:r,specType:i="openapi"}){return i==="openapi"?!r.some(n=>n.url===t.url&&"x-fern-server-name"in n&&"x-fern-server-name"in t&&n["x-fern-server-name"]===t["x-fern-server-name"]):!r.some(n=>n.url===t.url&&"name"in n&&"name"in t&&n.name===t.name)}addEndpointToIr({endpoint:t,audiences:r,endpointGroup:i,endpointGroupDisplayName:n,serviceName:a}){let o=this.context.getGroup({groupParts:i,namespace:this.context.namespace}),c=this.getOrCreatePackage({group:i}),d=[...o].map(l=>this.context.casingsGenerator.generateName(l)),s=d[d.length-1];c.service==null&&(c.service=a??`service_${o.map(l=>ou(l)).join("/")}`),this.ir.services[c.service]==null&&(this.ir.services[c.service]=this.createNewService({allParts:d,finalpart:s,endpointGroupDisplayName:n})),this.ir.services[c.service]?.endpoints.push(t);let u=this.ir.services[c.service];u!=null&&(this.irGraph.addEndpoint(u,t),this.irGraph.markEndpointForAudience(u.name,[t],r))}addWebhookToIr({webhook:t,operationId:r,audiences:i,group:n}){let a=n?.join(".")??r,o=this.getOrCreatePackage({group:n});this.ir.webhookGroups[a]==null&&(this.ir.webhookGroups[a]=[]),this.ir.webhookGroups[a].push(t),o.webhooks=a;let c=this.context.createFernFilepath();this.irGraph.addWebhook(c,t),i!=null&&this.irGraph.markWebhookForAudiences(c,t,i)}addWebsocketChannelToIr({websocketChannel:t,channelPath:r,audiences:i,websocketGroup:n}){let a=ou(n?.join(".")),o=ou(r),c=this.context.namespace?`${ou(this.context.namespace)}/`:"",d=a?`channel_${c}${a}`:`channel_${c}${o}`,s=n?this.getOrCreatePackage({group:n}):this.getOrCreatePackage({group:[o]});this.ir.websocketChannels={...this.ir.websocketChannels,[d]:t},d!==""?s.websocket==null&&(s.websocket=d):this.ir.rootPackage.websocket="";let u=this.context.createFernFilepath();this.irGraph.addChannel(u,d,t),i!=null&&this.irGraph.markChannelForAudiences(u,d,i)}addAuthToIR(t){this.ir.auth=t}addErrorsToIr(t){this.ir.errors=t;for(let r of Object.values(t))this.irGraph.addError(r)}addGlobalHeadersToIr(t){this.ir.headers=t}addEnvironmentsToIr({environmentConfig:t,audiences:r}){if(this.ir.environments=t,r!=null)for(let[i,n]of Object.entries(t??{}))r[i]!=null&&this.irGraph.markEnvironmentForAudiences(n,r[i])}addTypeToRootPackage(t){this.ir.rootPackage.types.push(t)}addSchemaOutputToIr(t,r){let{convertedSchema:i,inlinedTypes:n}=r,o=Object.keys(n).some(c=>c===t)?`${t}Wrapper`:t;this.addTypeToPackage(o),this.addTypesToIr({...n,[o]:i})}addTypeToPackage(t){let r=this.context.getGroup({groupParts:[],namespace:this.context.namespace});this.getOrCreatePackage({group:r}).types.push(t)}addTypesToIr(t){Object.assign(this.ir.types,Object.fromEntries(Object.entries(t).map(([r,i])=>[r,i.typeDeclaration])));for(let r of Object.values(t))this.irGraph.addType({declaredTypeName:r.typeDeclaration.name,descendantTypeIds:r.typeDeclaration.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:r.propertiesByAudience,descendantFilepaths:new Set}),this.irGraph.markTypeForAudiences(r.typeDeclaration.name,r.audiences)}updateEndpointsWithDefaultUrl(t){if(t!=null)for(let r of Object.values(this.ir.services))for(let i of r.endpoints)i.baseUrl==null&&(i.baseUrl=t)}createNewService({allParts:t,finalpart:r,endpointGroupDisplayName:i}){return{name:{fernFilepath:{allParts:t,packagePath:t.slice(0,-1),file:r}},displayName:i,basePath:DM(""),headers:[],pathParameters:[],availability:void 0,endpoints:[],transport:void 0,encoding:void 0,audiences:void 0}}createPackage(t={}){return{fernFilepath:this.context.createFernFilepath(t),service:void 0,types:[],errors:[],subpackages:[],docs:void 0,webhooks:void 0,websocket:void 0,hasEndpointsInTree:!1,navigationConfig:void 0}}getOrCreatePackage({group:t}){let r=[];if(this.context.namespace!=null&&r.push(this.context.namespace),r.push(...(t??[]).map(n=>ou(n))),r.length==0)return this.ir.rootPackage;let i=this.ir.rootPackage;for(let n=0;n<r.length;n++){let a=r[n]??"",c=`subpackage_${r.slice(0,n+1).join("/")}`;this.ir.subpackages[c]==null&&(this.ir.subpackages[c]={name:this.context.casingsGenerator.generateName(a),displayName:void 0,...this.createPackage({name:a})});let d=this.ir.subpackages[c];i.subpackages.includes(c)||i.subpackages.push(c),i=d}return i}};var Fm={};Yt(Fm,{AbstractConverters:()=>uxc,ExampleConverter:()=>gF,SchemaConverters:()=>oxc,ServersConverter:()=>tge});var uxc={};Yt(uxc,{AbstractMediaTypeObjectConverter:()=>gpu,AbstractParameterConverter:()=>Opu});var WVD=/^literal<\s*(?:"(.*)"|(true|false))\s*>$/;function GVD(e){return e.type==="array"||e.properties||e.oneOf||e.anyOf||e.allOf||e.additionalProperties?!1:!!(e.type==="string"||e.type==="number"||e.type==="integer"||e.type==="boolean"||e.const!==void 0||Array.isArray(e.enum)&&e.enum.length>0)}function Lph(e){if(e.const!==void 0)return e.const;if(Array.isArray(e.enum)&&e.enum.length>0)return e.enum[0]}var gF=class e extends Oa{MAX_DEPTH=12;EXAMPLE_STRING=xn.STRING;EXAMPLE_NUMBER=xn.DOUBLE;EXAMPLE_BOOLEAN=xn.BOOLEAN;EXAMPLE_INTEGER=xn.INT;EXAMPLE_DATE=xn.DATE;EXAMPLE_DATE_TIME=xn.DATE_TIME;schema;example;depth;exampleGenerationStrategy;generateOptionalProperties;seenRefs;constructor({breadcrumbs:t,context:r,schema:i,example:n,depth:a=0,exampleGenerationStrategy:o,generateOptionalProperties:c=!1,seenRefs:d=new Set}){super({breadcrumbs:t,context:r}),this.example=n,this.schema=i,this.depth=a,this.exampleGenerationStrategy=o,this.generateOptionalProperties=c,this.seenRefs=d}convert(){if(this.depth>this.MAX_DEPTH)return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:typeof this.example<"u"?this.example:{},errors:[]};if(this.context.isReferenceObject(this.schema)){let i=this.schema.$ref;if(this.seenRefs.has(i))return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}}let t=this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(t==null)return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:"Schema is not resolvable",path:this.breadcrumbs}]};if(typeof t!="object")return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Schema should be an object: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]};if("nullable"in t&&t.nullable===!0&&this.example===null)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let r=this.maybeConvertLiteralFernType(t);return r??(Array.isArray(t.type)?this.convertSchemaTypeArray({resolvedSchema:t}):t.type=="null"?this.convertNull():t.type=="boolean"?this.convertBoolean():t.enum!=null?this.convertEnum(t):t.type=="number"?this.convertNumber():t.type=="string"?this.convertString():t.type=="integer"?this.convertInteger():t.type=="array"?this.convertArray({resolvedSchema:t}):"oneOf"in t&&t.oneOf!=null?this.convertOneOf({resolvedSchema:t}):"anyOf"in t&&t.anyOf!=null?this.convertAnyOf({resolvedSchema:t}):t.type=="object"||t.properties!=null||t.allOf!=null?this.convertObject({resolvedSchema:t}):typeof t=="object"&&Object.keys(t).length===0?{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Unsupported schema type: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]})}convertNull(){let t=this.example===null;return t?{isValid:t,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Example is not null: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertBoolean(){let t=typeof this.example=="boolean";if(t)return{isValid:t,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.default:this.schema.default,i=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.const:this.schema.const;return typeof r=="boolean"||typeof i=="boolean"?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:i??r,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_BOOLEAN,errors:[{message:`Example is not a boolean: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertEnum(t){let r=t.enum?.includes(this.example)??!1;if(r)return{isValid:r,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let i=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return i!==void 0&&t.enum?.includes(i)?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:i,errors:[]}:{isValid:r,coerced:!1,usedProvidedExample:!1,validExample:t.enum?.[0],errors:[{message:`Example is not one of the allowed enum values: ${JSON.stringify(t.enum,null,2)}`,path:this.breadcrumbs}]}}convertNumber(){if(typeof this.example=="number")return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let t=Number(this.example);if(!isNaN(t))return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):this.schema,i=r?.default;return typeof i=="number"?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:i,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.adjustNumberToConstraints(this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_NUMBER,r),errors:[{message:`Example is not a number: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}adjustNumberToConstraints(t,r){if(r==null)return this.context.logger.debug("[ExampleConverter.adjustNumberToConstraints] Schema object is null, returning original number","number:",t.toString()),t;let{minimum:i,maximum:n,exclusiveMinimum:a,exclusiveMaximum:o}=r,c;a!=null?typeof a=="boolean"?c=i!=null?i+Math.max(Number.EPSILON,Math.abs(i)*1e-10):void 0:c=a+Math.max(Number.EPSILON,Math.abs(a)*1e-10):i!=null&&(c=i);let d;return o!=null?typeof o=="boolean"?d=n!=null?n-Math.max(Number.EPSILON,Math.abs(n)*Number.EPSILON):void 0:d=o-Math.max(Number.EPSILON,Math.abs(o)*Number.EPSILON):n!=null&&(d=n),c!==void 0&&d!==void 0?(t<c||t>d)&&(t=c+(d-c)/2):c!==void 0&&t<c?t=c+Math.abs(c*.1):d!==void 0&&t>d&&(t=d-Math.abs(d*.1)),Number(Number(t).toPrecision(3))}convertString(){if(typeof this.example=="string")return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};if(typeof this.example!="object"&&!Array.isArray(this.example)&&this.example!=null)return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:String(this.example),errors:[]};let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;if(typeof t=="string")return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):this.schema,i=r?.format==="date"?this.EXAMPLE_DATE:r?.format==="date-time"?this.EXAMPLE_DATE_TIME:this.EXAMPLE_STRING;return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??i,errors:[{message:`Example cannot be converted to string: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertInteger(){if(typeof this.example=="number"&&Number.isInteger(this.example))return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};if(typeof this.example=="string"){let r=Number(this.example);if(!isNaN(r)&&Number.isInteger(r))return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:r,errors:[]}}let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return typeof t=="number"&&Number.isInteger(t)?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:t,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_INTEGER,errors:[{message:`Example is not an integer: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertArray({resolvedSchema:t}){if(t.type!="array")return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};t.items==null&&(t.items={type:"string"});let r=this.example==null,i=this.example??t.example,a=(Array.isArray(i)?i:[i]).map(d=>new e({breadcrumbs:[...this.breadcrumbs,"items"],context:this.context,schema:t.items,example:d,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),o=a.every(d=>d?.isValid??!1)&&!r,c=!r&&a.some(d=>d.usedProvidedExample);return{isValid:o,coerced:!1,usedProvidedExample:c,validExample:a.map(d=>d.validExample),errors:o?[]:a.flatMap(d=>d.errors)}}convertObject({resolvedSchema:t}){if(t.type=="object"&&t.properties==null&&t.allOf==null)return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example??{},errors:[]};let r=typeof this.example!="object"||this.example==null?{}:this.example,i=Object.entries(t.properties??{}).map(([l,p])=>{if(typeof p!="object")return{key:l,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if(this.isDeprecatedProperty(p)&&!this.isRequiredProperty({key:l,resolvedSchema:t}))return{key:l,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("readOnly"in p&&p.readOnly===!0&&"writeOnly"in p&&p.writeOnly===!0)return{key:l,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("readOnly"in p&&p.readOnly===!0&&this.exampleGenerationStrategy==="request")return{key:l,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("writeOnly"in p&&p.writeOnly===!0&&this.exampleGenerationStrategy==="response")return{key:l,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};let _=!(l in r)||!("nullable"in p)&&r[l]==null||"nullable"in p&&p.nullable===!0&&r[l]===void 0,h=!t.required?.includes(l);if(_&&h){if(this.example===void 0&&this.generateOptionalProperties){let y=this.maybeResolveSchemaExample(p),b=new e({breadcrumbs:[...this.breadcrumbs,l],context:this.context,schema:p,example:y,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()});return{key:l,result:b.convert()}}return{key:l,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}}}else{let y=r[l],b=y!==void 0?y:this.maybeResolveSchemaExample(p),g=new e({breadcrumbs:[...this.breadcrumbs,l],context:this.context,schema:p,example:b,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();return{key:l,result:g}}}),n=(t.allOf??[]).map((l,p)=>new e({breadcrumbs:[...this.breadcrumbs,`allOf[${p}]`],context:this.context,schema:{...t,...l,allOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),a=i.every(l=>l.result.isValid)&&n.every(l=>l.isValid),o=this.example!==void 0&&(i.some(({result:l})=>l.usedProvidedExample)||n.some(l=>l.usedProvidedExample)),c=Object.fromEntries(i.map(({key:l,result:p})=>[l,p.validExample]).filter(([l,p])=>p!==void 0));for(let l of n)if(typeof l.validExample=="object"&&l.validExample!==null){let p=l.validExample;c={...c,...Object.fromEntries(Object.entries(p).filter(([_,h])=>h!==void 0))}}let d=[],s=new Set(Object.keys(t.properties??{})),u=Object.keys(r).filter(l=>!s.has(l));u.length>0&&(t.additionalProperties===!1?u.forEach(l=>{let p=[...this.breadcrumbs,l].join("."),_={message:`Found unexpected property '${l}' in example. This property does not exist in the schema${p?` at path: ${p}`:""}`,path:[...this.breadcrumbs,l]};d.push({key:l,result:{isValid:!1,coerced:!1,usedProvidedExample:!0,validExample:void 0,errors:[_]}})}):u.forEach(l=>{let p=[...this.breadcrumbs,l].join("."),_={message:`Additional property ${l} is not allowed`,path:[...this.breadcrumbs,l]};d.push({key:l,result:{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:void 0,errors:[_]}})}));for(let{key:l,result:p}of d)p.validExample!==void 0&&c[l]===void 0&&(c[l]=p.validExample);if(Object.keys(c).length===0){let l=n.find(p=>p.validExample!==void 0&&(typeof p.validExample!="object"||p.validExample===null));l&&(c=l.validExample)}return{isValid:a,coerced:!1,usedProvidedExample:o,validExample:c,errors:[...i.flatMap(({result:l})=>l.errors),...n.flatMap(l=>l.errors),...d.flatMap(({result:l})=>l.errors)]}}convertSchemaTypeArray({resolvedSchema:t}){if(!Array.isArray(t.type))return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};if(t.type.length===1)return new e({breadcrumbs:this.breadcrumbs,context:this.context,schema:{...t,type:t.type[0]},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();let r=t.type.map((c,d)=>new e({breadcrumbs:[...this.breadcrumbs,`type[${d}]`],context:this.context,schema:{...t,type:c},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),i=r.some(c=>c?.isValid??!1),a=r.find(c=>c.isValid)?.validExample??r[0]?.validExample??null,o=r.some(c=>c.usedProvidedExample);return{isValid:i,coerced:!1,usedProvidedExample:o,validExample:a,errors:i?[]:r.flatMap(c=>c?.errors??[])}}convertUnion({resolvedSchema:t,unionType:r}){let i=r==="oneOf"?t.oneOf:t.anyOf;if(!(r in t)||i==null)return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};let n=this.example??this.maybeResolveSchemaExample(t);if(this.example===void 0){let p=[];for(let h of i){if(!h)continue;let y=this.context.resolveMaybeReference({schemaOrReference:h,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});y&&p.push(y)}if(p.length>0&&p.every(h=>GVD(h))){let h=p.findIndex(y=>Lph(y)!==void 0);if(h!==-1){let y=i[h],b=p[h];if(y&&b){let v=Lph(b),m=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${h}]`],context:this.context,schema:r==="oneOf"?{...t,...y,oneOf:void 0}:y,example:v,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(m.isValid)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:m.validExample,errors:[]}}}}}let a=[],o=null,c=null;for(let p=0;p<i.length;p++){let _=i[p];if(!_)continue;let h=r==="oneOf"?{...t,..._,oneOf:void 0}:_,y=n??this.maybeResolveSchemaExample(h),v=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${p}]`],context:this.context,schema:h,example:y,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(v.isValid&&!v.coerced&&v.usedProvidedExample)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:v.validExample,errors:[]};if(v.isValid&&!v.coerced)return{isValid:!0,coerced:!1,usedProvidedExample:v.usedProvidedExample,validExample:v.validExample,errors:[]};a.push(v),v.isValid&&v.usedProvidedExample&&c===null&&(c=v),v.isValid&&o===null&&(o=v)}let d=c??o,s=d!==null,u=d?.validExample??a[0]?.validExample,l=d?.usedProvidedExample??!1;return{isValid:s,coerced:!1,usedProvidedExample:l,validExample:u,errors:s?[]:a.flatMap(p=>p.errors)}}convertOneOf({resolvedSchema:t}){return this.convertUnion({resolvedSchema:t,unionType:"oneOf"})}convertAnyOf({resolvedSchema:t}){return this.convertUnion({resolvedSchema:t,unionType:"anyOf"})}getMaybeUpdatedSeenRefs(){let t=new Set(this.seenRefs);return this.context.isReferenceObject(this.schema)&&t.add(this.schema.$ref),t}maybeResolveSchemaExample(t){if("example"in t)return t.example;if("examples"in t){let i=t.examples;if(Array.isArray(i)&&i.length>0)return i[0];if(i!=null&&typeof i=="object")return Object.values(i)[0]}let r=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(r!=null){if("example"in r)return r.example;if("examples"in r){let i=r.examples;return Array.isArray(i)&&i.length>0?i[0]:Object.values(i??{})[0]}}}maybeConvertLiteralFernType(t){let r=t["x-fern-type"];if(typeof r!="string")return;let i=r.match(WVD);if(i!=null){if(i[1]!=null)return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:i[1],errors:[]};if(i[2]!=null)return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:i[2]==="true",errors:[]}}}isDeprecatedProperty(t){return t!=null&&"availability"in t&&t.availability==="deprecated"}isRequiredProperty({key:t,resolvedSchema:r}){return r.required?.includes(t)??!1}};var oxc={};Yt(oxc,{ArraySchemaConverter:()=>Poa,EnumSchemaConverter:()=>Ooa,ObjectSchemaConverter:()=>moa,OneOfSchemaConverter:()=>Jbn,PrimitiveSchemaConverter:()=>Aoa,SchemaConverter:()=>SJi,SchemaOrReferenceConverter:()=>jW});function Vph(e){return hC({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return ii.primitive({v1:"BASE_64",v2:vn.base64({})});case"BOOLEAN":return ii.primitive({v1:"BOOLEAN",v2:vn.boolean({default:void 0})});case"DATE":return ii.primitive({v1:"DATE",v2:vn.date({})});case"DATE_TIME":return ii.primitive({v1:"DATE_TIME",v2:vn.dateTime({})});case"FLOAT":return ii.primitive({v1:"FLOAT",v2:vn.float({default:void 0,validation:void 0})});case"DOUBLE":return ii.primitive({v1:"DOUBLE",v2:vn.double({default:void 0,validation:void 0})});case"UINT":return ii.primitive({v1:"UINT",v2:vn.uint({default:void 0,validation:void 0})});case"UINT_64":return ii.primitive({v1:"UINT_64",v2:vn.uint64({default:void 0,validation:void 0})});case"INTEGER":return ii.primitive({v1:"INTEGER",v2:vn.integer({default:void 0,validation:void 0})});case"LONG":return ii.primitive({v1:"LONG",v2:vn.long({default:void 0,validation:void 0})});case"STRING":return ii.primitive({v1:"STRING",v2:vn.string({default:void 0,validation:void 0})});case"UUID":return ii.primitive({v1:"UUID",v2:vn.uuid({})});case"BIG_INTEGER":return ii.primitive({v1:"BIG_INTEGER",v2:vn.bigInteger({default:void 0})});default:return}},unknown:()=>ii.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return ii.container(Es.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return ii.container(Es.list(t))},optional:t=>{if(t!=null)return ii.container(Es.optional(t))},nullable:t=>{if(t!=null)return ii.container(Es.nullable(t))},set:t=>{if(t!=null)return ii.container(Es.set(t))},literal:t=>ii.container(Es.literal(t._visit({string:r=>lF.string(r),boolean:r=>lF.boolean(r),_other:()=>{throw new Error("Unexpected literal type")}}))),named:()=>{}}})}var Ooa=class extends Oa{schema;maybeFernEnum;constructor({context:t,breadcrumbs:r,schema:i,maybeFernEnum:n}){super({context:t,breadcrumbs:r}),this.schema=i,this.maybeFernEnum=n}convert(){if(!this.schema.enum)return;let r=this.schema.enum.filter(n=>typeof n=="string"||typeof n=="number").map(n=>{let a=n.toString(),o=this.maybeFernEnum?.[a],c=o?.name??a;return{name:this.context.casingsGenerator.generateNameAndWireValue({name:c,wireValue:a}),docs:o?.description,availability:void 0,casing:o?.casing}});if(r.length===0){this.context.errorCollector.collect({message:`Received enum schema with no valid values: ${JSON.stringify(this.schema)}`,path:this.breadcrumbs});return}let i=this.context.getAsString(this.schema.default);return{type:Al.enum({default:i!=null?r.find(n=>n.name.wireValue===i):void 0,values:r})}}};var bpu=class extends Oa{schemaOrReferenceOrBoolean;constructor({context:t,breadcrumbs:r,schemaOrReferenceOrBoolean:i}){super({context:t,breadcrumbs:r}),this.schemaOrReferenceOrBoolean=i}convert(){let t=this.tryConvertUnknownMap();if(t!=null)return t;let r=this.tryConvertTypedMap();if(r!=null)return r}tryConvertUnknownMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean"){let t=ii.container(Es.map({keyType:Oa.STRING,valueType:ii.unknown()}));return{type:Al.alias({aliasOf:t,resolvedType:t}),referencedTypes:new Set,inlinedTypes:{}}}}tryConvertTypedMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean")return;let r=new jW({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schemaOrReferenceOrBoolean}).convert();if(r!=null){let i=ii.container(Es.map({keyType:Oa.STRING,valueType:r.type})),n=new Set;for(let a of r.schema?.typeDeclaration.referencedTypes??[])n.add(a);for(let a of Object.keys(r.inlinedTypes))n.add(a);return{type:Al.alias({aliasOf:i,resolvedType:i}),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}};function Y7a({properties:e,required:t,breadcrumbs:r,context:i,errorCollector:n}){let a=[],o={},c={},d=new Set;for(let[s,u]of Object.entries(e??{})){let l=[...r,"properties",s];if(typeof u!="object"){n.collect({message:`Schema property ${s} should be an object`,path:l});continue}let p=xVD(r,u,i)??i.convertBreadcrumbsToName(l),_="nullable"in u?u.nullable:!1,y=new jW({context:i,breadcrumbs:l,schemaOrReference:u,schemaIdOverride:p,wrapAsOptional:!t.includes(s),wrapAsNullable:_}).convert();if(y!=null){a.push({name:i.casingsGenerator.generateNameAndWireValue({name:s,wireValue:s}),valueType:y.type,docs:u.description,availability:y.availability,propertyAccess:i.getPropertyAccess(u),v2Examples:y.schema?.typeDeclaration?.v2Examples??{userSpecifiedExamples:{},autogeneratedExamples:{}}}),o={...o,...y.inlinedTypes},y.schema?.typeDeclaration.referencedTypes!=null&&y.schema.typeDeclaration.referencedTypes.forEach(b=>{d.add(b)});for(let b of y.schema?.audiences??[])c[b]==null&&(c[b]=new Set),c[b].add(s)}}for(let s of Object.keys(o))d.add(s);return{convertedProperties:a,propertiesByAudience:c,inlinedTypesFromProperties:o,referencedTypes:d}}function xVD(e,t,r){return r.isReferenceObject(t)?void 0:new NR.FernTypeNameExtension({breadcrumbs:e,schema:t,context:r}).convert()}var moa=class extends Oa{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){let t=typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties;if(!this.schema.properties&&!this.schema.allOf)return{type:Al.object({properties:[],extends:[],extendedProperties:[],extraProperties:t}),propertiesByAudience:{},inlinedTypes:{},referencedTypes:new Set};let{convertedProperties:r,inlinedTypesFromProperties:i,referencedTypes:n,propertiesByAudience:a}=Y7a({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector}),o=[],c=n,d=this.schema.required!=null&&this.schema.required.length>0,s=i,u=a;for(let[l,p]of(this.schema.allOf??[]).entries()){let _=[...this.breadcrumbs,"allOf",l.toString()],h;if(this.context.isReferenceObject(p)){let m=this.context.resolveMaybeReference({schemaOrReference:p,breadcrumbs:_});if(m==null){this.context.logger.debug?.(`[ObjectSchemaConverter] allOf[${l}] reference could not be resolved. Skipping: ${JSON.stringify(p)}`);continue}if(h=m,typeof h.additionalProperties=="boolean"&&h.additionalProperties&&(t=!0),!d||Object.keys(h.properties??{}).every(O=>!this.schema.required?.includes(O))){this.addTypeReferenceToExtends({reference:p,breadcrumbs:_,extends_:o,referencedTypes:c});continue}}else h=p;typeof h.additionalProperties=="boolean"&&h.additionalProperties&&(t=!0);let{convertedProperties:y,inlinedTypesFromProperties:b,referencedTypes:v,propertiesByAudience:g}=Y7a({properties:h.properties??{},required:[...this.schema.required??[],...h.required??[]],breadcrumbs:_,context:this.context,errorCollector:this.context.errorCollector});r.push(...y),s={...s,...b},u={...u,...g},v.forEach(m=>{c.add(m)})}for(let l of Object.keys(s))c.add(l);return{type:Al.object({properties:r,extends:o.map(l=>this.context.typeReferenceToDeclaredTypeName(l)).filter(us),extendedProperties:[],extraProperties:t}),propertiesByAudience:u,referencedTypes:c,inlinedTypes:s}}addTypeReferenceToExtends({reference:t,breadcrumbs:r,extends_:i,referencedTypes:n}){let a=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:r});a.ok&&i.push(a.reference);let o=this.context.getTypeIdFromSchemaReference(t);o!=null&&n.add(o)}};var vpu=class extends fl{node;key="x-fern-discriminated";constructor({breadcrumbs:t,node:r,context:i}){super({breadcrumbs:t,context:i}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t!=null&&typeof t=="boolean")return t}};var Jbn=class extends Oa{schema;id;constructor({context:t,breadcrumbs:r,schema:i,id:n,inlinedTypes:a}){super({context:t,breadcrumbs:r}),this.schema=i,this.id=n}convert(){return this.shouldConvertAsNullableSchemaOrReference()?this.convertAsNullableSchemaOrReference():new vpu({context:this.context,breadcrumbs:this.breadcrumbs,node:this.schema}).convert()===!1?this.convertAsUndiscriminatedUnion():this.schema.discriminator!=null&&!this.unionVariantsContainLiteral({discriminantProperty:this.schema.discriminator.propertyName})?this.convertAsDiscriminatedUnion():this.convertAsUndiscriminatedUnion()}unionVariantsContainLiteral({discriminantProperty:t}){for(let[r,i]of Object.entries(this.schema.discriminator?.mapping??{})){let n=this.context.resolveReference({reference:{$ref:i},breadcrumbs:this.breadcrumbs});if(n.resolved&&!Object.keys(n.value.properties??{}).includes(t))return!1}return!0}convertAsDiscriminatedUnion(){if(this.schema.discriminator==null)return;let t=[],r=new Set,i={};for(let[d,s]of Object.entries(this.schema.discriminator.mapping??{})){let u=new jW({context:this.context,schemaOrReference:{$ref:s},breadcrumbs:[...this.breadcrumbs,"discriminator","mapping",d]}),l=this.context.getTypeIdFromSchemaReference({$ref:s});l!=null&&r.add(l);let p=u.convert();if(p?.type!=null&&l!=null){for(let h of Object.keys(p?.inlinedTypes??{}))r.add(h);for(let h of p.schema?.typeDeclaration.referencedTypes??[])r.add(h);let _=this.context.casingsGenerator.generateNameAndWireValue({name:d,wireValue:d});t.push({docs:void 0,discriminantValue:_,availability:p.availability,displayName:d,shape:cF.samePropertiesAsObject({typeId:l,name:this.context.casingsGenerator.generateName(l),fernFilepath:{allParts:[],packagePath:[],file:void 0},displayName:d})}),i={...i,...p.inlinedTypes}}}let{convertedProperties:n,referencedTypes:a,inlinedTypesFromProperties:o}=Y7a({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector});r=new Set([...r,...a]);let c=[];for(let[d,s]of(this.schema.allOf??[]).entries()){let u=[...this.breadcrumbs,"allOf",d.toString()];if(this.context.isReferenceObject(s)){let l=this.context.convertReferenceToTypeReference({reference:s,breadcrumbs:u});if(l.ok){let _=this.context.typeReferenceToDeclaredTypeName(l.reference);_!=null&&c.push(_)}let p=this.context.getTypeIdFromSchemaReference(s);p!=null&&r.add(p);continue}}for(let d of Object.keys({...i,...o}))r.add(d);return{type:Al.union({baseProperties:n,discriminant:this.context.casingsGenerator.generateNameAndWireValue({name:this.schema.discriminator.propertyName,wireValue:this.schema.discriminator.propertyName}),extends:c,types:t}),referencedTypes:r,inlinedTypes:{...i,...o}}}convertAsUndiscriminatedUnion(){if(!this.schema.oneOf&&!this.schema.anyOf||this.schema.anyOf?.length===0&&this.schema.oneOf?.length===0)return;let t=[],r=new Set,i={},n=[...this.schema.oneOf??[],...this.schema.anyOf??[]].filter(a=>!this.context.isReferenceObject(a));for(let[a,o]of[...(this.schema.oneOf??[]).entries(),...(this.schema.anyOf??[]).entries()]){if(this.context.isReferenceObject(o)){let p;if(this.context.isReferenceObjectWithIdentifier(o))p=this.context.convertReferenceToTypeReference({reference:o,displayNameOverride:o.summary??o.title??o.name??o.messageId,displayNameOverrideSource:"reference_identifier"});else if(this.getDiscriminatorKeyForRef(o)!=null){let h=this.getDiscriminatorKeyForRef(o);p=this.context.convertReferenceToTypeReference({reference:o,displayNameOverride:h,displayNameOverrideSource:"discriminator_key"})}else p=this.context.convertReferenceToTypeReference({reference:o,displayNameOverride:o.$ref.split("/").pop(),displayNameOverrideSource:"schema_identifier"});p.ok&&t.push({type:p.reference,docs:o.description});let _=this.context.getTypeIdFromSchemaReference(o);_!=null&&r.add(_);continue}let c=this.extendSubSchema(o),d=this.context.convertBreadcrumbsToName([`${this.id}_${a}`]),s=o.title,l=new SJi({context:this.context,id:d,nameOverride:s,breadcrumbs:[...this.breadcrumbs,`oneOf[${a}]`],schema:c??o}).convert();if(l!=null){let p=l.convertedSchema.typeDeclaration.shape;p.type==="alias"&&this.typeReferenceIsWrappedPrimitive(p.aliasOf)?t.push({type:p.aliasOf,docs:o.description}):p.type==="object"&&p.properties.length===0&&p.extends.length===0?t.push({type:ii.container(Es.map({keyType:Oa.STRING,valueType:ii.unknown()})),docs:o.description}):(t.push({type:this.context.createNamedTypeReference(d,s),docs:o.description}),i={...i,...l.inlinedTypes,[d]:l.convertedSchema}),l.convertedSchema.typeDeclaration.referencedTypes.forEach(_=>{r.add(_)})}}return{type:Al.undiscriminatedUnion({members:t}),referencedTypes:r,inlinedTypes:i}}shouldConvertAsNullableSchemaOrReference(){return this.schema.oneOf!=null?this.schema.oneOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):this.schema.anyOf!=null?this.schema.anyOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):!1}removeNullFromOneOfOrAnyOf(){let t=this.schema.oneOf??this.schema.anyOf,r=this.schema.oneOf!=null?"oneOf":"anyOf";if(t==null)return;let i=t.filter(n=>!("type"in n&&n.type==="null"));if(i.length===0){this.context.errorCollector.collect({message:`Received ${r} schema with no valid non-null types`,path:this.breadcrumbs});return}return i.length===1?{...this.schema,[r]:void 0,...i[0]}:{...this.schema,[r]:i}}convertAsNullableSchemaOrReference(){let t=this.removeNullFromOneOfOrAnyOf();if(t==null)return;let i=new jW({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(i==null)return;let n=this.wrapInNullable(i.type);return{type:Al.alias({aliasOf:n,resolvedType:n}),referencedTypes:i.schema?.typeDeclaration.referencedTypes??new Set,inlinedTypes:i.inlinedTypes}}typeReferenceIsWrappedPrimitive(t){switch(t.type){case"container":return this.containerTypeIsWrappedPrimitive(t.container);case"named":return!1;case"primitive":return!0;case"unknown":return!0;default:return!1}}containerTypeIsWrappedPrimitive(t){switch(t.type){case"list":return this.typeReferenceIsWrappedPrimitive(t.list);case"map":return this.typeReferenceIsWrappedPrimitive(t.keyType)&&this.typeReferenceIsWrappedPrimitive(t.valueType);case"nullable":return this.typeReferenceIsWrappedPrimitive(t.nullable);case"optional":return this.typeReferenceIsWrappedPrimitive(t.optional);case"set":return this.typeReferenceIsWrappedPrimitive(t.set);case"literal":return!0;default:return!1}}wrapInNullable(t){return ii.container(Es.nullable(t))}mergeIntoObjectSchema(t,r){return{...t,properties:{...r,...t.properties??{}}}}extendSubSchema(t){if(Object.entries(this.schema.properties??{}).length===0)return t;if(t.type==="object")return this.mergeIntoObjectSchema(t,this.schema.properties??{});this.context.isObjectSchemaType(t)||this.context.errorCollector.collect({message:"Received additional object properties for oneOf/anyOf that are not objects",path:this.breadcrumbs})}getDiscriminatorKeyForRef(t){return Object.entries(this.schema.discriminator?.mapping??{}).find(([r,i])=>i===t.$ref)?.[0]}};var Aoa=class extends Oa{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){switch(this.schema.type){case"string":{let t=this.context.getAsString(this.schema.const);if(t!=null)return ii.container(Es.literal(lF.string(t)));if(this.context.settings.typeDatesAsStrings===!1){if(this.schema.format==="date")return ii.primitive({v1:ku.Date,v2:vn.date({})});if(this.schema.format==="date-time")return ii.primitive({v1:ku.DateTime,v2:vn.dateTime({})})}return ii.primitive({v1:"STRING",v2:vn.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":switch(this.schema.format){case"double":return ii.primitive({v1:"DOUBLE",v2:vn.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return ii.primitive({v1:"FLOAT",v2:vn.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return ii.primitive({v1:"INTEGER",v2:vn.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return ii.primitive({v1:"LONG",v2:vn.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return ii.primitive({v1:"UINT",v2:vn.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return ii.primitive({v1:"UINT_64",v2:vn.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return ii.primitive({v1:"DOUBLE",v2:vn.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"integer":switch(this.schema.format){case"double":return ii.primitive({v1:"DOUBLE",v2:vn.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return ii.primitive({v1:"FLOAT",v2:vn.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return ii.primitive({v1:"INTEGER",v2:vn.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return ii.primitive({v1:"LONG",v2:vn.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return ii.primitive({v1:"UINT",v2:vn.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return ii.primitive({v1:"UINT_64",v2:vn.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return ii.primitive({v1:"INTEGER",v2:vn.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"boolean":{let t=this.context.getAsBoolean(this.schema.const);return t!=null?ii.container(Es.literal(lF.boolean(t))):ii.primitive({v1:"BOOLEAN",v2:vn.boolean({default:this.schema.default})})}default:return}}getNumberValidation(t){let r=t.minimum,i=t.maximum,n,a;return typeof t.exclusiveMinimum=="boolean"?n=t.exclusiveMinimum:typeof t.exclusiveMinimum=="number"&&(r=t.exclusiveMinimum,n=!0),typeof t.exclusiveMaximum=="boolean"?a=t.exclusiveMaximum:typeof t.exclusiveMaximum=="number"&&(i=t.exclusiveMaximum,a=!0),{max:i,min:r,exclusiveMax:a,exclusiveMin:n,multipleOf:t.multipleOf}}getStringValidation(t){return{minLength:t.minLength,maxLength:t.maxLength,pattern:t.pattern,format:t.format}}};var HVD=["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],SJi=class e extends Oa{schema;id;inlined;audiences;nameOverride;constructor({context:t,breadcrumbs:r,schema:i,id:n,inlined:a=!1,nameOverride:o}){super({context:t,breadcrumbs:r}),this.schema=i,this.id=n,this.inlined=a,this.nameOverride=o,this.audiences=this.context.getAudiences({operation:this.schema,breadcrumbs:this.breadcrumbs})??[]}convert(){let t=this.tryConvertFernTypeDeclaration();if(t!=null)return t;let r=this.tryConvertEnumSchema();if(r!=null)return r;let i=this.tryConvertSingularAllOfSchema();if(i!=null)return i;let n=this.tryConvertPrimitiveSchema();if(n!=null)return n;let a=this.tryConvertArraySchema();if(a!=null)return a;let o=this.tryConvertTypeArraySchema();if(o!=null)return o;let c=this.tryConvertOneOfAnyOfSchema();if(c!=null)return c;let d=this.tryConvertMapSchema();if(d!=null)return d;let s=this.tryConvertDiscriminatorMappingSchema();if(s!=null)return s;let u=this.tryConvertObjectAllOfSchema();if(u!=null)return u;let l=this.tryConvertUntypedSchema();if(l!=null)return l;this.context.errorCollector.collect({message:`Failed to convert schema object: ${JSON.stringify(this.schema,null,2)}`,path:this.breadcrumbs})}tryConvertEnumSchema(){if(!this.schema.enum?.length)return;let r=new NR.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),n=new Ooa({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,maybeFernEnum:r}).convert();if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:n.type,referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertSingularAllOfSchema(){if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&this.schema.allOf?.length===1&&this.schema.allOf[0]!=null){let r=this.context.resolveMaybeReference({schemaOrReference:this.schema.allOf[0],breadcrumbs:this.breadcrumbs});if(r!=null){let n=new e({context:this.context,breadcrumbs:[...this.breadcrumbs,"allOf","0"],schema:r,id:this.id,inlined:!0}).convert();if(n?.convertedSchema.typeDeclaration?.shape.type!=="object")return n}}if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&Array.isArray(this.schema.allOf)&&this.schema.allOf.length>=1){let r={};for(let n of this.schema.allOf??[]){if(this.context.isReferenceObject(n))return;r=d$n(r,n,(a,o)=>{if(o===n)return a;if(Array.isArray(a)&&Array.isArray(o))return[...a,...o]})}return new e({context:this.context,breadcrumbs:this.breadcrumbs,schema:r,id:this.id,inlined:!0}).convert()}}tryConvertPrimitiveSchema(){let r=new Aoa({context:this.context,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Al.alias({aliasOf:r,resolvedType:r}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertArraySchema(){if(this.schema.type==="array"){let r=new Poa({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Al.alias({aliasOf:r.typeReference,resolvedType:r.typeReference}),referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertTypeArraySchema(){if(Array.isArray(this.schema.type)&&this.schema.type.length>0)return this.schema.type.length===1?this.schema.type=this.schema.type[0]:(this.schema.oneOf=this.schema.type.map(t=>({type:t})),this.schema.type=void 0),this.convert()}tryConvertOneOfAnyOfSchema(){if(this.schema.oneOf!=null||this.schema.anyOf!=null){let r=new Jbn({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,inlinedTypes:{}}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertMapSchema(){if((typeof this.schema.additionalProperties=="object"||typeof this.schema.additionalProperties=="boolean")&&this.schema.additionalProperties!=null&&!this.schema.properties&&!this.schema.allOf){if(typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties===!1)return;let r=new bpu({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReferenceOrBoolean:this.schema.additionalProperties}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertDiscriminatorMappingSchema(){if(this.schema.discriminator?.mapping!=null&&Object.keys(this.schema.discriminator.mapping).length>0&&this.schema.oneOf==null&&this.schema.anyOf==null){let t={...this.schema,oneOf:Object.values(this.schema.discriminator.mapping).map(n=>({$ref:n}))},i=new Jbn({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:t,inlinedTypes:{}}).convert();if(i!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:i.type,referencedTypes:i.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:i.inlinedTypes}}}tryConvertObjectAllOfSchema(){if(this.schema.type==="object"||this.schema.properties!=null||this.schema.allOf!=null){let r=new moa({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:r.propertiesByAudience},inlinedTypes:r.inlinedTypes}}}tryConvertUntypedSchema(){if(this.isUntypedSchema())return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Al.alias({aliasOf:ii.unknown(),resolvedType:ii.unknown()}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertFernTypeDeclaration(){let r=new NR.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r==null)return;let i=Vph(r);if(i!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Al.alias({aliasOf:i,resolvedType:i}),referencedTypes:new Set,omitV2Examples:!0}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}createTypeDeclaration({shape:t,referencedTypes:r,omitV2Examples:i}){return{name:this.convertDeclaredTypeName(),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs}),docs:this.schema.description,referencedTypes:r,source:void 0,inline:this.inlined,v2Examples:i?void 0:this.convertSchemaExamples()}}convertDeclaredTypeName(){return{typeId:this.id,fernFilepath:this.context.createFernFilepath(),name:this.context.casingsGenerator.generateName(this.id),displayName:this.nameOverride}}schemaOnlyHasAllowedKeys(t){let r=[...HVD,...t];return Object.keys(this.schema).every(n=>r.includes(n))}isUntypedSchema(){return!!(this.schema&&typeof this.schema=="object"&&!("oneOf"in this.schema)&&!("anyOf"in this.schema)&&!("allOf"in this.schema)&&!("items"in this.schema)&&!("properties"in this.schema))}convertSchemaExamples(){let t={userSpecifiedExamples:{},autogeneratedExamples:{}},r=this.context.getExamplesFromSchema({schema:this.schema,breadcrumbs:this.breadcrumbs});if(r.length===0){let i=this.generateOrValidateExample({example:void 0,ignoreErrors:!0});return t.autogeneratedExamples={[`${this.id}_example_autogenerated`]:i},t}return t.userSpecifiedExamples=this.convertUserSpecifiedExamples(r),t}convertUserSpecifiedExamples(t){let r={};for(let[i,n]of t.entries()){let a=this.context.resolveExample(n),o=this.generateOrValidateExample({example:a});r[`${this.id}_example_${i}`]=o}return r}generateOrValidateExample({example:t,ignoreErrors:r}){let i=new gF({breadcrumbs:this.breadcrumbs,context:this.context,schema:this.schema,example:t}),{validExample:n,errors:a}=i.convert();return r||a.forEach(o=>{this.context.errorCollector.collect({message:o.message,path:o.path})}),n}};var jW=class extends Oa{schemaOrReference;schemaIdOverride;wrapAsOptional;wrapAsNullable;constructor({context:t,breadcrumbs:r,schemaOrReference:i,schemaIdOverride:n,wrapAsOptional:a=!1,wrapAsNullable:o=!1}){super({context:t,breadcrumbs:r}),this.schemaOrReference=i,this.schemaIdOverride=n,this.wrapAsOptional=a,this.wrapAsNullable=o}convert(){let t=this.maybeConvertReferenceObject({schemaOrReference:this.schemaOrReference});if(t!=null)return t;let r=this.maybeConvertSingularAllOfReferenceObject();return r??this.convertSchemaObject({schema:this.schemaOrReference})}maybeConvertReferenceObject({schemaOrReference:t}){if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:r.inlinedTypes??{}}}}maybeConvertSingularAllOfReferenceObject(){if(this.context.isReferenceObject(this.schemaOrReference)||this.schemaOrReference.allOf==null||this.schemaOrReference.allOf.length!==1)return;let t=this.schemaOrReference.allOf[0];if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:{}}}}convertSchemaObject({schema:t}){let r=this.schemaIdOverride??this.context.convertBreadcrumbsToName(this.breadcrumbs),i=new SJi({context:this.context,breadcrumbs:this.breadcrumbs,schema:t,id:r}),n=this.context.getAvailability({node:t,breadcrumbs:this.breadcrumbs}),a=i.convert();if(a!=null){let o=a.convertedSchema.typeDeclaration.shape;return o.type==="alias"?{type:this.wrapTypeReference(o.aliasOf),schema:a.convertedSchema,inlinedTypes:a.inlinedTypes,availability:n}:{type:this.wrapTypeReference(this.context.createNamedTypeReference(r)),schema:a.convertedSchema,inlinedTypes:{...a.inlinedTypes,[r]:a.convertedSchema},availability:n}}}wrapTypeReference(t){return this.wrapAsOptional&&this.wrapAsNullable?this.wrapInOptional(this.wrapInNullable(t)):this.wrapAsOptional?this.wrapInOptional(t):this.wrapAsNullable?this.wrapInNullable(t):t}wrapInOptional(t){return ii.container(Es.optional(t))}wrapInNullable(t){return ii.container(Es.nullable(t))}};var Poa=class e extends Oa{static LIST_UNKNOWN=ii.container(Es.list(ii.unknown()));schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){if(this.schema.items!=null){Array.isArray(this.schema.items)&&(this.schema.items={oneOf:this.schema.items});let r=new jW({context:this.context,breadcrumbs:[...this.breadcrumbs,"items"],schemaOrReference:this.schema.items}).convert();if(r!=null){let i=new Set;for(let n of r.schema?.typeDeclaration.referencedTypes??[])i.add(n);return r.inlinedTypes!=null&&Object.values(r.inlinedTypes).forEach(n=>{n.typeDeclaration.referencedTypes.forEach(a=>{i.add(a)})}),{typeReference:ii.container(Es.list(r.type)),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var gpu=class extends Oa{group;method;constructor({context:t,breadcrumbs:r,group:i,method:n}){super({context:t,breadcrumbs:r}),this.group=i,this.method=n}parseMediaTypeObject({mediaTypeObject:t,resolveSchema:r,contentType:i,schemaId:n}){if(t.schema==null)return;if(r){let d=this.context.resolveMaybeReference({schemaOrReference:t.schema,breadcrumbs:[...this.breadcrumbs,"content",i]});if(d==null)return;t.schema=d}let o=new jW({context:this.context,breadcrumbs:[...this.breadcrumbs,"content",i,"schema"],schemaOrReference:t.schema,schemaIdOverride:n}).convert();if(o==null)return;let c=t.examples!=null?Object.fromEntries(Object.entries(t.examples).map(([d,s])=>{if(this.context.isReferenceObject(s)){let u=this.context.resolveReference({reference:s,breadcrumbs:[...this.breadcrumbs,"content",i,"examples"],skipErrorCollector:!0});return u.resolved?[d,u.value.value??u.value]:null}return[d,s.value??s]}).filter(d=>d!=null)):void 0;return{...o,examples:c}}parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:r}){let n=new jW({context:this.context,breadcrumbs:[...this.breadcrumbs],schemaOrReference:t,schemaIdOverride:r}).convert();if(n!=null)return{...n,examples:void 0}}convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:r,exampleGenerationStrategy:i}){let n={userSpecifiedExamples:{},autogeneratedExamples:{}},a=t?.schema,o=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_example`});for(let[c,d]of o){let s=this.context.resolveExampleWithValue(d),u=this.context.resolveExampleRecursively({example:d,breadcrumbs:this.breadcrumbs}),l=this.context.isExampleWithSummary(u)?u.summary:c;s!=null&&(a!=null?n.userSpecifiedExamples[l]=this.generateOrValidateExample({schema:a,example:s,exampleGenerationStrategy:i}):n.userSpecifiedExamples[l]=s)}if(Object.keys(n.userSpecifiedExamples).length===0&&a!=null){let c=ou(`${[...this.group,this.method].join("_")}_example`);n.autogeneratedExamples[c]=this.generateOrValidateExample({schema:a,example:void 0,ignoreErrors:!0,generateOptionalProperties:r,exampleGenerationStrategy:i})}return n}generateOrValidateExample({schema:t,example:r,ignoreErrors:i,generateOptionalProperties:n,exampleGenerationStrategy:a}){let o=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(o==null)return;let c=this.context.getExamplesFromSchema({schema:o,breadcrumbs:this.breadcrumbs}),d=new gF({breadcrumbs:this.breadcrumbs,context:this.context,schema:o,example:r??c[0],generateOptionalProperties:n??!1,exampleGenerationStrategy:a}),{validExample:s,errors:u}=d.convert();return i||u.forEach(l=>{this.context.errorCollector.collect({message:l.message,path:l.path})}),s}};var Opu=class extends Oa{parameter;constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r}),this.parameter=i}convertToOutput({schema:t,typeReference:r,inlinedTypes:i}){let n=this.context.getAvailability({node:this.parameter,breadcrumbs:this.breadcrumbs}),a=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs}),o=this.getParameterSchemaWithExampleOverride({schema:a});switch(this.parameter.in){case"query":return{type:"query",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??Oa.OPTIONAL_STRING,allowMultiple:this.parameter.explode??!1,v2Examples:this.convertParameterExamples({schema:o??t}),availability:n,explode:this.getExplodeForQueryParameter()},inlinedTypes:i};case"header":return{type:"header",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??Oa.OPTIONAL_STRING,env:void 0,v2Examples:this.convertParameterExamples({schema:o??t}),availability:n},inlinedTypes:i};case"path":return{type:"path",parameter:{name:this.context.casingsGenerator.generateName(this.parameter.name),docs:this.parameter.description,valueType:r??Oa.STRING,location:"ENDPOINT",variable:void 0,v2Examples:this.convertParameterExamples({schema:o??t}),explode:this.getExplodeForPathParameter()},inlinedTypes:i};default:return}}getParameterSchemaWithExampleOverride({schema:t}){if(t!=null)return t.type==="string"&&t.example==null?{...t,example:this.parameter.name}:t}convertParameterExamples({schema:t}){let r={userSpecifiedExamples:{},autogeneratedExamples:{}},i=this.parameter.example,n=this.parameter.examples;for(let[a,o]of Object.entries(n??{})){let c=this.context.resolveExampleWithValue(o);c!=null&&(r.userSpecifiedExamples[a]=this.generateOrValidateExample({schema:t,example:c}))}if(i!=null){let a=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(r.userSpecifiedExamples)});r.userSpecifiedExamples[a]=this.generateOrValidateExample({schema:t,example:i})}if(Object.keys(r.userSpecifiedExamples).length===0){let a=`${this.parameter.name}_example`;r.autogeneratedExamples[a]=this.generateOrValidateExample({schema:t,example:void 0,ignoreErrors:!0})}return r}generateOrValidateExample({schema:t,ignoreErrors:r,example:i}){let n=new gF({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:i}),{validExample:a,errors:o}=n.convert();return r||o.forEach(c=>{this.context.errorCollector.collect({message:c.message,path:c.path})}),a}getExplodeForQueryParameter(){let t=this.parameter.style??"form",r=this.parameter.explode;if(r!==void 0)return t==="form"?r===!0?void 0:r:r===!1?void 0:r}getExplodeForPathParameter(){let t=this.parameter.explode;if(t!==void 0)return t===!1?void 0:t}};var mpu=class extends fl{server;key="x-fern-server-name";constructor({breadcrumbs:t,server:r,context:i}){super({breadcrumbs:t,context:i}),this.server=r}convert(){let t=this.getExtensionValue(this.server,"x-name");if(!(t==null||typeof t!="string"))return t}};var Wph="Base",tge=class e extends Oa{servers;endpointLevelServers;constructor({breadcrumbs:t,context:r,servers:i,endpointLevelServers:n}){super({breadcrumbs:t,context:r}),this.servers=i,this.endpointLevelServers=n}convert(){if(this.servers==null||this.servers.length===0||this.servers[0]==null)return;if(this.endpointLevelServers!=null&&this.endpointLevelServers.length>0){let r=this.getDefaultBaseUrlName(),i={id:r,name:this.context.casingsGenerator.generateName(r)},n=this.endpointLevelServers.map(c=>{let d=e.getServerName({server:c,context:this.context});return{id:d,name:this.context.casingsGenerator.generateName(d)}}).filter((c,d,s)=>s.findIndex(u=>u.id===c.id)===d),a=[i,...n],o=this.servers.map(c=>{let d=e.getServerName({server:c,context:this.context}),s=this.endpointLevelServers?.map(u=>[e.getServerName({server:u,context:this.context}),this.getServerUrl(u)]);return{id:d,name:this.context.casingsGenerator.generateName(d),urls:{[r]:this.getServerUrl(c),...Object.fromEntries(s??[])},docs:c.description}});return{value:{defaultEnvironment:o[0]?.id,environments:SM.multipleBaseUrls({baseUrls:a,environments:o})},defaultUrl:i.id}}let t=this.withExplodedServers(this.servers).map(r=>{let i=e.getServerName({server:r,context:this.context});return{id:i,name:this.context.casingsGenerator.generateName(i),url:this.maybeRemoveTrailingSlashIfNotEmpty(this.getServerUrl(r)),docs:r.description}}).filter(us);return{value:{defaultEnvironment:t[0]?.id,environments:SM.singleBaseUrl({environments:t})},defaultUrl:t[0]?.id}}static getServerExtensionName({server:t,context:r}){return new mpu({breadcrumbs:[],server:t,context:r}).convert()}static getServerName({server:t,context:r}){return t.name!=null?t.name:e.getServerExtensionName({server:t,context:r})??t.description??t.url}getServerUrl(t){if(t.variables==null)return t.url;let r=t.url;for(let[i,n]of Object.entries(t.variables))n.default!=null&&(r=r.replace(`{${i}}`,encodeURIComponent(n.default)));return r}withExplodedServers(t){return t.flatMap(r=>{if(r.variables==null)return[r];let i=Object.entries(r.variables).filter(([c,d])=>d.enum!=null&&d.enum.length>0);if(i.length===0)return[r];let n=i[0];if(n==null)return[r];let[a,o]=n;return o.enum==null?[r]:o.enum.map(c=>{let d=r.url.replace(`{${a}}`,encodeURIComponent(c)),s={};for(let[l,p]of Object.entries(r.variables??{}))l!==a&&(s[l]=p);let u={...r,url:d,variables:Object.keys(s).length>0?s:void 0,"x-fern-server-name":r.description?`${r.description}_${c}`:`${c}`,description:r.description};return this.withExplodedServers([u])[0]})}).filter(us)}getDefaultBaseUrlName(){return this.servers==null||this.servers.length===0||this.servers[0]==null?Wph:e.getServerExtensionName({server:this.servers[0],context:this.context})??Wph}maybeRemoveTrailingSlashIfNotEmpty(t){return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}};var $bn=class{context;constructor({context:t}){this.context=t}validateExample({example:t,schema:r,breadcrumbs:i,exampleGenerationStrategy:n}){return new gF({breadcrumbs:i,context:this.context,schema:r,example:t,depth:0,exampleGenerationStrategy:n,generateOptionalProperties:!1}).convert()}validateEndpointExample({exampleToValidate:t}){let r=[],i=[],n=!0,a=!1,o,c=[t.endpointPath,t.method];if(t.requestExample!==void 0&&t.requestSchema!==void 0){let s=this.validateExample({example:t.requestExample,schema:t.requestSchema,breadcrumbs:[...c,"request"],exampleGenerationStrategy:"request"});if(!s.isValid){n=!1;let u=t.exampleSource==="human"?zR.WARNING:zR.ERROR;r.push(...s.errors.map(l=>({...l,level:u,message:`Invalid request example: ${l.message}`})))}s.coerced&&(a=!0,i.push({level:zR.WARNING,message:"Request example was coerced to match schema",path:[...c,"request"]})),o={request:s.validExample}}let d=this.getResponseSchemaForValidation(t);if(t.responseExample!==void 0&&d!==void 0){let s=this.validateExample({example:t.responseExample,schema:d,breadcrumbs:[...c,"response"],exampleGenerationStrategy:"response"});if(!s.isValid){n=!1;let u=t.exampleSource==="human"?zR.WARNING:zR.ERROR;r.push(...s.errors.map(l=>({...l,level:u,message:`Invalid response example: ${l.message}`})))}s.coerced&&(a=!0,i.push({level:zR.WARNING,message:"Response example was coerced to match schema",path:[...c,"response"]})),o={...typeof o=="object"&&o!==null?o:{},response:s.validExample}}return{isValid:n,errors:r,warnings:i,endpointPath:t.endpointPath,method:t.method,exampleSource:t.exampleSource,exampleName:t.exampleName,validExample:o,coerced:a}}getResponseSchemaForValidation(t){let{responseStatusCode:r,responseSchemas:i,responseSchema:n}=t;return i&&Object.keys(i).length>0?r&&i[r]?i[r]:i[200]??i[201]:n}validateAiExamples({aiExamples:t,spec:r}){let i=[],n=[];for(let a of t){let{requestSchema:o,responseSchema:c,responseSchemas:d}=this.getSchemasForEndpoint({spec:r,endpointPath:a.endpointPath,method:a.method}),s={endpointPath:a.endpointPath,method:a.method,exampleSource:"ai",requestExample:a.request?.body,responseExample:a.response?.body,requestSchema:o,responseSchema:c,responseSchemas:d},u=this.validateEndpointExample({exampleToValidate:s}),l=this.hasUnexpectedProperties({requestExample:a.request?.body,responseExample:a.response?.body,requestSchema:o,responseSchema:c}),p=u.errors.length>0||u.warnings.length>0;!u.isValid||p||l?n.push({example:a,validationResult:u}):i.push(a)}return{validExamples:i,invalidExamples:n}}hasUnexpectedProperties({requestExample:t,responseExample:r,requestSchema:i,responseSchema:n}){return!!(t&&i&&this.exampleHasUnexpectedProperties(t,i)||r&&n&&this.exampleHasUnexpectedProperties(r,n))}exampleHasUnexpectedProperties(t,r){if(!t||typeof t!="object"||t===null)return!1;let i=this.context.resolveMaybeReference({schemaOrReference:r,breadcrumbs:[],skipErrorCollector:!0});if(!i||!i.properties)return!1;let n=t,a=new Set(Object.keys(i.properties));return Object.keys(n).some(c=>!a.has(c))}validateHumanExamples({spec:t}){let r=[],i=0,n=0,a=0,o=[],c=[];if(!t.paths)return{endpoints:r,totalExamples:i,validExamples:n,invalidExamples:a,hasInvalidHumanExamples:!1,hasInvalidAiExamples:!1,invalidHumanExamples:o,invalidAiExamples:c};for(let[d,s]of Object.entries(t.paths)){if(!s)continue;let u=["get","post","put","delete","patch","options","head","trace"];for(let l of u){let p=s[l];if(!p)continue;let _=[],{requestSchema:h,responseSchema:y,responseSchemas:b}=this.getSchemasForOperation({operation:p}),v=this.extractExamplesFromOperation({operation:p,path:d,method:l});for(let g of v){i++;let m={endpointPath:d,method:l,exampleName:g.name,exampleSource:g.source,requestExample:g.request,responseExample:g.response,requestSchema:h,responseSchema:y,responseStatusCode:g.statusCode,responseSchemas:b},O=this.validateEndpointExample({exampleToValidate:m});_.push(O),O.isValid?n++:(a++,g.source==="human"?o.push(O):g.source==="ai"&&c.push(O))}_.length>0&&r.push({endpointPath:d,method:l,results:_,hasInvalidExamples:_.some(g=>!g.isValid),invalidExampleCount:_.filter(g=>!g.isValid).length})}}return{endpoints:r,totalExamples:i,validExamples:n,invalidExamples:a,hasInvalidHumanExamples:o.length>0,hasInvalidAiExamples:c.length>0,invalidHumanExamples:o,invalidAiExamples:c}}getSchemasForEndpoint({spec:t,endpointPath:r,method:i}){let n=t.paths?.[r];if(!n)return{responseSchemas:{}};let a=n[i.toLowerCase()];return!a||typeof a!="object"||!("responses"in a)?{responseSchemas:{}}:this.getSchemasForOperation({operation:a})}getSchemasForOperation({operation:t}){let r,i,n={};if(t.requestBody&&!this.context.isReferenceObject(t.requestBody)){let o=t.requestBody.content?.["application/json"];o?.schema&&(r=o.schema)}if(t.responses){for(let[a,o]of Object.entries(t.responses)){if(!o||this.context.isReferenceObject(o))continue;let d=o.content?.["application/json"];d?.schema&&(n[a]=d.schema)}i=n[200]??n[201]}return{requestSchema:r,responseSchema:i,responseSchemas:n}}extractExamplesFromOperation({operation:t,path:r,method:i}){let n=[];if(t.requestBody&&!this.context.isReferenceObject(t.requestBody)){let c=t.requestBody.content?.["application/json"];if(c?.example!==void 0&&n.push({name:`${i}_${r}_request_example`,source:"openapi",request:c.example}),c?.examples)for(let[d,s]of Object.entries(c.examples)){let u=this.context.isReferenceObject(s)?this.context.resolveExample(s):s;u&&typeof u=="object"&&"value"in u&&n.push({name:d,source:"human",request:u.value})}}if(t.responses)for(let[o,c]of Object.entries(t.responses)){if(!c||this.context.isReferenceObject(c))continue;let s=c.content?.["application/json"];if(s?.example!==void 0){let u=n.find(l=>l.request!==void 0&&l.response===void 0);u?(u.response=s.example,u.statusCode=o):n.push({name:`${i}_${r}_response_${o}_example`,source:"openapi",response:s.example,statusCode:o})}if(s?.examples)for(let[u,l]of Object.entries(s.examples)){let p=this.context.isReferenceObject(l)?this.context.resolveExample(l):l;if(p&&typeof p=="object"&&"value"in p){let _=n.find(h=>h.name===u);_?(_.response=p.value,_.statusCode=o):n.push({name:u,source:"human",response:p.value,statusCode:o})}}}let a=t["x-fern-examples"];if(Array.isArray(a)){for(let o of a)if(typeof o=="object"&&o!==null){let c=o;n.push({name:c.name,source:"human",request:c.request?.body,response:c.response?.body})}}return n}};var Apu={400:"BadRequestError",401:"UnauthorizedError",402:"PaymentRequiredError",403:"ForbiddenError",404:"NotFoundError",405:"MethodNotAllowedError",406:"NotAcceptableError",407:"ProxyAuthenticationRequiredError",408:"RequestTimeoutError",409:"ConflictError",410:"GoneError",411:"LengthRequiredError",412:"PreconditionFailedError",413:"ContentTooLargeError",414:"URITooLongError",415:"UnsupportedMediaTypeError",416:"RangeNotSatisfiableError",417:"ExpectationFailedError",418:"ImATeapotError",419:"AuthenticationTimeoutError",420:"MethodFailureError",421:"MisdirectedRequestError",422:"UnprocessableEntityError",423:"LockedError",424:"FailedDependencyError",425:"TooEarlyError",426:"UpgradeRequiredError",428:"PreconditionError",429:"TooManyRequestsError",430:"RequestHeaderFieldsTooLargeError",431:"RequestHeaderFieldsTooLargeError",444:"NoResponseError",449:"RetryWithError",450:"BlockedByWindowsParentalControlsError",451:"UnavailableForLegalReasonsError",498:"InvalidTokenError",499:"ClientClosedRequestError",500:"InternalServerError",501:"NotImplementedError",502:"BadGatewayError",503:"ServiceUnavailableError",504:"GatewayTimeoutError",505:"HTTPVersionNotSupportedError",506:"VariantAlsoNegotiatesError",507:"InsufficientStorageError",508:"LoopDetectedError",509:"BandwidthLimitExceededError",510:"NotExtendedError",511:"NetworkAuthenticationRequiredError"},KVD=new Set(Object.values(Apu));var joa=class{enabled=!0;write(t,...r){this.enabled&&process.stderr.write(`[${t}] ${r.join(" ")}
1469
1469
  `)}disable(){this.enabled=!1}enable(){this.enabled=!0}trace(...t){this.write(Ou.Trace,...t)}debug(...t){this.write(Ou.Debug,...t)}info(...t){this.write(Ou.Info,...t)}warn(...t){this.write(Ou.Warn,...t)}error(...t){this.write(Ou.Error,...t)}log(t,...r){this.write(t,...r)}};function zYt(e){if(e?.deprecated)return{status:E1.Deprecated,message:"DEPRECATED"}}var h8t={FILE:{NAME:1,PACKAGE:2,DEPENDENCY:3,MESSAGE_TYPE:4,ENUM_TYPE:5,SERVICE:6,EXTENSION:7,OPTIONS:8,SOURCE_CODE_INFO:9,PUBLIC_DEPENDENCY:10,WEAK_DEPENDENCY:11,SYNTAX:12},MESSAGE:{NAME:1,FIELD:2,NESTED_TYPE:3,ENUM_TYPE:4,EXTENSION_RANGE:5,EXTENSION:6,OPTIONS:7,ONEOF_DECL:8,RESERVED_RANGE:9,RESERVED_NAME:10},ENUM:{NAME:1,VALUE:2,OPTIONS:3,RESERVED_RANGE:4,RESERVED_NAME:5},SERVICE:{NAME:1,METHOD:2,OPTIONS:3},METHOD:{NAME:1,INPUT_TYPE:2,OUTPUT_TYPE:3,OPTIONS:4,CLIENT_STREAMING:5,SERVER_STREAMING:6}},Ppu={MESSAGE:4,ENUM:5,SERVICE:6};var jpu=class extends Oa{enum;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,enum:i,sourceCodeInfoPath:n}){super({context:t,breadcrumbs:r}),this.enum=i,this.sourceCodeInfoPath=n}convert(){let t=this.enum.value.map((r,i)=>{let n=r.name;return{name:{name:this.context.casingsGenerator.generateName(n),wireValue:n},docs:this.context.getCommentForPath([...this.sourceCodeInfoPath,h8t.ENUM.VALUE,i]),availability:void 0}});return{type:Al.enum({default:void 0,values:t})}}};function Gph(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1)}var xph=new Set([Gf.DOUBLE,Gf.FLOAT,Gf.INT64,Gf.UINT64,Gf.INT32,Gf.FIXED64,Gf.FIXED32,Gf.BOOL,Gf.STRING,Gf.BYTES,Gf.UINT32,Gf.SFIXED32,Gf.SFIXED64,Gf.SINT32,Gf.SINT64]);var wpu=class e extends Oa{static LIST_UNKNOWN=ii.container(Es.list(ii.unknown()));field;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,field:i,sourceCodeInfoPath:n}){super({context:t,breadcrumbs:r}),this.field=i,this.sourceCodeInfoPath=n}convert(){if(this.field.label===3){let r=new MJi({context:this.context,breadcrumbs:this.breadcrumbs,field:{...this.field,label:qJn.OPTIONAL},sourceCodeInfoPath:this.sourceCodeInfoPath}).convert();if(r!=null){let i=new Set;return{typeReference:ii.container(Es.list(r.type)),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var Epu=class extends Oa{field;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,field:i,sourceCodeInfoPath:n}){super({context:t,breadcrumbs:r}),this.field=i,this.sourceCodeInfoPath=n}convert(){switch(this.field.type){case Gf.STRING:return ii.primitive({v1:ku.String,v2:vn.string({default:void 0,validation:void 0})});case Gf.DOUBLE:return ii.primitive({v1:ku.Double,v2:vn.double({default:void 0,validation:void 0})});case Gf.FLOAT:return ii.primitive({v1:ku.Float,v2:vn.float({default:void 0,validation:void 0})});case Gf.INT32:return ii.primitive({v1:ku.Integer,v2:vn.integer({default:void 0,validation:void 0})});case Gf.INT64:return ii.primitive({v1:ku.Long,v2:vn.long({default:void 0,validation:void 0})});case Gf.UINT32:return ii.primitive({v1:ku.Uint,v2:vn.uint({default:void 0,validation:void 0})});case Gf.UINT64:return ii.primitive({v1:ku.Uint64,v2:vn.uint64({default:void 0,validation:void 0})});case Gf.BOOL:return ii.primitive({v1:ku.Boolean,v2:vn.boolean({default:void 0})});default:return ii.unknown()}}};var MJi=class extends Oa{field;wrapAsOptional;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,field:i,wrapAsOptional:n,sourceCodeInfoPath:a}){super({context:t,breadcrumbs:r}),this.field=i,this.wrapAsOptional=n??!0,this.sourceCodeInfoPath=a}convert(){if(this.field.label===3){let i=new wpu({context:this.context,breadcrumbs:this.breadcrumbs,field:this.field,sourceCodeInfoPath:this.sourceCodeInfoPath}).convert();if(i!=null)return{type:this.wrapAsOptional?this.wrapInOptional(i.typeReference):i.typeReference,inlinedTypes:i.inlinedTypes,availability:zYt(this.field.options)}}if(xph.has(this.field.type)){let i=new Epu({context:this.context,breadcrumbs:this.breadcrumbs,field:this.field,sourceCodeInfoPath:this.sourceCodeInfoPath}).convert();if(i!=null)return{type:this.wrapAsOptional?this.wrapInOptional(i):i,inlinedTypes:{},availability:zYt(this.field.options)}}if((this.field.type===Gf.MESSAGE||this.field.type===Gf.ENUM)&&this.field.typeName!=null){let r=this.context.convertGrpcReferenceToTypeReference({typeName:this.field.typeName,displayNameOverride:this.field.name});if(r.ok)return{type:this.wrapAsOptional?this.wrapInOptional(r.reference):r.reference,inlinedTypes:{},availability:zYt(this.field.options)}}}wrapInOptional(t){return ii.container(Es.optional(t))}};function Hph({fields:e,breadcrumbs:t,context:r,sourceCodeInfoPath:i}){let n=[],a={},o=new Set,c={};for(let[d,s]of e.entries()){let l=new MJi({context:r,breadcrumbs:[...t,"fields",s.name],field:s,sourceCodeInfoPath:[...i,h8t.MESSAGE.FIELD,d]}).convert();if(l!=null){let p={name:r.casingsGenerator.generateNameAndWireValue({name:s.name,wireValue:s.name}),valueType:l.type,docs:r.getCommentForPath([...i,h8t.MESSAGE.FIELD,d]),availability:l.availability,propertyAccess:void 0,v2Examples:void 0};if(Object.hasOwn(s,"oneofIndex")&&s.oneofIndex!=null){c[s.oneofIndex]==null&&(c[s.oneofIndex]=[]),c[s.oneofIndex].push(s);continue}n.push(p)}}return{convertedFields:n,referencedTypes:o,propertiesByAudience:a,oneOfFields:c}}var Spu=class extends Oa{oneOfFields;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,oneOfFields:i,sourceCodeInfoPath:n}){super({context:t,breadcrumbs:r}),this.oneOfFields=i,this.sourceCodeInfoPath=n}convert(){let t=[];for(let r of this.oneOfFields){let n=new MJi({context:this.context,breadcrumbs:this.breadcrumbs,field:r,wrapAsOptional:!1,sourceCodeInfoPath:this.sourceCodeInfoPath}).convert();n!=null&&t.push({type:n.type,docs:void 0})}return{type:Al.undiscriminatedUnion({members:t}),referencedTypes:new Set,inlinedTypes:{},availability:zYt(this.getProtoAvailabilityOptions())}}getProtoAvailabilityOptions(){return{deprecated:this.oneOfFields.every(t=>t.options?.deprecated)}}};var Mpu=class extends Oa{message;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,message:i,sourceCodeInfoPath:n}){super({context:t,breadcrumbs:r}),this.message=i,this.sourceCodeInfoPath=n}convert(){let t={},r=new Set,{convertedFields:i,referencedTypes:n,propertiesByAudience:a,oneOfFields:o}=Hph({fields:this.message.field,breadcrumbs:this.breadcrumbs,context:this.context,sourceCodeInfoPath:this.sourceCodeInfoPath});for(let c of n)r.add(c);for(let[c,d]of this.message.nestedType.entries()){let u=new DJi({context:this.context,breadcrumbs:this.breadcrumbs,schema:d,sourceCodeInfoPath:[...this.sourceCodeInfoPath,h8t.MESSAGE.NESTED_TYPE,c],schemaIndex:c}).convert();if(u!=null){for(let l of u.convertedSchema.typeDeclaration.referencedTypes)r.add(l);t={...t,...Object.fromEntries(Object.entries(u.inlinedTypes).map(([l,p])=>[this.prependDelimitedParentMessageName(l),this.context.updateTypeId(p,this.prependDelimitedParentMessageName(l))])),[this.prependDelimitedParentMessageName(d.name)]:this.context.updateTypeId(u.convertedSchema,this.prependDelimitedParentMessageName(d.name))}}}for(let[c,d]of this.message.enumType.entries()){let u=new DJi({context:this.context,breadcrumbs:this.breadcrumbs,schema:d,sourceCodeInfoPath:[...this.sourceCodeInfoPath,h8t.MESSAGE.ENUM_TYPE,c],schemaIndex:c}).convert();if(u!=null){for(let l of u.convertedSchema.typeDeclaration.referencedTypes)r.add(l);t={...t,...Object.fromEntries(Object.entries(u.inlinedTypes).map(([l,p])=>[this.prependDelimitedParentMessageName(l),this.context.updateTypeId(p,this.prependDelimitedParentMessageName(l))])),[this.prependDelimitedParentMessageName(d.name)]:this.context.updateTypeId(u.convertedSchema,this.prependDelimitedParentMessageName(d.name))}}}for(let[c,d]of this.message.oneofDecl.entries()){let u=new Spu({context:this.context,breadcrumbs:this.breadcrumbs,oneOfFields:o[c]??[],sourceCodeInfoPath:[...this.sourceCodeInfoPath,h8t.MESSAGE.ONEOF_DECL,c]}).convert();if(u!=null){for(let _ of u.referencedTypes)r.add(_);let l={typeDeclaration:this.createTypeDeclaration({shape:u.type,referencedTypes:u.referencedTypes,typeName:this.prependParentMessageName(Gph(d.name))}),audiences:[],propertiesByAudience:{}},p=this.context.convertGrpcReferenceToTypeReference({typeName:this.context.maybePrependPackageName(l.typeDeclaration.name.typeId)});p.ok===!0&&(i.push({name:this.context.casingsGenerator.generateNameAndWireValue({name:d.name,wireValue:d.name}),valueType:p.reference,docs:void 0,availability:u.availability,propertyAccess:void 0,v2Examples:void 0}),t={...t,[l.typeDeclaration.name.typeId]:l})}}return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Al.object({properties:i,extends:[],extendedProperties:[],extraProperties:!1}),referencedTypes:r,typeName:this.message.name,docs:this.context.getCommentForPath(this.sourceCodeInfoPath),availability:zYt(this.message.options)}),audiences:[],propertiesByAudience:a},inlinedTypes:t}}createTypeDeclaration({shape:t,referencedTypes:r,typeName:i,docs:n,availability:a}){return{name:this.convertDeclaredTypeName(i),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:a,docs:n,referencedTypes:r,source:void 0,inline:!1,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}convertDeclaredTypeName(t){let r=this.context.maybePrependPackageName(t);return{typeId:r,fernFilepath:this.context.createFernFilepath(),name:this.context.casingsGenerator.generateName(r),displayName:t}}prependDelimitedParentMessageName(t,r="."){return`${this.message.name}${r}${t}`}prependParentMessageName(t){return`${this.message.name}${t}`}};var DJi=class extends Oa{schema;audiences;sourceCodeInfoPath;schemaIndex;constructor({context:t,breadcrumbs:r,schema:i,sourceCodeInfoPath:n,schemaIndex:a}){super({context:t,breadcrumbs:r}),this.schema=i,this.sourceCodeInfoPath=n,this.schemaIndex=a,this.audiences=[]}convert(){let t=this.tryConvertGrpcEnum();if(t!=null)return t;let r=this.tryConvertGrpcMessage();if(r!=null)return r}tryConvertGrpcEnum(){if(this.schema.$typeName==="google.protobuf.EnumDescriptorProto"){let r=new jpu({context:this.context,breadcrumbs:[...this.breadcrumbs,this.schema.name],enum:this.schema,sourceCodeInfoPath:this.sourceCodeInfoPath}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:new Set,docs:this.context.getCommentForPath(this.sourceCodeInfoPath),availability:zYt(this.schema.options)}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}}tryConvertGrpcMessage(){if(this.schema.$typeName==="google.protobuf.DescriptorProto"){let r=new Mpu({context:this.context,breadcrumbs:[...this.breadcrumbs,this.schema.name],message:this.schema,sourceCodeInfoPath:this.sourceCodeInfoPath}).convert();if(r!=null)return{convertedSchema:r.convertedSchema,inlinedTypes:r.inlinedTypes}}}createTypeDeclaration({shape:t,referencedTypes:r,docs:i,availability:n}){return{name:this.convertDeclaredTypeName(),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:n,docs:i,referencedTypes:r,source:void 0,inline:void 0,v2Examples:void 0}}convertDeclaredTypeName(){let t=this.context.maybePrependPackageName(this.schema.name);return{typeId:t,fernFilepath:this.context.createFernFilepath(),name:this.context.casingsGenerator.generateName(t),displayName:this.schema.name}}};var woa=class extends bC{comments;codeGeneratorRequest;constructor({comments:t,codeGeneratorRequest:r,...i}){super(i),this.comments=t,this.codeGeneratorRequest=r}resolveTypeIdToProtoFile(t){if(t.startsWith(this.spec.package)){for(let r of this.spec.messageType)if(`${this.spec.package}.${r.name}`===this.maybeRemoveLeadingPeriod(t))return{ok:!0,message:r,protoFileName:this.spec.name}}for(let r of this.codeGeneratorRequest.protoFile.filter(i=>i.name!==this.spec.name))if(t.startsWith(r.package)){for(let i of r.messageType)if(`${r.package}.${i.name}`===this.maybeRemoveLeadingPeriod(t))return{ok:!0,message:i,protoFileName:r.name}}return{ok:!1}}getCodeGeneratorRequest(){return this.codeGeneratorRequest}maybePrependPackageName(t){return this.maybeRemoveLeadingPeriod(t).startsWith(this.spec.package)?t:this.spec.package+"."+t}convertReferenceToTypeReference({reference:t}){return{ok:!1}}convertGrpcReferenceToTypeReference({typeName:t,displayNameOverride:r}){return{ok:!0,reference:ii.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(this.maybeRemoveLeadingPeriod(t)),typeId:this.maybeRemoveLeadingPeriod(t),default:void 0,inline:!1,displayName:r})}}maybeRemoveLeadingPeriod(t){return t.startsWith(".")?t.slice(1):t}maybeRemoveGrpcPackagePrefix(t){let r=t.split(".").filter(n=>n!==""),i=this.spec.package.split(".").filter(n=>n!=="");for(;r.length>0&&i.length>0;){if(r[0]!==i[0])return t;r.shift(),i.shift()}return r.length===0?t:r.join(".")}updateTypeId(t,r){return{...t,typeDeclaration:{...t.typeDeclaration,name:{...t.typeDeclaration.name,typeId:r}}}}getCommentForPath(t){if(!t||t.length===0)return;let r=t[0];if(!(r in this.comments))return;let i=this.comments[r];for(let n=1;n<t.length;n++){let a=t[n];if(a===void 0||!i)return;i=i[a]}return i?._comment}};function sxc(){return{4:{},5:{},6:{}}}function Kph(e){let t=sxc();return e.package?.startsWith("google.protobuf")||e.sourceCodeInfo?.location.forEach(r=>{let i=r.path;if(!i||i.length===0)return;let n=i[0];if(!(n in t))return;let a=r.leadingComments||r.trailingComments||"";if(!a)return;let o=t[n];for(let c=1;c<i.length;c++){let d=i[c];d!=null&&(d in o||(o[d]={}),o=o[d])}o._comment=a.trim()}),t}var X7a=class e extends Oa{MAX_DEPTH=12;EXAMPLE_STRING="example";EXAMPLE_NUMBER=42;EXAMPLE_BOOL=!0;EXAMPLE_BYTES="bytes";message;type;depth;seenMessages;constructor({breadcrumbs:t,context:r,message:i,type:n,depth:a=0,seenMessages:o=new Set}){super({context:r,breadcrumbs:t}),this.message=i,this.type=n,this.depth=a,this.seenMessages=o}convert(){if(this.depth>this.MAX_DEPTH)return{isValid:!0,coerced:!1,validExample:{},errors:[]};let t=this.getFullyQualifiedMessageName(this.message);if(this.seenMessages.has(t))return{isValid:!0,coerced:!1,validExample:{},errors:[]};let r=new Set(this.seenMessages);r.add(t);try{return this.convertMessage(r)}catch(i){return{isValid:!1,coerced:!1,validExample:{},errors:[`Failed to convert message ${t}: ${i}`]}}}getFullyQualifiedMessageName(t){let r=this.context.spec.package||"",i=t.name||"";return r?`${r}.${i}`:i}convertMessage(t){let r=new Map,i=new Map,n=new Map;this.message.oneofDecl&&this.message.oneofDecl.forEach((u,l)=>{u.name&&n.set(l,u.name)});for(let u of this.message.field)Object.hasOwn(u,"oneofIndex")&&u.oneofIndex!=null&&(i.has(u.oneofIndex)||i.set(u.oneofIndex,u));for(let u of this.message.field){let l=u.name??"";if(!(!l||Object.hasOwn(u,"oneofIndex")&&u.oneofIndex!=null&&i.get(u.oneofIndex)!==u))try{let _=this.convertField({field:u,seenMessages:t,fieldName:l});r.set(l,{field:u,result:_})}catch(_){r.set(l,{field:u,result:{isValid:!1,coerced:!1,validExample:null,errors:[`Error converting field ${l}: ${_}`]}})}}let a=Array.from(r.values()),o=a.every(({result:u})=>u.isValid),c=a.flatMap(({result:u})=>u.errors),d={},s=new Map;for(let[u,{field:l,result:p}]of r.entries()){if(!p.isValid||p.validExample===null||p.validExample===void 0)continue;if(Object.hasOwn(l,"oneofIndex")&&l.oneofIndex!=null&&n.has(l.oneofIndex)){let h=n.get(l.oneofIndex)??void 0;h!=null&&s.set(h,{fieldName:u,value:p.validExample})}else d[u]=p.validExample}for(let[u,{fieldName:l,value:p}]of s.entries())d[u]={[l]:p};return{isValid:o,coerced:!1,validExample:d,errors:c}}convertField({field:t,seenMessages:r,fieldName:i}){return t.label===qJn.REPEATED?this.convertRepeatedField({field:t,seenMessages:r,fieldName:i}):this.convertSingleField({field:t,seenMessages:r,fieldName:i})}convertRepeatedField({field:t,seenMessages:r,fieldName:i}){let n=this.convertSingleField({field:t,seenMessages:r,fieldName:i});return{isValid:n.isValid,coerced:!1,validExample:n.isValid?[n.validExample]:[],errors:n.errors}}convertSingleField({field:t,seenMessages:r,fieldName:i}){switch(t.type){case Gf.DOUBLE:case Gf.FLOAT:case Gf.INT64:case Gf.UINT64:case Gf.INT32:case Gf.FIXED64:case Gf.FIXED32:case Gf.UINT32:case Gf.SFIXED32:case Gf.SFIXED64:case Gf.SINT32:case Gf.SINT64:return this.convertNumber();case Gf.BOOL:return this.convertBoolean();case Gf.STRING:return this.convertString(this.EXAMPLE_STRING);case Gf.BYTES:return this.convertBytes();case Gf.ENUM:return this.convertEnum(t);case Gf.MESSAGE:return this.convertMessage_Field(t,r,i);default:return{isValid:!1,coerced:!1,validExample:null,errors:[`Unsupported field type: ${t.type}`]}}}convertNumber(){return{isValid:!0,coerced:!1,validExample:this.EXAMPLE_NUMBER,errors:[]}}convertBoolean(){return{isValid:!0,coerced:!1,validExample:this.EXAMPLE_BOOL,errors:[]}}convertString(t){return{isValid:!0,coerced:!1,validExample:t,errors:[]}}convertBytes(){return{isValid:!0,coerced:!1,validExample:this.EXAMPLE_BYTES,errors:[]}}convertEnum(t){let r=t.typeName??"",i=this.context.maybeRemoveLeadingPeriod(r),n=this.findEnumType(i);return n?n.value.length===0?{isValid:!0,coerced:!1,validExample:0,errors:[]}:{isValid:!0,coerced:!1,validExample:n.value[0]?.number??0,errors:[]}:{isValid:!1,coerced:!1,validExample:0,errors:[`Enum type ${t.typeName} not found`]}}convertMessage_Field(t,r,i){let n=t.typeName;if(!n)return{isValid:!1,coerced:!1,validExample:null,errors:[`Missing type name for message field ${i}`]};let a=this.context.maybeRemoveLeadingPeriod(n),o,c;if(this.context.getCodeGeneratorRequest())for(let s of this.context.getCodeGeneratorRequest().protoFile){let u=this.context.resolveTypeIdToProtoFile(a);if(u.ok){o=u.message,u.protoFileName!==this.context.spec.name?c=new woa({...this.context,comments:sxc(),codeGeneratorRequest:this.context.getCodeGeneratorRequest(),spec:s,logger:new joa}):c=this.context;break}}return!o||!c?{isValid:!0,coerced:!1,validExample:null,errors:[`Could not find message type ${a}`]}:new e({context:c,breadcrumbs:[...this.breadcrumbs,i],message:o,type:this.type,depth:this.depth+1,seenMessages:r}).convert()}findEnumType(t){let r=this.findEnumInFile(t,this.context.spec);if(!r&&this.context.getCodeGeneratorRequest()){for(let i of this.context.getCodeGeneratorRequest().protoFile)if(r=this.findEnumInFile(t,i),r!=null)break}return r}findEnumInFile(t,r){let i=r.package||"";for(let n of r.enumType)if((i?`${i}.${n.name}`:n.name||"")===t||n.name===t)return n;for(let n of r.messageType){let a=this.findEnumInMessage(t,n,i);if(a!=null)return a}}findEnumInMessage(t,r,i){let n=i?`${i}.${r.name}`:r.name||"";for(let a of r.enumType)if(`${n}.${a.name}`===t||a.name===t)return a;for(let a of r.nestedType){let o=this.findEnumInMessage(t,a,n);if(o!=null)return o}}};var Dpu=class extends Oa{operation;serviceName;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,operation:i,serviceName:n,sourceCodeInfoPath:a}){super({context:t,breadcrumbs:r}),this.operation=i,this.serviceName=n,this.sourceCodeInfoPath=a}convert(){let t=this.context.spec.package,r=this.convertRequestBody(),i=this.convertResponseBody();return{group:[t,this.serviceName],endpoint:{id:this.operation.name,docs:this.context.getCommentForPath(this.sourceCodeInfoPath),name:this.context.casingsGenerator.generateName(this.context.maybePrependPackageName(this.operation.name)),requestBody:r?.requestBody,v2RequestBodies:void 0,response:i?.responseBody,v2Responses:void 0,displayName:this.context.maybeRemoveGrpcPackagePrefix(this.operation.name),method:sw.Post,baseUrl:void 0,v2BaseUrls:void 0,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:{}},path:{head:this.operation.name,parts:[]},pathParameters:[],queryParameters:[],headers:[],sdkRequest:void 0,errors:[],auth:!1,security:void 0,availability:void 0,userSpecifiedExamples:[],autogeneratedExamples:[],idempotent:!1,basePath:void 0,fullPath:{head:this.operation.name,parts:[]},allPathParameters:[],pagination:void 0,transport:void 0,source:yW.proto({methodType:this.getGrpcMethodType()}),audiences:[],retries:void 0,apiPlayground:void 0,responseHeaders:[]}}}getGrpcMethodType(){return this.operation.clientStreaming&&this.operation.serverStreaming?s8t.BidirectionalStream:this.operation.clientStreaming?s8t.ClientStream:this.operation.serverStreaming?s8t.ServerStream:s8t.Unary}convertRequestBody(){let t=this.context.convertGrpcReferenceToTypeReference({typeName:this.operation.inputType,displayNameOverride:this.context.maybeRemoveGrpcPackagePrefix(this.operation.inputType)});return t.ok?{requestBody:Nm.reference({contentType:"application/proto",docs:void 0,requestBodyType:t.reference,v2Examples:void 0}),requestExample:void 0}:{requestBody:void 0,requestExample:void 0}}convertResponseBody(){let t=this.context.convertGrpcReferenceToTypeReference({typeName:this.operation.outputType,displayNameOverride:this.context.maybeRemoveGrpcPackagePrefix(this.operation.outputType)});return t.ok?{responseBody:{body:Ed.json(dC.response({responseBodyType:t.reference,docs:void 0,v2Examples:void 0})),statusCode:void 0,isWildcardStatusCode:void 0,docs:void 0},responseExample:void 0}:{responseBody:void 0,responseExample:void 0}}};var Bpu=class extends Oa{service;sourceCodeInfoPath;constructor({context:t,breadcrumbs:r,service:i,sourceCodeInfoPath:n}){super({context:t,breadcrumbs:r}),this.service=i,this.sourceCodeInfoPath=n}convert(){let t=[];for(let[r,i]of this.service.method.entries()){let a=new Dpu({context:this.context,breadcrumbs:this.breadcrumbs,operation:i,serviceName:this.service.name,sourceCodeInfoPath:[...this.sourceCodeInfoPath,h8t.SERVICE.METHOD,r]}).convert();a!=null&&t.push(a)}return{endpoints:t,serviceName:this.context.maybePrependPackageName(this.service.name),serviceDisplayName:this.service.name,inlinedTypes:{}}}};function Jph(){return{displayName:void 0,request:{endpoint:{method:gYt.Post,path:""},baseUrl:void 0,environment:void 0,auth:void 0,headers:void 0,docs:void 0,pathParameters:void 0,queryParameters:void 0,requestBody:void 0},response:{statusCode:200,body:Ar.V2HttpEndpointResponseBody.json({}),docs:void 0},codeSamples:[]}}var Ipu=class extends _8t{constructor({breadcrumbs:t,context:r,audiences:i}){super({breadcrumbs:t,context:r,audiences:i})}convert(){return this.convertOptions(),this.convertEnumsAndMessages(),this.convertServices(),this.generateExamplesForServices(),this.finalizeIr()}convertOptions(){}convertEnumsAndMessages(){for(let[t,r]of this.context.spec.enumType.entries()){let n=new DJi({context:this.context,breadcrumbs:[...this.breadcrumbs,this.context.spec.package],schema:r,sourceCodeInfoPath:[Ppu.ENUM,t],schemaIndex:t}).convert();n!=null&&this.addTypesToIr({...$ph(n.inlinedTypes,this.context.maybePrependPackageName.bind(this.context)),[this.context.maybePrependPackageName(r.name)]:n.convertedSchema})}for(let[t,r]of this.context.spec.messageType.entries()){let n=new DJi({context:this.context,breadcrumbs:[...this.breadcrumbs,this.context.spec.package],schema:r,sourceCodeInfoPath:[Ppu.MESSAGE,t],schemaIndex:t}).convert();n!=null&&this.addTypesToIr({...$ph(n.inlinedTypes,this.context.maybePrependPackageName.bind(this.context)),[this.context.maybePrependPackageName(r.name)]:n.convertedSchema})}}convertServices(){for(let[t,r]of this.context.spec.service.entries()){let n=new Bpu({context:this.context,breadcrumbs:this.breadcrumbs,service:r,sourceCodeInfoPath:[Ppu.SERVICE,t]}).convert();if(n!=null)for(let a of n.endpoints)this.addEndpointToIr({endpointGroup:a.group,endpoint:a.endpoint,audiences:[],serviceName:n.serviceName,endpointGroupDisplayName:n.serviceDisplayName})}}generateExamplesForServices(){for(let[t,r]of Object.entries(this.ir.services))for(let[i,n]of Object.entries(r.endpoints)){let a=Jph(),o=this.constructRequestBodyExample(n),c=this.constructResponseBodyExample(n);o!=null&&a.request!=null&&(a.request.requestBody=o),c!=null&&a.response!=null&&(a.response.body=S1.json(c)),n.v2Examples={userSpecifiedExamples:{},autogeneratedExamples:{[i]:a}}}}constructRequestBodyExample(t){let r=t.requestBody.requestBodyType.typeId,i=this.context.resolveTypeIdToProtoFile(r);if(i.ok)return new X7a({context:this.context,breadcrumbs:this.breadcrumbs,message:i.message,type:"request"}).convert().validExample}constructResponseBodyExample(t){let r=(t.response?.body).value.responseBodyType.typeId,i=this.context.resolveTypeIdToProtoFile(r);if(i.ok)return new X7a({context:this.context,breadcrumbs:this.breadcrumbs,message:i.message,type:"response"}).convert().validExample}addEndpointToIr({endpoint:t,audiences:r,endpointGroup:i,endpointGroupDisplayName:n,serviceName:a}){let o=this.context.getGroup({groupParts:i,namespace:this.context.namespace}),c=this.getOrCreatePackage({group:i}),d=[...o].map(l=>this.context.casingsGenerator.generateName(l)),s=d[d.length-1];c.service==null&&(c.service=a??`service_${o.map(l=>ou(l)).join("/")}`),this.ir.services[c.service]==null&&(this.ir.services[c.service]=this.createNewService({allParts:d,finalpart:s,endpointGroupDisplayName:n})),this.ir.services[c.service]?.endpoints.push(t);let u=this.ir.services[c.service];u!=null&&(this.irGraph.addEndpoint(u,t),this.irGraph.markEndpointForAudience(u.name,[t],r))}getOrCreatePackage({group:t}){let r=[];if(this.context.namespace!=null&&r.push(this.context.namespace),r.push(...t??[]),r.length==0)return this.ir.rootPackage;let i=this.ir.rootPackage;for(let n=0;n<r.length;n++){let a=r[n]??"",c=`subpackage_${r.slice(0,n+1).join("/")}`;this.ir.subpackages[c]==null&&(this.ir.subpackages[c]={name:this.context.casingsGenerator.generateName(a),displayName:a,...this.createPackage({name:a})});let d=this.ir.subpackages[c];i.subpackages.includes(c)||i.subpackages.push(c),i=d}return i}finalizeIr(){return{...this.ir,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})},audiences:this.audiences.type==="select"?this.audiences.audiences:void 0}}};function $ph(e,t){return Object.fromEntries(Object.entries(e).map(([r,i])=>[t(r),i]))}function Yph({req:e,options:t}){let r,i=lx({generationLanguage:void 0,keywords:void 0,smartCasing:!1});for(let a of e.protoFile){let c=new Ipu({context:new woa({codeGeneratorRequest:e,spec:a,settings:{},errorCollector:new GEe({logger:{log:(d,...s)=>{}},relativeFilepathToSpec:void 0}),logger:new joa,generationLanguage:void 0,smartCasing:!1,exampleGenerationArgs:{disabled:!0},enableUniqueErrorsPerEndpoint:!1,generateV1Examples:!1,comments:Kph(a)}),breadcrumbs:[],audiences:{type:"all"}}).convert();c!=null&&(r=r===void 0?c:Hbn(r,c,i))}let n=$n.IntermediateRepresentation.json(r,{allowUnrecognizedEnumValues:!0,skipValidation:!0});return n.ok?{name:"ir.json",content:JSON.stringify(n.value,null,2)}:{name:"ir.json",content:JSON.stringify(n.errors,null,2)}}function Xph(e){return{}}var cxc=JVD({name:"protoc-gen-fern",version:`v${String(ufh)}`,run:Yph});function JVD({name:e,version:t,run:r}){return{name:e,version:t,run(i){let n=Xph(i.parameter),a=r({req:i,options:n});return $VD([a],Kjp,Jjp)}}}function $VD(e,t,r){return IUa(fTo,{supportedFeatures:Lj.parse(FUa.PROTO3_OPTIONAL|FUa.SUPPORTS_EDITIONS),minimumEdition:t,maximumEdition:r,file:e})}var e_h=ue(require("net"),1),t_h=ue(require("os"),1),Cpu=class extends Error{constructor(t){super(`${t} is locked`)}},Eoa={old:new Set,young:new Set},YVD=1e3*15;var Z7a,XVD=()=>{let e=t_h.default.networkInterfaces(),t=new Set([void 0,"0.0.0.0"]);for(let r of Object.values(e))for(let i of r)t.add(i.address);return t},Zph=e=>new Promise((t,r)=>{let i=e_h.default.createServer();i.unref(),i.on("error",r),i.listen(e,()=>{let{port:n}=i.address();i.close(()=>{t(n)})})}),kph=async(e,t)=>{if(e.host||e.port===0)return Zph(e);for(let r of t)try{await Zph({port:e.port,host:r})}catch(i){if(!["EADDRNOTAVAIL","EINVAL"].includes(i.code))throw i}return e.port},ZVD=function*(e){e&&(yield*e),yield 0};async function Soa(e){let t,r=new Set;if(e&&(e.port&&(t=typeof e.port=="number"?[e.port]:e.port),e.exclude)){let n=e.exclude;if(typeof n[Symbol.iterator]!="function")throw new TypeError("The `exclude` option must be an iterable.");for(let a of n){if(typeof a!="number")throw new TypeError("Each item in the `exclude` option must be a number corresponding to the port you want excluded.");if(!Number.isSafeInteger(a))throw new TypeError(`Number ${a} in the exclude option is not a safe integer and can't be used`)}r=new Set(n)}Z7a===void 0&&(Z7a=setTimeout(()=>{Z7a=void 0,Eoa.old=Eoa.young,Eoa.young=new Set},YVD),Z7a.unref&&Z7a.unref());let i=XVD();for(let n of ZVD(t))try{if(r.has(n))continue;let a=await kph({...e,port:n},i);for(;Eoa.old.has(a)||Eoa.young.has(a);){if(n!==0)throw new Cpu(n);a=await kph({...e,port:n},i)}return Eoa.young.add(a),a}catch(a){if(!["EADDRINUSE","EACCES"].includes(a.code)&&!(a instanceof Cpu))throw a}throw new Error("No available ports found")}Cic();var lhh=ue(chh(),1),{applyExtends:H3D,cjsPlatformShim:K3D,Parser:J3D,processArgv:$3D,Yargs:Jpu}=lhh.default;Jpu.applyExtends=(e,t,r)=>H3D(e,t,r,K3D);Jpu.hideBin=$3D.hideBin;Jpu.Parser=J3D;var fhh=Jpu;var dhh=require("fs/promises");var phh=require("path"),_hh=ue(j4(),1);async function hhh({url:e,logger:t}){try{let r=await Y3D({url:e,logger:t}),i=await _hh.default.dir(),n=(0,phh.join)(i.path,e.endsWith(".json")?"openapi.json":"openapi.yaml");return t.debug("tmpDir",i.path),t.debug("filePath",n),await(0,dhh.writeFile)(n,r),{status:"success",filePath:n}}catch(r){return t.debug(`Encountered an error while loading OpenAPI spec: ${JSON.stringify(r)}`),{status:"failure",errorMessage:`Failed to load OpenAPI spec from ${e}`}}}async function Y3D({url:e,logger:t}){let r=await eI.get(e),i=r.headers["content-type"]??"";return i.includes("json")||e.endsWith(".json")?typeof r.data=="string"?r.data:JSON.stringify(r.data,null,2):i.includes("yaml")||e.endsWith(".yml")||e.endsWith(".yaml")?typeof r.data=="string"?r.data:Gdn(r.data):(t.warn(`Unrecognized Content-Type "${i}" from endpoint ${e}. Please ensure you're pointing to a URL that returns JSON or YAML and not HTML (e.g. Swagger UI webpage)`),Gdn(r.data))}var sKa=ue(jJ(),1);function xxc(e,t){if(e=sKa.default.parse(e),t=sKa.default.parse(t),!(sKa.default.compareBuild(e,t)>=0))return sKa.default.diff(e,t)||"build"}var X3D=/^([0-9]+)\.([0-9]+)\.([0-9]+)-([0-9]+)-([a-z0-9])+$/,Z3D=/^([0-9]+)\.([0-9]+)\.([0-9]+)-rc[.-]?([0-9]+)-([0-9]+)-([a-z0-9])+$/,k3D=/^([0-9]+)\.([0-9]+)\.([0-9]+)-rc[.-]?([0-9]+)$/,e8D=/^([0-9]+)\.([0-9]+)\.([0-9]+)$/,t8D=/^([0-9]+)\.([0-9]+)\.([0-9]+)-alpha[.-]?([0-9]+)$/,r8D=/^([0-9]+)\.([0-9]+)\.([0-9]+)-beta[.-]?([0-9]+)$/;function ovn(e){let t=e.match(t8D);if(t!=null){let[c,d,s,u,l]=t,p=IM(d),_=IM(s),h=IM(u),y=IM(l);if(p==null||_==null||h==null||y==null)throw new Error("Cannot parse alpha version: "+e);return{type:"alpha",major:p,minor:_,patch:h,index:y}}let r=e.match(r8D);if(r!=null){let[c,d,s,u,l]=r,p=IM(d),_=IM(s),h=IM(u),y=IM(l);if(p==null||_==null||h==null||y==null)throw new Error("Cannot parse beta version: "+e);return{type:"beta",major:p,minor:_,patch:h,index:y}}let i=e.match(X3D);if(i!=null){let[c,d,s,u,l]=i,p=IM(d),_=IM(s),h=IM(u),y=IM(l);if(p==null||_==null||h==null||y==null)throw new Error("Cannot parse post-release commit version: "+e);return{type:"post-release-commit",major:p,minor:_,patch:h,commitIndex:y}}let n=e.match(k3D);if(n!=null){let[c,d,s,u,l]=n,p=IM(d),_=IM(s),h=IM(u),y=IM(l);if(p==null||_==null||h==null||y==null)throw new Error("Cannot parse RC version: "+e);return{type:"rc",major:p,minor:_,patch:h,releaseCandidateIndex:y}}let a=e.match(Z3D);if(a!=null){let[c,d,s,u,l,p]=a,_=IM(d),h=IM(s),y=IM(u),b=IM(l),v=IM(p);if(_==null||h==null||y==null||b==null||v==null)throw new Error("Cannot parse post-RC version: "+e);return{type:"post-rc-commit",major:_,minor:h,patch:y,releaseCandidateIndex:b,commitIndex:v}}let o=e.match(e8D);if(o!=null){let[c,d,s,u]=o,l=IM(d),p=IM(s),_=IM(u);if(l==null||p==null||_==null)throw new Error("Cannot parse release version: "+e);return{type:"release",major:l,minor:p,patch:_}}throw new Error("Failed to parse version: "+e)}function IM(e){if(e==null||e.length===0)return;let t=Number(e);if(!isNaN(t))return t}function lY(e,t){if(e===t)return!1;let r=ovn(e),i=ovn(t);if(r.major!==i.major||r.minor!==i.minor||r.patch!==i.patch)return xxc(yhh(r),yhh(i))==null;if(r.type==="post-release-commit")return i.type!=="post-release-commit"||r.commitIndex>i.commitIndex;if(r.type==="release")return i.type!=="post-release-commit";if(r.type==="rc"){switch(i.type){case"release":case"post-release-commit":return!1;case"alpha":case"beta":return!0}return r.releaseCandidateIndex!==i.releaseCandidateIndex&&r.releaseCandidateIndex>i.releaseCandidateIndex}if(r.type==="post-rc-commit"){switch(i.type){case"release":case"post-release-commit":return!1;case"alpha":case"beta":return!0}if(i.type==="post-rc-commit")return r.releaseCandidateIndex!==i.releaseCandidateIndex?r.releaseCandidateIndex>i.releaseCandidateIndex:r.commitIndex>i.commitIndex}if(r.type==="beta"){switch(i.type){case"release":case"post-release-commit":case"rc":case"post-rc-commit":return!1;case"alpha":return!0}return r.index>i.index}if(r.type==="alpha"){switch(i.type){case"release":case"post-release-commit":case"rc":case"post-rc-commit":return!1}return r.index>i.index}return!lY(t,e)}function yhh(e){return`${e.major}.${e.minor}.${e.patch}`}var yL=(e,t=[])=>e.name==="up"||t.includes("vim")&&e.name==="k"||t.includes("emacs")&&e.ctrl&&e.name==="p",fY=(e,t=[])=>e.name==="down"||t.includes("vim")&&e.name==="j"||t.includes("emacs")&&e.ctrl&&e.name==="n",Hxc=e=>e.name==="space",uvn=e=>e.name==="backspace",hUi=e=>e.name==="tab",cKa=e=>"1234567890".includes(e.name),OC=e=>e.name==="enter"||e.name==="return";var $pu=class extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(t){super(),this.cause=t?.cause}},Ypu=class extends Error{name="CancelPromptError";message="Prompt was canceled"},lKa=class extends Error{name="ExitPromptError"},Xpu=class extends Error{name="HookError"},QYt=class extends Error{name="ValidationError"};var Ohh=require("async_hooks");var Zpu=require("async_hooks");var bhh=new Zpu.AsyncLocalStorage;function i8D(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function vhh(e,t){let r=i8D(e);return bhh.run(r,()=>{function i(n){r.handleChange=()=>{r.index=0,n()},r.handleChange()}return t(i)})}function svn(){let e=bhh.getStore();if(!e)throw new Xpu("[Inquirer] Hook functions can only be called from within a prompt");return e}function Kxc(){return svn().rl}function Jxc(e){let t=(...r)=>{let i=svn(),n=!1,a=i.handleChange;i.handleChange=()=>{n=!0};let o=e(...r);return n&&a(),i.handleChange=a,o};return Zpu.AsyncResource.bind(t)}function Toa(e){let t=svn(),{index:r}=t,i={get(){return t.hooks[r]},set(a){t.hooks[r]=a},initialized:r in t.hooks},n=e(i);return t.index++,n}function ghh(){svn().handleChange()}var cvn={queue(e){let t=svn(),{index:r}=t;t.hooksEffect.push(()=>{t.hooksCleanup[r]?.();let i=e(Kxc());if(i!=null&&typeof i!="function")throw new QYt("useEffect return value must be a cleanup function or nothing.");t.hooksCleanup[r]=i})},run(){let e=svn();Jxc(()=>{e.hooksEffect.forEach(t=>{t()}),e.hooksEffect.length=0})()},clearAll(){let e=svn();e.hooksCleanup.forEach(t=>{t?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function pf(e){return Toa(t=>{let r=Ohh.AsyncResource.bind(function(a){t.get()!==a&&(t.set(a),ghh())});if(t.initialized)return[t.get(),r];let i=typeof e=="function"?e():e;return t.set(i),[i,r]})}function oge(e,t){Toa(r=>{let i=r.get();(!Array.isArray(i)||t.some((a,o)=>!Object.is(a,i[o])))&&cvn.queue(e),r.set(t)})}var $Ee=ue(PR(),1);var mhh={prefix:{idle:$Ee.default.blue("?"),done:$Ee.default.green(_1.tick)},spinner:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map(e=>$Ee.default.yellow(e))},style:{answer:$Ee.default.cyan,message:$Ee.default.bold,error:e=>$Ee.default.red(`> ${e}`),defaultAnswer:e=>$Ee.default.dim(`(${e})`),help:$Ee.default.dim,highlight:$Ee.default.cyan,key:e=>$Ee.default.cyan($Ee.default.bold(`<${e}>`))}};function Ahh(e){if(typeof e!="object"||e===null)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function Phh(...e){let t={};for(let r of e)for(let[i,n]of Object.entries(r)){let a=t[i];t[i]=Ahh(a)&&Ahh(n)?Phh(a,n):n}return t}function MD(...e){let t=[mhh,...e.filter(r=>r!=null)];return Phh(...t)}function mC({status:e="idle",theme:t}){let[r,i]=pf(!1),[n,a]=pf(0),{prefix:o,spinner:c}=MD(t);return oge(()=>{if(e==="loading"){let s,u=-1,l=setTimeout(()=>{i(!0),s=setInterval(()=>{u=u+1,a(u%c.frames.length)},c.interval)},300);return()=>{clearTimeout(l),clearInterval(s)}}else i(!1)},[e]),r?c.frames[n]:typeof o=="string"?o:o[e==="loading"?"idle":e]??o.idle}function dY(e,t){return Toa(r=>{let i=r.get();if(!i||i.dependencies.length!==t.length||i.dependencies.some((n,a)=>n!==t[a])){let n=e();return r.set({value:n,dependencies:t}),n}return i.value})}function YEe(e){return pf({current:e})[0]}function AC(e){let t=YEe(e);t.current=e,oge(r=>{let i=!1,n=Jxc((a,o)=>{i||t.current(o,r)});return r.input.on("keypress",n),()=>{i=!0,r.input.removeListener("keypress",n)}},[])}var jhh=ue(RTc(),1),whh=ue(WTc(),1);function fKa(e,t){return e.split(`
1470
1470
  `).flatMap(r=>(0,whh.default)(r,t,{trim:!1,hard:!0}).split(`
1471
1471
  `).map(i=>i.trimEnd())).join(`
@@ -1500,7 +1500,7 @@ ${O}${g}${A}${Roa}`});var pKa=class{result=Qw.Success;logImmediately;logPrefix;s
1500
1500
  Run ${Rt.cyan("fern generator upgrade")} to upgrade your generators.`),n.length>2&&(r+=`
1501
1501
  Run ${Rt.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),nra(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function _Hc({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!Whh(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+=`
1502
1502
  ${await q8D(c.generatorName)} (${c.apiName!=null?"API: "+c.apiName+", ":""}Group: ${c.generatorGroup}) `+Rt.dim(c.currentVersion)+Rt.reset(" \u2192 ")+Rt.green(c.latestVersion);return n+=`
1503
- `,i?nra(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function q8D(e){let r=await new Vhh.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 T8D({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await xhh({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,u,l)=>{c.versions[s]==null&&(c.versions[s]={});let p=oHi(u.name,l),_=await m3t({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:n,includeMajor:a,context:l});_!=null&&(c.versions[s][u.name]={previousVersion:u.version,latestVersion:_})},generatorFilter:r,groupFilter:i}),c}let o={type:"multiApi",versions:{}};return await xhh({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 l=oHi(s.name,u),p=await m3t({generatorName:l,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 xhh({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 Dve({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(c==null||c.groups==null)return;let d=i!=null?zN(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 Hhh(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=lY(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 a_u({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let o=[];if(e!=null){let c=await T8D({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(...Hhh(s,d,t.logger));else o.push(...Hhh(c.versions,void 0,t.logger))}return o}var _Ka=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 Noa=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var hHc=(()=>{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})(),Khh=typeof globalThis.AbortController=="function",Jhh=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",$hh=typeof globalThis.ReadableStream=="function",Yhh=typeof globalThis.FormData=="function",o_u=["get","post","put","patch","head","delete"],R8D=()=>{};R8D();var Xhh={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},u_u=2147483647,Zhh=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,s_u=Symbol("stop"),khh={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},eyh={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 z8D=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=Zhh,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},tyh=(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))}}))},ryh=(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(tyh(e.body,r,t),{status:e.status,statusText:e.statusText,headers:e.headers})},iyh=(e,t,r)=>{if(!e.body)return e;let i=z8D(r??e.body);return new Request(e,{duplex:"half",body:tyh(e.body,i,t)})};var Foa=e=>e!==null&&typeof e=="object";var hKa=(...e)=>{for(let t of e)if((!Foa(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return vHc({},...e)},yHc=(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 c_u(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:vHc(e[r]??[],t[r]??[])}var bHc=(e={},t={})=>({beforeRequest:c_u(e,t,"beforeRequest"),beforeRetry:c_u(e,t,"beforeRetry"),afterResponse:c_u(e,t,"afterResponse"),beforeError:c_u(e,t,"beforeError")}),vHc=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(Foa(n)){for(let[a,o]of Object.entries(n))Foa(o)&&a in t&&(o=vHc(t[a],o)),t={...t,[a]:o};Foa(n.hooks)&&(i=bHc(i,n.hooks),t.hooks=i),Foa(n.headers)&&(r=yHc(r,n.headers),t.headers=r)}return t};var ayh=e=>o_u.includes(e)?e.toUpperCase():e,N8D=["get","put","head","delete","options","trace"],F8D=[408,413,429,500,502,503,504],Q8D=[413,429,503],nyh={limit:2,methods:N8D,statusCodes:F8D,afterStatusCodes:Q8D,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},oyh=(e={})=>{if(typeof e=="number")return{...nyh,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{...nyh,...e}};async function gHc(e,t,r,i){return new Promise((n,a)=>{let o=setTimeout(()=>{r&&r.abort(),a(new Noa(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function OHc(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 uyh=(e,t)=>{let r={};for(let i in t)!(i in eyh)&&!(i in khh)&&!(i in e)&&(r[i]=t[i]);return r},syh=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 yKa=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>u_u)throw new RangeError(`The \`timeout\` option cannot be greater than ${u_u}`);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 _Ka(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(!$hh)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return ryh(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(Xhh))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:yHc(this._input.headers,r.headers),hooks:bHc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:ayh(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:oyh(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(Khh&&Jhh){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(hHc&&(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),syh(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);(Yhh&&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(!hHc)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=iyh(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof Noa)throw t;if(t instanceof _Ka){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),u_u);if(this._retryCount<1)throw r;await OHc(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})===s_u)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=uyh(this.request,this._options);return this._originalRequest=this.request,this.request=this._originalRequest.clone(),this._options.timeout===!1?this._options.fetch(this._originalRequest,t):gHc(this._originalRequest,t,this.abortController,this._options)}};var mHc=e=>{let t=(r,i)=>yKa.create(r,hKa(e,i));for(let r of o_u)t[r]=(i,n)=>yKa.create(i,hKa(e,n,{method:r}));return t.create=r=>mHc(hKa(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),mHc(hKa(e,r))),t.stop=s_u,t},U8D=mHc(),cyh=U8D;var Cyh=ue(Iyh(),1);function EHc(e){let t=(0,Cyh.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var Ebh=ue(wbh(),1),Sbh=ue(jJ(),1),QHc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},UHc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function LHc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??EHc(n),o=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,Ebh.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 cyh(o,{headers:d,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new QHc(e):l}if(t.allVersions)return s;let u=new UHc(e,r);if(s["dist-tags"][r]){let{time:l}=s;s=s.versions[s["dist-tags"][r]],s.time=l}else if(r){let l=!!s.versions[r];if(i&&!l)for(let[_,h]of Object.entries(s.versions))h.deprecated&&delete s.versions[_];if(!l){let _=Object.keys(s.versions);if(r=Sbh.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 AKa(e,t){let{version:r}=await LHc(e.toLowerCase(),t);return r}async function RJi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:AKa(e.packageName,{version:t?"prerelease":"latest"})}var Mbh=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],m_u=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Ou.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new Zfn(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.47.4"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${Rt.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new pM}failWithoutThrowing(t,r){this.didSucceed=!1,V4a({message:t,error:r,logger:this.logger})}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await Kta()).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 Ghh({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1503
+ `,i?nra(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function q8D(e){let r=await new Vhh.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 T8D({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await xhh({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,u,l)=>{c.versions[s]==null&&(c.versions[s]={});let p=oHi(u.name,l),_=await m3t({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:n,includeMajor:a,context:l});_!=null&&(c.versions[s][u.name]={previousVersion:u.version,latestVersion:_})},generatorFilter:r,groupFilter:i}),c}let o={type:"multiApi",versions:{}};return await xhh({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 l=oHi(s.name,u),p=await m3t({generatorName:l,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 xhh({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 Dve({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(c==null||c.groups==null)return;let d=i!=null?zN(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 Hhh(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=lY(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 a_u({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let o=[];if(e!=null){let c=await T8D({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(...Hhh(s,d,t.logger));else o.push(...Hhh(c.versions,void 0,t.logger))}return o}var _Ka=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 Noa=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var hHc=(()=>{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})(),Khh=typeof globalThis.AbortController=="function",Jhh=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",$hh=typeof globalThis.ReadableStream=="function",Yhh=typeof globalThis.FormData=="function",o_u=["get","post","put","patch","head","delete"],R8D=()=>{};R8D();var Xhh={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},u_u=2147483647,Zhh=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,s_u=Symbol("stop"),khh={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},eyh={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 z8D=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=Zhh,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},tyh=(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))}}))},ryh=(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(tyh(e.body,r,t),{status:e.status,statusText:e.statusText,headers:e.headers})},iyh=(e,t,r)=>{if(!e.body)return e;let i=z8D(r??e.body);return new Request(e,{duplex:"half",body:tyh(e.body,i,t)})};var Foa=e=>e!==null&&typeof e=="object";var hKa=(...e)=>{for(let t of e)if((!Foa(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return vHc({},...e)},yHc=(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 c_u(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:vHc(e[r]??[],t[r]??[])}var bHc=(e={},t={})=>({beforeRequest:c_u(e,t,"beforeRequest"),beforeRetry:c_u(e,t,"beforeRetry"),afterResponse:c_u(e,t,"afterResponse"),beforeError:c_u(e,t,"beforeError")}),vHc=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(Foa(n)){for(let[a,o]of Object.entries(n))Foa(o)&&a in t&&(o=vHc(t[a],o)),t={...t,[a]:o};Foa(n.hooks)&&(i=bHc(i,n.hooks),t.hooks=i),Foa(n.headers)&&(r=yHc(r,n.headers),t.headers=r)}return t};var ayh=e=>o_u.includes(e)?e.toUpperCase():e,N8D=["get","put","head","delete","options","trace"],F8D=[408,413,429,500,502,503,504],Q8D=[413,429,503],nyh={limit:2,methods:N8D,statusCodes:F8D,afterStatusCodes:Q8D,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},oyh=(e={})=>{if(typeof e=="number")return{...nyh,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{...nyh,...e}};async function gHc(e,t,r,i){return new Promise((n,a)=>{let o=setTimeout(()=>{r&&r.abort(),a(new Noa(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function OHc(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 uyh=(e,t)=>{let r={};for(let i in t)!(i in eyh)&&!(i in khh)&&!(i in e)&&(r[i]=t[i]);return r},syh=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 yKa=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>u_u)throw new RangeError(`The \`timeout\` option cannot be greater than ${u_u}`);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 _Ka(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(!$hh)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return ryh(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(Xhh))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:yHc(this._input.headers,r.headers),hooks:bHc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:ayh(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:oyh(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(Khh&&Jhh){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(hHc&&(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),syh(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);(Yhh&&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(!hHc)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=iyh(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof Noa)throw t;if(t instanceof _Ka){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),u_u);if(this._retryCount<1)throw r;await OHc(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})===s_u)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=uyh(this.request,this._options);return this._originalRequest=this.request,this.request=this._originalRequest.clone(),this._options.timeout===!1?this._options.fetch(this._originalRequest,t):gHc(this._originalRequest,t,this.abortController,this._options)}};var mHc=e=>{let t=(r,i)=>yKa.create(r,hKa(e,i));for(let r of o_u)t[r]=(i,n)=>yKa.create(i,hKa(e,n,{method:r}));return t.create=r=>mHc(hKa(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),mHc(hKa(e,r))),t.stop=s_u,t},U8D=mHc(),cyh=U8D;var Cyh=ue(Iyh(),1);function EHc(e){let t=(0,Cyh.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var Ebh=ue(wbh(),1),Sbh=ue(jJ(),1),QHc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},UHc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function LHc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??EHc(n),o=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,Ebh.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 cyh(o,{headers:d,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new QHc(e):l}if(t.allVersions)return s;let u=new UHc(e,r);if(s["dist-tags"][r]){let{time:l}=s;s=s.versions[s["dist-tags"][r]],s.time=l}else if(r){let l=!!s.versions[r];if(i&&!l)for(let[_,h]of Object.entries(s.versions))h.deprecated&&delete s.versions[_];if(!l){let _=Object.keys(s.versions);if(r=Sbh.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 AKa(e,t){let{version:r}=await LHc(e.toLowerCase(),t);return r}async function RJi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:AKa(e.packageName,{version:t?"prerelease":"latest"})}var Mbh=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],m_u=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Ou.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new Zfn(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.47.6"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${Rt.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new pM}failWithoutThrowing(t,r){this.didSucceed=!1,V4a({message:t,error:r,logger:this.logger})}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await Kta()).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 Ghh({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1504
1504
  `)||(r+=`
1505
1505
  `),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=rnc(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 pKa(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 pM}finally{i.finish()}return n}async instrumentPostHogEvent(t){this.isLocal||(await Kta()).sendEvent(t)}logger=Zbe((t,...r)=>this.log(t,...r));stderr=Zbe((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=Dbh(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?Dbh(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=Mbh[this.numTasks++%Mbh.length],o=Rt.hex(a)(n);return{...this.constructTaskInit(),logPrefix:o}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===Qw.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=>kLt.indexOf(n.level)>=kLt.indexOf(this.logLevel));this.ttyAwareLogger.log(i,{includeDebugInfo:this.logLevel===Ou.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 RJi({cliEnvironment:this.environment,includePreReleases:t}),i=lY(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await a_u({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){try{return await dHc({message:t,choices:[{name:"No",value:!1},{name:"Yes",value:!0}],default:r,theme:{prefix:Rt.yellow("?"),style:{answer:n=>Rt.cyan(n),message:n=>Rt.bold(n),highlight:n=>Rt.cyan(n)}}})}catch(i){throw i?.name==="ExitPromptError"?(this.logger.info(`
1506
1506
  Cancelled by user.`),new pM):i}}async getInput(t){return await sHc({message:t.message,default:t.default})}};function Dbh(e){return`[${e}]:`}var g8t=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 A_u(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)=>A_u.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 Bbh(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 Ibh(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 Cbh=Function.bind,qbh=Cbh.bind(Cbh);function Tbh(e,t,r){let i=qbh(Ibh,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]=qbh(Bbh,null).apply(null,a)})}function HWD(){let e=Symbol("Singular"),t={registry:{}},r=A_u.bind(null,t,e);return Tbh(r,t,e),r}function KWD(){let e={registry:{}},t=A_u.bind(null,e);return Tbh(t,e),t}var Rbh={Singular:HWD,Collection:KWD};var JWD="0.0.0-development",$WD=`octokit-endpoint.js/${JWD} ${LN()}`,YWD={method:"GET",baseUrl:"https://api.github.com",headers:{accept:"application/vnd.github.v3+json","user-agent":$WD},mediaType:{format:""}};function XWD(e){return e?Object.keys(e).reduce((t,r)=>(t[r.toLowerCase()]=e[r],t),{}):{}}function ZWD(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 Fbh(e,t){let r=Object.assign({},e);return Object.keys(t).forEach(i=>{ZWD(t[i])?i in e?r[i]=Fbh(e[i],t[i]):Object.assign(r,{[i]:t[i]}):Object.assign(r,{[i]:t[i]})}),r}function zbh(e){for(let t in e)e[t]===void 0&&delete e[t];return e}function WHc(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=XWD(r.headers),zbh(r),zbh(r.headers);let i=Fbh(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 kWD(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 e5D=/\{[^{}}]+\}/g;function t5D(e){return e.replace(/(?:^\W+)|(?:(?<!\W)\W+$)/g,"").split(/,/)}function r5D(e){let t=e.match(e5D);return t?t.map(t5D).reduce((r,i)=>r.concat(i),[]):[]}function Nbh(e,t){let r={__proto__:null};for(let i of Object.keys(e))t.indexOf(i)===-1&&(r[i]=e[i]);return r}function Qbh(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 Hoa(e){return encodeURIComponent(e).replace(/[!'()*]/g,function(t){return"%"+t.charCodeAt(0).toString(16).toUpperCase()})}function PKa(e,t,r){return t=e==="+"||e==="#"?Qbh(t):Hoa(t),r?Hoa(r)+"="+t:t}function xoa(e){return e!=null}function VHc(e){return e===";"||e==="&"||e==="?"}function i5D(e,t,r,i){var n=e[r],a=[];if(xoa(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(PKa(t,n,VHc(t)?r:""));else if(i==="*")Array.isArray(n)?n.filter(xoa).forEach(function(o){a.push(PKa(t,o,VHc(t)?r:""))}):Object.keys(n).forEach(function(o){xoa(n[o])&&a.push(PKa(t,n[o],o))});else{let o=[];Array.isArray(n)?n.filter(xoa).forEach(function(c){o.push(PKa(t,c))}):Object.keys(n).forEach(function(c){xoa(n[c])&&(o.push(Hoa(c)),o.push(PKa(t,n[c].toString())))}),VHc(t)?a.push(Hoa(r)+"="+o.join(",")):o.length!==0&&a.push(o.join(","))}else t===";"?xoa(n)&&a.push(Hoa(r)):n===""&&(t==="&"||t==="?")?a.push(Hoa(r)+"="):n===""&&a.push("");return a}function n5D(e){return{expand:a5D.bind(null,e)}}function a5D(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(i5D(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 Qbh(a)}),e==="/"?e:e.replace(/\/$/,"")}function Ubh(e){let t=e.method.toUpperCase(),r=(e.url||"/").replace(/:([a-z]\w+)/g,"{$1}"),i=Object.assign({},e.headers),n,a=Nbh(e,["method","baseUrl","url","headers","request","mediaType"]),o=r5D(r);r=n5D(r).expand(a),/^http/.test(r)||(r=e.baseUrl+r);let c=Object.keys(e).filter(u=>o.includes(u)).concat("baseUrl"),d=Nbh(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(l=>{let p=e.mediaType.format?`.${e.mediaType.format}`:"+json";return`application/vnd.github.${l}-preview${p}`}).join(",")}return["GET","HEAD"].includes(t)?r=kWD(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 o5D(e,t,r){return Ubh(WHc(e,t,r))}function Lbh(e,t){let r=WHc(e,t),i=o5D.bind(null,r);return Object.assign(i,{DEFAULTS:r,defaults:Lbh.bind(null,r),merge:WHc.bind(null,r),parse:Ubh})}var Vbh=Lbh(null,YWD);var Jbh=ue(Hbh(),1);var O8t=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 u5D="10.0.6",s5D={headers:{"user-agent":`octokit-request.js/${u5D} ${LN()}`}};function c5D(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 Kbh(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=c5D(e.body)||Array.isArray(e.body)?JSON.stringify(e.body):e.body,a=Object.fromEntries(Object.entries(e.headers).map(([l,p])=>[l,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(l){let p="Unknown Error";if(l instanceof Error){if(l.name==="AbortError")throw l.status=500,l;p=l.message,l.name==="TypeError"&&"cause"in l&&(l.cause instanceof Error?p=l.cause.message:typeof l.cause=="string"&&(p=l.cause))}let _=new O8t(p,500,{request:e});throw _.cause=l,_}let c=o.status,d=o.url,s={};for(let[l,p]of o.headers)s[l]=p;let u={url:d,status:c,headers:s,data:""};if("deprecation"in s){let l=s.link&&s.link.match(/<([^<>]+)>; rel="deprecation"/),p=l&&l.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 O8t(o.statusText,c,{response:u,request:e})}if(c===304)throw u.data=await GHc(o),new O8t("Not modified",c,{response:u,request:e});if(c>=400)throw u.data=await GHc(o),new O8t(f5D(u.data),c,{response:u,request:e});return u.data=i?await GHc(o):o.body,u}async function GHc(e){let t=e.headers.get("content-type");if(!t)return e.text().catch(()=>"");let r=(0,Jbh.safeParse)(t);if(l5D(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 l5D(e){return e.type==="application/json"||e.type==="application/scim+json"}function f5D(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 xHc(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 Kbh(r.parse(o));let c=(d,s)=>Kbh(r.parse(r.merge(d,s)));return Object.assign(c,{endpoint:r,defaults:xHc.bind(null,r)}),o.request.hook(c,o)},{endpoint:r,defaults:xHc.bind(null,r)})}var Qm=xHc(Vbh,s5D);var d5D="0.0.0-development";function p5D(e){return`Request failed due to following response errors:
@@ -1521,7 +1521,7 @@ Cancelled by user.`),new pM):i}}async getInput(t){return await sHc({message:t.me
1521
1521
  Location: ${n.join("-> ")}`),ai.unknown({nameOverride:l,generatedName:h,title:y,description:b,availability:v,namespace:c,groupName:_,example:void 0})}}function $GD(e){if(e!=null){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.toLowerCase();if(t==="true")return!0;if(t==="false")return!1}}}function XJi(e){if(e.$ref.startsWith(Tvn))return e.$ref.replace(Tvn,"")}function W7c(e,t,r,i){let n=Ei(e,xi.TYPE_NAME),a=jC(t,i),o=e.description,c=BW(e),d=XJi(e);if(d==null)throw new Error(`Invalid schema reference ${JSON.stringify(e)}`);return nc.reference({generatedName:a,nameOverride:n,title:void 0,schema:d,description:o??void 0,availability:c,namespace:void 0,groupName:void 0,source:r})}function YGD(e){return e.oneOf==null||e.oneOf.length===0}function zOh(e){return e.allOf==null||e.allOf.length===0}function nbu(e){return e.properties==null||UA(e.properties)===0}function obu(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function $Yt(e,t,r,i){if(e.type==="reference")return ai.reference({...e,description:t,availability:e.availability,namespace:r,groupName:i});if(e.type==="optional"){let n=$Yt(e.value,t,r,i);return ai.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:n,description:t,availability:e.availability,namespace:r,groupName:i,inline:void 0})}else if(e.type==="nullable"){let n=$Yt(e.value,t,r,i);return ai.nullable({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:n,description:t,availability:e.availability,namespace:r,groupName:i,inline:void 0})}else if(e.type==="primitive"&&t!=null&&e.description==null)return ai.primitive({...e,description:t});return e}function abu(e){return Bn(e)||e.type==="object"||e.properties!=null?!0:e.allOf!=null?e.allOf.every(t=>abu(t)):e.oneOf!=null?e.oneOf.every(t=>abu(t)):e.anyOf!=null?e.anyOf.every(t=>abu(t)):!1}function NOh({literal:e,wrapAsOptional:t,wrapAsNullable:r,namespace:i,groupName:n,description:a,availability:o,nameOverride:c,generatedName:d,title:s}){let u=ai.literal({nameOverride:c,generatedName:d,title:s,value:e,namespace:i,groupName:n,description:a,availability:o});return r&&(u=ai.nullable({nameOverride:c,generatedName:d,title:s,value:u,namespace:i,groupName:n,description:a,availability:o,inline:void 0})),t&&(u=ai.optional({nameOverride:c,generatedName:d,title:s,value:u,namespace:i,groupName:n,description:a,availability:o,inline:void 0})),u}function IW({primitive:e,wrapAsOptional:t,wrapAsNullable:r,namespace:i,groupName:n,description:a,availability:o,generatedName:c,nameOverride:d,title:s}){n=typeof n=="string"?[n]:n;let u=ai.primitive({nameOverride:d,generatedName:c,title:s,schema:e,description:a,availability:o,namespace:i,groupName:n});return r&&(u=ai.nullable({nameOverride:d,generatedName:c,title:s,value:u,namespace:i,groupName:n,description:a,availability:o,inline:void 0})),t&&(u=ai.optional({nameOverride:d,generatedName:c,title:s,value:u,namespace:i,groupName:n,description:a,availability:o,inline:void 0})),u}function XGD({schemas:e}){let t=new Set;for(let r of e){if(Bn(r))return;if(r.enum!=null&&obu(r.enum))r.enum.forEach(i=>t.add(i));else return}return Array.from(t)}function FOh({schemas:e,context:t}){let r={};for(let i of e){let n=UOh({schema:i,context:t});for(let[a,o]of Object.entries(n)){let c=r[a];c!=null?c[o]=i:r[a]={[o]:i}}}for(let[i,n]of Object.entries(r))if(Object.keys(n).length===e.length)return{discriminant:i,schemas:n}}function UOh({schema:e,context:t}){let r=Bn(e)?t.resolveSchemaReference(e):e;return ZGD({schema:r,context:t})}function ZGD({schema:e,context:t}){let r={};if(e.anyOf!=null){for(let i of e.anyOf){let n=UOh({schema:i,context:t});for(let[a,o]of Object.entries(n??{}))r[a]=o}return r}for(let[i,n]of Object.entries(e.properties??{})){let a=Bn(n)?t.resolveSchemaReference(n):n;a.type==="string"&&a.enum!=null&&obu(a.enum)&&kGD(a.enum).length===1&&a.enum[0]!=null&&(r[i]=a.enum[0]);let o=LOh(a,"const");a.type==="string"&&o!=null&&(r[i]=o),i==="type"&&a.example!=null&&(r[i]=a.example)}return r}function kGD(e){if(!e)return[];let t=new Set;return e.forEach(r=>{typeof r=="string"?t.add(r.toLowerCase()):t.add(r)}),Array.from(t)}function LOh(e,t){let r=e[t];if(r!=null)return r}function exD({schema:e,logger:t}){let r=bOh({schema:e,logger:t});if(r!=null)return wOh(r)}var Tua=class{document;taskContext;logger;DUMMY;options;namespace;static MESSAGE_REFERENCE_PREFIX="#/components/messages/";constructor({document:t,taskContext:r,options:i,namespace:n}){this.document=t,this.taskContext=r,this.logger=r.logger,this.DUMMY=this,this.options=i,this.namespace=n}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveTags(t,r){if(this.namespace==null&&t==null&&r!=null)return[r];let i=[];if(this.namespace!=null){let n={type:"namespace",name:this.namespace};i.push(n)}return i.concat(t??[])}resolveSchemaReference(t){if(!t.$ref.startsWith(Tvn))throw new Error(`Failed to resolve schema reference: ${t.$ref}`);let i=t.$ref.substring(Tvn.length).split("/"),n=this.document.components;if(n==null||n.schemas==null)throw new Error("Document does not have components.schemas.");let[a,o,c]=i;if(a==null||a==="")throw new Error(`${t.$ref} cannot be resolved. No schema key provided.`);let d=n.schemas[a];if(d==null)throw new Error(`Schema "${a}" is undefined in document.components.schemas.`);if(Bn(d)&&(d=this.resolveSchemaReference(d)),o==="properties"&&c!=null){let s=d.properties?.[c];if(s==null)throw new Error(`Property "${c}" not found on "${a}". Full ref: ${t.$ref}`);Bn(s)?d=this.resolveSchemaReference(s):d=s}return d}referenceExists(t){let r=t.substring(2).split("/").map(n=>n.replace(/~1/g,"/")),i=this.document;for(let n of r){if(typeof i!="object"||i==null)return!1;i=i[n]}return!0}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}markReferencedByDiscriminatedUnion(t,r,i){}markSchemaWithDiscriminantValue(t,r,i){}};var ubu=class extends Tua{getExampleMessageReference(t){return`#/components/messages/${t.messageId}`}resolveMessageReference(t){let r="#/components/messages/",i=this.document.components;if(i==null||i.messages==null||!t.$ref.startsWith(r))throw new Error(`Failed to resolve message reference: ${t.$ref} in v2 components`);let n=t.$ref.substring(r.length),a=i.messages[n];if(a==null)throw new Error(`${t.$ref} is undefined`);return a}};function Rua(e,t){let r={};if(e!=null)return{rootSchemas:r,namespacedSchemas:{[e]:t}};let i={};for(let[n,a]of Object.entries(t))switch(a.type){case"object":case"array":case"map":case"optional":case"enum":case"literal":case"reference":case"nullable":case"primitive":{if(a.namespace==null){r[n]=a;continue}let o=a.namespace;i[o]??={},i[o][n]=a;continue}case"oneOf":case"unknown":r[n]=a;continue;default:vt(a)}return{rootSchemas:r,namespacedSchemas:i}}var zua=ue(require("fs"),1),Rvn=ue(require("path"),1);function kJi(e){if(typeof e=="string")return Pl.primitive(go.string(e));if(typeof e=="number")return Number.isInteger(e)?Pl.primitive(go.int(e)):Pl.primitive(go.double(e));if(typeof e=="boolean")return Pl.primitive(go.boolean(e));if(Array.isArray(e)){let t=e.map(r=>kJi(r));return t.length===0?void 0:Pl.array(t.filter(r=>r!=null))}else if(e!=null&&typeof e=="object"&&Object.keys(e).every(t=>typeof t=="string")){let t=[];for(let[r,i]of Object.entries(e)){let n=kJi(i);n!=null&&t.push({key:go.string(r),value:n})}return Pl.map(t)}}function JKa(e){if(e!=null&&typeof e=="object"&&Object.keys(e).every(t=>typeof t=="string"))return e}function VOh(e){if(e!=null&&Array.isArray(e))return e}var e$i=class{schemas;nonRequestReferencedSchemas;context;constructor(t,r,i){this.schemas=t,this.nonRequestReferencedSchemas=r,this.context=i}buildExample({schema:t,exampleId:r,example:i,options:n,skipReadonly:a}){return this.buildExampleHelper({schema:t,visitedSchemaIds:new Set,exampleId:r,example:i,options:{...n,maxCheckerDepth:n.maxCheckerDepth??5},depth:0,skipReadonly:a??!1})}buildExampleHelper({exampleId:t,example:r,schema:i,depth:n,visitedSchemaIds:a,options:o,skipReadonly:c}){switch(i.type){case"enum":return typeof r=="string"&&WOh({schema:i,value:r})?Pl.enum(r):i.values[0]!=null?Pl.enum(i.values[0]?.value):void 0;case"literal":return Pl.literal(i.value);case"nullable":{if(r===null)return Pl.null({});if(r==null&&!this.hasExample(i.value,0,a,o)&&this.exceedsMaxDepth(n,o))return Pl.null({});let d=this.buildExampleHelper({schema:i.value,visitedSchemaIds:a,exampleId:t,example:r,depth:n,options:o,skipReadonly:c});return d??Pl.null({})}case"optional":{if(r==null&&!this.hasExample(i.value,0,a,o)&&(o.ignoreOptionals||this.exceedsMaxDepth(n,o))||Object.is(r,null))return;let d=this.buildExampleHelper({schema:i.value,visitedSchemaIds:a,exampleId:t,example:r,depth:n,options:o,skipReadonly:c});return d!=null&&d.type==="array"&&d.value.length===0||d!=null&&d.type==="map"&&d.value.length===0||d!=null&&d.type==="object"&&Object.keys(d.properties).length===0?void 0:d}case"primitive":{let d=this.buildExampleFromPrimitive({schema:i.schema,example:r,options:o});return Pl.primitive(d)}case"reference":{let d=this.schemas[i.schema];if(d!=null&&!a.has(i.schema)){a.add(i.schema);let s=d?.type==="object"&&!this.nonRequestReferencedSchemas.has(i.schema),u=this.buildExampleHelper({example:r,schema:d,exampleId:t,visitedSchemaIds:a,depth:n,options:o,skipReadonly:s||this.context.options.respectReadonlySchemas?c:!1});return a.delete(i.schema),u}return}case"oneOf":switch(i.value.type){case"discriminated":{let d={},s={},u={},l=JKa(r),p=l?.[i.value.discriminantProperty],_=i.value.schemas[p],h=[],y=this.getDiscriminatedUnionVariantSchema(i.value,l);y!=null&&h.push(y),h.push(...Object.entries(i.value.schemas));for(let b of h)if(p!=null&&_!=null&&_.type==="object"){s=this.getAllProperties(_),u=this.getAllRequiredProperties(_),d[i.value.discriminantProperty]=Pl.primitive(go.string(p));break}else{let v=this.buildExampleHelper({exampleId:t,schema:b[1],example:void 0,visitedSchemaIds:a,depth:n,options:o,skipReadonly:c});if(v!=null){this.mergeExampleWith(v,d),d[i.value.discriminantProperty]=Pl.primitive(go.string(b[0]));break}}for(let b of i.value.commonProperties){s[b.key]={schema:b.schema,readonly:!1};let v=this.getResolvedSchema(b.schema);v.type!=="optional"&&v.type!=="nullable"&&(u[b.key]=b.schema)}for(let[b,v]of Object.entries(s)){let g=b in u;if(g&&l?.[b]!=null){let m=this.buildExampleHelper({schema:v.schema,exampleId:t,example:l[b],visitedSchemaIds:a,depth:n+1,options:o,skipReadonly:c});if(m!=null)d[b]=m;else return}else{let m=this.buildExampleHelper({exampleId:t,schema:v.schema,example:l?.[b],visitedSchemaIds:a,depth:n+1,options:o,skipReadonly:c});if(m!=null)d[b]=m;else if(g)return}}return Pl.oneOf(FJi.discriminated(d))}case"undiscriminated":{let d=this.getUnDiscriminatedUnionVariantSchema(i.value,r);if(d!=null)return this.buildExampleHelper({exampleId:t,example:r,schema:d,visitedSchemaIds:a,depth:n,options:o,skipReadonly:c});break}}return;case"unknown":if(r!=null){let d=kJi(r);if(d!=null)return Pl.unknown(d)}return o.ignoreOptionals||this.exceedsMaxDepth(n,o)?void 0:o.isParameter?Pl.primitive(go.string(o.name??"string")):Pl.map([{key:go.string("key"),value:Pl.primitive(go.string("value"))}]);case"array":{let d=VOh(r),s=[];if(d!=null&&d.length>0)for(let u of d){let l=this.buildExampleHelper({exampleId:t,example:u,schema:i.value,depth:n+1,visitedSchemaIds:a,options:o,skipReadonly:c});l!=null&&s.push(l)}else if(i.example!=null&&i.example.length>0)for(let u of i.example){let l=this.buildExampleHelper({exampleId:t,example:u,schema:i.value,depth:n+1,visitedSchemaIds:a,options:o,skipReadonly:c});l!=null&&s.push(l)}else{let u=this.buildExampleHelper({exampleId:t,example:void 0,schema:i.value,depth:n+1,visitedSchemaIds:a,options:o,skipReadonly:c});u!=null&&s.push(u)}return Pl.array(s)}case"map":{let d=JKa(r??i.example);if(d!=null&&Object.entries(d).length>0){let l=[];for(let[p,_]of Object.entries(d)){let h=this.buildExampleFromPrimitive({schema:i.key.schema,example:p,options:o}),y=this.buildExampleHelper({exampleId:t,example:_,schema:i.value,visitedSchemaIds:a,depth:n+1,options:o,skipReadonly:c});y!=null&&l.push({key:h,value:y})}return Pl.map(l)}if(i.key.schema.type==="string"&&i.value.type==="unknown")return Pl.map([{key:go.string("key"),value:Pl.unknown(Pl.primitive(go.string("value")))}]);let s=this.buildExampleFromPrimitive({schema:i.key.schema,example:void 0,options:{...o,name:"key"}}),u=this.buildExampleHelper({exampleId:t,example:void 0,schema:i.value,visitedSchemaIds:a,depth:n+1,options:{...o,name:"value"},skipReadonly:c});return u!=null&&u.type!=="null"?Pl.map([{key:s,value:u}]):Pl.map([])}case"object":{let d={},s=i.fullExamples?.find(_=>_.name===t)??i.fullExamples?.find(_=>_.name==null)??i.fullExamples?.[0],u=JKa(r)??(s!=null?JKa(s.value):{})??{},l=this.getAllProperties(i),p=this.getAllRequiredProperties(i);for(let[_,h]of Object.entries(l)){if(c&&h.readonly||h.schema._visit({optional:A=>typeof A.availability=="string"&&A.availability==="Deprecated",primitive:()=>!1,object:()=>!1,array:()=>!1,map:()=>!1,enum:()=>!1,reference:()=>!1,literal:()=>!1,oneOf:()=>!1,nullable:()=>!1,unknown:()=>!1,_other:()=>!1}))continue;let y=_ in p,b=Object.keys(u).includes(_),v=u[_],g=this.getSchemaExample(h.schema),m=b?v:g,O=this.buildExampleHelper({schema:h.schema,exampleId:t,example:m,visitedSchemaIds:a,depth:n+1,options:{...o,name:_},skipReadonly:c});if(y&&O!=null)d[_]=O;else{if(y)return;(b&&O!=null||!o.ignoreOptionals&&O!=null)&&(d[_]=O)}}if(i.additionalProperties){for(let[_,h]of Object.entries(u))if(!(_ in d)){let y=this.buildExampleHelper({schema:ai.unknown({example:h,title:void 0,availability:void 0,description:void 0,generatedName:"",nameOverride:void 0,namespace:void 0,groupName:void 0}),exampleId:t,example:h,visitedSchemaIds:a,depth:n+1,options:{...o,name:_},skipReadonly:c});y!=null&&(d[_]=y)}}return Pl.object({properties:d})}default:vt(i)}}mergeExampleWith(t,r){t._visit({array:It,enum:It,literal:It,map:i=>{for(let n of i){let a=n.key;a.type==="string"&&(r[a.value]=n.value)}},object:i=>{for(let[n,a]of Object.entries(i.properties))r[n]=a},oneOf:i=>{if(i.type==="discriminated")for(let[n,a]of Object.entries(i.value))r[n]=a;else this.mergeExampleWith(i.value,r)},primitive:It,unknown:It,null:It,_other:It})}getObjectSchema(t){if(t.type==="object")return t;if(t.type==="reference"){let r=this.schemas[t.schema];if(r!=null)return this.getObjectSchema(r)}}getDiscriminatedUnionVariantSchema(t,r){let i=r?.[t.discriminantProperty];if(i==null||typeof i!="string")return Object.entries(t.schemas)[0];let n=t.schemas[i];return n==null?Object.entries(t.schemas)[0]:[i,n]}getUnDiscriminatedUnionVariantSchema(t,r){if(r==null){let a=t.schemas.find(c=>this.hasExample(c,0,new Set,{ignoreOptionals:!1,isParameter:!1}));if(a!=null)return a;let o=t.schemas.find(c=>this.hasInherentExample(c));return o??t.schemas[0]}return t.schemas.map(a=>({schema:a,heuristic:this.calcExampleHeuristic(a,r)})).sort((a,o)=>o.heuristic-a.heuristic)[0]?.schema}calcExampleHeuristic(t,r){switch(t.type){case"literal":return t.value.value===r?5:0;case"enum":return WOh({schema:t,value:r})?5:0;case"object":{if(!yl(r))return 0;let i=this.getAllProperties(t),n=0;for(let[a,o]of Object.entries(i))r[a]!=null?(n++,n+=this.calcExampleHeuristic(o.schema,r[a])):n--;return n}case"array":{if(!Array.isArray(r))return 0;let i=0;for(let n of r)i+=this.calcExampleHeuristic(t.value,n);return i}case"map":{if(!yl(r))return 0;let i=0;for(let[,n]of Object.entries(r))i+=this.calcExampleHeuristic(t.value,n);return i}case"nullable":case"optional":return this.calcExampleHeuristic(t.value,r);case"reference":{let i=this.getResolvedSchema(t);return i==null?0:this.calcExampleHeuristic(i,r)}case"oneOf":return Object.values(t.value.schemas).map(n=>this.calcExampleHeuristic(n,r)).sort((n,a)=>a-n)[0]??0;case"primitive":return r==null?0:t.schema._visit({int:()=>typeof r=="number",int64:()=>typeof r=="number",uint:()=>typeof r=="number",uint64:()=>typeof r=="number",float:()=>typeof r=="number",double:()=>typeof r=="number",string:()=>typeof r=="string",datetime:()=>typeof r=="string",date:()=>typeof r=="string",base64:()=>typeof r=="string",boolean:()=>typeof r=="boolean",_other:()=>!0})?1:-1;default:return 0}}hasExample(t,r,i=new Set,n){if(this.exceedsMaxCheckerDepth(r,n))return!1;switch(t.type){case"array":return this.hasExample(t.value,r+1,i,n);case"enum":return t.example!=null;case"literal":return!1;case"map":return t.example!=null||t.key.schema.example!=null&&this.hasExample(t.value,r+1,i,n);case"object":{if(t.fullExamples!=null&&t.fullExamples.length>0)return!0;for(let o of t.properties)if(this.hasExample(o.schema,r+1,i,n))return!0;return!1}case"primitive":return t.schema.example!=null;case"reference":{let a=this.schemas[t.schema];if(a!=null&&!i.has(t.schema)){i.add(t.schema);let o=this.hasExample(a,r,i,n);return i.delete(t.schema),o}return!1}case"unknown":return t.example!=null;case"oneOf":return Object.values(t.value.schemas).some(a=>this.hasExample(a,r,i,n));default:return!1}}hasInherentExample(t){switch(t.type){case"literal":return!0;case"enum":return t.values.length>0;case"optional":case"nullable":return this.hasInherentExample(t.value);case"reference":{let r=this.schemas[t.schema];return r!=null?this.hasInherentExample(r):!1}default:return!1}}exceedsMaxCheckerDepth(t,r){return t>(r.maxCheckerDepth??0)}exceedsMaxDepth(t,r){return t>(r.maxDepth??0)}getAllProperties(t){let r={};for(let i of t.properties)r[i.key]={schema:i.schema,readonly:i.readonly??!1};for(let i of t.allOf){let n=this.schemas[i.schema];if(n==null)continue;let a=this.getResolvedSchema(n);a.type==="object"&&(r={...this.getAllProperties(a),...r})}return r}getAllRequiredProperties(t){let r={};for(let i of t.properties){let n=this.getResolvedSchema(i.schema);n.type!=="optional"&&n.type!=="nullable"&&(r[i.key]=i.schema)}for(let i of t.allOf){let n=this.schemas[i.schema];if(n==null)continue;let a=this.getResolvedSchema(n);a.type==="object"&&(r={...this.getAllRequiredProperties(a),...r})}return r}getResolvedSchema(t){for(;t.type==="reference";){let r=this.schemas[t.schema];if(r==null)throw new Error(`Unexpected error: Failed to resolve schema reference: ${t.schema}`);t=r}return t}getSchemaExample(t){return t._visit({primitive:r=>r.schema.example,object:r=>r.fullExamples?.[0]?.value,array:r=>r.example,map:r=>r.example,optional:r=>this.getSchemaExample(r.value),enum:r=>r.example,reference:r=>{let i=this.schemas[r.schema];return i!=null?this.getSchemaExample(i):void 0},literal:()=>{},oneOf:()=>{},nullable:r=>this.getSchemaExample(r.value),unknown:r=>r.example,_other:()=>{}})}buildExampleFromPrimitive({example:t,schema:r,options:i}){switch(r.type){case"string":return t!=null&&typeof t=="string"?go.string(t):r.example!=null?go.string(r.example):go.string(i.name??xn.STRING);case"base64":return t!=null&&typeof t=="string"?go.base64(t):r.example!=null?go.base64(r.example):go.base64(xn.BASE64);case"boolean":return t!=null&&typeof t=="boolean"?go.boolean(t):r.example!=null?go.boolean(r.example):go.boolean(xn.BOOLEAN);case"date":return t!=null&&typeof t=="string"?go.date(t):r.example!=null?go.date(r.example):go.date(xn.DATE);case"datetime":return t!=null&&typeof t=="string"?go.datetime(t):r.example!=null?go.datetime(r.example):go.datetime(xn.DATE_TIME);case"double":return t!=null&&typeof t=="number"?go.double(t):r.example!=null?go.double(r.example):go.double(xn.DOUBLE);case"float":return t!=null&&typeof t=="number"?go.float(t):r.example!=null?go.float(r.example):go.float(xn.FLOAT);case"int":return t!=null&&typeof t=="number"?go.int(t):r.example!=null?go.int(r.example):go.int(xn.INT);case"int64":return t!=null&&typeof t=="number"?go.int64(t):r.example!=null?go.int64(r.example):go.int64(xn.INT64);case"uint":return t!=null&&typeof t=="number"?go.uint(t):r.example!=null?go.uint(r.example):go.uint(xn.UINT);case"uint64":return t!=null&&typeof t=="number"?go.uint64(t):r.example!=null?go.uint64(r.example):go.uint64(xn.UINT64);default:vt(r)}}};function WOh({schema:e,value:t}){return e.values.map(r=>r.value).includes(t)}function j8t(e){switch(e.type){case"object":return ai.object({allOf:e.allOf,properties:e.properties.map(t=>rxD(t)),allOfPropertyConflicts:e.allOfPropertyConflicts,description:e.description,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,namespace:e.namespace,groupName:e.groupName,fullExamples:void 0,additionalProperties:e.additionalProperties,availability:e.availability,source:e.source,inline:void 0,minProperties:e.minProperties,maxProperties:e.maxProperties});case"array":return ai.array({description:e.description,availability:e.availability,value:j8t(e.value),generatedName:e.generatedName,title:e.title,namespace:e.namespace,nameOverride:e.nameOverride,groupName:e.groupName,example:void 0,inline:void 0,minItems:e.minItems,maxItems:e.maxItems});case"enum":return ai.enum({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,values:e.values,default:e.default,namespace:e.namespace,groupName:e.groupName,example:void 0,source:e.source,inline:void 0});case"literal":return ai.literal({description:e.description,availability:e.availability,value:e.value,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,namespace:e.namespace,groupName:e.groupName});case"nullable":return ai.nullable({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:j8t(e.value),namespace:e.namespace,groupName:e.groupName,inline:void 0});case"optional":return ai.optional({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:j8t(e.value),namespace:e.namespace,groupName:e.groupName,inline:void 0});case"primitive":return ai.primitive({description:e.description,availability:e.availability,schema:GOh(e.schema),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName});case"map":return ai.map({description:e.description,availability:e.availability,key:ai.primitive({description:e.key.description,availability:e.key.availability,schema:GOh(e.key.schema),generatedName:e.key.generatedName,nameOverride:e.key.nameOverride,title:e.key.title,namespace:e.namespace,groupName:e.groupName}),value:j8t(e.value),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,example:void 0,inline:void 0,minProperties:e.minProperties,maxProperties:e.maxProperties});case"reference":return ai.reference({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schema:e.schema,namespace:e.namespace,groupName:e.groupName,source:e.source});case"oneOf":return ai.oneOf(txD(e.value));case"unknown":return ai.unknown({nameOverride:e.nameOverride,generatedName:e.generatedName,title:void 0,example:void 0,namespace:void 0,groupName:void 0,description:void 0,availability:void 0});default:vt(e)}}function txD(e){switch(e.type){case"discriminated":return sge.discriminated({commonProperties:e.commonProperties.map(t=>({key:t.key,schema:j8t(t.schema)})),description:e.description,availability:e.availability,discriminantProperty:e.discriminantProperty,discriminantPropertyNameOverride:e.discriminantPropertyNameOverride,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schemas:Object.fromEntries(Object.entries(e.schemas).map(([t,r])=>[t,j8t(r)])),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:void 0});case"undiscriminated":return sge.undiscriminated({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schemas:e.schemas.map(t=>j8t(t)),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:void 0});default:vt(e)}}function GOh(e){switch(e.type){case"string":return kn.string({default:e.default,pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:void 0});case"base64":return kn.base64({example:void 0});case"boolean":return kn.boolean({default:e.default,example:void 0});case"date":return kn.date({example:void 0});case"datetime":return kn.datetime({example:void 0});case"double":return kn.double({default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:e.exclusiveMinimum,exclusiveMaximum:e.exclusiveMaximum,multipleOf:e.multipleOf,example:void 0});case"float":return kn.float({example:void 0});case"int":return kn.int({default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:e.exclusiveMinimum,exclusiveMaximum:e.exclusiveMaximum,multipleOf:e.multipleOf,example:void 0});case"int64":return kn.int64({default:e.default,example:void 0});case"uint":return kn.uint({default:void 0,example:void 0});case"uint64":return kn.uint64({default:void 0,example:void 0});default:vt(e)}}function rxD(e){return{conflict:e.conflict,generatedName:e.generatedName,key:e.key,schema:j8t(e.schema),audiences:e.audiences,nameOverride:e.nameOverride,availability:e.availability,readonly:e.readonly,writeonly:e.writeonly}}function sbu(e){return e.type!=="optional"&&e.type!=="nullable"}function x7c(e){return e==="POST"||e==="PUT"||e==="PATCH"}function $Ka(e){if(e.type==="full")return e.request==null&&e.response==null&&e.queryParameters==null&&e.pathParameters==null&&e.headers==null;{let t=e.value;return t.request==null&&t.response==null&&t["query-parameters"]==null&&t["path-parameters"]==null&&t.headers==null}}var cbu=class{schemas;context;globalHeaders;exampleTypeFactory;logger;missingExamples=[];constructor(t,r,i){this.schemas=t,this.context=r,this.globalHeaders=i,this.schemas=t,this.exampleTypeFactory=new e$i(t,r.nonRequestReferencedSchemas,r),this.logger=r.logger}addMissingExampleRecord(t,r,i,n,a={}){this.missingExamples.push({endpoint:t.path,method:t.method.toUpperCase(),type:r,schemaType:i,reason:n,operationSummary:t.summary,operationDescription:t.description,schemaDescription:a.schemaDescription,autoGeneratedExample:a.autoGeneratedExample})}writeMissingExamplesLog(){if(this.missingExamples.length===0)return;let t;if(this.context.source.type==="openapi"){let a=this.context.source.file,o=Rvn.dirname(a),c=o;for(;c!==Rvn.dirname(c);){let d=Rvn.join(c,"fern");if(zua.existsSync(d)&&zua.statSync(d).isDirectory()){t=d;break}c=Rvn.dirname(c)}t||(t=o)}else t=process.cwd();let r=t??process.cwd(),i=Rvn.join(r,"schemas_missing_examples.txt"),n=["# Schemas Missing Examples Report",`# Generated on: ${new Date().toISOString()}`,`# Total missing examples: ${this.missingExamples.length}`,"",...this.missingExamples.flatMap(a=>{let o=[];if(o.push(`${a.method} ${a.endpoint} - ${a.type.toUpperCase()} (${a.schemaType}): ${a.reason}`),a.operationSummary&&o.push(` Operation: ${a.operationSummary}`),a.operationDescription&&a.operationDescription!==a.operationSummary&&o.push(` Description: ${a.operationDescription}`),a.schemaDescription&&o.push(` ${a.type==="request"?"Request":"Response"} Schema: ${a.schemaDescription}`),a.autoGeneratedExample){o.push(" Auto-generated example:");let d=JSON.stringify(a.autoGeneratedExample,null,4).split(`
1522
1522
  `).map(s=>` ${s}`).join(`
1523
1523
  `);o.push(d)}return o.push(""),o}),""].join(`
1524
- `);try{zua.writeFileSync(i,n,"utf8"),this.logger.info(`Missing examples report written to: ${i}`)}catch(a){this.logger.warn(`Failed to write missing examples report to ${i}:`,String(a))}}finalize(){}convertExampleToJson(t){switch(t.type){case"primitive":return t.value;case"array":return t.value.map(r=>this.convertExampleToJson(r));case"object":{let r={};return Object.entries(t.properties).forEach(([i,n])=>{r[i]=this.convertExampleToJson(n)}),r}case"map":{let r={};return t.value.forEach(i=>{r[String(i.key)]=this.convertExampleToJson(i.value)}),r}case"oneOf":if(t.value.type==="undiscriminated")return this.convertExampleToJson(t.value.value);{let r={};return Object.entries(t.value.value).forEach(([i,n])=>{r[i]=this.convertExampleToJson(n)}),r}case"enum":return t.value;case"literal":return t.value;case"null":return null;case"unknown":return this.convertExampleToJson(t.value);default:return t}}getSchemaDescription(t){if("description"in t)return t.description}getSchemaTypeName(t){switch(t.type){case"primitive":return`primitive (${t.schema.type})`;case"object":return t.generatedName||"object";case"array":return"array";case"map":return"map";case"optional":return`optional (${this.getSchemaTypeName(t.value)})`;case"nullable":return`nullable (${this.getSchemaTypeName(t.value)})`;case"reference":return t.generatedName||"reference";case"enum":return t.generatedName||"enum";case"literal":return"literal";case"oneOf":return"oneOf";case"unknown":return"unknown";default:return"unknown"}}buildEndpointExample(t){let r=nxD(t.request),i=axD(t.response);if(r?.type==="unsupported"||i?.type==="unsupported")return[];let n=[];if(r!=null&&r.type==="present"){let l=this.isSchemaRequired(r.schema);if(r.examples.length===0){let p=this.exampleTypeFactory.buildExample({skipReadonly:x7c(t.method),schema:r.schema,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});p!=null?(n.push([void 0,p]),this.addMissingExampleRecord(t,"request",this.getSchemaTypeName(r.schema),"No user-provided examples found in OpenAPI spec",{schemaDescription:this.getSchemaDescription(r.schema),autoGeneratedExample:this.convertExampleToJson(p)})):this.addMissingExampleRecord(t,"request",this.getSchemaTypeName(r.schema),"Auto-generation failed (schema too complex or circular references)",{schemaDescription:this.getSchemaDescription(r.schema)})}else for(let{name:p,value:_}of r.examples){let h=this.exampleTypeFactory.buildExample({skipReadonly:x7c(t.method),schema:r.schema,exampleId:p,example:_,options:{isParameter:!1,ignoreOptionals:!0}});h!=null?n.push([p,h]):this.addMissingExampleRecord(t,"request",this.getSchemaTypeName(r.schema),`Failed to build example from provided data (example id: ${p})`,{schemaDescription:this.getSchemaDescription(r.schema)})}if(l&&n.length===0)return this.logger.trace(`Failed to generate required request example for ${t.method.toUpperCase()} ${t.path}`),[]}let a=[];if(i!=null&&i.type==="present"){let l=this.isSchemaRequired(i.schema);if(i.examples.length===0){let p=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:i.schema,exampleId:void 0,example:void 0,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});p!=null?(t.response?.type==="json"?a.push([void 0,ZEe.withoutStreaming(p)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&a.push([void 0,ZEe.withStreaming({sse:t.response?.type==="streamingSse",events:[p]})]),this.addMissingExampleRecord(t,"response",this.getSchemaTypeName(i.schema),"No user-provided examples found in OpenAPI spec",{schemaDescription:this.getSchemaDescription(i.schema),autoGeneratedExample:this.convertExampleToJson(p)})):this.addMissingExampleRecord(t,"response",this.getSchemaTypeName(i.schema),"Auto-generation failed (schema too complex or circular references)",{schemaDescription:this.getSchemaDescription(i.schema)})}else for(let{name:p,value:_}of i.examples){let h=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:i.schema,exampleId:p,example:_,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});h!=null?t.response?.type==="json"?a.push([p,ZEe.withoutStreaming(h)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&a.push([void 0,ZEe.withStreaming({sse:t.response?.type==="streamingSse",events:[h]})]):this.addMissingExampleRecord(t,"response",this.getSchemaTypeName(i.schema),`Failed to build example from provided data (example id: ${p})`,{schemaDescription:this.getSchemaDescription(i.schema)})}if(l&&a.length===0)return this.logger.trace(`Failed to generate required response example for ${t.method.toUpperCase()} ${t.path}`),[]}let o=[];for(let l of t.pathParameters){let p=this.isSchemaRequired(l.schema),_=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(_!=null&&!w8t(_)&&(this.logger.debug(`Expected a primitive example but got ${_.type} for path parameter ${l.name} for ${t.method.toUpperCase()} ${t.path}`),_=void 0),p&&_==null)return[];_!=null&&o.push({name:l.name,parameterNameOverride:l.parameterNameOverride,value:_})}let c=[];for(let l of t.queryParameters){let p=this.isSchemaRequired(l.schema),_=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(_!=null&&!w8t(_)&&(this.logger.debug(`Expected a primitive example but got ${_.type} for query parameter ${l.name} for ${t.method.toUpperCase()} ${t.path}`),_=void 0),p&&_==null)return[];_!=null&&c.push({name:l.name,value:_})}let d=[];for(let l of t.headers){let p=this.isSchemaRequired(l.schema),_=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(_!=null&&!w8t(_)&&(this.logger.debug(`Expected a primitive example but got ${_.type} for header ${l.name} for ${t.method.toUpperCase()} ${t.path}`),_=void 0),p&&_==null)return[];_!=null&&d.push({name:l.name,value:_})}for(let l of this.globalHeaders){let p=l.schema!=null?j8t(l.schema):ai.primitive({nameOverride:void 0,generatedName:"",title:void 0,description:void 0,availability:void 0,namespace:void 0,groupName:void 0,schema:kn.string({default:void 0,pattern:void 0,maxLength:void 0,minLength:void 0,example:void 0,format:void 0})}),_=this.exampleTypeFactory.buildExample({schema:p,exampleId:void 0,example:void 0,options:{name:l.header,isParameter:!0,ignoreOptionals:!0}});if(_!=null&&!w8t(_)&&(this.logger.debug(`Expected a primitive example but got ${_.type} for global header ${l.header} for ${t.method.toUpperCase()} ${t.path}`),_=void 0),_==null)return[];_!=null&&d.push({name:l.header,value:_})}let s=[];t.request!=null&&t.response!=null?s=ixD(n,a):t.request!=null?s=n.map(([l,p])=>({id:l,request:p,response:void 0})):t.response!=null&&(s=a.map(([l,p])=>({id:l,request:void 0,response:p})));let u=t.examples.filter(l=>$Ka(l)).flatMap(l=>{if(l.type==="unknown"){if(l.value!=null){let p=l.value["code-samples"];if(p!=null)return this.convertCodeSamples(p)}return}else return l.codeSamples}).filter(l=>us(l));return s.length===0?[XEe.full({name:void 0,description:void 0,pathParameters:o,queryParameters:c,headers:d,request:void 0,response:void 0,codeSamples:u})]:s.map(({id:l,request:p,response:_})=>XEe.full({name:l,description:void 0,pathParameters:o,queryParameters:c,headers:d,request:p,response:_,codeSamples:u}))}convertCodeSamples(t){return t.map(r=>"language"in r?UYt.language({name:r.name??void 0,description:r.docs??void 0,language:r.language,code:r.code,install:r.install??void 0}):UYt.sdk({name:r.name??void 0,description:r.docs??void 0,sdk:r.sdk==="c#"?jF.Csharp:r.sdk,code:r.code})).filter(us)}isSchemaRequired(t){return sbu(this.getResolvedSchema(t))}getResolvedSchema(t){return t}};function ixD(e,t){let r=[];if(e.length<=1){let[n,a]=e[0]??[];if(t.length===0)return r.push({id:n,request:a,response:void 0}),r;for(let[o,c]of t)r.push({id:o??n,request:a,response:c});return r}if(t.length<=1){let[n,a]=t[0]??[];if(t.length===0)return r.push({id:n,request:void 0,response:a}),r;for(let[o,c]of e)r.push({id:o??n,request:c,response:a});return r}let i=new Set;for(let[n,a]of e){let o=t.find(([d])=>d==null)?.[1]??t[0]?.[1];if(n==null){if(o==null)continue;r.push({id:void 0,request:a,response:o});continue}let c=!1;for(let d=0;d<t.length;d++){let[s,u]=t[d];s==null||i.has(d)||n===s&&(r.push({id:n,request:a,response:u}),s!=null&&i.add(d),c=!0)}!c&&o!=null&&r.push({id:n,request:a,response:o})}for(let n=0;n<t.length;n++){if(i.has(n))continue;let[a,o]=t[n],c=e.find(([d])=>d==null)?.[1]??e[0]?.[1];c!=null&&r.push({id:a,request:c,response:o})}return r}function nxD(e){if(e!=null)return e.type==="multipart"?{type:"present",schema:oxD(e),examples:[]}:e.type==="json"||e.type==="formUrlEncoded"?{type:"present",schema:e.schema,examples:e.fullExamples??[]}:{type:"unsupported"}}function axD(e){if(e!=null)return e.type!=="json"&&e.type!=="streamingJson"&&e.type!=="streamingSse"?{type:"unsupported"}:{type:"present",schema:e.schema,examples:e.fullExamples??[]}}function w8t(e){switch(e.type){case"primitive":case"enum":case"literal":return!0;case"unknown":return w8t(e);case"array":case"object":case"map":return!1;case"oneOf":switch(e.value.type){case"discriminated":return!1;case"undiscriminated":return w8t(e.value.value);default:return!1}case"null":return!0;default:vt(e)}}function oxD(e){return ai.object({properties:e.properties.map(t=>t.schema.type==="file"?null:{key:t.key,schema:j8t(t.schema.value),audiences:[],conflict:{},generatedName:t.key,nameOverride:void 0,availability:void 0,readonly:void 0,writeonly:void 0,inline:void 0}).filter(us),allOf:[],allOfPropertyConflicts:[],fullExamples:void 0,description:e.description,nameOverride:void 0,generatedName:"",title:void 0,namespace:void 0,groupName:void 0,additionalProperties:!1,availability:void 0,source:e.source,inline:void 0,minProperties:void 0,maxProperties:void 0})}var Nua=class{exampleTypeFactory;schemas;constructor(t,r){this.exampleTypeFactory=new e$i(t,new Set,r),this.schemas=t}buildWebsocketSessionExamplesForExtension({context:t,extensionExamples:r,handshake:i,source:n,namespace:a}){let o=[];for(let c of r){let d=[];for(let l of i.queryParameters){let p=this.isSchemaRequired(l.schema),_=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:c.queryParameters?.[l.name],options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});_!=null&&!w8t(_)&&(_=void 0),!(p&&_==null)&&_!=null&&d.push({name:l.name,value:_})}let s=[];for(let l of i.headers){let p=this.isSchemaRequired(l.schema),_=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:c.headers?.[l.name],options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});_!=null&&!w8t(_)&&(_=void 0),!(p&&_==null)&&_!=null&&s.push({name:l.name,value:_})}let u=[];for(let l of c.messages){let p=t.getExampleMessageReference(l),_=t.resolveMessageReference({$ref:p}),h=Bn(_.payload)?t.resolveSchemaReference(_.payload):_.payload,y=this.exampleTypeFactory.buildExample({schema:kl(h,!1,!1,t,[l.messageId],n,a),exampleId:void 0,example:l.value,options:{isParameter:!1,ignoreOptionals:!0}});y!=null&&u.push({messageType:l.type,payload:y,description:void 0})}o.push({name:c.summary,queryParameters:d,headers:s,description:c.description,messages:u})}return o}buildWebsocketSessionExample({handshake:t,messages:r}){let i={name:void 0,queryParameters:[],headers:[],description:void 0,messages:[]},n=[];for(let o of t.queryParameters){let c=this.isSchemaRequired(o.schema),d=this.exampleTypeFactory.buildExample({schema:o.schema,exampleId:void 0,example:void 0,options:{name:o.name,isParameter:!0,ignoreOptionals:!0}});if(d!=null&&!w8t(d)&&(d=void 0),c&&d==null)return;d!=null&&n.push({name:o.name,value:d})}let a=[];for(let o of t.headers){let c=this.isSchemaRequired(o.schema),d=this.exampleTypeFactory.buildExample({schema:o.schema,exampleId:void 0,example:void 0,options:{name:o.name,isParameter:!0,ignoreOptionals:!0}});if(d!=null&&!w8t(d)&&(d=void 0),c&&d==null)return;d!=null&&a.push({name:o.name,value:d})}for(let o of r){let c=this.exampleTypeFactory.buildExample({schema:o.payload,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});c!=null&&i.messages.push({messageType:o.type,payload:c,description:void 0})}return i}isSchemaRequired(t){return sbu(this.getResolvedSchema(t))}getResolvedSchema(t){for(;t.type==="reference";){let r=this.schemas[t.schema];if(r==null)throw new Error(`Unexpected error: Failed to resolve schema reference: ${t.schema}`);t=r}return t}};var OL={FERN_PARAMETER_OPTIONAL:"x-fern-optional",FERN_CHANNEL_ADDRESS:"x-fern-address",FERN_DISPLAY_NAME:"x-fern-display-name",FERN_SDK_GROUP_NAME:"x-fern-sdk-group-name",FERN_SDK_METHOD_NAME:"x-fern-sdk-method-name",FERN_EXAMPLES:"x-fern-examples",BASE_PATH:"x-fern-base-path",FERN_ENUM:"x-fern-enum",IGNORE:"x-fern-ignore",FERN_PARAMETER_NAME:"x-fern-parameter-name"};function lbu(e){return Ei(e,OL.FERN_EXAMPLES)??[]}function fbu(e,t){return t.includes("://")?t:`${e}://${t}`}function dbu(e){return e.startsWith("/")?e:"/"+e}function KOh({context:e,breadcrumbs:t,source:r,asyncApiOptions:i,document:n}){let a={},o={};for(let[s,u]of Object.entries(n.components?.schemas??{})){let l=kl(u,!1,!1,e,[s],r,e.namespace);a[s]=l}let c=new Nua(a,e),d={};for(let[s,u]of Object.entries(n.servers??{}))d[s]={name:s,url:fbu(u.protocol,u.url)};for(let[s,u]of Object.entries(n.channels??{})){let l=Ei(u,OL.IGNORE);if(l!=null&&l){e.logger.debug(`Channel ${s} is marked with x-fern-ignore. Skipping.`);continue}let p=[];if(u.parameters!=null)for(let[v,g]of Object.entries(u.parameters??{})){let m=Ei(g,OL.FERN_PARAMETER_NAME);p.push({name:v,description:g.description,parameterNameOverride:m,schema:g.schema!=null?kl(g.schema,!1,!1,e,t,r,e.namespace):ai.primitive({schema:kn.string({default:void 0,pattern:void 0,format:void 0,maxLength:void 0,minLength:void 0,example:void 0}),description:void 0,availability:void 0,generatedName:"",title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0}),variableReference:void 0,availability:BW(g),source:r,explode:void 0})}let _=[],h=[];if(u.bindings?.ws!=null){if(u.bindings.ws.headers!=null){let v=u.bindings.ws.headers.required??[];for(let[g,m]of Object.entries(u.bindings.ws.headers.properties??{})){if(Bn(m)){let M=e.resolveSchemaReference(m);_.push({name:g,schema:AUi(m,!1,!1,e,t,void 0,r,e.namespace),description:M.description,parameterNameOverride:void 0,env:void 0,availability:BW(M),source:r});continue}let O=v.includes(g),[A,j]=e.options.coerceOptionalSchemasToNullable?[!1,!O]:[!O,!1];_.push({name:g,schema:kl(m,A,j,e,[...t,g],r,e.namespace),description:m.description,parameterNameOverride:void 0,env:void 0,availability:BW(m),source:r})}}if(u.bindings.ws.query!=null){let v=u.bindings.ws.query.required??[];for(let[g,m]of Object.entries(u.bindings.ws.query.properties??{})){if(Bn(m)){let M=e.resolveSchemaReference(m);h.push({name:g,schema:AUi(m,!1,!1,e,t,void 0,r,e.namespace),description:M.description,parameterNameOverride:void 0,availability:BW(M),source:r,explode:void 0});continue}let O=v.includes(g),[A,j]=e.options.coerceOptionalSchemasToNullable?[!1,!O]:[!O,!1];h.push({name:g,schema:kl(m,A,j,e,[...t,g],r,e.namespace),description:m.description,parameterNameOverride:void 0,availability:BW(m),source:r,explode:void 0})}}}let y;u.publish!=null&&("oneOf"in u.publish.message?y=xOh({generatedName:u.publish.operationId??"PublishEvent",event:u.publish,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:i}):y=HOh({action:"Publish",channelPath:s,message:u.publish.message,context:e,source:r}));let b;if(u.subscribe!=null&&("oneOf"in u.subscribe.message?b=xOh({generatedName:u.subscribe.operationId??"SubscribeEvent",event:u.subscribe,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:i}):b=HOh({action:"Subscribe",channelPath:s,message:u.subscribe.message,context:e,source:r})),_.length>0||h.length>0||y!=null||b!=null){let v=lbu(u),g=[];if(v.length>0)g=c.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:v,handshake:{headers:_,queryParameters:h},source:r,namespace:e.namespace});else{let j=[];y!=null&&j.push({type:"publish",payload:y}),b!=null&&j.push({type:"subscribe",payload:b});let M=c.buildWebsocketSessionExample({handshake:{headers:_,queryParameters:h},messages:j});M!=null&&g.push(M)}let m=Ei(u,OL.FERN_CHANNEL_ADDRESS),O=m??dbu(s),A=[];y!=null&&A.push({origin:"client",name:"publish",body:Um(y),methodName:void 0}),b!=null&&A.push({origin:"server",name:"subscribe",body:Um(b),methodName:void 0}),o[s]={audiences:Ei(u,xi.AUDIENCES)??[],handshake:{headers:_.map(j=>({...j,schema:Um(j.schema),env:j.env})),queryParameters:h.map(j=>({...j,schema:Um(j.schema)})),pathParameters:p.map(j=>({...j,schema:Um(j.schema)}))},groupName:e.resolveGroupName([Ei(u,OL.FERN_SDK_GROUP_NAME)??s]),messages:A,servers:(u.servers?.map(j=>d[j])??Object.values(d)).filter(j=>j!=null&&j.name!=null).map(j=>({...j,name:j.name})),summary:Ei(u,OL.FERN_DISPLAY_NAME),path:O,description:u.description,examples:g,source:r}}}return{groupedSchemas:Rua(e.namespace,a),channels:o??void 0,servers:Object.values(d).map(s=>({...s,name:s.name})),basePath:Ei(n,OL.BASE_PATH)}}function xOh({generatedName:e,event:t,context:r,breadcrumbs:i,source:n,options:a,asyncApiOptions:o}){if("oneOf"in t.message&&t.message.oneOf!=null){let c=[],d=[];for(let s of t.message.oneOf){let u,l={type:"notFound"};if(Bn(s)){let p=r.resolveMessageReference(s);!Bn(p.payload)&&o.naming==="v2"?(l=p.name?{type:"name",name:p.name}:l,u={...p.payload,title:p.name??p.payload.title,description:p.name??p.payload.description}):u=p.payload}else u=s;d.push(l),c.push(u)}return ZJi({description:t.description??t.message.description,availability:BW(t.message),subtypes:c,nameOverride:t.operationId,generatedName:e,title:t.message.title,groupName:void 0,wrapAsOptional:!1,wrapAsNullable:!1,breadcrumbs:i,context:r,encoding:void 0,source:n,namespace:r.namespace,subtypeSuffixOverrides:o.naming==="v2"?d:[]})}}function HOh({action:e,channelPath:t,message:r,context:i,source:n}){if(r.payload!=null){let a=r.payload;return Bn(r.payload)&&(a=i.resolveSchemaReference(r.payload)),kl(a,!1,!1,i,[t,e],n,i.namespace)}}var pbu=class extends Tua{getExampleMessageReference(t){return`#/channels/${t.channelId}/messages/${t.messageId}`}resolveParameterReference(t){let r="#/components/parameters/";if(this.document.components==null||this.document.components.parameters==null||!t.$ref.startsWith(r))throw new Error(`Failed to resolve ${t.$ref}`);let i=t.$ref.substring(r.length),n=this.document.components.parameters[i];if(n==null)throw new Error(`${t.$ref} is undefined`);return"$ref"in n?this.resolveParameterReference(n):n}resolveMessageReference(t,r=!1){let i="#/channels/",n="#/components/messages/";if(t.$ref.startsWith(i)){let d=t.$ref.split("/"),s=d[2],u=d[4];if(s==null||u==null||!this.document.channels?.[s])throw new Error(`Failed to resolve message reference ${t.$ref} in channel ${s}`);let p=this.document.channels[s].messages?.[u];if(p==null)throw new Error(`${t.$ref} is undefined`);return"$ref"in p&&!r?this.resolveMessageReference(p):{...p,name:u}}let a=this.document.components;if(!t.$ref.startsWith(n)||!a?.messages)throw new Error(`Failed to resolve message reference: ${t.$ref} in v3 components`);let o=t.$ref.substring(n.length),c=a.messages[o];if(c==null)throw new Error(`${t.$ref} is undefined`);return{...c,name:o}}isMessageWithPayload(t){return t!=null&&typeof t=="object"&&"payload"in t}isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}};var JOh="#/channels/",$Oh="#/servers/",H7c="$message.";function XOh({context:e,breadcrumbs:t,source:r,asyncApiOptions:i,document:n}){let a={},o={},c={},d=[],s={};e.logger.debug("Parsing V3 AsyncAPI...");for(let[v,g]of Object.entries(n.components?.schemas??{}))a[v]=kl(g,!1,!1,e,[v],r,e.namespace);for(let[v,g]of Object.entries(n.channels??{}))if(o[v]||(o[v]={}),g.messages)for(let[m,O]of Object.entries(g.messages))if(c[m]||(c[m]=[]),e.isReferenceObject(O)){let A=e.resolveMessageReference(O);c[m].push({channelId:v,payload:A.payload})}else e.isMessageWithPayload(O)&&c[m].push({channelId:v,payload:O.payload});for(let[v,g]of Object.entries(c))if(g.length===1){let m=g[0],O=m.channelId;o[O]=o[O]||{},o[O][v]=kl(m.payload,!1,!1,e,[v],r,e.namespace)}else{d.push(v);for(let{channelId:m,payload:O}of g){let A=`${m}_${v}`;o[m]||(o[m]={}),o[m][A]=kl(O,!1,!1,e,[A],r,e.namespace)}}let u=Object.values(o).reduce((v,g)=>({...v,...g}),{}),l=new Nua(u,e),p={};for(let[v,g]of Object.entries(n.servers??{}))p[v]={name:v,url:fbu(g.protocol,g.host)};let _={};for(let[v,g]of Object.entries(n.operations??{})){if(Ei(g,OL.IGNORE))continue;let m=uxD(g);_[m]||(_[m]={subscribe:[],publish:[],__parsedMessages:[]});let O=Ei(g,OL.FERN_SDK_METHOD_NAME),A=g.messages.map(j=>({ref:j,methodName:O}));if(g.action==="receive")_[m].subscribe.push(...A);else if(g.action==="send")_[m].publish.push(...A);else throw new Error(`Operation ${v} has an invalid action: ${g.action}`)}for(let[v,g]of Object.entries(_)){let m=[];m.push(...YOh({messages:g.subscribe,channelPath:v,origin:"server",messageSchemas:o[v]??{},duplicatedMessageIds:d,context:e})),m.push(...YOh({messages:g.publish,channelPath:v,origin:"client",messageSchemas:o[v]??{},duplicatedMessageIds:d,context:e})),_[v]!=null&&(_[v].__parsedMessages=m)}for(let[v,g]of Object.entries(n.channels??{})){if(Ei(g,OL.IGNORE))continue;let m=[],O=[],A=[];if(g.parameters!=null)for(let[j,M]of Object.entries(g.parameters)){let w=e.isReferenceObject(M)?e.resolveParameterReference(M):M,{type:D,parameterKey:B}=w.location!=null?sxD(w.location):{type:g.address?.includes(`={${j}}`)?"query":"path",parameterKey:j},T=Ei(w,OL.FERN_PARAMETER_OPTIONAL),R=Z0(ou(v))+Z0(ou(j)),q={...w,type:"string",title:R,example:w.examples?.[0],default:w.default,enum:w.enum,required:void 0},z=kl(q,!1,!1,e,[B],r,e.namespace);T&&(z=ai.optional({value:z,description:void 0,availability:void 0,generatedName:"",title:R,namespace:void 0,groupName:void 0,nameOverride:void 0,inline:void 0}));let N={name:B,description:w.description,parameterNameOverride:void 0,schema:z,variableReference:void 0,availability:BW(M),source:r,explode:void 0};D==="header"?m.push({...N,env:void 0}):D==="path"?O.push(N):(D==="payload"||D==="query")&&A.push(N)}if(m.length>0||A.length>0||_[v]!=null&&(_[v].publish!=null||_[v].subscribe!=null)){let j=lbu(g),M=_[v]?.__parsedMessages??[],w=[];if(j.length>0)w=l.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:j,handshake:{headers:m,queryParameters:A},source:r,namespace:e.namespace});else{let R=[],{examplePublishMessage:q,exampleSubscribeMessage:z}=lxD({messages:M,messageSchemas:o[v]??{}});q!=null&&R.push(q),z!=null&&R.push(z);let N=l.buildWebsocketSessionExample({handshake:{headers:m,queryParameters:A},messages:R});N!=null&&w.push(N)}let D=Ei(g,OL.FERN_SDK_GROUP_NAME),B=(g.servers?.map(R=>cxD(p,R))??Object.values(p)).map(R=>({...R,name:R.name})),T=g.address?.split("?")[0]??dbu(v);s[v]={audiences:Ei(g,xi.AUDIENCES)??[],handshake:{headers:m.map(R=>({...R,schema:Um(R.schema),env:R.env})),queryParameters:A.map(R=>({...R,schema:Um(R.schema)})),pathParameters:O.map(R=>({...R,parameterNameOverride:void 0,schema:Um(R.schema)}))},groupName:e.resolveGroupName(typeof D=="string"?[D]:D??[v]),messages:M,summary:Ei(g,OL.FERN_DISPLAY_NAME),servers:B,path:T,description:g.description,examples:w,source:r}}else e.logger.warn(`Skipping AsyncAPI channel ${v} as it does not qualify for inclusion (no headers, query params, or operations)`)}let h=Rua(e.namespace,a),y=Object.values(p).map(v=>({...v,name:v.name})),b=Ei(n,OL.BASE_PATH);return{groupedSchemas:h,channels:s,servers:y,basePath:b}}function uxD(e){if(!e.channel.$ref.startsWith(JOh))throw new Error(`Failed to resolve channel path from operation ${e.channel.$ref}`);return e.channel.$ref.substring(JOh.length)}function sxD(e){try{let[t,r]=e.split("#/");if(t==null||r==null)throw new Error(`Invalid location format: ${e}; unable to parse message type and parameter key`);if(!t.startsWith(H7c))throw new Error(`Invalid location format: ${e}; expected ${H7c} prefix`);let i=t.substring(H7c.length);if(i!=="header"&&i!=="path"&&i!=="payload")throw new Error(`Invalid message type: ${i}. Must be one of: header, path, payload`);return{type:i,parameterKey:r}}catch{throw new Error(`Invalid location format: ${e}; see here for more details: https://www.asyncapi.com/docs/reference/specification/v3.0.0#runtimeExpression`)}}function cxD(e,t){if(!t.$ref.startsWith($Oh))throw new Error(`Failed to resolve server name from server ref ${t.$ref}`);let r=t.$ref.substring($Oh.length),i=e[r];if(i==null)throw new Error(`Failed to find server with name ${r}`);return i}function YOh({messages:e,channelPath:t,origin:r,messageSchemas:i,duplicatedMessageIds:n,context:a}){let o=[];return e.forEach((c,d)=>{let u=a.resolveMessageReference(c.ref,!0).name;n.includes(u)&&(u=`${t}_${u}`);let l=i[u];l!=null&&o.push({origin:r,name:u??`${r}Message${d+1}`,body:Um(l),methodName:c.methodName})}),o}function lxD({messages:e,messageSchemas:t}){let r=e.find(o=>o.origin==="client")?.name,i=e.find(o=>o.origin==="server")?.name,n=r!=null?t[r]:void 0,a=i!=null?t[i]:void 0;return{examplePublishMessage:n!=null&&r!=null?{type:r,payload:n}:void 0,exampleSubscribeMessage:a!=null&&i!=null?{type:i,payload:a}:void 0}}function ZOh({document:e,taskContext:t,options:r,source:i,asyncApiOptions:n,namespace:a}){let o=[];if(a!=null&&o.push(a),parseFloat(e.asyncapi)<3){let c=e;c.tags?.[0]!=null?o.push(c.tags[0].name):n.naming!=="v2"&&o.push("websocket");let d=new ubu({document:c,taskContext:t,options:r,namespace:a});return KOh({context:d,breadcrumbs:o,source:i,asyncApiOptions:n,document:c})}else{let c=e,d=new pbu({document:c,taskContext:t,options:r,namespace:a});return XOh({context:d,breadcrumbs:o,source:i,asyncApiOptions:n,document:c})}}function kOh(e){return Ei(e,xi.ASYNC_CONFIG)}var emh="$request.";function tmh(e){let t=Ei(e,xi.STREAMING);if(t!=null)return typeof t=="boolean"?t?{type:"stream",format:"json"}:void 0:t["stream-condition"]==null&&t.format!=null?{type:"stream",format:t.format}:{type:"streamCondition",format:t.format??"json",streamDescription:t["stream-description"],streamConditionProperty:fxD(t["stream-condition"]),responseStream:t["response-stream"],response:t.response}}function fxD(e){return e.startsWith(emh)?e.slice(emh.length):e}function rmh(e){let t=e;if(t.cursor!=null)return uge.cursor({cursor:t.cursor,nextCursor:t.next_cursor,results:t.results});if("offset"in e){let r=e;return uge.offset({offset:r.offset,results:r.results,step:r.step,hasNextPage:r["has-next-page"]})}if("type"in e&&e.type==="custom"){let r=e;return uge.custom({results:r.results})}throw new Error("Invalid pagination extension")}function imh(e,t){let r=Ei(t,xi.PAGINATION);if(r!=null){if(typeof r=="boolean"){let i=Ei(e,xi.PAGINATION);if(typeof i=="boolean")throw new Error("Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.");return i==null?void 0:rmh(i)}return rmh(r)}}function nmh(e){let t=dxD(e),r={};return K7c({obj:t,occurrences:r,breadcrumbs:[]}),r}function K7c({obj:e,occurrences:t,breadcrumbs:r}){if(e!=null){if(Array.isArray(e)){for(let i of e)K7c({obj:i,occurrences:t,breadcrumbs:r});return}if(typeof e=="object"){if(e.$ref!=null&&typeof e.$ref=="string"){let i=e.$ref;t[i]==null?t[i]=1:t[i]+=1;return}for(let i in e)K7c({obj:e[i],occurrences:t,breadcrumbs:[...r,i]})}}}function dxD(e){return{...e,paths:Object.fromEntries(Object.entries(e.paths??{}).map(([t,r])=>[t,{...r,get:r?.get!=null?YKa(r.get):void 0,put:r?.put!=null?YKa(r.put):void 0,post:r?.post!=null?YKa(r.post):void 0,patch:r?.patch!=null?YKa(r.patch):void 0,delete:r?.delete!=null?YKa(r.delete):void 0}]))}}function YKa(e){return{...e,requestBody:e.requestBody!=null?Bn(e.requestBody)?e.requestBody:pxD(e.requestBody):void 0}}function pxD(e){let t,r;for(let i in e.content){let n=tm.parse(i);n!=null&&(n.isJSON()?t=e.content[i]:n.isMultipart()&&(r=e.content[i]))}return r!=null&&t!=null?{...e,content:{[tm.MULTIPART_FORM_DATA]:r}}:e}var _bu=class{endpoints;parser=new zbn;constructor({context:t,options:r}){this.endpoints=r.filter?.endpoints?new Set(this.validateAndFilterEndpoints({context:t,endpoints:r.filter.endpoints})):void 0}skipEndpoint({method:t,path:r}){return this.endpoints!=null&&!this.endpoints.has(`${t} ${r}`)}hasEndpoints(){return this.endpoints!=null}validateAndFilterEndpoints({context:t,endpoints:r}){let i=[];for(let n of r){let a=this.parser.tryParse(n);if(a==null){t.logger.debug(`Ignoring configured filter endpoint "${n}"; expected format "POST /users/get"`);continue}i.push(`${a.method} ${a.path}`)}return i}};var amh="#/components/parameters/",omh="#/components/responses/",umh="#/components/examples/",smh="#/components/requestBodies/",cmh="#/components/securitySchemes/",Fua=class{logger;document;taskContext;authHeaders;refOccurrences;DUMMY;options;source;filter;namespace;constructor({document:t,taskContext:r,authHeaders:i,options:n,source:a,namespace:o}){this.document=t,this.logger=r.logger,this.taskContext=r,this.authHeaders=i,this.refOccurrences=nmh(t),this.options=n,this.source=a,this.filter=new _bu({context:r,options:n}),this.DUMMY=this.getDummy(),this.namespace=o}getNumberOfOccurrencesForRef(t){return this.refOccurrences[t.$ref]??0}resolveTagsToTagIds(t){let r=[];return this.namespace!=null&&r.push(this.namespace),r.concat(t??[])}resolveTags(t){let r=[];if(this.namespace!=null){let i={type:"namespace",name:this.namespace};r.push(i)}return r.concat(t??[])}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveSchemaReference(t){let r=t.$ref.substring(2).split("/").map(n=>n.replace(/~1/g,"/")),i=this.document;for(let n of r){if(typeof i!="object"||i==null)return{"x-fern-type":"unknown"};if(Array.isArray(i)){let a=parseInt(n,10);if(isNaN(a)||a<0||a>=i.length)return{"x-fern-type":"unknown"};i=i[a]}else i=i[n]}return i==null?(this.logger.debug(`Encountered undefined reference: ${t.$ref}`),{"x-fern-type":"unknown"}):(Bn(i)&&(i=this.resolveSchemaReference(i)),i)}resolveParameterReference(t){if(this.document.components==null||this.document.components.parameters==null||!t.$ref.startsWith(amh))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(amh.length),i=this.document.components.parameters[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return Bn(i)?this.resolveParameterReference(i):i}resolveRequestBodyReference(t){if(this.document.components==null||this.document.components.requestBodies==null||!t.$ref.startsWith(smh))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(smh.length),i=this.document.components.requestBodies[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return Bn(i)?this.resolveRequestBodyReference(i):i}resolveResponseReference(t){if(this.document.components==null||this.document.components.responses==null||!t.$ref.startsWith(omh))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(omh.length),i=this.document.components.responses[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return Bn(i)?this.resolveResponseReference(i):i}resolveExampleReference(t){if(this.document.components==null||this.document.components.examples==null||!t.$ref.startsWith(umh))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(umh.length),i=this.document.components.examples[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return Bn(i)?this.resolveExampleReference(i):i}resolveSecuritySchemeReference(t){if(this.document.components==null||this.document.components.securitySchemes==null||!t.$ref.startsWith(cmh))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(cmh.length),i=this.document.components.securitySchemes[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return Bn(i)?this.resolveSecuritySchemeReference(i):i}referenceExists(t){let r=t.substring(2).split("/").map(n=>n.replace(/~1/g,"/")),i=this.document;for(let n of r){if(typeof i!="object"||i==null)return!1;i=i[n]}return!0}};var zvn=class extends Fua{constructor({document:t,taskContext:r,options:i,source:n,namespace:a}){super({document:t,taskContext:r,authHeaders:new Set,options:i,source:n,namespace:a})}getDummy(){return this}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}getReferencedSchemas(){return new Set}markReferencedByDiscriminatedUnion(t,r,i){}getReferencesFromDiscriminatedUnion(t){}excludeSchema(t){}isSchemaExcluded(t){return!1}markSchemaWithDiscriminantValue(t,r,i){}getDiscriminatedUnionMetadata(t){}};var hbu=require("fs"),ybu=require("path");var _xD=Qt.object({lang:Qt.string(),label:Qt.optional(Qt.string()),source:Qt.string()}),J7c=Qt.array(_xD);var lmh={README_EXT:"x-readme"};function hxD(e){if(!Array.isArray(e))return!1;for(let t of e)if(!yl(t)||typeof t.language!="string"||typeof t.code!="string")return!1;return!0}function fmh(e){let t=Ei(e,lmh.README_EXT);if(!yl(t))return[];let r=t["code-samples"];if(!hxD(r))return[];let i=[];for(let n of r)i.push({name:n.name,language:n.language,code:n.code,install:n.install,docs:void 0});return i}function yxD(e){return yl(e)&&typeof e.$ref=="string"}function bxD(e,t){if(e!=null){if(typeof e=="string")return e;if(yxD(e)){let r=(0,ybu.resolve)(t??process.cwd(),e.$ref);if((0,hbu.existsSync)(r))try{return(0,hbu.readFileSync)(r,"utf-8")}catch{return}}}}function vxD(e,t){if(!Array.isArray(e))return[];let r=[];for(let i of e){if(!yl(i))continue;let a=bxD(i.code,t);a!=null&&r.push({...i,code:a})}return r}function dmh(e,t,r){let i=Ei(t,xi.EXAMPLES),n=r.source.type==="openapi"?(0,ybu.dirname)(r.source.file):void 0,o=(i??[]).map(l=>{if(!yl(l))return l;let _=l["code-samples"];if(_!=null){let h=vxD(_,n);return{...l,"code-samples":h}}return l}).filter(l=>{let p=cI.serialization.ExampleEndpointCallSchema.parse(l);return p.ok||r.logger.error(`Failed to parse x-fern-example in ${e.path}/${e.method}`),p.ok}),c=GKa(t,gL.REDOCLY_CODE_SAMPLES_KEBAB,J7c,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],s=[...GKa(t,gL.REDOCLY_CODE_SAMPLES_CAMEL,J7c,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],...c];s.length>0&&o.push({"code-samples":s.map(l=>({name:l.label??l.lang,language:l.lang,code:l.source,install:void 0,docs:void 0}))});let u=fmh(t);return u.length>0&&o.push({"code-samples":u}),o.map(XEe.unknown)}function pmh(e){let t=Ei(e,xi.AVAILABILITY);if(t==="ga"||t==="generally-available")return PF.GenerallyAvailable;if(t==="beta"||t==="pre-release")return PF.Beta;if(t==="deprecated")return PF.Deprecated;if(e.deprecated)return PF.Deprecated}function _mh(e){let t=Ei(e,xi.RETRIES);if(t!=null&&t.disabled===!0)return N_u.RetriesConfiguration.disabled(t.disabled)}function bbu(e,t){return{url:gxD({url:e.url,variables:e.variables??{}}),description:e.description,name:OxD(e,t),audiences:Ei(e,xi.AUDIENCES)}}function gxD({url:e,variables:t}){let r=Object.fromEntries(Object.entries(t).map(([i,n])=>[i,n.default]));for(let[i,n]of Object.entries(r))e=e.replace(`{${i}}`,encodeURIComponent(n));return e}function OxD(e,t){let r=Ei(e,[xi.SERVER_NAME_V1,xi.SERVER_NAME_V2]);if(r!=null)return r;if(e.description?.toLowerCase()==="production")return"Production";if(e.description?.toLowerCase()==="sandbox")return"Sandbox";if(t?.groupMultiApiEnvironments&&e.description!=null&&e.description.trim()!==""){let i=e.description.toLowerCase();return i==="prd"?"Production":i==="sbx"?"Sandbox":i==="staging"||i==="stg"?"Staging":i==="development"||i==="dev"?"Development":e.description}}function hmh(e){return Ei(e,xi.PARAMETER_NAME)}function ymh(e){return Ei(e,xi.SDK_VARIABLE)}function vbu({path:e,httpMethod:t,parameters:r,context:i,requestBreadcrumbs:n,source:a}){let o={pathParameters:[],queryParameters:[],headers:[]};for(let c of r){let d=Ei(c,xi.IGNORE);if(d!=null&&d){i.logger.debug(`${t.toUpperCase()} ${e} has a parameter marked with x-fern-ignore. Skipping.`);continue}let s=Bn(c)?i.resolveParameterReference(c):c,u=s.required??!1,l=BW(s),p=[...n,s.name],_=jC(p,i.options.preserveSchemaIds),[h,y]=i.options.coerceOptionalSchemasToNullable?[!1,!u]:[!u,!1],b=s.schema!=null?kl(s.schema,h,y,i,p,a,i.namespace,!1,new Set,JYt({schema:s,logger:i.logger})):u?ai.primitive({nameOverride:void 0,generatedName:_,title:void 0,schema:kn.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:JYt({schema:s,logger:i.logger})}),description:void 0,availability:l,namespace:void 0,groupName:void 0}):ai.optional({nameOverride:void 0,generatedName:_,title:void 0,value:ai.primitive({nameOverride:void 0,generatedName:_,title:void 0,schema:kn.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:JYt({schema:s,logger:i.logger})}),description:void 0,availability:void 0,namespace:void 0,groupName:void 0}),description:void 0,availability:l,namespace:void 0,groupName:void 0,inline:void 0});if(s.in==="header"&&s.schema!=null&&!Bn(s.schema)&&s.schema.default!=null){let g=s.schema.default;typeof g=="string"&&g.length>0&&(b=ai.literal({nameOverride:void 0,generatedName:_,title:void 0,value:nE.string(g),description:void 0,availability:l,namespace:void 0,groupName:void 0}))}let v={name:s.name,schema:b,description:s.description,parameterNameOverride:hmh(s),availability:l,source:a};s.in==="query"?o.queryParameters.push({...v,explode:AxD(s)}):s.in==="path"?o.pathParameters.push({...v,variableReference:ymh(s),explode:PxD(s)}):s.in==="header"?!mxD.has(s.name.toLowerCase())&&!i.authHeaders.has(s.name)?o.headers.push({...v,env:void 0}):i.logger.debug(`Ignoring ${s.name} header, in ${t.toUpperCase()} ${e}`):i.logger.warn(`Skipping ${s.in} parameter, ${s.name}, in ${t.toUpperCase()} ${e}`)}return o}var mxD=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]);function AxD(e){let t=e.style??"form",r=e.explode;if(r!==void 0)return t==="form"?r===!0?void 0:r:r===!1?void 0:r}function PxD(e){let t=e.explode;if(t!==void 0)return t===!1?void 0:t}function bmh(e,t){for(let r of Object.keys(e))if(r.includes("text/event-stream")){let i=e[r];if(i==null)continue;let n=i.schema;return{contentType:r,schema:n??{},examples:XKa(i,t)}}}function jxD(e){return e.includes("json")||e==="*/*"}function $7c({content:e,context:t}){for(let[r,i]of Object.entries(e))if(gbu({mediaType:r,mediaTypeObject:i,context:t})!=null)return[r,i]}function gbu({mediaType:e,mediaTypeObject:t,context:r}){if(!jxD(e))return;let i=t.schema;return{contentType:e.includes("*")?void 0:e,schema:i??{},examples:XKa(t,r)}}function Obu({content:e,context:t}){let r=$7c({content:e,context:t});if(!r)return;let[i,n]=r;return gbu({mediaType:i,mediaTypeObject:n,context:t})}function vmh(e,t){for(let r of Object.keys(e)){let i=e[r];if(i==null)continue;return{schema:i.schema??{},examples:XKa(i,t)}}}function XKa(e,t){let r=[];e.example!=null&&r.push({name:void 0,value:e.example,description:void 0});let i=Ei(e,gL.EXAMPLES);return i!=null&&Object.keys(i).length>0&&r.push(...Object.entries(i).map(([n,a])=>({name:a.summary??n,value:a.value,description:a.description}))),e.examples!=null&&Object.keys(e.examples).length>0&&r.push(...Object.entries(e.examples).map(([n,a])=>{let o=Bn(a)?t.resolveExampleReference(a):a;return{name:o.summary??n,value:o.value,description:o.description}})),r}function wxD({content:e,context:t}){for(let[r,i]of Object.entries(e))if(Omh({mediaType:r,mediaTypeObject:i,context:t}))return[r,i]}function Omh({mediaType:e,mediaTypeObject:t,context:r}){if(tm.parse(e)?.isURLEncoded())return{schema:t.schema,contentType:e,examples:XKa(t,r)}}function ExD({content:e}){for(let[t,r]of Object.entries(e))if(mmh({mediaType:t,mediaTypeObject:r}))return[t,r]}function mmh({mediaType:e,mediaTypeObject:t}){if(tm.parse(e)?.isMultipart())return{schema:t.schema,encoding:t.encoding}}function Amh({mediaType:e}){return tm.parse(e)?.isBinary()??!1}function SxD({content:e}){for(let[t,r]of Object.entries(e))if(Amh({mediaType:t}))return[t,r]}function MxD(e,t){let r=Bn(e)?Y7c(e,t):{id:void 0,schema:e};return Object.entries(r.schema.properties??{}).find(([i,n])=>!Bn(n)&&n.type==="string"&&n.format==="binary")!=null}function Abu({content:e,description:t,document:r,context:i,requestBreadcrumbs:n,source:a,namespace:o}){let c=SxD({content:e});if(c){let[p,_]=c;return YYt({mediaType:p,mediaTypeObject:_,description:t,document:r,context:i,requestBreadcrumbs:n,source:a,namespace:o})}let d=ExD({content:e}),s=$7c({content:e,context:i}),u=DxD({json:s,multipart:d,document:r,visitor:{json:([p,_])=>YYt({mediaType:p,mediaTypeObject:_,description:t,document:r,context:i,requestBreadcrumbs:n,source:a,namespace:o}),multipart:([p,_])=>YYt({mediaType:p,mediaTypeObject:_,description:t,document:r,context:i,requestBreadcrumbs:n,source:a,namespace:o}),neither:()=>{}}});if(u)return u;let l=wxD({content:e,context:i});if(l){let[p,_]=l;return YYt({mediaType:p,mediaTypeObject:_,description:t,document:r,context:i,requestBreadcrumbs:n,source:a,namespace:o})}}function DxD({json:e,multipart:t,document:r,visitor:i}){if(!e&&!t)return i.neither();let[,n]=e??[void 0,void 0],[,a]=t??[void 0,void 0];return!n?.schema&&!a?.schema?i.neither():n?.schema&&a?.schema?n.schema&&MxD(n.schema,r)?i.multipart(t):i.json(e):n?.schema?i.json(e):a?.schema?i.multipart(t):i.neither()}function YYt({mediaType:e,mediaTypeObject:t,description:r,document:i,context:n,requestBreadcrumbs:a,source:o,namespace:c}){let d=BxD({mediaTypeObject:t});if(Amh({mediaType:e}))return _x.octetStream({description:r,source:o,sdkMethodName:d,contentType:e});let s=mmh({mediaType:e,mediaTypeObject:t}),u=s?.schema,l=s?.encoding;if(u){let h=Bn(u)?Y7c(u,i):{id:void 0,schema:u},y=kl(h.schema,!1,!1,n,a,o,c,!1),b=[];if(y.type==="object"){let v=new Set(h.schema.required??[]);for(let g of y.properties){let m=v.has(g.key),{isFile:O,isOptional:A,isArray:j,description:M}=mbu({schema:g.schema,isOptional:!m});if(O){let w=gmh(g.key,l);b.push({key:g.key,schema:LYt.file({isOptional:A,isArray:j,description:M}),description:M,contentType:w,exploded:!1,encoding:w==null?n.options.defaultFormParameterEncoding:void 0})}else{let w=gmh(g.key,l);b.push({key:g.key,schema:LYt.json(g.schema),description:void 0,contentType:w,exploded:l?.[g.key]?.explode,encoding:w==null?n.options.defaultFormParameterEncoding:CxD(w)})}}}return _x.multipart({name:Bn(u)&&n.getNumberOfOccurrencesForRef(u)===1?h.id:void 0,description:h.schema.description,properties:b,source:o,sdkMethodName:d})}let p=gbu({mediaType:e,mediaTypeObject:t,context:n});if(p){let h=kl(p.schema,!1,!1,n,a,o,c,!0);return _x.json({description:void 0,schema:h,contentType:p.contentType,fullExamples:p.examples,additionalProperties:!Bn(p.schema)&&HKa(p.schema.additionalProperties,n.options),source:o,sdkMethodName:d})}let _=Omh({mediaType:e,mediaTypeObject:t,context:n});if(_!=null&&_.schema!=null){let h=kl(_.schema,!1,!1,n,a,o,c,!1);return _x.formUrlEncoded({schema:h,description:r,contentType:_.contentType,source:o,fullExamples:_.examples,additionalProperties:!1,sdkMethodName:d})}}function BxD({mediaTypeObject:e}){return Ei(e,xi.SDK_METHOD_NAME)}var IxD={"application/json":"json"};function CxD(e){return e?IxD[e]:void 0}function Y7c(e,t){if(!e.$ref.startsWith(Tvn))throw new Error(`Failed to resolve schema reference because of unsupported prefix: ${e.$ref}`);let r=XJi(e);if(r==null)throw new Error(`Failed to resolve schema reference because missing schema id: ${e.$ref}`);let i=t.components?.schemas?.[r];if(i==null)throw new Error(`Failed to resolve schema reference because missing: ${e.$ref}`);return Bn(i)?Y7c(i,t):{id:r,schema:i}}function mbu({schema:e,isOptional:t,isArray:r,description:i}){return TxD(e)?mbu({schema:e.value,isOptional:!0,isArray:r,description:e.description}):RxD(e)?mbu({schema:e.value,isOptional:t,isArray:r,description:e.description}):zxD(e)?mbu({schema:e.value,isOptional:t,isArray:!0,description:e.description}):qxD(e)?{isFile:!0,isOptional:t??!1,isArray:r??!1,description:i??e.description}:{isFile:!1,isOptional:t??!1,isArray:r??!1,description:void 0}}function qxD(e){return e.type==="primitive"&&e.schema.type==="string"&&e.schema.format==="binary"}function TxD(e){return e.type==="optional"}function RxD(e){return e.type==="nullable"}function zxD(e){return e.type==="array"}function gmh(e,t){return t?.[e]?.contentType}var X7c={400:"BadRequestError",401:"UnauthorizedError",402:"PaymentRequiredError",403:"ForbiddenError",404:"NotFoundError",405:"MethodNotAllowedError",406:"NotAcceptableError",407:"ProxyAuthenticationRequiredError",408:"RequestTimeoutError",409:"ConflictError",410:"GoneError",411:"LengthRequiredError",412:"PreconditionFailedError",413:"ContentTooLargeError",414:"URITooLongError",415:"UnsupportedMediaTypeError",416:"RangeNotSatisfiableError",417:"ExpectationFailedError",418:"ImATeapotError",419:"AuthenticationTimeoutError",420:"MethodFailureError",421:"MisdirectedRequestError",422:"UnprocessableEntityError",423:"LockedError",424:"FailedDependencyError",425:"TooEarlyError",426:"UpgradeRequiredError",428:"PreconditionError",429:"TooManyRequestsError",430:"RequestHeaderFieldsTooLargeError",431:"RequestHeaderFieldsTooLargeError",444:"NoResponseError",449:"RetryWithError",450:"BlockedByWindowsParentalControlsError",451:"UnavailableForLegalReasonsError",498:"InvalidTokenError",499:"ClientClosedRequestError",500:"InternalServerError",501:"NotImplementedError",502:"BadGatewayError",503:"ServiceUnavailableError",504:"GatewayTimeoutError",505:"HTTPVersionNotSupportedError",506:"VariantAlsoNegotiatesError",507:"InsufficientStorageError",508:"LoopDetectedError",509:"BandwidthLimitExceededError",510:"NotExtendedError",511:"NetworkAuthenticationRequiredError"},Pmh=new Set(Object.values(X7c));var NxD=["200","201","202","204"];function Pbu({operationContext:e,responses:t,context:r,responseBreadcrumbs:i,responseStatusCode:n,streamFormat:a,source:o}){if(t==null)return{value:void 0,errors:{}};let c=FxD({responses:t,context:r,source:o,namespace:r.namespace}),d=!1,s;for(let u of n!=null?[n]:NxD){let l=t[u];l!=null&&(d=!0,s==null&&(s=jmh({operationContext:e,response:l,context:r,responseBreadcrumbs:i,streamFormat:a,source:o,namespace:r.namespace,statusCode:typeof u=="string"?parseInt(u):u})))}if(s==null&&!d&&t.default!=null&&(s=jmh({operationContext:e,response:t.default,context:r,responseBreadcrumbs:i,streamFormat:a,source:o,namespace:r.namespace})),s!=null)switch(s.type){case"json":return{value:s,errors:c};case"streamingJson":case"streamingSse":return{value:s,errors:c};case"bytes":case"file":case"text":case"streamingText":return{value:s,errors:c};default:vt(s)}return{value:void 0,errors:c}}function jmh({operationContext:e,streamFormat:t,response:r,context:i,responseBreadcrumbs:n,source:a,namespace:o,statusCode:c}){let d=Bn(r)?i.resolveResponseReference(r):r;if(d.content!=null&&Object.entries(d.content).find(([p,_])=>{if(_.schema==null)return!1;let h=Bn(_.schema)?i.resolveSchemaReference(_.schema):_.schema;return h.type==="string"&&h.format==="binary"}))return i.options.useBytesForBinaryResponse&&t==null?R0.bytes({description:d.description,source:a,statusCode:c}):R0.file({description:d.description,source:a,statusCode:c});let s=bmh(d.content??{},i);if(s!=null&&t!=null)switch(t){case"json":return R0.streamingJson({statusCode:c,description:d.description,responseProperty:Ei(e.operation,xi.RESPONSE_PROPERTY),fullExamples:s.examples,schema:kl(s.schema,!1,!1,i,n,a,o),source:a});case"sse":return R0.streamingSse({description:d.description,responseProperty:void 0,fullExamples:s.examples,schema:kl(s.schema,!1,!1,i,n,a,o),source:a,statusCode:c})}let u=Obu({context:i,content:d.content??{}});if(u){if(t!=null)switch(t){case"json":return R0.streamingJson({description:d.description,responseProperty:void 0,fullExamples:u.examples,schema:kl(u.schema,!1,!1,i,n,a,o),source:a,statusCode:c});case"sse":return R0.streamingSse({description:d.description,responseProperty:void 0,fullExamples:u.examples,schema:kl(u.schema,!1,!1,i,n,a,o),source:a,statusCode:c})}return R0.json({description:d.description,schema:kl(u.schema,!1,!1,i,n,a,o),responseProperty:Ei(e.operation,xi.RESPONSE_PROPERTY),fullExamples:u.examples,source:a,statusCode:c})}for(let[l,p]of Object.entries(d.content??{})){let _=tm.parse(l);if(_!=null){if(_.isOctetStream()||_.isPDF()||_.isAudio()||_.isImage()||_.isVideo()||_.isMultiPartMixed())return R0.file({description:d.description,source:a,statusCode:c});if(_.isPlainText()){let h=p.schema;if(h==null)return R0.text({description:d.description,source:a,statusCode:c});let y=Bn(h)?i.resolveSchemaReference(h):h;return y.type==="string"&&y.format==="byte"?R0.file({description:d.description,source:a,statusCode:c}):R0.text({description:d.description,source:a,statusCode:c})}}}}function FxD({responses:e,context:t,source:r,namespace:i}){let n={};for(let[a,o]of Object.entries(e)){if(a==="default")continue;let c=parseInt(a);if(c<400||c>600)continue;let d=Bn(o)?t.resolveResponseReference(o):o,s=vmh(d.content??{},t),u=X7c[c];if(u==null){t.logger.warn(`No error name found for status code ${a}`);continue}n[c]={statusCode:c,nameOverride:void 0,generatedName:u,description:d.description,schema:kl(s?.schema??{},!1,!1,t,[u,"Body"],r,i),fullExamples:s?.examples,source:r}}return n}function PUi({operationContext:e,context:t,responseStatusCode:r,suffix:i,streamFormat:n,source:a}){let{document:o,operation:c,path:d,method:s,baseBreadcrumbs:u}=e,l=Ei(c,xi.IDEMPOTENT),p=Ei(c,[xi.REQUEST_NAME_V1,xi.REQUEST_NAME_V2]),_=[...u,"Request"],h=vbu({parameters:[...e.pathItemParameters,...e.operationParameters],context:t,requestBreadcrumbs:_,path:d,httpMethod:s,source:a}),y=/{([^}]+)}/g,b=[...d.matchAll(y)].map(B=>B[1]).filter(B=>B!==void 0),v=[...d.matchAll(y)].map(B=>B[1]);switch(t.options.pathParameterOrder){case an.PathParameterOrder.SpecOrder:{let B=v.filter(T=>!h.pathParameters.some(R=>R.name===T));if(B.length>0)for(let T of B)h.pathParameters.push({name:T??"",variableReference:void 0,parameterNameOverride:void 0,availability:void 0,source:a,schema:ai.primitive({schema:kn.string({default:void 0,example:void 0,format:void 0,maxLength:void 0,minLength:void 0,pattern:void 0}),description:void 0,generatedName:"",nameOverride:void 0,namespace:void 0,groupName:void 0,availability:void 0,title:void 0}),description:void 0,explode:void 0})}break;case an.PathParameterOrder.UrlOrder:if(b.length>0){let B=new Map(h.pathParameters.map(q=>[q.name,q])),T=[],R=new Set;for(let q of b){let z=B.get(q);R.add(q),z?T.push(z):T.push({name:q,variableReference:void 0,parameterNameOverride:void 0,availability:void 0,source:a,schema:ai.primitive({schema:kn.string({default:void 0,example:void 0,format:void 0,maxLength:void 0,minLength:void 0,pattern:void 0}),description:void 0,generatedName:"",nameOverride:void 0,namespace:void 0,groupName:void 0,availability:void 0,title:void 0}),description:void 0,explode:void 0})}for(let q of h.pathParameters)R.has(q.name)||T.push(q);h.pathParameters=T}break;default:vt(t.options.pathParameterOrder)}let g=(()=>{if(e.method==="GET")return[void 0];if(!c.requestBody)return[void 0];let B=Bn(c.requestBody)?t.resolveRequestBodyReference(c.requestBody):c.requestBody,T=Object.values(B.content).every(q=>UxD({mediaTypeObject:q})!=null),R=[];if(T)return R.push(...Object.entries(B.content).map(([q,z])=>{let N=YYt({mediaType:q,mediaTypeObject:z,description:B.description,document:o,context:new zvn({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:_,source:a,namespace:t.namespace});return wmh({context:t,convertedParameters:h})&&N!=null&&(N.type==="json"||N.type==="formUrlEncoded")&&N.schema.type!=="object"&&c.requestBody!=null?N=YYt({mediaType:q,mediaTypeObject:z,description:B.description,document:o,context:t,requestBreadcrumbs:[..._,"Body"],source:a,namespace:t.namespace}):c.requestBody!=null&&(N=YYt({mediaType:q,mediaTypeObject:z,description:B.description,document:o,context:t,requestBreadcrumbs:[..._],source:a,namespace:t.namespace})),N}).filter(q=>q!=null)),R.length===0?[void 0]:R;{let q=Abu({content:B.content,description:B.description,document:o,context:new zvn({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:_,source:a,namespace:t.namespace});return wmh({context:t,convertedParameters:h})&&q!=null&&(q.type==="json"||q.type==="formUrlEncoded")&&q.schema.type!=="object"&&c.requestBody!=null?q=Abu({content:B.content,description:B.description,document:o,context:t,requestBreadcrumbs:[..._,"Body"],source:a,namespace:t.namespace}):c.requestBody!=null&&(q=Abu({content:B.content,description:B.description,document:o,context:t,requestBreadcrumbs:[..._],source:a,namespace:t.namespace})),[q]}})(),m=g.length>1,O=[...u,"Response"],A=Pbu({operationContext:e,streamFormat:n,responses:c.responses,context:t,responseBreadcrumbs:O,responseStatusCode:r,source:a}),j=_mh(c),M=pmh(c),w=dmh(e,c,t),D=Ei(c,xi.SERVER_NAME_V2);return g.map(B=>({summary:c.summary,internal:Ei(c,gL.INTERNAL),idempotent:l,audiences:Ei(c,xi.AUDIENCES)??[],operationId:c.operationId!=null&&i!=null?c.operationId+"_"+i:c.operationId,tags:t.resolveTagsToTagIds(c.tags),namespace:t.namespace,sdkName:LxD({operationContext:e,request:B}),pathParameters:h.pathParameters,queryParameters:h.queryParameters,headers:h.headers,requestNameOverride:p??void 0,generatedRequestName:jC(m?QxD({breadcrumbs:_,request:B}):_,t.options.preserveSchemaIds),request:B,response:A.value,errors:A.errors,servers:D!=null?[{name:D,url:void 0,audiences:void 0}]:(c.servers??[]).map(T=>bbu(T,{groupMultiApiEnvironments:t.options.groupMultiApiEnvironments})),description:c.description,authed:WxD(c,o),security:VxD(c),availability:M,method:s,path:d,examples:w,pagination:e.pagination,source:a,retries:j}))}function QxD({breadcrumbs:e,request:t}){return t?[...e,t.type]:e}function UxD({mediaTypeObject:e}){return Ei(e,xi.SDK_METHOD_NAME)}function LxD({operationContext:e,request:t}){return!t||!t.sdkMethodName?e.sdkMethodName:e.sdkMethodName?{groupName:[...e.sdkMethodName.groupName],methodName:t.sdkMethodName??e.sdkMethodName.methodName}:{groupName:[],methodName:t.sdkMethodName}}function VxD(e){return e.security}function WxD(e,t){return e.security!=null?Object.keys(e.security).length>0:t.security!=null?Object.keys(t.security).length>0:!1}function wmh({context:e,convertedParameters:t}){return e.options.inlinePathParameters&&t.pathParameters.length>0||t.queryParameters.length>0||t.headers.length>0}function Smh({operationContext:e,context:t,asyncExtension:r,source:i}){let{operation:n,pathItemParameters:a,operationParameters:o}=e,c=r.discriminant.name,d=r.discriminant.value,s=r["response-status-code"],u=Emh({context:t,headerToIgnore:c,parameters:a}),l=Emh({context:t,headerToIgnore:c,parameters:o}),p=PUi({operationContext:{...e,pathItemParameters:u,operationParameters:l,operation:{...n,responses:Object.fromEntries(Object.entries(n.responses).filter(([h])=>parseInt(h)!==s))}},context:t,streamFormat:void 0,source:i}),_=PUi({operationContext:{...e,pathItemParameters:u,operationParameters:l,baseBreadcrumbs:[...e.baseBreadcrumbs,"async"]},context:t,suffix:"async",responseStatusCode:s,streamFormat:void 0,source:i});return _.forEach(h=>{h.headers.push({name:c,schema:ai.literal({nameOverride:void 0,generatedName:jC([c],t.options.preserveSchemaIds),title:void 0,description:void 0,availability:void 0,value:nE.string(d),namespace:void 0,groupName:void 0}),description:void 0,parameterNameOverride:void 0,env:void 0,availability:void 0,source:i})}),{sync:p,async:_}}function Emh({context:e,headerToIgnore:t,parameters:r}){return r.filter(i=>{let n=Bn(i)?e.resolveParameterReference(i):i;return!(n.in==="header"&&n.name===t)})}var Z7c="stream";function Imh({operationContext:e,context:t,streamingExtension:r}){switch(r.type){case"stream":return{streaming:PUi({operationContext:e,context:t,streamFormat:r.format,source:t.source}),nonStreaming:[]};case"streamCondition":{let i=Mmh({context:t,operation:e.operation,streamingExtension:r,isStreaming:!0});if(i?.schemaReference!=null){let s=XJi(i.schemaReference);s!=null&&t.excludeSchema(s)}let n=Dmh({operation:e.operation,response:r.responseStream}),a=PUi({operationContext:{...e,sdkMethodName:e.sdkMethodName!=null?{groupName:e.sdkMethodName.groupName,methodName:e.sdkMethodName.methodName+"_"+Z7c}:void 0,operation:{...e.operation,description:r.streamDescription??e.operation.description,requestBody:i?.requestBody,responses:n},baseBreadcrumbs:[...e.baseBreadcrumbs,Z7c]},context:t,streamFormat:r.format,suffix:Z7c,source:t.source});a.forEach(s=>{s.examples=s.examples.filter(u=>Bmh(u,t)!==!1)});let o=Mmh({context:t,operation:e.operation,streamingExtension:r,isStreaming:!1}),c=Dmh({operation:e.operation,response:r.response}),d=PUi({streamFormat:void 0,operationContext:{...e,operation:{...e.operation,requestBody:o?.requestBody,responses:c}},context:t,source:t.source});return d.forEach(s=>{s.examples=s.examples.filter(u=>Bmh(u,t)!==!0)}),{streaming:a,nonStreaming:d}}default:vt(r)}}function Mmh({context:e,operation:t,streamingExtension:r,isStreaming:i}){if(t.requestBody==null)return;let n=Bn(t.requestBody)?e.resolveRequestBodyReference(t.requestBody):t.requestBody,a=Obu({content:n.content,context:e});if(a==null)return;let o=Bn(a.schema)?e.resolveSchemaReference(a.schema):a.schema;if(o.allOf==null&&o.properties==null)return;let c=o.properties?.[r.streamConditionProperty];c!=null&&Bn(c)&&(c=void 0);let d={...o,properties:{...o.properties,[r.streamConditionProperty]:{type:"boolean","x-fern-boolean-literal":i,...c??{}}},title:void 0,required:[...o.required??[],r.streamConditionProperty]};return{requestBody:{content:{[tm.APPLICATION_JSON]:{schema:d}}},schemaReference:Bn(a.schema)?a.schema:void 0}}function Dmh({operation:e,response:t}){return{...e.responses,200:{description:"",content:{[tm.APPLICATION_JSON]:{schema:t}}}}}function Bmh(e,t){return e._visit({unknown:r=>{let i=cI.serialization.ExampleEndpointCallSchema.parse(r);if(i.ok&&i.value.response!=null)return i.value.response.stream!=null},full:()=>{},_other:()=>{}})}var Cmh=require("crypto");function qmh({context:e,operationContext:t,source:r}){let{document:i,operation:n,path:a,method:o,baseBreadcrumbs:c,sdkMethodName:d}=t,s=[...c,"Payload"],u=[...c,"Response"],l=vbu({parameters:[...t.pathItemParameters,...t.operationParameters],context:e,requestBreadcrumbs:s,path:a,httpMethod:o,source:r});if(n.requestBody==null)return e.logger.error(`Skipping webhook ${o.toUpperCase()} ${a}: Missing a request body`),[];let p=n.operationId??xxD({path:a,method:o,sdkMethodName:d}),_=n.responses?Pbu({operationContext:t,streamFormat:void 0,responses:n.responses,context:e,responseBreadcrumbs:u,source:r}):void 0;if(o!=="POST"&&o!=="GET")return e.logger.error(`Skipping webhook ${o.toUpperCase()} ${a}: Not POST or GET`),[];let h=Bn(n.requestBody)?e.resolveRequestBodyReference(n.requestBody):n.requestBody;return Object.entries(h.content).map(([y,b])=>YYt({mediaType:y,mediaTypeObject:b,description:h.description,document:i,context:e,requestBreadcrumbs:[...c,"Payload"],source:r,namespace:e.namespace})).filter(y=>y!=null).map(y=>{if(y==null||y.type!=="json"&&y.type!=="formUrlEncoded"&&y.type!=="multipart"){e.logger.error(`Skipping webhook ${a} because non-json, non-formUrlEncoded, and non-multipart request body`);return}let b,v;return y.type==="multipart"?(b={name:y.name,properties:y.properties,description:y.description,source:y.source},v=ai.unknown({nameOverride:void 0,generatedName:jC(s,e.options.preserveSchemaIds),title:void 0,description:y.description,availability:void 0,namespace:e.namespace,groupName:void 0,example:void 0})):v=y.schema,{summary:n.summary,audiences:Ei(n,xi.AUDIENCES)??[],sdkName:d,namespace:e.namespace,method:o,operationId:p,tags:e.resolveTagsToTagIds(n.tags),headers:l.headers,generatedPayloadName:jC(s,e.options.preserveSchemaIds),payload:v,multipartFormData:b,response:_?.value,description:n.description,examples:GxD(y.type==="multipart"?void 0:y.fullExamples),source:r}}).filter(y=>y!=null)}function GxD(e){if(e==null)return[];let t=[];for(let r of e){let i=kJi(r.value);i!=null&&t.push({description:r.description,name:r.name,payload:i})}return t}function xxD({path:e,method:t,sdkMethodName:r}){let i=r?.methodName??HxD(e),n=(0,Cmh.createHash)("sha256").update(e).digest("hex").slice(0,8);return KxD(`${i}_${t.toLowerCase()}_${n}`)}function HxD(e){return e.replace(/[{$}#]/g,"").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").replace(/_+/g,"_").toLowerCase().slice(0,64)}function KxD(e){return e.split("_").map((t,r)=>r===0?t.toLowerCase():t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}function k7c({context:e,pathItemContext:t,operation:r,convertToWebhook:i}){let n=Ei(r,xi.IGNORE);if(n!=null&&n){e.logger.debug(`${t.method.toUpperCase()} ${t.path} is marked with x-fern-ignore. Skipping.`);return}let a=JxD(r,e),o=imh(e.document,r),c={...t,sdkMethodName:a,baseBreadcrumbs:$xD({operation:r,sdkMethodName:a,httpMethod:t.method,path:t.path,shouldUseIdiomaticRequestNames:e.options.shouldUseIdiomaticRequestNames}),operation:r,operationParameters:r.parameters??[],pagination:o};if(i)return{type:"webhook",value:qmh({context:e,operationContext:c,source:e.source})};let d=tmh(r);if(d!=null){let l=Imh({context:e,operationContext:c,streamingExtension:d});return l!=null?{type:"streaming",streaming:l.streaming,nonStreaming:l.nonStreaming}:void 0}let s=kOh(r);if(s!=null){let l=Smh({context:e,operationContext:c,asyncExtension:s,source:e.source});return{type:"async",async:l.async,sync:l.sync}}return{type:"http",value:PUi({context:e,operationContext:c,streamFormat:void 0,source:e.source})}}function JxD(e,t){let r=Ei(e,xi.SDK_METHOD_NAME),i=Ei(e,xi.SDK_GROUP_NAME)??[];if(r!=null){let n=typeof i=="string"?[i]:i;return n=t.resolveGroupName(n),{groupName:n,methodName:r}}}function $xD({sdkMethodName:e,operation:t,httpMethod:r,path:i,shouldUseIdiomaticRequestNames:n}){let a=[];if(e!=null){if(n&&a.push(e.methodName),e.groupName.length>0){let o=e.groupName[e.groupName.length-1];o!=null&&a.push(typeof o=="string"?o:o.name)}n||a.push(e.methodName)}else t.operationId!=null?a.push(t.operationId):a.push(ou(`${r}_${i.split("/").join("_")}`));return a}function Tmh(e,t,r,i){let n=[],a=zmh(t),o={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let c of a){if(i.filter.skipEndpoint({method:c.method,path:e})){i.logger.debug(`Skipping endpoint "${c.method} ${e}"`);continue}let d=YxD({operation:c.operation}),s=k7c({context:i,pathItemContext:{...o,method:c.method},operation:c.operation,convertToWebhook:d});s&&n.push(s)}return n}function Rmh(e,t,r,i){let n=[],a=zmh(t),o={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let c of a){if(i.filter.skipEndpoint({method:c.method,path:e})){i.logger.debug(`Skipping endpoint "${c.method} ${e}"`);continue}let d=k7c({context:i,pathItemContext:{...o,method:c.method},operation:c.operation,convertToWebhook:!0});d&&n.push(d)}return n}function zmh(e){let t=[];return e.get!=null&&t.push({method:wF.Get,operation:e.get}),e.post!=null&&t.push({method:wF.Post,operation:e.post}),e.put!=null&&t.push({method:wF.Put,operation:e.put}),e.delete!=null&&t.push({method:wF.Delete,operation:e.delete}),e.patch!=null&&t.push({method:wF.Patch,operation:e.patch}),e.head!=null&&t.push({method:wF.Head,operation:e.head}),t}function YxD({operation:e}){return Ei(e,[xi.WEBHOOK])??!1}function Nmh(e){let t=Ei(e,xi.BASIC_AUTH_USERNAME_VARIABLE_NAME),r=Ei(e,xi.BASIC_AUTH_PASSWORD_VARIABLE_NAME);return{usernameVariable:t,passwordVariable:r}}function Fmh(e){return Ei(e,xi.FERN_BASIC_AUTH)}function Umh(e,t,r,i){if(Bn(e)){if(i==null)throw new Error(`Converting referenced security schemes requires context: ${JSON.stringify(e)}`);let n=i.resolveSecuritySchemeReference(e);return Qmh(n,t,r)}return Qmh(e,t,r)}function Qmh(e,t,r){try{if(e.type==="apiKey"&&e.in==="header"){let i=Ei(e,gL.BEARER_FORMAT),n=Ei(e,xi.FERN_HEADER_AUTH);return AF.header({headerName:e.name,prefix:i!=null?"Bearer":n?.prefix,headerVariableName:n?.name??Ei(e,xi.HEADER_VARIABLE_NAME),headerEnvVar:n?.env})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="bearer"){let i=Ei(e,xi.FERN_BEARER_TOKEN);return AF.bearer({tokenVariableName:i?.name??Ei(e,xi.BEARER_TOKEN_VARIABLE_NAME),tokenEnvVar:i?.env})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="basic"){let i=Fmh(e),n=Nmh(e);return AF.basic({usernameVariableName:i?.username?.name??n.usernameVariable,usernameEnvVar:i?.username?.env,passwordVariableName:i?.password?.name??n.passwordVariable,passwordEnvVar:i?.password?.env})}else{if(e.type==="openIdConnect")return AF.bearer({tokenVariableName:void 0,tokenEnvVar:void 0});if(e.type==="oauth2")return AF.oauth({scopesEnum:XxD(e,t)})}}catch(i){r.logger.debug(`Error converting security scheme: ${i?.message}`)}r.logger.debug(`Skipping security scheme: ${JSON.stringify(e,null)} - not currently supported. Please reach out to Fern support team!`)}function XxD(e,t){let r=e.flows.authorizationCode?.scopes??e.flows.clientCredentials?.scopes??e.flows.implicit?.scopes??e.flows.password?.scopes;if(r!=null){let i=YJi({nameOverride:void 0,generatedName:"OauthScope",title:void 0,enumValues:Object.keys(r),fernEnum:Object.fromEntries(Object.entries(r).map(([a,o])=>[a,{description:o}])),_default:void 0,description:void 0,availability:void 0,enumVarNames:void 0,wrapAsOptional:!1,wrapAsNullable:!1,namespace:void 0,groupName:void 0,context:void 0,source:t,inline:void 0}),n=Um(i);if(n.type==="enum")return n}}function Lmh(e){return Ei(e,xi.BASE_PATH)}var ZxD=Qt.record(Qt.string(),Qt.object({summary:Qt.string().optional(),description:Qt.string().optional()}));function Vmh({document:e,context:t}){return GKa(e,xi.GROUPS,ZxD,t.logger)}function Wmh({context:e,document:t}){return Ei(t,xi.FERN_VERSION)??void 0}function Gmh(e){let t=Ei(e,xi.FERN_GLOBAL_HEADERS),r=[];for(let i of t??[])r.push({...i,schema:i.type!=null?xKa({fernType:i.type,description:void 0,availability:void 0,generatedName:i.name??i.header,title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}function xmh(e){let t=Ei(e,xi.FERN_IDEMPOTENCY_HEADERS),r=[];for(let i of t??[])r.push({...i,schema:i.type!=null?xKa({fernType:i.type,description:void 0,availability:void 0,generatedName:i.name??i.header,title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}function Hmh(e,t){let r=Ei(e,xi.SDK_VARIABLES);return r==null?{}:Object.fromEntries(Object.entries(r).map(([i,n])=>{if(n.type==="string")return[i,{nameOverride:void 0,generatedName:jC([i],t),title:n.title,schema:Uh.string({default:qua(n),pattern:n.pattern,format:n.format,minLength:n.minLength,maxLength:n.maxLength}),description:n.description,availability:void 0,namespace:void 0,groupName:void 0}];throw new Error(`Variable ${i} has unsupported schema ${JSON.stringify(n)}`)}))}var kxD="webhooks";function Kmh(e){return Ei(e,kxD)??{}}var ZKa=class extends Fua{nonRequestReferencedSchemas=new Set;twoOrMoreRequestsReferencedSchemas=new Set;singleRequestReferencedSchemas=new Set;discriminatedUnionReferences={};discriminatedUnionMetadata={};schemasToExclude=new Set;constructor({document:t,taskContext:r,authHeaders:i,options:n,source:a,namespace:o}){super({document:t,taskContext:r,authHeaders:i,options:n,source:a,namespace:o})}getDummy(){return new zvn({document:this.document,taskContext:this.taskContext,options:this.options,source:this.source,namespace:this.namespace})}markSchemaAsReferencedByNonRequest(t){this.nonRequestReferencedSchemas.add(t)}markSchemaAsReferencedByRequest(t){this.singleRequestReferencedSchemas.has(t)?this.twoOrMoreRequestsReferencedSchemas.add(t):this.singleRequestReferencedSchemas.add(t)}getReferencedSchemas(){return new Set([...this.nonRequestReferencedSchemas,...this.twoOrMoreRequestsReferencedSchemas])}markReferencedByDiscriminatedUnion(t,r,i){let n=this.discriminatedUnionReferences[t.$ref];n!=null?(n.discriminants.add(r),n.numReferences+=i):this.discriminatedUnionReferences[t.$ref]={discriminants:new Set([r]),numReferences:i}}getReferencesFromDiscriminatedUnion(t){return this.discriminatedUnionReferences[t.$ref]}markSchemaWithDiscriminantValue(t,r,i){let n=this.discriminatedUnionMetadata[t.$ref];n!=null?n.discriminants.set(r,i):this.discriminatedUnionMetadata[t.$ref]={discriminants:new Map([[r,i]])}}getDiscriminatedUnionMetadata(t){return this.discriminatedUnionMetadata[t.$ref]}excludeSchema(t){this.schemasToExclude.add(t)}isSchemaExcluded(t){return this.schemasToExclude.has(t)}};function Jmh(e){return Ei(e,xi.RESOLUTIONS)}function $mh({openapi:e}){let t=Jmh(e);if(t==null)return e;let r={};for(let i of t){let n=`#/components/schemas/${i.name}`;for(let a of i.resolutions)e=eHD({openapi:e,schemaReference:a,schemaName:i.name}),e=Ymh({openapi:e,replaceReference:a,schemaReference:n,replacedReferences:r}),r={...r,...Object.fromEntries(i.resolutions.map(o=>[n,o]))}}return e}function eHD({openapi:e,schemaReference:t,schemaName:r}){let i=t.replace("#/","").split("/").map(a=>a.replaceAll("~1","/")),n=e;for(let a of i){let o=n[a];if(o==null)return e;n=o}return e.components==null&&(e.components={}),e.components.schemas==null&&(e.components.schemas={}),e.components.schemas[r]=n,e}function Ymh({openapi:e,replaceReference:t,schemaReference:r,replacedReferences:i}){let n=Object.keys(i).filter(d=>t.startsWith(d)).sort((d,s)=>s.length-d.length)[0];if(n!=null){let d=i[n];if(d!=null){let s=r.replace(n,d);return Ymh({openapi:e,replaceReference:t,schemaReference:s,replacedReferences:{}})}}let a=t.replace("#/","").split("/").map(d=>d.replaceAll("~1","/")),o=e;for(let d of a.slice(0,-1)){let s=o[d];if(s==null)return e;o=s}let c=a[a.length-1];return c==null||(o[c]={$ref:r}),e}function Zmh({openApi:e,taskContext:t,options:r,source:i,namespace:n}){e=$mh({openapi:e});let a=new ZKa({document:e,taskContext:t,authHeaders:new Set,options:r,source:i,namespace:n}),o=Object.fromEntries(Object.entries(e.components?.securitySchemes??{}).map(([B,T])=>{let R=Umh(T,i,t,a);return R==null?null:[B,R]}).filter(B=>B!==null)),c=e.security?.filter(B=>B!=null),d=new Set(...Object.entries(o).map(([B,T])=>T.type==="basic"||T.type==="bearer"?"Authorization":T.type==="header"?T.headerName:null)),s=Hmh(e,r.preserveSchemaIds),u=Gmh(e),l=xmh(e),p=r.audiences??[],_=[],h=[],y=new ZKa({document:e,taskContext:t,authHeaders:d,options:r,source:i,namespace:n});y.filter.hasEndpoints()&&t.logger.debug("Endpoint filter applied..."),Object.entries(e.paths??{}).forEach(([B,T])=>{if(T==null)return;let R=Tmh(B,T,e,y);for(let q of R){let z=Xmh({operation:q});if(!(p.length>0&&!p.some(N=>z.includes(N))))switch(q.type){case"async":_.push(...q.sync),_.push(...q.async);break;case"http":_.push(...q.value);break;case"streaming":_.push(...q.streaming),q.nonStreaming&&_.push(...q.nonStreaming);break;case"webhook":h.push(...q.value);break;default:vt(q)}}}),Object.entries(Kmh(e)).forEach(([B,T])=>{if(T==null)return;t.logger.debug(`Converting path ${B}`);let R=Rmh(B,T,e,y);for(let q of R){let z=Xmh({operation:q});p.length>0&&!p.some(N=>z.includes(N))||h.push(...q.value)}});let b=Object.fromEntries(Object.entries(e.components?.schemas??{}).map(([B,T])=>{let R=Ei(T,xi.SDK_NAMESPACE);if(!Bn(T)){let q=Ei(T,xi.IGNORE);if(q!=null&&q)return[];if(Pmh.has(B))return[B,kl({...T,"x-fern-type-name":`${B}Body`},!1,!1,y,[B],i,R??n)]}return[B,kl(T,!1,!1,y,[B],i,R??n)]}).filter(B=>B.length>0)),v=tHD(b,y,i),g=rHD(v,y),m={};for(let[B,T]of Object.entries(g)){let R=Um(T);y.isSchemaExcluded(B)||(m[B]=R)}let O=new e$i(g,y.nonRequestReferencedSchemas,y),A=h.map(B=>{let R=B.examples;if(!r.disableExamples&&R.length===0){let q=O.buildExample({schema:B.payload,exampleId:void 0,example:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});q!=null&&(R=[{name:void 0,description:void 0,payload:q}])}return{...B,payload:Um(B.payload),examples:R}}),j=new cbu(g,y,u),M=_.map(B=>{let T=B.examples,R=T;if(!r.disableExamples&&(T.length===0||T.every($Ka))){let N=j.buildEndpointExample(B);N.length>0&&(R=[...N,...T.filter(H=>!$Ka(H))])}let q=B.request,z=B.response;return{...B,request:q?.type==="json"||q?.type==="formUrlEncoded"?{...q,schema:Um(q.schema)}:q,response:z?.type==="json"?{...z,schema:Um(z.schema)}:z,queryParameters:B.queryParameters.map(N=>({description:N.description,name:N.name,schema:Um(N.schema),parameterNameOverride:N.parameterNameOverride,availability:N.availability,source:N.source})),pathParameters:B.pathParameters.map(N=>({description:N.description,name:N.name,schema:Um(N.schema),parameterNameOverride:N.parameterNameOverride,variableReference:N.variableReference,availability:N.availability,source:N.source})),headers:B.headers.map(N=>({description:N.description,name:N.name,schema:Um(N.schema),parameterNameOverride:N.parameterNameOverride,env:N.env,availability:N.availability,source:N.source})),examples:R,errors:nn(B.errors,N=>{let H=N.fullExamples?.map($=>{let de=kJi($.value);if(de!=null)return{name:$.name,description:$.description,example:de}}).filter(us);if(H?.length===0){let $=O.buildExample({schema:N.schema,example:void 0,exampleId:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});$!=null&&H.push({name:void 0,description:void 0,example:$})}return{generatedName:N.generatedName,nameOverride:N.nameOverride,schema:Um(N.schema),description:N.description,source:N.source,examples:H}}),retries:B.retries}});j.finalize();let w=Vmh({document:e,context:y});return{apiVersion:Wmh({context:y,document:e}),basePath:Lmh(e),title:e.info.title??"",description:e.info.description,groups:Object.fromEntries(Object.entries(w??{}).map(([B,T])=>[B,{summary:T.summary??void 0,description:T.description??void 0}])),servers:(e.servers??[]).map(B=>bbu(B,{groupMultiApiEnvironments:r.groupMultiApiEnvironments})),websocketServers:[],tags:{tagsById:Object.fromEntries((e.tags??[]).map(B=>[B.name,{id:B.name,description:B.description}])),orderedTagIds:e.tags?.map(B=>B.name)},endpoints:M,webhooks:A,channels:{},groupedSchemas:Rua(n,m),securitySchemes:o,security:c,hasEndpointsMarkedInternal:M.some(B=>B.internal),nonRequestReferencedSchemas:y.getReferencedSchemas(),variables:s,globalHeaders:u,idempotencyHeaders:l}}function tHD(e,t,r){if(t.options.removeDiscriminantsFromSchemas===an.RemoveDiscriminantsFromSchemas.Never)return e;let i={};for(let[n,a]of Object.entries(e)){if(a.type!=="object"){i[n]=a;continue}let o={$ref:`#/components/schemas/${n}`},c=t.getReferencesFromDiscriminatedUnion(o);if(c==null){i[n]=a;continue}if(t.getReferencedSchemas().has(n)){i[n]=a;continue}let s={...a,type:"object",properties:a.properties.filter(l=>!c.discriminants.has(l.key)),allOfPropertyConflicts:a.allOfPropertyConflicts.filter(l=>!c.discriminants.has(l.propertyKey)),source:r};i[n]=s;let u=kmh({schema:a,schemas:e});for(let l of[...new Set(u)]){let p=i[l]??e[l];p==null||p.type!=="object"||(i[l]={...p,type:"object",properties:p.properties.filter(_=>!c.discriminants.has(_.key)),allOfPropertyConflicts:p.allOfPropertyConflicts.filter(_=>!c.discriminants.has(_.propertyKey))})}}return i}function rHD(e,t){let r={};for(let[i,n]of Object.entries(e)){if(n.type!=="object"){r[i]=n;continue}let a={$ref:`#/components/schemas/${i}`},o=t.getDiscriminatedUnionMetadata(a);if(o==null){r[i]=n;continue}let c=[];for(let s of n.properties)if(o.discriminants.has(s.key)){let u=o.discriminants.get(s.key);u!=null&&c.push({...s,schema:ai.literal({nameOverride:void 0,generatedName:jC([n.generatedName,u],t.options.preserveSchemaIds),title:void 0,value:nE.string(u),namespace:void 0,groupName:void 0,description:void 0,availability:n.availability})})}else c.push(s);let d={...n,type:"object",properties:c};r[i]=d}return r}function kmh({schema:e,schemas:t}){let r=[];for(let i of e.allOf){r.push(i.schema);let n=t[i.schema];n!=null&&n.type==="object"&&r.push(...kmh({schema:n,schemas:t}))}return r}function jbu(e){return[...new Set(e)]}function Xmh({operation:e}){let t=[];switch(e.type){case"async":t=jbu(e.async.flatMap(r=>r.audiences));break;case"http":t=jbu(e.value.flatMap(r=>r.audiences));break;case"streaming":t=jbu(e.streaming.flatMap(r=>r.audiences));break;case"webhook":t=jbu(e.value.flatMap(r=>r.audiences));break;default:vt(e)}return t}function Nvn({context:e,documents:t,options:r}){let i={apiVersion:void 0,title:void 0,description:void 0,basePath:void 0,servers:[],websocketServers:[],tags:{tagsById:{},orderedTagIds:void 0},hasEndpointsMarkedInternal:!1,endpoints:[],webhooks:[],channels:{},groupedSchemas:{rootSchemas:{},namespacedSchemas:{}},variables:{},nonRequestReferencedSchemas:new Set,securitySchemes:{},security:void 0,globalHeaders:[],idempotencyHeaders:[],groups:{}},n=0;for(let a of t)try{let o=a.source!=null?a.source:SW.openapi({file:"<memory>"});switch(a.type){case"openapi":{let c=Zmh({taskContext:e,openApi:a.value,options:rSe({options:a.settings,overrides:r}),source:o,namespace:a.namespace});i=oHD(i,c,rSe({options:a.settings,overrides:r})),n++;break}case"asyncapi":{let c=ZOh({document:a.value,taskContext:e,options:rSe({options:a.settings,overrides:r}),source:o,asyncApiOptions:iHD({options:a.settings}),namespace:a.namespace});c.servers!=null&&(i.websocketServers=[...i.websocketServers,...c.servers.map(d=>({...d,audiences:void 0,description:void 0}))]),c.channels!=null&&(i.channels={...i.channels,...c.channels}),c.groupedSchemas!=null&&(i.groupedSchemas=wbu(i.groupedSchemas,c.groupedSchemas)),c.basePath!=null&&(i.basePath=c.basePath),n++;break}default:vt(a)}}catch(o){e.logger.debug(`Skipping parsing document ${a.type==="openapi"?a.value.info?.title:a.source?.file}`),o instanceof Error&&e.logger.debug(o.message,o.stack?`
1524
+ `);try{zua.writeFileSync(i,n,"utf8"),this.logger.info(`Missing examples report written to: ${i}`)}catch(a){this.logger.warn(`Failed to write missing examples report to ${i}:`,String(a))}}finalize(){}convertExampleToJson(t){switch(t.type){case"primitive":return t.value;case"array":return t.value.map(r=>this.convertExampleToJson(r));case"object":{let r={};return Object.entries(t.properties).forEach(([i,n])=>{r[i]=this.convertExampleToJson(n)}),r}case"map":{let r={};return t.value.forEach(i=>{r[String(i.key)]=this.convertExampleToJson(i.value)}),r}case"oneOf":if(t.value.type==="undiscriminated")return this.convertExampleToJson(t.value.value);{let r={};return Object.entries(t.value.value).forEach(([i,n])=>{r[i]=this.convertExampleToJson(n)}),r}case"enum":return t.value;case"literal":return t.value;case"null":return null;case"unknown":return this.convertExampleToJson(t.value);default:return t}}getSchemaDescription(t){if("description"in t)return t.description}getSchemaTypeName(t){switch(t.type){case"primitive":return`primitive (${t.schema.type})`;case"object":return t.generatedName||"object";case"array":return"array";case"map":return"map";case"optional":return`optional (${this.getSchemaTypeName(t.value)})`;case"nullable":return`nullable (${this.getSchemaTypeName(t.value)})`;case"reference":return t.generatedName||"reference";case"enum":return t.generatedName||"enum";case"literal":return"literal";case"oneOf":return"oneOf";case"unknown":return"unknown";default:return"unknown"}}buildEndpointExample(t){let r=nxD(t.request),i=axD(t.response);if(r?.type==="unsupported"||i?.type==="unsupported")return[];let n=[];if(r!=null&&r.type==="present"){let l=this.isSchemaRequired(r.schema);if(r.examples.length===0){let p=this.exampleTypeFactory.buildExample({skipReadonly:x7c(t.method),schema:r.schema,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});p!=null?(n.push([void 0,p]),this.addMissingExampleRecord(t,"request",this.getSchemaTypeName(r.schema),"No user-provided examples found in OpenAPI spec",{schemaDescription:this.getSchemaDescription(r.schema),autoGeneratedExample:this.convertExampleToJson(p)})):this.addMissingExampleRecord(t,"request",this.getSchemaTypeName(r.schema),"Auto-generation failed (schema too complex or circular references)",{schemaDescription:this.getSchemaDescription(r.schema)})}else for(let{name:p,value:_}of r.examples){let h=this.exampleTypeFactory.buildExample({skipReadonly:x7c(t.method),schema:r.schema,exampleId:p,example:_,options:{isParameter:!1,ignoreOptionals:!0}});h!=null?n.push([p,h]):this.addMissingExampleRecord(t,"request",this.getSchemaTypeName(r.schema),`Failed to build example from provided data (example id: ${p})`,{schemaDescription:this.getSchemaDescription(r.schema)})}if(l&&n.length===0)return this.logger.trace(`Failed to generate required request example for ${t.method.toUpperCase()} ${t.path}`),[]}let a=[];if(i!=null&&i.type==="present"){let l=this.isSchemaRequired(i.schema);if(i.examples.length===0){let p=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:i.schema,exampleId:void 0,example:void 0,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});p!=null?(t.response?.type==="json"?a.push([void 0,ZEe.withoutStreaming(p)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&a.push([void 0,ZEe.withStreaming({sse:t.response?.type==="streamingSse",events:[p]})]),this.addMissingExampleRecord(t,"response",this.getSchemaTypeName(i.schema),"No user-provided examples found in OpenAPI spec",{schemaDescription:this.getSchemaDescription(i.schema),autoGeneratedExample:this.convertExampleToJson(p)})):this.addMissingExampleRecord(t,"response",this.getSchemaTypeName(i.schema),"Auto-generation failed (schema too complex or circular references)",{schemaDescription:this.getSchemaDescription(i.schema)})}else for(let{name:p,value:_}of i.examples){let h=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:i.schema,exampleId:p,example:_,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});h!=null?t.response?.type==="json"?a.push([p,ZEe.withoutStreaming(h)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&a.push([void 0,ZEe.withStreaming({sse:t.response?.type==="streamingSse",events:[h]})]):this.addMissingExampleRecord(t,"response",this.getSchemaTypeName(i.schema),`Failed to build example from provided data (example id: ${p})`,{schemaDescription:this.getSchemaDescription(i.schema)})}if(l&&a.length===0)return this.logger.trace(`Failed to generate required response example for ${t.method.toUpperCase()} ${t.path}`),[]}let o=[];for(let l of t.pathParameters){let p=this.isSchemaRequired(l.schema),_=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(_!=null&&!w8t(_)&&(this.logger.debug(`Expected a primitive example but got ${_.type} for path parameter ${l.name} for ${t.method.toUpperCase()} ${t.path}`),_=void 0),p&&_==null)return[];_!=null&&o.push({name:l.name,parameterNameOverride:l.parameterNameOverride,value:_})}let c=[];for(let l of t.queryParameters){let p=this.isSchemaRequired(l.schema),_=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(_!=null&&!w8t(_)&&(this.logger.debug(`Expected a primitive example but got ${_.type} for query parameter ${l.name} for ${t.method.toUpperCase()} ${t.path}`),_=void 0),p&&_==null)return[];_!=null&&c.push({name:l.name,value:_})}let d=[];for(let l of t.headers){let p=this.isSchemaRequired(l.schema),_=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(_!=null&&!w8t(_)&&(this.logger.debug(`Expected a primitive example but got ${_.type} for header ${l.name} for ${t.method.toUpperCase()} ${t.path}`),_=void 0),p&&_==null)return[];_!=null&&d.push({name:l.name,value:_})}for(let l of this.globalHeaders){let p=l.schema!=null?j8t(l.schema):ai.primitive({nameOverride:void 0,generatedName:"",title:void 0,description:void 0,availability:void 0,namespace:void 0,groupName:void 0,schema:kn.string({default:void 0,pattern:void 0,maxLength:void 0,minLength:void 0,example:void 0,format:void 0})}),_=this.exampleTypeFactory.buildExample({schema:p,exampleId:void 0,example:void 0,options:{name:l.header,isParameter:!0,ignoreOptionals:!0}});if(_!=null&&!w8t(_)&&(this.logger.debug(`Expected a primitive example but got ${_.type} for global header ${l.header} for ${t.method.toUpperCase()} ${t.path}`),_=void 0),_==null)return[];_!=null&&d.push({name:l.header,value:_})}let s=[];t.request!=null&&t.response!=null?s=ixD(n,a):t.request!=null?s=n.map(([l,p])=>({id:l,request:p,response:void 0})):t.response!=null&&(s=a.map(([l,p])=>({id:l,request:void 0,response:p})));let u=t.examples.filter(l=>$Ka(l)).flatMap(l=>{if(l.type==="unknown"){if(l.value!=null){let p=l.value["code-samples"];if(p!=null)return this.convertCodeSamples(p)}return}else return l.codeSamples}).filter(l=>us(l));return s.length===0?[XEe.full({name:void 0,description:void 0,pathParameters:o,queryParameters:c,headers:d,request:void 0,response:void 0,codeSamples:u})]:s.map(({id:l,request:p,response:_})=>XEe.full({name:l,description:void 0,pathParameters:o,queryParameters:c,headers:d,request:p,response:_,codeSamples:u}))}convertCodeSamples(t){return t.map(r=>"language"in r?UYt.language({name:r.name??void 0,description:r.docs??void 0,language:r.language,code:r.code,install:r.install??void 0}):UYt.sdk({name:r.name??void 0,description:r.docs??void 0,sdk:r.sdk==="c#"?jF.Csharp:r.sdk,code:r.code})).filter(us)}isSchemaRequired(t){return sbu(this.getResolvedSchema(t))}getResolvedSchema(t){return t}};function ixD(e,t){let r=[];if(e.length<=1){let[n,a]=e[0]??[];if(t.length===0)return r.push({id:n,request:a,response:void 0}),r;for(let[o,c]of t)r.push({id:o??n,request:a,response:c});return r}if(t.length<=1){let[n,a]=t[0]??[];if(t.length===0)return r.push({id:n,request:void 0,response:a}),r;for(let[o,c]of e)r.push({id:o??n,request:c,response:a});return r}let i=new Set;for(let[n,a]of e){let o=t.find(([d])=>d==null)?.[1]??t[0]?.[1];if(n==null){if(o==null)continue;r.push({id:void 0,request:a,response:o});continue}let c=!1;for(let d=0;d<t.length;d++){let[s,u]=t[d];s==null||i.has(d)||n===s&&(r.push({id:n,request:a,response:u}),s!=null&&i.add(d),c=!0)}!c&&o!=null&&r.push({id:n,request:a,response:o})}for(let n=0;n<t.length;n++){if(i.has(n))continue;let[a,o]=t[n],c=e.find(([d])=>d==null)?.[1]??e[0]?.[1];c!=null&&r.push({id:a,request:c,response:o})}return r}function nxD(e){if(e!=null)return e.type==="multipart"?{type:"present",schema:oxD(e),examples:[]}:e.type==="json"||e.type==="formUrlEncoded"?{type:"present",schema:e.schema,examples:e.fullExamples??[]}:{type:"unsupported"}}function axD(e){if(e!=null)return e.type!=="json"&&e.type!=="streamingJson"&&e.type!=="streamingSse"?{type:"unsupported"}:{type:"present",schema:e.schema,examples:e.fullExamples??[]}}function w8t(e){switch(e.type){case"primitive":case"enum":case"literal":return!0;case"unknown":return w8t(e);case"array":case"object":case"map":return!1;case"oneOf":switch(e.value.type){case"discriminated":return!1;case"undiscriminated":return w8t(e.value.value);default:return!1}case"null":return!0;default:vt(e)}}function oxD(e){return ai.object({properties:e.properties.map(t=>t.schema.type==="file"?null:{key:t.key,schema:j8t(t.schema.value),audiences:[],conflict:{},generatedName:t.key,nameOverride:void 0,availability:void 0,readonly:void 0,writeonly:void 0,inline:void 0}).filter(us),allOf:[],allOfPropertyConflicts:[],fullExamples:void 0,description:e.description,nameOverride:void 0,generatedName:"",title:void 0,namespace:void 0,groupName:void 0,additionalProperties:!1,availability:void 0,source:e.source,inline:void 0,minProperties:void 0,maxProperties:void 0})}var Nua=class{exampleTypeFactory;schemas;constructor(t,r){this.exampleTypeFactory=new e$i(t,new Set,r),this.schemas=t}buildWebsocketSessionExamplesForExtension({context:t,extensionExamples:r,handshake:i,source:n,namespace:a}){let o=[];for(let c of r){let d=[];for(let l of i.queryParameters){let p=this.isSchemaRequired(l.schema),_=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:c.queryParameters?.[l.name],options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});_!=null&&!w8t(_)&&(_=void 0),!(p&&_==null)&&_!=null&&d.push({name:l.name,value:_})}let s=[];for(let l of i.headers){let p=this.isSchemaRequired(l.schema),_=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:c.headers?.[l.name],options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});_!=null&&!w8t(_)&&(_=void 0),!(p&&_==null)&&_!=null&&s.push({name:l.name,value:_})}let u=[];for(let l of c.messages){let p=t.getExampleMessageReference(l),_=t.resolveMessageReference({$ref:p}),h=Bn(_.payload)?t.resolveSchemaReference(_.payload):_.payload,y=this.exampleTypeFactory.buildExample({schema:kl(h,!1,!1,t,[l.messageId],n,a),exampleId:void 0,example:l.value,options:{isParameter:!1,ignoreOptionals:!0}});y!=null&&u.push({messageType:l.type,payload:y,description:void 0})}o.push({name:c.summary,queryParameters:d,headers:s,description:c.description,messages:u})}return o}buildWebsocketSessionExample({handshake:t,messages:r}){let i={name:void 0,queryParameters:[],headers:[],description:void 0,messages:[]},n=[];for(let o of t.queryParameters){let c=this.isSchemaRequired(o.schema),d=this.exampleTypeFactory.buildExample({schema:o.schema,exampleId:void 0,example:void 0,options:{name:o.name,isParameter:!0,ignoreOptionals:!0}});if(d!=null&&!w8t(d)&&(d=void 0),c&&d==null)return;d!=null&&n.push({name:o.name,value:d})}let a=[];for(let o of t.headers){let c=this.isSchemaRequired(o.schema),d=this.exampleTypeFactory.buildExample({schema:o.schema,exampleId:void 0,example:void 0,options:{name:o.name,isParameter:!0,ignoreOptionals:!0}});if(d!=null&&!w8t(d)&&(d=void 0),c&&d==null)return;d!=null&&a.push({name:o.name,value:d})}for(let o of r){let c=this.exampleTypeFactory.buildExample({schema:o.payload,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});c!=null&&i.messages.push({messageType:o.type,payload:c,description:void 0})}return i}isSchemaRequired(t){return sbu(this.getResolvedSchema(t))}getResolvedSchema(t){for(;t.type==="reference";){let r=this.schemas[t.schema];if(r==null)throw new Error(`Unexpected error: Failed to resolve schema reference: ${t.schema}`);t=r}return t}};var OL={FERN_PARAMETER_OPTIONAL:"x-fern-optional",FERN_CHANNEL_ADDRESS:"x-fern-address",FERN_DISPLAY_NAME:"x-fern-display-name",FERN_SDK_GROUP_NAME:"x-fern-sdk-group-name",FERN_SDK_METHOD_NAME:"x-fern-sdk-method-name",FERN_EXAMPLES:"x-fern-examples",BASE_PATH:"x-fern-base-path",FERN_ENUM:"x-fern-enum",IGNORE:"x-fern-ignore",FERN_PARAMETER_NAME:"x-fern-parameter-name"};function lbu(e){return Ei(e,OL.FERN_EXAMPLES)??[]}function fbu(e,t){return t.includes("://")?t:`${e}://${t}`}function dbu(e){return e.startsWith("/")?e:"/"+e}function KOh({context:e,breadcrumbs:t,source:r,asyncApiOptions:i,document:n}){let a={},o={};for(let[s,u]of Object.entries(n.components?.schemas??{})){let l=kl(u,!1,!1,e,[s],r,e.namespace);a[s]=l}let c=new Nua(a,e),d={};for(let[s,u]of Object.entries(n.servers??{}))d[s]={name:s,url:fbu(u.protocol,u.url)};for(let[s,u]of Object.entries(n.channels??{})){let l=Ei(u,OL.IGNORE);if(l!=null&&l){e.logger.debug(`Channel ${s} is marked with x-fern-ignore. Skipping.`);continue}let p=[];if(u.parameters!=null)for(let[v,g]of Object.entries(u.parameters??{})){let m=Ei(g,OL.FERN_PARAMETER_NAME);p.push({name:v,description:g.description,parameterNameOverride:m,schema:g.schema!=null?kl(g.schema,!1,!1,e,t,r,e.namespace):ai.primitive({schema:kn.string({default:void 0,pattern:void 0,format:void 0,maxLength:void 0,minLength:void 0,example:void 0}),description:void 0,availability:void 0,generatedName:"",title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0}),variableReference:void 0,availability:BW(g),source:r,explode:void 0})}let _=[],h=[];if(u.bindings?.ws!=null){if(u.bindings.ws.headers!=null){let v=u.bindings.ws.headers.required??[];for(let[g,m]of Object.entries(u.bindings.ws.headers.properties??{})){if(Bn(m)){let M=e.resolveSchemaReference(m),w=v.includes(g),[D,B]=e.options.coerceOptionalSchemasToNullable?[!1,!w]:[!w,!1];_.push({name:g,schema:AUi(m,D,B,e,t,void 0,r,e.namespace),description:M.description,parameterNameOverride:void 0,env:void 0,availability:BW(M),source:r});continue}let O=v.includes(g),[A,j]=e.options.coerceOptionalSchemasToNullable?[!1,!O]:[!O,!1];_.push({name:g,schema:kl(m,A,j,e,[...t,g],r,e.namespace),description:m.description,parameterNameOverride:void 0,env:void 0,availability:BW(m),source:r})}}if(u.bindings.ws.query!=null){let v=u.bindings.ws.query.required??[];for(let[g,m]of Object.entries(u.bindings.ws.query.properties??{})){if(Bn(m)){let M=e.resolveSchemaReference(m),w=v.includes(g),[D,B]=e.options.coerceOptionalSchemasToNullable?[!1,!w]:[!w,!1];h.push({name:g,schema:AUi(m,D,B,e,t,void 0,r,e.namespace),description:M.description,parameterNameOverride:void 0,availability:BW(M),source:r,explode:void 0});continue}let O=v.includes(g),[A,j]=e.options.coerceOptionalSchemasToNullable?[!1,!O]:[!O,!1];h.push({name:g,schema:kl(m,A,j,e,[...t,g],r,e.namespace),description:m.description,parameterNameOverride:void 0,availability:BW(m),source:r,explode:void 0})}}}let y;u.publish!=null&&("oneOf"in u.publish.message?y=xOh({generatedName:u.publish.operationId??"PublishEvent",event:u.publish,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:i}):y=HOh({action:"Publish",channelPath:s,message:u.publish.message,context:e,source:r}));let b;if(u.subscribe!=null&&("oneOf"in u.subscribe.message?b=xOh({generatedName:u.subscribe.operationId??"SubscribeEvent",event:u.subscribe,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:i}):b=HOh({action:"Subscribe",channelPath:s,message:u.subscribe.message,context:e,source:r})),_.length>0||h.length>0||y!=null||b!=null){let v=lbu(u),g=[];if(v.length>0)g=c.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:v,handshake:{headers:_,queryParameters:h},source:r,namespace:e.namespace});else{let j=[];y!=null&&j.push({type:"publish",payload:y}),b!=null&&j.push({type:"subscribe",payload:b});let M=c.buildWebsocketSessionExample({handshake:{headers:_,queryParameters:h},messages:j});M!=null&&g.push(M)}let m=Ei(u,OL.FERN_CHANNEL_ADDRESS),O=m??dbu(s),A=[];y!=null&&A.push({origin:"client",name:"publish",body:Um(y),methodName:void 0}),b!=null&&A.push({origin:"server",name:"subscribe",body:Um(b),methodName:void 0}),o[s]={audiences:Ei(u,xi.AUDIENCES)??[],handshake:{headers:_.map(j=>({...j,schema:Um(j.schema),env:j.env})),queryParameters:h.map(j=>({...j,schema:Um(j.schema)})),pathParameters:p.map(j=>({...j,schema:Um(j.schema)}))},groupName:e.resolveGroupName([Ei(u,OL.FERN_SDK_GROUP_NAME)??s]),messages:A,servers:(u.servers?.map(j=>d[j])??Object.values(d)).filter(j=>j!=null&&j.name!=null).map(j=>({...j,name:j.name})),summary:Ei(u,OL.FERN_DISPLAY_NAME),path:O,description:u.description,examples:g,source:r}}}return{groupedSchemas:Rua(e.namespace,a),channels:o??void 0,servers:Object.values(d).map(s=>({...s,name:s.name})),basePath:Ei(n,OL.BASE_PATH)}}function xOh({generatedName:e,event:t,context:r,breadcrumbs:i,source:n,options:a,asyncApiOptions:o}){if("oneOf"in t.message&&t.message.oneOf!=null){let c=[],d=[];for(let s of t.message.oneOf){let u,l={type:"notFound"};if(Bn(s)){let p=r.resolveMessageReference(s);!Bn(p.payload)&&o.naming==="v2"?(l=p.name?{type:"name",name:p.name}:l,u={...p.payload,title:p.name??p.payload.title,description:p.name??p.payload.description}):u=p.payload}else u=s;d.push(l),c.push(u)}return ZJi({description:t.description??t.message.description,availability:BW(t.message),subtypes:c,nameOverride:t.operationId,generatedName:e,title:t.message.title,groupName:void 0,wrapAsOptional:!1,wrapAsNullable:!1,breadcrumbs:i,context:r,encoding:void 0,source:n,namespace:r.namespace,subtypeSuffixOverrides:o.naming==="v2"?d:[]})}}function HOh({action:e,channelPath:t,message:r,context:i,source:n}){if(r.payload!=null){let a=r.payload;return Bn(r.payload)&&(a=i.resolveSchemaReference(r.payload)),kl(a,!1,!1,i,[t,e],n,i.namespace)}}var pbu=class extends Tua{getExampleMessageReference(t){return`#/channels/${t.channelId}/messages/${t.messageId}`}resolveParameterReference(t){let r="#/components/parameters/";if(this.document.components==null||this.document.components.parameters==null||!t.$ref.startsWith(r))throw new Error(`Failed to resolve ${t.$ref}`);let i=t.$ref.substring(r.length),n=this.document.components.parameters[i];if(n==null)throw new Error(`${t.$ref} is undefined`);return"$ref"in n?this.resolveParameterReference(n):n}resolveMessageReference(t,r=!1){let i="#/channels/",n="#/components/messages/";if(t.$ref.startsWith(i)){let d=t.$ref.split("/"),s=d[2],u=d[4];if(s==null||u==null||!this.document.channels?.[s])throw new Error(`Failed to resolve message reference ${t.$ref} in channel ${s}`);let p=this.document.channels[s].messages?.[u];if(p==null)throw new Error(`${t.$ref} is undefined`);return"$ref"in p&&!r?this.resolveMessageReference(p):{...p,name:u}}let a=this.document.components;if(!t.$ref.startsWith(n)||!a?.messages)throw new Error(`Failed to resolve message reference: ${t.$ref} in v3 components`);let o=t.$ref.substring(n.length),c=a.messages[o];if(c==null)throw new Error(`${t.$ref} is undefined`);return{...c,name:o}}isMessageWithPayload(t){return t!=null&&typeof t=="object"&&"payload"in t}isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}};var JOh="#/channels/",$Oh="#/servers/",H7c="$message.";function XOh({context:e,breadcrumbs:t,source:r,asyncApiOptions:i,document:n}){let a={},o={},c={},d=[],s={};e.logger.debug("Parsing V3 AsyncAPI...");for(let[v,g]of Object.entries(n.components?.schemas??{}))a[v]=kl(g,!1,!1,e,[v],r,e.namespace);for(let[v,g]of Object.entries(n.channels??{}))if(o[v]||(o[v]={}),g.messages)for(let[m,O]of Object.entries(g.messages))if(c[m]||(c[m]=[]),e.isReferenceObject(O)){let A=e.resolveMessageReference(O);c[m].push({channelId:v,payload:A.payload})}else e.isMessageWithPayload(O)&&c[m].push({channelId:v,payload:O.payload});for(let[v,g]of Object.entries(c))if(g.length===1){let m=g[0],O=m.channelId;o[O]=o[O]||{},o[O][v]=kl(m.payload,!1,!1,e,[v],r,e.namespace)}else{d.push(v);for(let{channelId:m,payload:O}of g){let A=`${m}_${v}`;o[m]||(o[m]={}),o[m][A]=kl(O,!1,!1,e,[A],r,e.namespace)}}let u=Object.values(o).reduce((v,g)=>({...v,...g}),{}),l=new Nua(u,e),p={};for(let[v,g]of Object.entries(n.servers??{}))p[v]={name:v,url:fbu(g.protocol,g.host)};let _={};for(let[v,g]of Object.entries(n.operations??{})){if(Ei(g,OL.IGNORE))continue;let m=uxD(g);_[m]||(_[m]={subscribe:[],publish:[],__parsedMessages:[]});let O=Ei(g,OL.FERN_SDK_METHOD_NAME),A=g.messages.map(j=>({ref:j,methodName:O}));if(g.action==="receive")_[m].subscribe.push(...A);else if(g.action==="send")_[m].publish.push(...A);else throw new Error(`Operation ${v} has an invalid action: ${g.action}`)}for(let[v,g]of Object.entries(_)){let m=[];m.push(...YOh({messages:g.subscribe,channelPath:v,origin:"server",messageSchemas:o[v]??{},duplicatedMessageIds:d,context:e})),m.push(...YOh({messages:g.publish,channelPath:v,origin:"client",messageSchemas:o[v]??{},duplicatedMessageIds:d,context:e})),_[v]!=null&&(_[v].__parsedMessages=m)}for(let[v,g]of Object.entries(n.channels??{})){if(Ei(g,OL.IGNORE))continue;let m=[],O=[],A=[];if(g.parameters!=null)for(let[j,M]of Object.entries(g.parameters)){let w=e.isReferenceObject(M)?e.resolveParameterReference(M):M,{type:D,parameterKey:B}=w.location!=null?sxD(w.location):{type:g.address?.includes(`={${j}}`)?"query":"path",parameterKey:j},T=Ei(w,OL.FERN_PARAMETER_OPTIONAL),R=Z0(ou(v))+Z0(ou(j)),q={...w,type:"string",title:R,example:w.examples?.[0],default:w.default,enum:w.enum,required:void 0},z=kl(q,!1,!1,e,[B],r,e.namespace);T&&(z=ai.optional({value:z,description:void 0,availability:void 0,generatedName:"",title:R,namespace:void 0,groupName:void 0,nameOverride:void 0,inline:void 0}));let N={name:B,description:w.description,parameterNameOverride:void 0,schema:z,variableReference:void 0,availability:BW(M),source:r,explode:void 0};D==="header"?m.push({...N,env:void 0}):D==="path"?O.push(N):(D==="payload"||D==="query")&&A.push(N)}if(m.length>0||A.length>0||_[v]!=null&&(_[v].publish!=null||_[v].subscribe!=null)){let j=lbu(g),M=_[v]?.__parsedMessages??[],w=[];if(j.length>0)w=l.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:j,handshake:{headers:m,queryParameters:A},source:r,namespace:e.namespace});else{let R=[],{examplePublishMessage:q,exampleSubscribeMessage:z}=lxD({messages:M,messageSchemas:o[v]??{}});q!=null&&R.push(q),z!=null&&R.push(z);let N=l.buildWebsocketSessionExample({handshake:{headers:m,queryParameters:A},messages:R});N!=null&&w.push(N)}let D=Ei(g,OL.FERN_SDK_GROUP_NAME),B=(g.servers?.map(R=>cxD(p,R))??Object.values(p)).map(R=>({...R,name:R.name})),T=g.address?.split("?")[0]??dbu(v);s[v]={audiences:Ei(g,xi.AUDIENCES)??[],handshake:{headers:m.map(R=>({...R,schema:Um(R.schema),env:R.env})),queryParameters:A.map(R=>({...R,schema:Um(R.schema)})),pathParameters:O.map(R=>({...R,parameterNameOverride:void 0,schema:Um(R.schema)}))},groupName:e.resolveGroupName(typeof D=="string"?[D]:D??[v]),messages:M,summary:Ei(g,OL.FERN_DISPLAY_NAME),servers:B,path:T,description:g.description,examples:w,source:r}}else e.logger.warn(`Skipping AsyncAPI channel ${v} as it does not qualify for inclusion (no headers, query params, or operations)`)}let h=Rua(e.namespace,a),y=Object.values(p).map(v=>({...v,name:v.name})),b=Ei(n,OL.BASE_PATH);return{groupedSchemas:h,channels:s,servers:y,basePath:b}}function uxD(e){if(!e.channel.$ref.startsWith(JOh))throw new Error(`Failed to resolve channel path from operation ${e.channel.$ref}`);return e.channel.$ref.substring(JOh.length)}function sxD(e){try{let[t,r]=e.split("#/");if(t==null||r==null)throw new Error(`Invalid location format: ${e}; unable to parse message type and parameter key`);if(!t.startsWith(H7c))throw new Error(`Invalid location format: ${e}; expected ${H7c} prefix`);let i=t.substring(H7c.length);if(i!=="header"&&i!=="path"&&i!=="payload")throw new Error(`Invalid message type: ${i}. Must be one of: header, path, payload`);return{type:i,parameterKey:r}}catch{throw new Error(`Invalid location format: ${e}; see here for more details: https://www.asyncapi.com/docs/reference/specification/v3.0.0#runtimeExpression`)}}function cxD(e,t){if(!t.$ref.startsWith($Oh))throw new Error(`Failed to resolve server name from server ref ${t.$ref}`);let r=t.$ref.substring($Oh.length),i=e[r];if(i==null)throw new Error(`Failed to find server with name ${r}`);return i}function YOh({messages:e,channelPath:t,origin:r,messageSchemas:i,duplicatedMessageIds:n,context:a}){let o=[];return e.forEach((c,d)=>{let u=a.resolveMessageReference(c.ref,!0).name;n.includes(u)&&(u=`${t}_${u}`);let l=i[u];l!=null&&o.push({origin:r,name:u??`${r}Message${d+1}`,body:Um(l),methodName:c.methodName})}),o}function lxD({messages:e,messageSchemas:t}){let r=e.find(o=>o.origin==="client")?.name,i=e.find(o=>o.origin==="server")?.name,n=r!=null?t[r]:void 0,a=i!=null?t[i]:void 0;return{examplePublishMessage:n!=null&&r!=null?{type:r,payload:n}:void 0,exampleSubscribeMessage:a!=null&&i!=null?{type:i,payload:a}:void 0}}function ZOh({document:e,taskContext:t,options:r,source:i,asyncApiOptions:n,namespace:a}){let o=[];if(a!=null&&o.push(a),parseFloat(e.asyncapi)<3){let c=e;c.tags?.[0]!=null?o.push(c.tags[0].name):n.naming!=="v2"&&o.push("websocket");let d=new ubu({document:c,taskContext:t,options:r,namespace:a});return KOh({context:d,breadcrumbs:o,source:i,asyncApiOptions:n,document:c})}else{let c=e,d=new pbu({document:c,taskContext:t,options:r,namespace:a});return XOh({context:d,breadcrumbs:o,source:i,asyncApiOptions:n,document:c})}}function kOh(e){return Ei(e,xi.ASYNC_CONFIG)}var emh="$request.";function tmh(e){let t=Ei(e,xi.STREAMING);if(t!=null)return typeof t=="boolean"?t?{type:"stream",format:"json"}:void 0:t["stream-condition"]==null&&t.format!=null?{type:"stream",format:t.format}:{type:"streamCondition",format:t.format??"json",streamDescription:t["stream-description"],streamConditionProperty:fxD(t["stream-condition"]),responseStream:t["response-stream"],response:t.response}}function fxD(e){return e.startsWith(emh)?e.slice(emh.length):e}function rmh(e){let t=e;if(t.cursor!=null)return uge.cursor({cursor:t.cursor,nextCursor:t.next_cursor,results:t.results});if("offset"in e){let r=e;return uge.offset({offset:r.offset,results:r.results,step:r.step,hasNextPage:r["has-next-page"]})}if("type"in e&&e.type==="custom"){let r=e;return uge.custom({results:r.results})}throw new Error("Invalid pagination extension")}function imh(e,t){let r=Ei(t,xi.PAGINATION);if(r!=null){if(typeof r=="boolean"){let i=Ei(e,xi.PAGINATION);if(typeof i=="boolean")throw new Error("Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.");return i==null?void 0:rmh(i)}return rmh(r)}}function nmh(e){let t=dxD(e),r={};return K7c({obj:t,occurrences:r,breadcrumbs:[]}),r}function K7c({obj:e,occurrences:t,breadcrumbs:r}){if(e!=null){if(Array.isArray(e)){for(let i of e)K7c({obj:i,occurrences:t,breadcrumbs:r});return}if(typeof e=="object"){if(e.$ref!=null&&typeof e.$ref=="string"){let i=e.$ref;t[i]==null?t[i]=1:t[i]+=1;return}for(let i in e)K7c({obj:e[i],occurrences:t,breadcrumbs:[...r,i]})}}}function dxD(e){return{...e,paths:Object.fromEntries(Object.entries(e.paths??{}).map(([t,r])=>[t,{...r,get:r?.get!=null?YKa(r.get):void 0,put:r?.put!=null?YKa(r.put):void 0,post:r?.post!=null?YKa(r.post):void 0,patch:r?.patch!=null?YKa(r.patch):void 0,delete:r?.delete!=null?YKa(r.delete):void 0}]))}}function YKa(e){return{...e,requestBody:e.requestBody!=null?Bn(e.requestBody)?e.requestBody:pxD(e.requestBody):void 0}}function pxD(e){let t,r;for(let i in e.content){let n=tm.parse(i);n!=null&&(n.isJSON()?t=e.content[i]:n.isMultipart()&&(r=e.content[i]))}return r!=null&&t!=null?{...e,content:{[tm.MULTIPART_FORM_DATA]:r}}:e}var _bu=class{endpoints;parser=new zbn;constructor({context:t,options:r}){this.endpoints=r.filter?.endpoints?new Set(this.validateAndFilterEndpoints({context:t,endpoints:r.filter.endpoints})):void 0}skipEndpoint({method:t,path:r}){return this.endpoints!=null&&!this.endpoints.has(`${t} ${r}`)}hasEndpoints(){return this.endpoints!=null}validateAndFilterEndpoints({context:t,endpoints:r}){let i=[];for(let n of r){let a=this.parser.tryParse(n);if(a==null){t.logger.debug(`Ignoring configured filter endpoint "${n}"; expected format "POST /users/get"`);continue}i.push(`${a.method} ${a.path}`)}return i}};var amh="#/components/parameters/",omh="#/components/responses/",umh="#/components/examples/",smh="#/components/requestBodies/",cmh="#/components/securitySchemes/",Fua=class{logger;document;taskContext;authHeaders;refOccurrences;DUMMY;options;source;filter;namespace;constructor({document:t,taskContext:r,authHeaders:i,options:n,source:a,namespace:o}){this.document=t,this.logger=r.logger,this.taskContext=r,this.authHeaders=i,this.refOccurrences=nmh(t),this.options=n,this.source=a,this.filter=new _bu({context:r,options:n}),this.DUMMY=this.getDummy(),this.namespace=o}getNumberOfOccurrencesForRef(t){return this.refOccurrences[t.$ref]??0}resolveTagsToTagIds(t){let r=[];return this.namespace!=null&&r.push(this.namespace),r.concat(t??[])}resolveTags(t){let r=[];if(this.namespace!=null){let i={type:"namespace",name:this.namespace};r.push(i)}return r.concat(t??[])}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveSchemaReference(t){let r=t.$ref.substring(2).split("/").map(n=>n.replace(/~1/g,"/")),i=this.document;for(let n of r){if(typeof i!="object"||i==null)return{"x-fern-type":"unknown"};if(Array.isArray(i)){let a=parseInt(n,10);if(isNaN(a)||a<0||a>=i.length)return{"x-fern-type":"unknown"};i=i[a]}else i=i[n]}return i==null?(this.logger.debug(`Encountered undefined reference: ${t.$ref}`),{"x-fern-type":"unknown"}):(Bn(i)&&(i=this.resolveSchemaReference(i)),i)}resolveParameterReference(t){if(this.document.components==null||this.document.components.parameters==null||!t.$ref.startsWith(amh))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(amh.length),i=this.document.components.parameters[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return Bn(i)?this.resolveParameterReference(i):i}resolveRequestBodyReference(t){if(this.document.components==null||this.document.components.requestBodies==null||!t.$ref.startsWith(smh))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(smh.length),i=this.document.components.requestBodies[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return Bn(i)?this.resolveRequestBodyReference(i):i}resolveResponseReference(t){if(this.document.components==null||this.document.components.responses==null||!t.$ref.startsWith(omh))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(omh.length),i=this.document.components.responses[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return Bn(i)?this.resolveResponseReference(i):i}resolveExampleReference(t){if(this.document.components==null||this.document.components.examples==null||!t.$ref.startsWith(umh))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(umh.length),i=this.document.components.examples[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return Bn(i)?this.resolveExampleReference(i):i}resolveSecuritySchemeReference(t){if(this.document.components==null||this.document.components.securitySchemes==null||!t.$ref.startsWith(cmh))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(cmh.length),i=this.document.components.securitySchemes[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return Bn(i)?this.resolveSecuritySchemeReference(i):i}referenceExists(t){let r=t.substring(2).split("/").map(n=>n.replace(/~1/g,"/")),i=this.document;for(let n of r){if(typeof i!="object"||i==null)return!1;i=i[n]}return!0}};var zvn=class extends Fua{constructor({document:t,taskContext:r,options:i,source:n,namespace:a}){super({document:t,taskContext:r,authHeaders:new Set,options:i,source:n,namespace:a})}getDummy(){return this}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}getReferencedSchemas(){return new Set}markReferencedByDiscriminatedUnion(t,r,i){}getReferencesFromDiscriminatedUnion(t){}excludeSchema(t){}isSchemaExcluded(t){return!1}markSchemaWithDiscriminantValue(t,r,i){}getDiscriminatedUnionMetadata(t){}};var hbu=require("fs"),ybu=require("path");var _xD=Qt.object({lang:Qt.string(),label:Qt.optional(Qt.string()),source:Qt.string()}),J7c=Qt.array(_xD);var lmh={README_EXT:"x-readme"};function hxD(e){if(!Array.isArray(e))return!1;for(let t of e)if(!yl(t)||typeof t.language!="string"||typeof t.code!="string")return!1;return!0}function fmh(e){let t=Ei(e,lmh.README_EXT);if(!yl(t))return[];let r=t["code-samples"];if(!hxD(r))return[];let i=[];for(let n of r)i.push({name:n.name,language:n.language,code:n.code,install:n.install,docs:void 0});return i}function yxD(e){return yl(e)&&typeof e.$ref=="string"}function bxD(e,t){if(e!=null){if(typeof e=="string")return e;if(yxD(e)){let r=(0,ybu.resolve)(t??process.cwd(),e.$ref);if((0,hbu.existsSync)(r))try{return(0,hbu.readFileSync)(r,"utf-8")}catch{return}}}}function vxD(e,t){if(!Array.isArray(e))return[];let r=[];for(let i of e){if(!yl(i))continue;let a=bxD(i.code,t);a!=null&&r.push({...i,code:a})}return r}function dmh(e,t,r){let i=Ei(t,xi.EXAMPLES),n=r.source.type==="openapi"?(0,ybu.dirname)(r.source.file):void 0,o=(i??[]).map(l=>{if(!yl(l))return l;let _=l["code-samples"];if(_!=null){let h=vxD(_,n);return{...l,"code-samples":h}}return l}).filter(l=>{let p=cI.serialization.ExampleEndpointCallSchema.parse(l);return p.ok||r.logger.error(`Failed to parse x-fern-example in ${e.path}/${e.method}`),p.ok}),c=GKa(t,gL.REDOCLY_CODE_SAMPLES_KEBAB,J7c,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],s=[...GKa(t,gL.REDOCLY_CODE_SAMPLES_CAMEL,J7c,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],...c];s.length>0&&o.push({"code-samples":s.map(l=>({name:l.label??l.lang,language:l.lang,code:l.source,install:void 0,docs:void 0}))});let u=fmh(t);return u.length>0&&o.push({"code-samples":u}),o.map(XEe.unknown)}function pmh(e){let t=Ei(e,xi.AVAILABILITY);if(t==="ga"||t==="generally-available")return PF.GenerallyAvailable;if(t==="beta"||t==="pre-release")return PF.Beta;if(t==="deprecated")return PF.Deprecated;if(e.deprecated)return PF.Deprecated}function _mh(e){let t=Ei(e,xi.RETRIES);if(t!=null&&t.disabled===!0)return N_u.RetriesConfiguration.disabled(t.disabled)}function bbu(e,t){return{url:gxD({url:e.url,variables:e.variables??{}}),description:e.description,name:OxD(e,t),audiences:Ei(e,xi.AUDIENCES)}}function gxD({url:e,variables:t}){let r=Object.fromEntries(Object.entries(t).map(([i,n])=>[i,n.default]));for(let[i,n]of Object.entries(r))e=e.replace(`{${i}}`,encodeURIComponent(n));return e}function OxD(e,t){let r=Ei(e,[xi.SERVER_NAME_V1,xi.SERVER_NAME_V2]);if(r!=null)return r;if(e.description?.toLowerCase()==="production")return"Production";if(e.description?.toLowerCase()==="sandbox")return"Sandbox";if(t?.groupMultiApiEnvironments&&e.description!=null&&e.description.trim()!==""){let i=e.description.toLowerCase();return i==="prd"?"Production":i==="sbx"?"Sandbox":i==="staging"||i==="stg"?"Staging":i==="development"||i==="dev"?"Development":e.description}}function hmh(e){return Ei(e,xi.PARAMETER_NAME)}function ymh(e){return Ei(e,xi.SDK_VARIABLE)}function vbu({path:e,httpMethod:t,parameters:r,context:i,requestBreadcrumbs:n,source:a}){let o={pathParameters:[],queryParameters:[],headers:[]};for(let c of r){let d=Ei(c,xi.IGNORE);if(d!=null&&d){i.logger.debug(`${t.toUpperCase()} ${e} has a parameter marked with x-fern-ignore. Skipping.`);continue}let s=Bn(c)?i.resolveParameterReference(c):c,u=s.required??!1,l=BW(s),p=[...n,s.name],_=jC(p,i.options.preserveSchemaIds),[h,y]=i.options.coerceOptionalSchemasToNullable?[!1,!u]:[!u,!1],b=s.schema!=null?kl(s.schema,h,y,i,p,a,i.namespace,!1,new Set,JYt({schema:s,logger:i.logger})):u?ai.primitive({nameOverride:void 0,generatedName:_,title:void 0,schema:kn.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:JYt({schema:s,logger:i.logger})}),description:void 0,availability:l,namespace:void 0,groupName:void 0}):ai.optional({nameOverride:void 0,generatedName:_,title:void 0,value:ai.primitive({nameOverride:void 0,generatedName:_,title:void 0,schema:kn.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:JYt({schema:s,logger:i.logger})}),description:void 0,availability:void 0,namespace:void 0,groupName:void 0}),description:void 0,availability:l,namespace:void 0,groupName:void 0,inline:void 0});if(s.in==="header"&&s.schema!=null&&!Bn(s.schema)&&s.schema.default!=null){let g=s.schema.default;typeof g=="string"&&g.length>0&&(b=ai.literal({nameOverride:void 0,generatedName:_,title:void 0,value:nE.string(g),description:void 0,availability:l,namespace:void 0,groupName:void 0}))}let v={name:s.name,schema:b,description:s.description,parameterNameOverride:hmh(s),availability:l,source:a};s.in==="query"?o.queryParameters.push({...v,explode:AxD(s)}):s.in==="path"?o.pathParameters.push({...v,variableReference:ymh(s),explode:PxD(s)}):s.in==="header"?!mxD.has(s.name.toLowerCase())&&!i.authHeaders.has(s.name)?o.headers.push({...v,env:void 0}):i.logger.debug(`Ignoring ${s.name} header, in ${t.toUpperCase()} ${e}`):i.logger.warn(`Skipping ${s.in} parameter, ${s.name}, in ${t.toUpperCase()} ${e}`)}return o}var mxD=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]);function AxD(e){let t=e.style??"form",r=e.explode;if(r!==void 0)return t==="form"?r===!0?void 0:r:r===!1?void 0:r}function PxD(e){let t=e.explode;if(t!==void 0)return t===!1?void 0:t}function bmh(e,t){for(let r of Object.keys(e))if(r.includes("text/event-stream")){let i=e[r];if(i==null)continue;let n=i.schema;return{contentType:r,schema:n??{},examples:XKa(i,t)}}}function jxD(e){return e.includes("json")||e==="*/*"}function $7c({content:e,context:t}){for(let[r,i]of Object.entries(e))if(gbu({mediaType:r,mediaTypeObject:i,context:t})!=null)return[r,i]}function gbu({mediaType:e,mediaTypeObject:t,context:r}){if(!jxD(e))return;let i=t.schema;return{contentType:e.includes("*")?void 0:e,schema:i??{},examples:XKa(t,r)}}function Obu({content:e,context:t}){let r=$7c({content:e,context:t});if(!r)return;let[i,n]=r;return gbu({mediaType:i,mediaTypeObject:n,context:t})}function vmh(e,t){for(let r of Object.keys(e)){let i=e[r];if(i==null)continue;return{schema:i.schema??{},examples:XKa(i,t)}}}function XKa(e,t){let r=[];e.example!=null&&r.push({name:void 0,value:e.example,description:void 0});let i=Ei(e,gL.EXAMPLES);return i!=null&&Object.keys(i).length>0&&r.push(...Object.entries(i).map(([n,a])=>({name:a.summary??n,value:a.value,description:a.description}))),e.examples!=null&&Object.keys(e.examples).length>0&&r.push(...Object.entries(e.examples).map(([n,a])=>{let o=Bn(a)?t.resolveExampleReference(a):a;return{name:o.summary??n,value:o.value,description:o.description}})),r}function wxD({content:e,context:t}){for(let[r,i]of Object.entries(e))if(Omh({mediaType:r,mediaTypeObject:i,context:t}))return[r,i]}function Omh({mediaType:e,mediaTypeObject:t,context:r}){if(tm.parse(e)?.isURLEncoded())return{schema:t.schema,contentType:e,examples:XKa(t,r)}}function ExD({content:e}){for(let[t,r]of Object.entries(e))if(mmh({mediaType:t,mediaTypeObject:r}))return[t,r]}function mmh({mediaType:e,mediaTypeObject:t}){if(tm.parse(e)?.isMultipart())return{schema:t.schema,encoding:t.encoding}}function Amh({mediaType:e}){return tm.parse(e)?.isBinary()??!1}function SxD({content:e}){for(let[t,r]of Object.entries(e))if(Amh({mediaType:t}))return[t,r]}function MxD(e,t){let r=Bn(e)?Y7c(e,t):{id:void 0,schema:e};return Object.entries(r.schema.properties??{}).find(([i,n])=>!Bn(n)&&n.type==="string"&&n.format==="binary")!=null}function Abu({content:e,description:t,document:r,context:i,requestBreadcrumbs:n,source:a,namespace:o}){let c=SxD({content:e});if(c){let[p,_]=c;return YYt({mediaType:p,mediaTypeObject:_,description:t,document:r,context:i,requestBreadcrumbs:n,source:a,namespace:o})}let d=ExD({content:e}),s=$7c({content:e,context:i}),u=DxD({json:s,multipart:d,document:r,visitor:{json:([p,_])=>YYt({mediaType:p,mediaTypeObject:_,description:t,document:r,context:i,requestBreadcrumbs:n,source:a,namespace:o}),multipart:([p,_])=>YYt({mediaType:p,mediaTypeObject:_,description:t,document:r,context:i,requestBreadcrumbs:n,source:a,namespace:o}),neither:()=>{}}});if(u)return u;let l=wxD({content:e,context:i});if(l){let[p,_]=l;return YYt({mediaType:p,mediaTypeObject:_,description:t,document:r,context:i,requestBreadcrumbs:n,source:a,namespace:o})}}function DxD({json:e,multipart:t,document:r,visitor:i}){if(!e&&!t)return i.neither();let[,n]=e??[void 0,void 0],[,a]=t??[void 0,void 0];return!n?.schema&&!a?.schema?i.neither():n?.schema&&a?.schema?n.schema&&MxD(n.schema,r)?i.multipart(t):i.json(e):n?.schema?i.json(e):a?.schema?i.multipart(t):i.neither()}function YYt({mediaType:e,mediaTypeObject:t,description:r,document:i,context:n,requestBreadcrumbs:a,source:o,namespace:c}){let d=BxD({mediaTypeObject:t});if(Amh({mediaType:e}))return _x.octetStream({description:r,source:o,sdkMethodName:d,contentType:e});let s=mmh({mediaType:e,mediaTypeObject:t}),u=s?.schema,l=s?.encoding;if(u){let h=Bn(u)?Y7c(u,i):{id:void 0,schema:u},y=kl(h.schema,!1,!1,n,a,o,c,!1),b=[];if(y.type==="object"){let v=new Set(h.schema.required??[]);for(let g of y.properties){let m=v.has(g.key),{isFile:O,isOptional:A,isArray:j,description:M}=mbu({schema:g.schema,isOptional:!m});if(O){let w=gmh(g.key,l);b.push({key:g.key,schema:LYt.file({isOptional:A,isArray:j,description:M}),description:M,contentType:w,exploded:!1,encoding:w==null?n.options.defaultFormParameterEncoding:void 0})}else{let w=gmh(g.key,l);b.push({key:g.key,schema:LYt.json(g.schema),description:void 0,contentType:w,exploded:l?.[g.key]?.explode,encoding:w==null?n.options.defaultFormParameterEncoding:CxD(w)})}}}return _x.multipart({name:Bn(u)&&n.getNumberOfOccurrencesForRef(u)===1?h.id:void 0,description:h.schema.description,properties:b,source:o,sdkMethodName:d})}let p=gbu({mediaType:e,mediaTypeObject:t,context:n});if(p){let h=kl(p.schema,!1,!1,n,a,o,c,!0);return _x.json({description:void 0,schema:h,contentType:p.contentType,fullExamples:p.examples,additionalProperties:!Bn(p.schema)&&HKa(p.schema.additionalProperties,n.options),source:o,sdkMethodName:d})}let _=Omh({mediaType:e,mediaTypeObject:t,context:n});if(_!=null&&_.schema!=null){let h=kl(_.schema,!1,!1,n,a,o,c,!1);return _x.formUrlEncoded({schema:h,description:r,contentType:_.contentType,source:o,fullExamples:_.examples,additionalProperties:!1,sdkMethodName:d})}}function BxD({mediaTypeObject:e}){return Ei(e,xi.SDK_METHOD_NAME)}var IxD={"application/json":"json"};function CxD(e){return e?IxD[e]:void 0}function Y7c(e,t){if(!e.$ref.startsWith(Tvn))throw new Error(`Failed to resolve schema reference because of unsupported prefix: ${e.$ref}`);let r=XJi(e);if(r==null)throw new Error(`Failed to resolve schema reference because missing schema id: ${e.$ref}`);let i=t.components?.schemas?.[r];if(i==null)throw new Error(`Failed to resolve schema reference because missing: ${e.$ref}`);return Bn(i)?Y7c(i,t):{id:r,schema:i}}function mbu({schema:e,isOptional:t,isArray:r,description:i}){return TxD(e)?mbu({schema:e.value,isOptional:!0,isArray:r,description:e.description}):RxD(e)?mbu({schema:e.value,isOptional:t,isArray:r,description:e.description}):zxD(e)?mbu({schema:e.value,isOptional:t,isArray:!0,description:e.description}):qxD(e)?{isFile:!0,isOptional:t??!1,isArray:r??!1,description:i??e.description}:{isFile:!1,isOptional:t??!1,isArray:r??!1,description:void 0}}function qxD(e){return e.type==="primitive"&&e.schema.type==="string"&&e.schema.format==="binary"}function TxD(e){return e.type==="optional"}function RxD(e){return e.type==="nullable"}function zxD(e){return e.type==="array"}function gmh(e,t){return t?.[e]?.contentType}var X7c={400:"BadRequestError",401:"UnauthorizedError",402:"PaymentRequiredError",403:"ForbiddenError",404:"NotFoundError",405:"MethodNotAllowedError",406:"NotAcceptableError",407:"ProxyAuthenticationRequiredError",408:"RequestTimeoutError",409:"ConflictError",410:"GoneError",411:"LengthRequiredError",412:"PreconditionFailedError",413:"ContentTooLargeError",414:"URITooLongError",415:"UnsupportedMediaTypeError",416:"RangeNotSatisfiableError",417:"ExpectationFailedError",418:"ImATeapotError",419:"AuthenticationTimeoutError",420:"MethodFailureError",421:"MisdirectedRequestError",422:"UnprocessableEntityError",423:"LockedError",424:"FailedDependencyError",425:"TooEarlyError",426:"UpgradeRequiredError",428:"PreconditionError",429:"TooManyRequestsError",430:"RequestHeaderFieldsTooLargeError",431:"RequestHeaderFieldsTooLargeError",444:"NoResponseError",449:"RetryWithError",450:"BlockedByWindowsParentalControlsError",451:"UnavailableForLegalReasonsError",498:"InvalidTokenError",499:"ClientClosedRequestError",500:"InternalServerError",501:"NotImplementedError",502:"BadGatewayError",503:"ServiceUnavailableError",504:"GatewayTimeoutError",505:"HTTPVersionNotSupportedError",506:"VariantAlsoNegotiatesError",507:"InsufficientStorageError",508:"LoopDetectedError",509:"BandwidthLimitExceededError",510:"NotExtendedError",511:"NetworkAuthenticationRequiredError"},Pmh=new Set(Object.values(X7c));var NxD=["200","201","202","204"];function Pbu({operationContext:e,responses:t,context:r,responseBreadcrumbs:i,responseStatusCode:n,streamFormat:a,source:o}){if(t==null)return{value:void 0,errors:{}};let c=FxD({responses:t,context:r,source:o,namespace:r.namespace}),d=!1,s;for(let u of n!=null?[n]:NxD){let l=t[u];l!=null&&(d=!0,s==null&&(s=jmh({operationContext:e,response:l,context:r,responseBreadcrumbs:i,streamFormat:a,source:o,namespace:r.namespace,statusCode:typeof u=="string"?parseInt(u):u})))}if(s==null&&!d&&t.default!=null&&(s=jmh({operationContext:e,response:t.default,context:r,responseBreadcrumbs:i,streamFormat:a,source:o,namespace:r.namespace})),s!=null)switch(s.type){case"json":return{value:s,errors:c};case"streamingJson":case"streamingSse":return{value:s,errors:c};case"bytes":case"file":case"text":case"streamingText":return{value:s,errors:c};default:vt(s)}return{value:void 0,errors:c}}function jmh({operationContext:e,streamFormat:t,response:r,context:i,responseBreadcrumbs:n,source:a,namespace:o,statusCode:c}){let d=Bn(r)?i.resolveResponseReference(r):r;if(d.content!=null&&Object.entries(d.content).find(([p,_])=>{if(_.schema==null)return!1;let h=Bn(_.schema)?i.resolveSchemaReference(_.schema):_.schema;return h.type==="string"&&h.format==="binary"}))return i.options.useBytesForBinaryResponse&&t==null?R0.bytes({description:d.description,source:a,statusCode:c}):R0.file({description:d.description,source:a,statusCode:c});let s=bmh(d.content??{},i);if(s!=null&&t!=null)switch(t){case"json":return R0.streamingJson({statusCode:c,description:d.description,responseProperty:Ei(e.operation,xi.RESPONSE_PROPERTY),fullExamples:s.examples,schema:kl(s.schema,!1,!1,i,n,a,o),source:a});case"sse":return R0.streamingSse({description:d.description,responseProperty:void 0,fullExamples:s.examples,schema:kl(s.schema,!1,!1,i,n,a,o),source:a,statusCode:c})}let u=Obu({context:i,content:d.content??{}});if(u){if(t!=null)switch(t){case"json":return R0.streamingJson({description:d.description,responseProperty:void 0,fullExamples:u.examples,schema:kl(u.schema,!1,!1,i,n,a,o),source:a,statusCode:c});case"sse":return R0.streamingSse({description:d.description,responseProperty:void 0,fullExamples:u.examples,schema:kl(u.schema,!1,!1,i,n,a,o),source:a,statusCode:c})}return R0.json({description:d.description,schema:kl(u.schema,!1,!1,i,n,a,o),responseProperty:Ei(e.operation,xi.RESPONSE_PROPERTY),fullExamples:u.examples,source:a,statusCode:c})}for(let[l,p]of Object.entries(d.content??{})){let _=tm.parse(l);if(_!=null){if(_.isOctetStream()||_.isPDF()||_.isAudio()||_.isImage()||_.isVideo()||_.isMultiPartMixed())return R0.file({description:d.description,source:a,statusCode:c});if(_.isPlainText()){let h=p.schema;if(h==null)return R0.text({description:d.description,source:a,statusCode:c});let y=Bn(h)?i.resolveSchemaReference(h):h;return y.type==="string"&&y.format==="byte"?R0.file({description:d.description,source:a,statusCode:c}):R0.text({description:d.description,source:a,statusCode:c})}}}}function FxD({responses:e,context:t,source:r,namespace:i}){let n={};for(let[a,o]of Object.entries(e)){if(a==="default")continue;let c=parseInt(a);if(c<400||c>600)continue;let d=Bn(o)?t.resolveResponseReference(o):o,s=vmh(d.content??{},t),u=X7c[c];if(u==null){t.logger.warn(`No error name found for status code ${a}`);continue}n[c]={statusCode:c,nameOverride:void 0,generatedName:u,description:d.description,schema:kl(s?.schema??{},!1,!1,t,[u,"Body"],r,i),fullExamples:s?.examples,source:r}}return n}function PUi({operationContext:e,context:t,responseStatusCode:r,suffix:i,streamFormat:n,source:a}){let{document:o,operation:c,path:d,method:s,baseBreadcrumbs:u}=e,l=Ei(c,xi.IDEMPOTENT),p=Ei(c,[xi.REQUEST_NAME_V1,xi.REQUEST_NAME_V2]),_=[...u,"Request"],h=vbu({parameters:[...e.pathItemParameters,...e.operationParameters],context:t,requestBreadcrumbs:_,path:d,httpMethod:s,source:a}),y=/{([^}]+)}/g,b=[...d.matchAll(y)].map(B=>B[1]).filter(B=>B!==void 0),v=[...d.matchAll(y)].map(B=>B[1]);switch(t.options.pathParameterOrder){case an.PathParameterOrder.SpecOrder:{let B=v.filter(T=>!h.pathParameters.some(R=>R.name===T));if(B.length>0)for(let T of B)h.pathParameters.push({name:T??"",variableReference:void 0,parameterNameOverride:void 0,availability:void 0,source:a,schema:ai.primitive({schema:kn.string({default:void 0,example:void 0,format:void 0,maxLength:void 0,minLength:void 0,pattern:void 0}),description:void 0,generatedName:"",nameOverride:void 0,namespace:void 0,groupName:void 0,availability:void 0,title:void 0}),description:void 0,explode:void 0})}break;case an.PathParameterOrder.UrlOrder:if(b.length>0){let B=new Map(h.pathParameters.map(q=>[q.name,q])),T=[],R=new Set;for(let q of b){let z=B.get(q);R.add(q),z?T.push(z):T.push({name:q,variableReference:void 0,parameterNameOverride:void 0,availability:void 0,source:a,schema:ai.primitive({schema:kn.string({default:void 0,example:void 0,format:void 0,maxLength:void 0,minLength:void 0,pattern:void 0}),description:void 0,generatedName:"",nameOverride:void 0,namespace:void 0,groupName:void 0,availability:void 0,title:void 0}),description:void 0,explode:void 0})}for(let q of h.pathParameters)R.has(q.name)||T.push(q);h.pathParameters=T}break;default:vt(t.options.pathParameterOrder)}let g=(()=>{if(e.method==="GET")return[void 0];if(!c.requestBody)return[void 0];let B=Bn(c.requestBody)?t.resolveRequestBodyReference(c.requestBody):c.requestBody,T=Object.values(B.content).every(q=>UxD({mediaTypeObject:q})!=null),R=[];if(T)return R.push(...Object.entries(B.content).map(([q,z])=>{let N=YYt({mediaType:q,mediaTypeObject:z,description:B.description,document:o,context:new zvn({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:_,source:a,namespace:t.namespace});return wmh({context:t,convertedParameters:h})&&N!=null&&(N.type==="json"||N.type==="formUrlEncoded")&&N.schema.type!=="object"&&c.requestBody!=null?N=YYt({mediaType:q,mediaTypeObject:z,description:B.description,document:o,context:t,requestBreadcrumbs:[..._,"Body"],source:a,namespace:t.namespace}):c.requestBody!=null&&(N=YYt({mediaType:q,mediaTypeObject:z,description:B.description,document:o,context:t,requestBreadcrumbs:[..._],source:a,namespace:t.namespace})),N}).filter(q=>q!=null)),R.length===0?[void 0]:R;{let q=Abu({content:B.content,description:B.description,document:o,context:new zvn({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:_,source:a,namespace:t.namespace});return wmh({context:t,convertedParameters:h})&&q!=null&&(q.type==="json"||q.type==="formUrlEncoded")&&q.schema.type!=="object"&&c.requestBody!=null?q=Abu({content:B.content,description:B.description,document:o,context:t,requestBreadcrumbs:[..._,"Body"],source:a,namespace:t.namespace}):c.requestBody!=null&&(q=Abu({content:B.content,description:B.description,document:o,context:t,requestBreadcrumbs:[..._],source:a,namespace:t.namespace})),[q]}})(),m=g.length>1,O=[...u,"Response"],A=Pbu({operationContext:e,streamFormat:n,responses:c.responses,context:t,responseBreadcrumbs:O,responseStatusCode:r,source:a}),j=_mh(c),M=pmh(c),w=dmh(e,c,t),D=Ei(c,xi.SERVER_NAME_V2);return g.map(B=>({summary:c.summary,internal:Ei(c,gL.INTERNAL),idempotent:l,audiences:Ei(c,xi.AUDIENCES)??[],operationId:c.operationId!=null&&i!=null?c.operationId+"_"+i:c.operationId,tags:t.resolveTagsToTagIds(c.tags),namespace:t.namespace,sdkName:LxD({operationContext:e,request:B}),pathParameters:h.pathParameters,queryParameters:h.queryParameters,headers:h.headers,requestNameOverride:p??void 0,generatedRequestName:jC(m?QxD({breadcrumbs:_,request:B}):_,t.options.preserveSchemaIds),request:B,response:A.value,errors:A.errors,servers:D!=null?[{name:D,url:void 0,audiences:void 0}]:(c.servers??[]).map(T=>bbu(T,{groupMultiApiEnvironments:t.options.groupMultiApiEnvironments})),description:c.description,authed:WxD(c,o),security:VxD(c),availability:M,method:s,path:d,examples:w,pagination:e.pagination,source:a,retries:j}))}function QxD({breadcrumbs:e,request:t}){return t?[...e,t.type]:e}function UxD({mediaTypeObject:e}){return Ei(e,xi.SDK_METHOD_NAME)}function LxD({operationContext:e,request:t}){return!t||!t.sdkMethodName?e.sdkMethodName:e.sdkMethodName?{groupName:[...e.sdkMethodName.groupName],methodName:t.sdkMethodName??e.sdkMethodName.methodName}:{groupName:[],methodName:t.sdkMethodName}}function VxD(e){return e.security}function WxD(e,t){return e.security!=null?Object.keys(e.security).length>0:t.security!=null?Object.keys(t.security).length>0:!1}function wmh({context:e,convertedParameters:t}){return e.options.inlinePathParameters&&t.pathParameters.length>0||t.queryParameters.length>0||t.headers.length>0}function Smh({operationContext:e,context:t,asyncExtension:r,source:i}){let{operation:n,pathItemParameters:a,operationParameters:o}=e,c=r.discriminant.name,d=r.discriminant.value,s=r["response-status-code"],u=Emh({context:t,headerToIgnore:c,parameters:a}),l=Emh({context:t,headerToIgnore:c,parameters:o}),p=PUi({operationContext:{...e,pathItemParameters:u,operationParameters:l,operation:{...n,responses:Object.fromEntries(Object.entries(n.responses).filter(([h])=>parseInt(h)!==s))}},context:t,streamFormat:void 0,source:i}),_=PUi({operationContext:{...e,pathItemParameters:u,operationParameters:l,baseBreadcrumbs:[...e.baseBreadcrumbs,"async"]},context:t,suffix:"async",responseStatusCode:s,streamFormat:void 0,source:i});return _.forEach(h=>{h.headers.push({name:c,schema:ai.literal({nameOverride:void 0,generatedName:jC([c],t.options.preserveSchemaIds),title:void 0,description:void 0,availability:void 0,value:nE.string(d),namespace:void 0,groupName:void 0}),description:void 0,parameterNameOverride:void 0,env:void 0,availability:void 0,source:i})}),{sync:p,async:_}}function Emh({context:e,headerToIgnore:t,parameters:r}){return r.filter(i=>{let n=Bn(i)?e.resolveParameterReference(i):i;return!(n.in==="header"&&n.name===t)})}var Z7c="stream";function Imh({operationContext:e,context:t,streamingExtension:r}){switch(r.type){case"stream":return{streaming:PUi({operationContext:e,context:t,streamFormat:r.format,source:t.source}),nonStreaming:[]};case"streamCondition":{let i=Mmh({context:t,operation:e.operation,streamingExtension:r,isStreaming:!0});if(i?.schemaReference!=null){let s=XJi(i.schemaReference);s!=null&&t.excludeSchema(s)}let n=Dmh({operation:e.operation,response:r.responseStream}),a=PUi({operationContext:{...e,sdkMethodName:e.sdkMethodName!=null?{groupName:e.sdkMethodName.groupName,methodName:e.sdkMethodName.methodName+"_"+Z7c}:void 0,operation:{...e.operation,description:r.streamDescription??e.operation.description,requestBody:i?.requestBody,responses:n},baseBreadcrumbs:[...e.baseBreadcrumbs,Z7c]},context:t,streamFormat:r.format,suffix:Z7c,source:t.source});a.forEach(s=>{s.examples=s.examples.filter(u=>Bmh(u,t)!==!1)});let o=Mmh({context:t,operation:e.operation,streamingExtension:r,isStreaming:!1}),c=Dmh({operation:e.operation,response:r.response}),d=PUi({streamFormat:void 0,operationContext:{...e,operation:{...e.operation,requestBody:o?.requestBody,responses:c}},context:t,source:t.source});return d.forEach(s=>{s.examples=s.examples.filter(u=>Bmh(u,t)!==!0)}),{streaming:a,nonStreaming:d}}default:vt(r)}}function Mmh({context:e,operation:t,streamingExtension:r,isStreaming:i}){if(t.requestBody==null)return;let n=Bn(t.requestBody)?e.resolveRequestBodyReference(t.requestBody):t.requestBody,a=Obu({content:n.content,context:e});if(a==null)return;let o=Bn(a.schema)?e.resolveSchemaReference(a.schema):a.schema;if(o.allOf==null&&o.properties==null)return;let c=o.properties?.[r.streamConditionProperty];c!=null&&Bn(c)&&(c=void 0);let d={...o,properties:{...o.properties,[r.streamConditionProperty]:{type:"boolean","x-fern-boolean-literal":i,...c??{}}},title:void 0,required:[...o.required??[],r.streamConditionProperty]};return{requestBody:{content:{[tm.APPLICATION_JSON]:{schema:d}}},schemaReference:Bn(a.schema)?a.schema:void 0}}function Dmh({operation:e,response:t}){return{...e.responses,200:{description:"",content:{[tm.APPLICATION_JSON]:{schema:t}}}}}function Bmh(e,t){return e._visit({unknown:r=>{let i=cI.serialization.ExampleEndpointCallSchema.parse(r);if(i.ok&&i.value.response!=null)return i.value.response.stream!=null},full:()=>{},_other:()=>{}})}var Cmh=require("crypto");function qmh({context:e,operationContext:t,source:r}){let{document:i,operation:n,path:a,method:o,baseBreadcrumbs:c,sdkMethodName:d}=t,s=[...c,"Payload"],u=[...c,"Response"],l=vbu({parameters:[...t.pathItemParameters,...t.operationParameters],context:e,requestBreadcrumbs:s,path:a,httpMethod:o,source:r});if(n.requestBody==null)return e.logger.error(`Skipping webhook ${o.toUpperCase()} ${a}: Missing a request body`),[];let p=n.operationId??xxD({path:a,method:o,sdkMethodName:d}),_=n.responses?Pbu({operationContext:t,streamFormat:void 0,responses:n.responses,context:e,responseBreadcrumbs:u,source:r}):void 0;if(o!=="POST"&&o!=="GET")return e.logger.error(`Skipping webhook ${o.toUpperCase()} ${a}: Not POST or GET`),[];let h=Bn(n.requestBody)?e.resolveRequestBodyReference(n.requestBody):n.requestBody;return Object.entries(h.content).map(([y,b])=>YYt({mediaType:y,mediaTypeObject:b,description:h.description,document:i,context:e,requestBreadcrumbs:[...c,"Payload"],source:r,namespace:e.namespace})).filter(y=>y!=null).map(y=>{if(y==null||y.type!=="json"&&y.type!=="formUrlEncoded"&&y.type!=="multipart"){e.logger.error(`Skipping webhook ${a} because non-json, non-formUrlEncoded, and non-multipart request body`);return}let b,v;return y.type==="multipart"?(b={name:y.name,properties:y.properties,description:y.description,source:y.source},v=ai.unknown({nameOverride:void 0,generatedName:jC(s,e.options.preserveSchemaIds),title:void 0,description:y.description,availability:void 0,namespace:e.namespace,groupName:void 0,example:void 0})):v=y.schema,{summary:n.summary,audiences:Ei(n,xi.AUDIENCES)??[],sdkName:d,namespace:e.namespace,method:o,operationId:p,tags:e.resolveTagsToTagIds(n.tags),headers:l.headers,generatedPayloadName:jC(s,e.options.preserveSchemaIds),payload:v,multipartFormData:b,response:_?.value,description:n.description,examples:GxD(y.type==="multipart"?void 0:y.fullExamples),source:r}}).filter(y=>y!=null)}function GxD(e){if(e==null)return[];let t=[];for(let r of e){let i=kJi(r.value);i!=null&&t.push({description:r.description,name:r.name,payload:i})}return t}function xxD({path:e,method:t,sdkMethodName:r}){let i=r?.methodName??HxD(e),n=(0,Cmh.createHash)("sha256").update(e).digest("hex").slice(0,8);return KxD(`${i}_${t.toLowerCase()}_${n}`)}function HxD(e){return e.replace(/[{$}#]/g,"").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").replace(/_+/g,"_").toLowerCase().slice(0,64)}function KxD(e){return e.split("_").map((t,r)=>r===0?t.toLowerCase():t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}function k7c({context:e,pathItemContext:t,operation:r,convertToWebhook:i}){let n=Ei(r,xi.IGNORE);if(n!=null&&n){e.logger.debug(`${t.method.toUpperCase()} ${t.path} is marked with x-fern-ignore. Skipping.`);return}let a=JxD(r,e),o=imh(e.document,r),c={...t,sdkMethodName:a,baseBreadcrumbs:$xD({operation:r,sdkMethodName:a,httpMethod:t.method,path:t.path,shouldUseIdiomaticRequestNames:e.options.shouldUseIdiomaticRequestNames}),operation:r,operationParameters:r.parameters??[],pagination:o};if(i)return{type:"webhook",value:qmh({context:e,operationContext:c,source:e.source})};let d=tmh(r);if(d!=null){let l=Imh({context:e,operationContext:c,streamingExtension:d});return l!=null?{type:"streaming",streaming:l.streaming,nonStreaming:l.nonStreaming}:void 0}let s=kOh(r);if(s!=null){let l=Smh({context:e,operationContext:c,asyncExtension:s,source:e.source});return{type:"async",async:l.async,sync:l.sync}}return{type:"http",value:PUi({context:e,operationContext:c,streamFormat:void 0,source:e.source})}}function JxD(e,t){let r=Ei(e,xi.SDK_METHOD_NAME),i=Ei(e,xi.SDK_GROUP_NAME)??[];if(r!=null){let n=typeof i=="string"?[i]:i;return n=t.resolveGroupName(n),{groupName:n,methodName:r}}}function $xD({sdkMethodName:e,operation:t,httpMethod:r,path:i,shouldUseIdiomaticRequestNames:n}){let a=[];if(e!=null){if(n&&a.push(e.methodName),e.groupName.length>0){let o=e.groupName[e.groupName.length-1];o!=null&&a.push(typeof o=="string"?o:o.name)}n||a.push(e.methodName)}else t.operationId!=null?a.push(t.operationId):a.push(ou(`${r}_${i.split("/").join("_")}`));return a}function Tmh(e,t,r,i){let n=[],a=zmh(t),o={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let c of a){if(i.filter.skipEndpoint({method:c.method,path:e})){i.logger.debug(`Skipping endpoint "${c.method} ${e}"`);continue}let d=YxD({operation:c.operation}),s=k7c({context:i,pathItemContext:{...o,method:c.method},operation:c.operation,convertToWebhook:d});s&&n.push(s)}return n}function Rmh(e,t,r,i){let n=[],a=zmh(t),o={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let c of a){if(i.filter.skipEndpoint({method:c.method,path:e})){i.logger.debug(`Skipping endpoint "${c.method} ${e}"`);continue}let d=k7c({context:i,pathItemContext:{...o,method:c.method},operation:c.operation,convertToWebhook:!0});d&&n.push(d)}return n}function zmh(e){let t=[];return e.get!=null&&t.push({method:wF.Get,operation:e.get}),e.post!=null&&t.push({method:wF.Post,operation:e.post}),e.put!=null&&t.push({method:wF.Put,operation:e.put}),e.delete!=null&&t.push({method:wF.Delete,operation:e.delete}),e.patch!=null&&t.push({method:wF.Patch,operation:e.patch}),e.head!=null&&t.push({method:wF.Head,operation:e.head}),t}function YxD({operation:e}){return Ei(e,[xi.WEBHOOK])??!1}function Nmh(e){let t=Ei(e,xi.BASIC_AUTH_USERNAME_VARIABLE_NAME),r=Ei(e,xi.BASIC_AUTH_PASSWORD_VARIABLE_NAME);return{usernameVariable:t,passwordVariable:r}}function Fmh(e){return Ei(e,xi.FERN_BASIC_AUTH)}function Umh(e,t,r,i){if(Bn(e)){if(i==null)throw new Error(`Converting referenced security schemes requires context: ${JSON.stringify(e)}`);let n=i.resolveSecuritySchemeReference(e);return Qmh(n,t,r)}return Qmh(e,t,r)}function Qmh(e,t,r){try{if(e.type==="apiKey"&&e.in==="header"){let i=Ei(e,gL.BEARER_FORMAT),n=Ei(e,xi.FERN_HEADER_AUTH);return AF.header({headerName:e.name,prefix:i!=null?"Bearer":n?.prefix,headerVariableName:n?.name??Ei(e,xi.HEADER_VARIABLE_NAME),headerEnvVar:n?.env})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="bearer"){let i=Ei(e,xi.FERN_BEARER_TOKEN);return AF.bearer({tokenVariableName:i?.name??Ei(e,xi.BEARER_TOKEN_VARIABLE_NAME),tokenEnvVar:i?.env})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="basic"){let i=Fmh(e),n=Nmh(e);return AF.basic({usernameVariableName:i?.username?.name??n.usernameVariable,usernameEnvVar:i?.username?.env,passwordVariableName:i?.password?.name??n.passwordVariable,passwordEnvVar:i?.password?.env})}else{if(e.type==="openIdConnect")return AF.bearer({tokenVariableName:void 0,tokenEnvVar:void 0});if(e.type==="oauth2")return AF.oauth({scopesEnum:XxD(e,t)})}}catch(i){r.logger.debug(`Error converting security scheme: ${i?.message}`)}r.logger.debug(`Skipping security scheme: ${JSON.stringify(e,null)} - not currently supported. Please reach out to Fern support team!`)}function XxD(e,t){let r=e.flows.authorizationCode?.scopes??e.flows.clientCredentials?.scopes??e.flows.implicit?.scopes??e.flows.password?.scopes;if(r!=null){let i=YJi({nameOverride:void 0,generatedName:"OauthScope",title:void 0,enumValues:Object.keys(r),fernEnum:Object.fromEntries(Object.entries(r).map(([a,o])=>[a,{description:o}])),_default:void 0,description:void 0,availability:void 0,enumVarNames:void 0,wrapAsOptional:!1,wrapAsNullable:!1,namespace:void 0,groupName:void 0,context:void 0,source:t,inline:void 0}),n=Um(i);if(n.type==="enum")return n}}function Lmh(e){return Ei(e,xi.BASE_PATH)}var ZxD=Qt.record(Qt.string(),Qt.object({summary:Qt.string().optional(),description:Qt.string().optional()}));function Vmh({document:e,context:t}){return GKa(e,xi.GROUPS,ZxD,t.logger)}function Wmh({context:e,document:t}){return Ei(t,xi.FERN_VERSION)??void 0}function Gmh(e){let t=Ei(e,xi.FERN_GLOBAL_HEADERS),r=[];for(let i of t??[])r.push({...i,schema:i.type!=null?xKa({fernType:i.type,description:void 0,availability:void 0,generatedName:i.name??i.header,title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}function xmh(e){let t=Ei(e,xi.FERN_IDEMPOTENCY_HEADERS),r=[];for(let i of t??[])r.push({...i,schema:i.type!=null?xKa({fernType:i.type,description:void 0,availability:void 0,generatedName:i.name??i.header,title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}function Hmh(e,t){let r=Ei(e,xi.SDK_VARIABLES);return r==null?{}:Object.fromEntries(Object.entries(r).map(([i,n])=>{if(n.type==="string")return[i,{nameOverride:void 0,generatedName:jC([i],t),title:n.title,schema:Uh.string({default:qua(n),pattern:n.pattern,format:n.format,minLength:n.minLength,maxLength:n.maxLength}),description:n.description,availability:void 0,namespace:void 0,groupName:void 0}];throw new Error(`Variable ${i} has unsupported schema ${JSON.stringify(n)}`)}))}var kxD="webhooks";function Kmh(e){return Ei(e,kxD)??{}}var ZKa=class extends Fua{nonRequestReferencedSchemas=new Set;twoOrMoreRequestsReferencedSchemas=new Set;singleRequestReferencedSchemas=new Set;discriminatedUnionReferences={};discriminatedUnionMetadata={};schemasToExclude=new Set;constructor({document:t,taskContext:r,authHeaders:i,options:n,source:a,namespace:o}){super({document:t,taskContext:r,authHeaders:i,options:n,source:a,namespace:o})}getDummy(){return new zvn({document:this.document,taskContext:this.taskContext,options:this.options,source:this.source,namespace:this.namespace})}markSchemaAsReferencedByNonRequest(t){this.nonRequestReferencedSchemas.add(t)}markSchemaAsReferencedByRequest(t){this.singleRequestReferencedSchemas.has(t)?this.twoOrMoreRequestsReferencedSchemas.add(t):this.singleRequestReferencedSchemas.add(t)}getReferencedSchemas(){return new Set([...this.nonRequestReferencedSchemas,...this.twoOrMoreRequestsReferencedSchemas])}markReferencedByDiscriminatedUnion(t,r,i){let n=this.discriminatedUnionReferences[t.$ref];n!=null?(n.discriminants.add(r),n.numReferences+=i):this.discriminatedUnionReferences[t.$ref]={discriminants:new Set([r]),numReferences:i}}getReferencesFromDiscriminatedUnion(t){return this.discriminatedUnionReferences[t.$ref]}markSchemaWithDiscriminantValue(t,r,i){let n=this.discriminatedUnionMetadata[t.$ref];n!=null?n.discriminants.set(r,i):this.discriminatedUnionMetadata[t.$ref]={discriminants:new Map([[r,i]])}}getDiscriminatedUnionMetadata(t){return this.discriminatedUnionMetadata[t.$ref]}excludeSchema(t){this.schemasToExclude.add(t)}isSchemaExcluded(t){return this.schemasToExclude.has(t)}};function Jmh(e){return Ei(e,xi.RESOLUTIONS)}function $mh({openapi:e}){let t=Jmh(e);if(t==null)return e;let r={};for(let i of t){let n=`#/components/schemas/${i.name}`;for(let a of i.resolutions)e=eHD({openapi:e,schemaReference:a,schemaName:i.name}),e=Ymh({openapi:e,replaceReference:a,schemaReference:n,replacedReferences:r}),r={...r,...Object.fromEntries(i.resolutions.map(o=>[n,o]))}}return e}function eHD({openapi:e,schemaReference:t,schemaName:r}){let i=t.replace("#/","").split("/").map(a=>a.replaceAll("~1","/")),n=e;for(let a of i){let o=n[a];if(o==null)return e;n=o}return e.components==null&&(e.components={}),e.components.schemas==null&&(e.components.schemas={}),e.components.schemas[r]=n,e}function Ymh({openapi:e,replaceReference:t,schemaReference:r,replacedReferences:i}){let n=Object.keys(i).filter(d=>t.startsWith(d)).sort((d,s)=>s.length-d.length)[0];if(n!=null){let d=i[n];if(d!=null){let s=r.replace(n,d);return Ymh({openapi:e,replaceReference:t,schemaReference:s,replacedReferences:{}})}}let a=t.replace("#/","").split("/").map(d=>d.replaceAll("~1","/")),o=e;for(let d of a.slice(0,-1)){let s=o[d];if(s==null)return e;o=s}let c=a[a.length-1];return c==null||(o[c]={$ref:r}),e}function Zmh({openApi:e,taskContext:t,options:r,source:i,namespace:n}){e=$mh({openapi:e});let a=new ZKa({document:e,taskContext:t,authHeaders:new Set,options:r,source:i,namespace:n}),o=Object.fromEntries(Object.entries(e.components?.securitySchemes??{}).map(([B,T])=>{let R=Umh(T,i,t,a);return R==null?null:[B,R]}).filter(B=>B!==null)),c=e.security?.filter(B=>B!=null),d=new Set(...Object.entries(o).map(([B,T])=>T.type==="basic"||T.type==="bearer"?"Authorization":T.type==="header"?T.headerName:null)),s=Hmh(e,r.preserveSchemaIds),u=Gmh(e),l=xmh(e),p=r.audiences??[],_=[],h=[],y=new ZKa({document:e,taskContext:t,authHeaders:d,options:r,source:i,namespace:n});y.filter.hasEndpoints()&&t.logger.debug("Endpoint filter applied..."),Object.entries(e.paths??{}).forEach(([B,T])=>{if(T==null)return;let R=Tmh(B,T,e,y);for(let q of R){let z=Xmh({operation:q});if(!(p.length>0&&!p.some(N=>z.includes(N))))switch(q.type){case"async":_.push(...q.sync),_.push(...q.async);break;case"http":_.push(...q.value);break;case"streaming":_.push(...q.streaming),q.nonStreaming&&_.push(...q.nonStreaming);break;case"webhook":h.push(...q.value);break;default:vt(q)}}}),Object.entries(Kmh(e)).forEach(([B,T])=>{if(T==null)return;t.logger.debug(`Converting path ${B}`);let R=Rmh(B,T,e,y);for(let q of R){let z=Xmh({operation:q});p.length>0&&!p.some(N=>z.includes(N))||h.push(...q.value)}});let b=Object.fromEntries(Object.entries(e.components?.schemas??{}).map(([B,T])=>{let R=Ei(T,xi.SDK_NAMESPACE);if(!Bn(T)){let q=Ei(T,xi.IGNORE);if(q!=null&&q)return[];if(Pmh.has(B))return[B,kl({...T,"x-fern-type-name":`${B}Body`},!1,!1,y,[B],i,R??n)]}return[B,kl(T,!1,!1,y,[B],i,R??n)]}).filter(B=>B.length>0)),v=tHD(b,y,i),g=rHD(v,y),m={};for(let[B,T]of Object.entries(g)){let R=Um(T);y.isSchemaExcluded(B)||(m[B]=R)}let O=new e$i(g,y.nonRequestReferencedSchemas,y),A=h.map(B=>{let R=B.examples;if(!r.disableExamples&&R.length===0){let q=O.buildExample({schema:B.payload,exampleId:void 0,example:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});q!=null&&(R=[{name:void 0,description:void 0,payload:q}])}return{...B,payload:Um(B.payload),examples:R}}),j=new cbu(g,y,u),M=_.map(B=>{let T=B.examples,R=T;if(!r.disableExamples&&(T.length===0||T.every($Ka))){let N=j.buildEndpointExample(B);N.length>0&&(R=[...N,...T.filter(H=>!$Ka(H))])}let q=B.request,z=B.response;return{...B,request:q?.type==="json"||q?.type==="formUrlEncoded"?{...q,schema:Um(q.schema)}:q,response:z?.type==="json"?{...z,schema:Um(z.schema)}:z,queryParameters:B.queryParameters.map(N=>({description:N.description,name:N.name,schema:Um(N.schema),parameterNameOverride:N.parameterNameOverride,availability:N.availability,source:N.source})),pathParameters:B.pathParameters.map(N=>({description:N.description,name:N.name,schema:Um(N.schema),parameterNameOverride:N.parameterNameOverride,variableReference:N.variableReference,availability:N.availability,source:N.source})),headers:B.headers.map(N=>({description:N.description,name:N.name,schema:Um(N.schema),parameterNameOverride:N.parameterNameOverride,env:N.env,availability:N.availability,source:N.source})),examples:R,errors:nn(B.errors,N=>{let H=N.fullExamples?.map($=>{let de=kJi($.value);if(de!=null)return{name:$.name,description:$.description,example:de}}).filter(us);if(H?.length===0){let $=O.buildExample({schema:N.schema,example:void 0,exampleId:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});$!=null&&H.push({name:void 0,description:void 0,example:$})}return{generatedName:N.generatedName,nameOverride:N.nameOverride,schema:Um(N.schema),description:N.description,source:N.source,examples:H}}),retries:B.retries}});j.finalize();let w=Vmh({document:e,context:y});return{apiVersion:Wmh({context:y,document:e}),basePath:Lmh(e),title:e.info.title??"",description:e.info.description,groups:Object.fromEntries(Object.entries(w??{}).map(([B,T])=>[B,{summary:T.summary??void 0,description:T.description??void 0}])),servers:(e.servers??[]).map(B=>bbu(B,{groupMultiApiEnvironments:r.groupMultiApiEnvironments})),websocketServers:[],tags:{tagsById:Object.fromEntries((e.tags??[]).map(B=>[B.name,{id:B.name,description:B.description}])),orderedTagIds:e.tags?.map(B=>B.name)},endpoints:M,webhooks:A,channels:{},groupedSchemas:Rua(n,m),securitySchemes:o,security:c,hasEndpointsMarkedInternal:M.some(B=>B.internal),nonRequestReferencedSchemas:y.getReferencedSchemas(),variables:s,globalHeaders:u,idempotencyHeaders:l}}function tHD(e,t,r){if(t.options.removeDiscriminantsFromSchemas===an.RemoveDiscriminantsFromSchemas.Never)return e;let i={};for(let[n,a]of Object.entries(e)){if(a.type!=="object"){i[n]=a;continue}let o={$ref:`#/components/schemas/${n}`},c=t.getReferencesFromDiscriminatedUnion(o);if(c==null){i[n]=a;continue}if(t.getReferencedSchemas().has(n)){i[n]=a;continue}let s={...a,type:"object",properties:a.properties.filter(l=>!c.discriminants.has(l.key)),allOfPropertyConflicts:a.allOfPropertyConflicts.filter(l=>!c.discriminants.has(l.propertyKey)),source:r};i[n]=s;let u=kmh({schema:a,schemas:e});for(let l of[...new Set(u)]){let p=i[l]??e[l];p==null||p.type!=="object"||(i[l]={...p,type:"object",properties:p.properties.filter(_=>!c.discriminants.has(_.key)),allOfPropertyConflicts:p.allOfPropertyConflicts.filter(_=>!c.discriminants.has(_.propertyKey))})}}return i}function rHD(e,t){let r={};for(let[i,n]of Object.entries(e)){if(n.type!=="object"){r[i]=n;continue}let a={$ref:`#/components/schemas/${i}`},o=t.getDiscriminatedUnionMetadata(a);if(o==null){r[i]=n;continue}let c=[];for(let s of n.properties)if(o.discriminants.has(s.key)){let u=o.discriminants.get(s.key);u!=null&&c.push({...s,schema:ai.literal({nameOverride:void 0,generatedName:jC([n.generatedName,u],t.options.preserveSchemaIds),title:void 0,value:nE.string(u),namespace:void 0,groupName:void 0,description:void 0,availability:n.availability})})}else c.push(s);let d={...n,type:"object",properties:c};r[i]=d}return r}function kmh({schema:e,schemas:t}){let r=[];for(let i of e.allOf){r.push(i.schema);let n=t[i.schema];n!=null&&n.type==="object"&&r.push(...kmh({schema:n,schemas:t}))}return r}function jbu(e){return[...new Set(e)]}function Xmh({operation:e}){let t=[];switch(e.type){case"async":t=jbu(e.async.flatMap(r=>r.audiences));break;case"http":t=jbu(e.value.flatMap(r=>r.audiences));break;case"streaming":t=jbu(e.streaming.flatMap(r=>r.audiences));break;case"webhook":t=jbu(e.value.flatMap(r=>r.audiences));break;default:vt(e)}return t}function Nvn({context:e,documents:t,options:r}){let i={apiVersion:void 0,title:void 0,description:void 0,basePath:void 0,servers:[],websocketServers:[],tags:{tagsById:{},orderedTagIds:void 0},hasEndpointsMarkedInternal:!1,endpoints:[],webhooks:[],channels:{},groupedSchemas:{rootSchemas:{},namespacedSchemas:{}},variables:{},nonRequestReferencedSchemas:new Set,securitySchemes:{},security:void 0,globalHeaders:[],idempotencyHeaders:[],groups:{}},n=0;for(let a of t)try{let o=a.source!=null?a.source:SW.openapi({file:"<memory>"});switch(a.type){case"openapi":{let c=Zmh({taskContext:e,openApi:a.value,options:rSe({options:a.settings,overrides:r}),source:o,namespace:a.namespace});i=oHD(i,c,rSe({options:a.settings,overrides:r})),n++;break}case"asyncapi":{let c=ZOh({document:a.value,taskContext:e,options:rSe({options:a.settings,overrides:r}),source:o,asyncApiOptions:iHD({options:a.settings}),namespace:a.namespace});c.servers!=null&&(i.websocketServers=[...i.websocketServers,...c.servers.map(d=>({...d,audiences:void 0,description:void 0}))]),c.channels!=null&&(i.channels={...i.channels,...c.channels}),c.groupedSchemas!=null&&(i.groupedSchemas=wbu(i.groupedSchemas,c.groupedSchemas)),c.basePath!=null&&(i.basePath=c.basePath),n++;break}default:vt(a)}}catch(o){e.logger.debug(`Skipping parsing document ${a.type==="openapi"?a.value.info?.title:a.source?.file}`),o instanceof Error&&e.logger.debug(o.message,o.stack?`
1525
1525
  `+o.stack:"")}return i}function iHD({options:e,overrides:t}){return{naming:t?.naming??e?.asyncApiNaming??yOh.naming}}function Ebu(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 nHD(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 eKc(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 aHD(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=Ebu(a);r.set(o,a.url)}let i=!0,n=!0;for(let a of t){let o=Ebu(a),c=r.get(o);c?c===a.url&&(n=!1):i=!1}return i&&n}function eAh(e){if(e.length===0||!e[0])return"api";let t=e[0].url;return nHD(t)}function oHD(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:wbu(e.groupedSchemas,t.groupedSchemas),variables:{...e.variables,...t.variables},nonRequestReferencedSchemas:new Set([...e.nonRequestReferencedSchemas,...t.nonRequestReferencedSchemas]),securitySchemes:{...e.securitySchemes,...t.securitySchemes},security:eKc(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(aHD(e.servers,t.servers)){let a=[],o=[],c=eAh(e.servers),d=eAh(t.servers),s=new Map;for(let p of e.servers){let _=Ebu(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 _=Ebu(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}]})),l=t.endpoints.map(p=>({...p,type:"multi-api",apiName:d,servers:[{name:d,url:void 0,audiences:void 0}]}));return o=[...u,...l],{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,...g}=p;return{...g,__apiName:b,servers:v}}let{type:_,...h}=p;return h}),webhooks:[...e.webhooks,...t.webhooks],channels:{...e.channels,...t.channels},groupedSchemas:wbu(e.groupedSchemas,t.groupedSchemas),variables:{...e.variables,...t.variables},nonRequestReferencedSchemas:new Set([...e.nonRequestReferencedSchemas,...t.nonRequestReferencedSchemas]),securitySchemes:{...e.securitySchemes,...t.securitySchemes},security:eKc(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:wbu(e.groupedSchemas,t.groupedSchemas),variables:{...e.variables,...t.variables},nonRequestReferencedSchemas:new Set([...e.nonRequestReferencedSchemas,...t.nonRequestReferencedSchemas]),securitySchemes:{...e.securitySchemes,...t.securitySchemes},security:eKc(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 wbu(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 fBh=ue(gmu(),1),Omu={config:new fBh.Config({apis:{},styleguide:{plugins:[Q7c],rules:{struct:"warn"}}},void 0),dereference:!1,removeUnusedComponents:!1,keepUrlRefs:!1};function T8t({options:e,overrides:t}={}){return{...rSe({options:e,overrides:t}),...Evn({options:e,overrides:t})}}var JpB={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 $pB(e,t,r){r!==void 0&&(e[t]=r)}function mmu(e){let t={};if(e!=null)for(let[r,i]of Object.entries(JpB)){let n=e[r],a=Array.isArray(i)?i:[i];for(let o of a)$pB(t,o,n)}return T8t({options:t})}function Tsa(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 r$a(e){return e.swagger!=null}function dZc(e){return e.openapi!=null}function M$i(e,t={}){return{...Object.fromEntries(UI(e.namedDefinitionFiles).map(([r,i])=>[r,{...i,defaultUrl:t.defaultURL}])),...UI(e.importedDefinitions).reduce((r,[i,n])=>({...r,...e4a(M$i(n.definition,{defaultURL:n.url}),(a,o)=>VB(i,Vu.of(o)))}),{})}}function i$a(e,t={}){return{...Object.fromEntries(UI(e.packageMarkers).map(([r,i])=>[r,{...i,defaultUrl:t.defaultURL}])),...UI(e.importedDefinitions).reduce((r,[i,n])=>({...r,...e4a(i$a(n.definition,{defaultURL:n.url}),(a,o)=>VB(i,Vu.of(o)))}),{})}}function LUi(e){return{...i$a(e),...M$i(e)}}function fSe(e,t){return LUi(e.definition)[t]?.contents}function SC(e,t){for(let[r,i]of UI(LUi(e.definition)))t(r,i.contents,{isPackageMarker:udn(r)===Xb,defaultUrl:i.defaultUrl})}function cgn(e,t){for(let[r,i]of UI(i$a(e.definition)))t(r,i.contents)}var dBh={None:"none",Header:"header"};var Gmu={};Yt(Gmu,{ConjureAliasDeclaration:()=>Mmu,ConjureArgument:()=>Lmu,ConjureArgumentWithParamType:()=>Umu,ConjureAuthDefinition:()=>Fsa,ConjureAuthDefinitionType:()=>Fmu,ConjureDefinitions:()=>zmu,ConjureEndpointDefinition:()=>Vmu,ConjureEnumDeclaration:()=>Tmu,ConjureEnumVariant:()=>qmu,ConjureEnumWithDocs:()=>Cmu,ConjureObjectDeclaration:()=>Imu,ConjureParamType:()=>Qmu,ConjurePrimitive:()=>Smu,ConjureService:()=>Wmu,ConjureServiceName:()=>Emu,ConjureType:()=>I$i,ConjureTypeDeclaration:()=>Rmu,ConjureTypeReference:()=>C$i,ConjureTypeWithDocs:()=>Dmu,ConjureTypes:()=>Nmu,ConjureUnionDeclaration:()=>Bmu,DefinitionFile:()=>UBh,WithDocs:()=>aXt,commons:()=>bZc,conjure:()=>vZc,services:()=>gZc,types:()=>OZc});var bZc={};Yt(bZc,{WithDocs:()=>aXt});var ea={};Yt(ea,{JsonError:()=>Rsa,ParseError:()=>zsa,any:()=>SBh,bigint:()=>_Bh,boolean:()=>MBh,booleanLiteral:()=>EBh,date:()=>hBh,discriminant:()=>NBh,enum_:()=>Pmu,getObjectLikeUtils:()=>R8t,getObjectUtils:()=>lgn,getSchemaUtils:()=>ej,isProperty:()=>B$i,lazy:()=>yBh,lazyObject:()=>PBh,list:()=>wmu,number:()=>DBh,object:()=>jmu,objectWithoutOptionalProperties:()=>ABh,optional:()=>pZc,property:()=>vBh,record:()=>qBh,set:()=>TBh,string:()=>BBh,stringLiteral:()=>wBh,transform:()=>_Zc,undiscriminatedUnion:()=>zBh,union:()=>QBh,unknown:()=>IBh,withParsedProperties:()=>yZc});var Wh={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 MA(e,t){return`Expected ${t}. Received ${YpB(e)}.`}function YpB(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 DF(e){return{...e,json:pBh(e.json),parse:pBh(e.parse)}}function pBh(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(`
1526
1526
  `)),{ok:!0,value:t}):i}}function Amu(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var Rsa=class e extends Error{errors;constructor(t){super(t.map(Amu).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var zsa=class e extends Error{errors;constructor(t){super(t.map(Amu).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function ej(e){return{optional:()=>pZc(e),transform:t=>_Zc(e,t),parseOrThrow:(t,r)=>{let i=e.parse(t,r);if(i.ok)return i.value;throw new zsa(i.errors)},jsonOrThrow:(t,r)=>{let i=e.json(t,r);if(i.ok)return i.value;throw new Rsa(i.errors)}}}function pZc(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:()=>Wh.OPTIONAL};return{...t,...ej(t)}}function _Zc(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,...ej(r)}}function _Bh(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:MA(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:MA(t,"bigint")}]},getType:()=>Wh.BIGINT};return{...DF(e),...ej(e)}}var XpB=/^([+-]?\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 hBh(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:MA(t,"string")}]}:XpB.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:MA(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:MA(t,"Date object")}]},getType:()=>Wh.DATE};return{...DF(e),...ej(e)}}function NW(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{...DF(r),...ej(r)}}}function Pmu(e){let t=new Set(e);return NW(Wh.ENUM,(i,{allowUnrecognizedEnumValues:n,breadcrumbsPrefix:a=[]}={})=>typeof i!="string"?{ok:!1,errors:[{path:a,message:MA(i,"string")}]}:!t.has(i)&&!n?{ok:!1,errors:[{path:a,message:MA(i,"enum")}]}:{ok:!0,value:i})()}function yBh(e){let t=hZc(e);return{...t,...ej(t)}}function hZc(e){return{parse:(t,r)=>Nsa(e).parse(t,r),json:(t,r)=>Nsa(e).json(t,r),getType:()=>Nsa(e).getType()}}function Nsa(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function n$a(e){return Object.entries(e)}function a$a(e,t){let r=new Set(t);return Object.entries(e).reduce((i,[n,a])=>(r.has(n)&&(i[n]=a),i),{})}function D$i(e){if(typeof e!="object"||e===null)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function o$a(e){return Object.keys(e)}function bBh(e,t){let r=[],i=[];for(let n of e)t(n)?r.push(n):i.push(n);return[r,i]}function R8t(e){return{withParsedProperties:t=>yZc(e,t)}}function yZc(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(!D$i(i))return{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:MA(i,"object")}]};let a=new Set(Object.keys(t)),o=a$a(i,Object.keys(i).filter(c=>!a.has(c)));return e.json(o,n)},getType:()=>e.getType()};return{...r,...ej(r),...R8t(r)}}function vBh(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function B$i(e){return e.isProperty}function jmu(e){let t={_getRawProperties:()=>Object.entries(e).map(([r,i])=>B$i(i)?i.rawKey:r),_getParsedProperties:()=>o$a(e),parse:(r,i)=>{let n={},a=[];for(let[o,c]of n$a(e)){let d=B$i(c)?c.rawKey:o,s=B$i(c)?c.valueSchema:c,u={rawKey:d,parsedKey:o,valueSchema:s};n[d]=u,mBh(s)&&a.push(d)}return gBh({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 n$a(e)){let c=B$i(o)?o.valueSchema:o;mBh(c)&&n.push(a)}return gBh({value:r,requiredKeys:n,getProperty:a=>{let o=e[a];if(o!=null)return B$i(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:()=>Wh.OBJECT};return{...DF(t),...ej(t),...R8t(t),...lgn(t)}}function gBh({value:e,requiredKeys:t,getProperty:r,unrecognizedObjectKeys:i="fail",skipValidation:n=!1,breadcrumbsPrefix:a=[]}){if(!D$i(e))return{ok:!1,errors:[{path:a,message:MA(e,"object")}]};let o=new Set(t),c=[],d={};for(let[s,u]of Object.entries(e)){let l=r(s);if(l!=null){o.delete(s);let p=l.transform(u);p.ok?d[l.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 lgn(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(i,n)=>OBh({extensionKeys:t._getRawProperties(),value:i,transformBase:a=>e.parse(a,n),transformExtension:a=>t.parse(a,n)}),json:(i,n)=>OBh({extensionKeys:t._getParsedProperties(),value:i,transformBase:a=>e.json(a,n),transformExtension:a=>t.json(a,n)}),getType:()=>Wh.OBJECT};return{...r,...ej(r),...R8t(r),...lgn(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:()=>Wh.OBJECT};return{...t,...ej(t),...R8t(t),...lgn(t)}}}}function OBh({extensionKeys:e,value:t,transformBase:r,transformExtension:i}){let n=new Set(e),[a,o]=bBh(o$a(t),s=>n.has(s)),c=r(a$a(t,o)),d=i(a$a(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 mBh(e){return!ZpB(e)}function ZpB(e){switch(e.getType()){case Wh.ANY:case Wh.UNKNOWN:case Wh.OPTIONAL:return!0;default:return!1}}function ABh(e){return jmu(e)}function PBh(e){let t={...hZc(e),_getRawProperties:()=>Nsa(e)._getRawProperties(),_getParsedProperties:()=>Nsa(e)._getParsedProperties()};return{...t,...ej(t),...R8t(t),...lgn(t)}}function wmu(e){let t={parse:(r,i)=>jBh(r,(n,a)=>e.parse(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),json:(r,i)=>jBh(r,(n,a)=>e.json(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),getType:()=>Wh.LIST};return{...DF(t),...ej(t)}}function jBh(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:MA(e,"list"),path:[]}]}}function wBh(e){return NW(Wh.STRING_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:MA(r,`"${e}"`)}]})()}function EBh(e){return NW(Wh.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:MA(r,`${e.toString()}`)}]})()}var SBh=NW(Wh.ANY,e=>({ok:!0,value:e}));var MBh=NW(Wh.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:MA(e,"boolean")}]});var DBh=NW(Wh.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:MA(e,"number")}]});var BBh=NW(Wh.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:MA(e,"string")}]});var IBh=NW(Wh.UNKNOWN,e=>({ok:!0,value:e}));function qBh(e,t){let r={parse:(i,n)=>CBh({value:i,isKeyNumeric:e.getType()===Wh.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()===Wh.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:()=>Wh.RECORD};return{...DF(r),...ej(r)}}function CBh({value:e,isKeyNumeric:t,transformKey:r,transformValue:i,breadcrumbsPrefix:n=[]}){return D$i(e)?n$a(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),l=i(c,s);if(d.ok&&u.ok&&l.ok)return{ok:!0,value:{...d.value,[u.value]:l.value}};let p=[];return d.ok||p.push(...d.errors),u.ok||p.push(...u.errors),l.ok||p.push(...l.errors),{ok:!1,errors:p}},{ok:!0,value:{}}):{ok:!1,errors:[{path:n,message:MA(e,"object")}]}}function TBh(e){let t=wmu(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:MA(i,"Set")}]},getType:()=>Wh.SET};return{...DF(r),...ej(r)}}function zBh(e){let t={parse:(r,i)=>RBh((n,a)=>n.parse(r,a),e,i),json:(r,i)=>RBh((n,a)=>n.json(r,a),e,i),getType:()=>Wh.UNDISCRIMINATED_UNION};return{...DF(t),...ej(t)}}function RBh(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 NBh(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}function QBh(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,i=typeof e=="string"?e:e.parsedDiscriminant,n=Pmu(o$a(t)),a={parse:(o,c)=>FBh({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)=>FBh({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:()=>Wh.UNION};return{...DF(a),...ej(a),...R8t(a)}}function FBh({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:i,getAdditionalPropertiesSchema:n,allowUnrecognizedUnionMembers:a=!1,transformAdditionalProperties:o,breadcrumbsPrefix:c=[]}){if(!D$i(e))return{ok:!1,errors:[{path:c,message:MA(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 l=n(u.value);if(l==null)return a?{ok:!0,value:{[r]:u.value,...s}}:{ok:!1,errors:[{path:[...c,t],message:"Unexpected discriminant value"}]};let p=o(s,l);return p.ok?{ok:!0,value:{[r]:d,...p.value}}:p}var aXt=ea.objectWithoutOptionalProperties({docs:ea.string().optional()});var vZc={};Yt(vZc,{ConjureServiceName:()=>Emu,DefinitionFile:()=>UBh});var Emu=ea.string();var Smu=ea.enum_(["rid","string","safelong","integer","double","boolean","binary"]);var I$i=ea.undiscriminatedUnion([Smu,ea.string()]);var Mmu=ea.objectWithoutOptionalProperties({alias:I$i,docs:ea.string().optional()});var Dmu=ea.objectWithoutOptionalProperties({type:I$i,docs:ea.string().optional()});var C$i=ea.undiscriminatedUnion([I$i,Dmu]);var Bmu=ea.objectWithoutOptionalProperties({union:ea.record(ea.string(),C$i)});var Imu=ea.objectWithoutOptionalProperties({fields:ea.record(ea.string(),C$i)});var Cmu=ea.objectWithoutOptionalProperties({value:ea.string()}).extend(aXt);var qmu=ea.undiscriminatedUnion([ea.string(),Cmu]);var Tmu=ea.objectWithoutOptionalProperties({values:ea.list(qmu)});var Rmu=ea.undiscriminatedUnion([Mmu,Bmu,Imu,Tmu]);var zmu=ea.objectWithoutOptionalProperties({objects:ea.record(ea.string(),Rmu).optional()});var Nmu=ea.objectWithoutOptionalProperties({conjureImports:ea.property("conjure-imports",ea.record(ea.string(),ea.string()).optional()),definitions:zmu.optional()});var Fmu=ea.enum_(["none","header"]);var Fsa=ea.undiscriminatedUnion([Fmu,ea.string()]);var Qmu=ea.enum_(["path","query","body"]);var Umu=ea.objectWithoutOptionalProperties({paramType:ea.property("param-type",Qmu),type:ea.string()}).extend(aXt);var Lmu=ea.undiscriminatedUnion([ea.string(),Umu]);var Vmu=ea.objectWithoutOptionalProperties({http:ea.string(),auth:Fsa.optional(),args:ea.record(ea.string(),Lmu).optional(),returns:C$i.optional()}).extend(aXt);var Wmu=ea.objectWithoutOptionalProperties({name:ea.string().optional(),package:ea.string().optional(),basePath:ea.property("base-path",ea.string().optional()),defaultAuth:ea.property("default-auth",Fsa.optional()),endpoints:ea.record(ea.string(),Vmu).optional()}).extend(aXt);var UBh=ea.objectWithoutOptionalProperties({types:Nmu.optional(),services:ea.record(Emu,Wmu).optional()});var gZc={};Yt(gZc,{ConjureArgument:()=>Lmu,ConjureArgumentWithParamType:()=>Umu,ConjureAuthDefinition:()=>Fsa,ConjureAuthDefinitionType:()=>Fmu,ConjureEndpointDefinition:()=>Vmu,ConjureParamType:()=>Qmu,ConjureService:()=>Wmu});var OZc={};Yt(OZc,{ConjureAliasDeclaration:()=>Mmu,ConjureDefinitions:()=>zmu,ConjureEnumDeclaration:()=>Tmu,ConjureEnumVariant:()=>qmu,ConjureEnumWithDocs:()=>Cmu,ConjureObjectDeclaration:()=>Imu,ConjurePrimitive:()=>Smu,ConjureType:()=>I$i,ConjureTypeDeclaration:()=>Rmu,ConjureTypeReference:()=>C$i,ConjureTypeWithDocs:()=>Dmu,ConjureTypes:()=>Nmu,ConjureUnionDeclaration:()=>Bmu});var LBh=require("fs/promises");async function VBh(e,t){let r=[];for(let i of await m4(e,t))r.push(await kpB({relativeFilepath:Xf(e,i),absoluteFilepath:i}));return r}async function kpB({relativeFilepath:e,absoluteFilepath:t}){let r=(await(0,LBh.readFile)(t)).toString().replaceAll(/: rid(?:$|\s)/g,`: string
1527
1527
  `).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:Gmu.conjure.DefinitionFile.parseOrThrow(qi.load(r),{unrecognizedObjectKeys:"passthrough",allowUnrecognizedEnumValues:!0,allowUnrecognizedUnionMembers:!0})}}function WBh(e,t){if(e_B(e))return t.alias(e);if(t_B(e))return t.enum(e);if(r_B(e))return t.object(e);if(i_B(e))return t.union(e);vt(e)}function e_B(e){return e?.alias!=null}function t_B(e){return e?.values!=null}function r_B(e){return e?.fields!=null}function i_B(e){return e?.union!=null}var u$a=class extends VKa{fernDefinitionBuilder=new Ivn(!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 GBh(t,(a,o,c)=>{for(let[u,l]of Object.entries(c.services??{})){let p=dRo({value:u,suffix:"Service"});this.conjureFilepathToFernFilepath[o]=He.of(`${p}/__package__.yml`);return}let s=eNi(o)?.split(".")[0];s!=null&&(this.conjureFilepathToFernFilepath[o]=He.of(`${s}/__package__.yml`))}),await GBh(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 l=this.getFernFileToImport({absoluteFilePathToConjureFile:a,absoluteFilePathToConjureFolder:t,importFilePath:He.of(u)});this.fernDefinitionBuilder.addImport({file:d,fileToImport:He.of(l),alias:s})}this.importAllTypes({conjureFile:c,fernFilePath:d});return}for(let[d,s]of Object.entries(c.services)){let u=dRo({value:d,suffix:"Service"}),l=He.of(`${u}/__package__.yml`),p={};s.basePath!=null&&(p["base-path"]=s.basePath),s.docs!=null&&(p.docs=s.docs),this.fernDefinitionBuilder.setServiceInfo(l,p),this.importAllTypes({conjureFile:c,fernFilePath:l});for(let[_,h]of Object.entries(c.types?.conjureImports??{})){let y=this.getFernFileToImport({absoluteFilePathToConjureFile:a,absoluteFilePathToConjureFolder:t,importFilePath:He.of(h)});this.fernDefinitionBuilder.addImport({file:l,fileToImport:He.of(y),alias:_})}for(let[_,h]of Object.entries(s.endpoints??{})){let y=bnc(h.http);if(y.type==="failure"){this.context?.logger.error(`Failed to parse ${h.http}. Skipping.`);continue}let v={auth:(h.auth??s.defaultAuth)!==dBh.None,path:y.path,method:y.method,response:h.returns==="binary"?"file":h.returns};h.docs!=null&&(v.docs=h.docs);let g={};if(h.args!=null)for(let m of y.pathParameters){let O=h.args[m];if(O==null)throw new Error(`Failed to find path parameter ${m} in ${h.http}`);g[m]=typeof O=="string"?O:{type:O.type}}Object.entries(g).length>0&&(v["path-parameters"]=g);for(let[m,O]of Object.entries(h.args??{}))if(g[m]==null)if(typeof O=="string")v.request?typeof v.request=="string"&&(v.request={body:v.request}):v.request={},v.request.body=O==="binary"?"bytes":O;else switch(O.paramType){case"body":v.request={body:O.type==="binary"?"bytes":O.type};break;case"query":v.request==null?v.request={"query-parameters":{[m]:O.type}}:typeof v.request!="string"&&v.request?.["query-parameters"]==null?v.request["query-parameters"]={[m]:O.type}:typeof v.request!="string"&&v.request?.["query-parameters"]!=null&&(v.request["query-parameters"][m]=O.type)}v.request!=null&&typeof v.request!="string"&&v.request?.["query-parameters"]!=null&&(v.request.name=`${_}Request`),this.fernDefinitionBuilder.addEndpoint(l,{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??{}))WBh(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=Tt(rn(t),He.of(r)),a=CJ(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 GBh(e,t){for(let r of await VBh(e,"{yml,yaml}"))await t(r.absoluteFilepath,r.relativeFilepath,r.fileContents)}function xBh(e,t){return nn(e,t)}var xmu=class extends g8t{type="conjure";absolutePathToConjureFolder;constructor({relativePathToConjureDirectory:t,...r}){super(r),this.absolutePathToConjureFolder=Tt(r.absoluteFilePath,t)}async toFernWorkspace({context:t},r){let i=await this.getDefinition({context:t},r);return new pY({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 u$a(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:qi.dump(n.rootApiFile)},namedDefinitionFiles:{...xBh(n.definitionFiles,a=>({absoluteFilepath:Sr.of("/DUMMY_PATH"),rawContents:qi.dump(a),contents:a})),[He.of(Xb)]:{absoluteFilepath:Sr.of("/DUMMY_PATH"),rawContents:qi.dump(n.packageMarkerFile),contents:n.packageMarkerFile}},packageMarkers:{},importedDefinitions:{}}}getAbsoluteFilePaths(){return[this.absolutePathToConjureFolder]}};var pCh=ue(XBh(),1);var Wp;(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"})(Wp||(Wp={}));function ZBh(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Hmu(e,t){for(let[r,i]of UI(e))a_B({relativeFilepath:r,failure:i,logger:t})}function a_B({relativeFilepath:e,failure:t,logger:r}){switch(t.type){case Wp.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 Wp.FILE_READ:r.error("Failed to open file: "+e);break;case Wp.FILE_MISSING:r.error("Missing file: "+e);break;case Wp.FILE_PARSE:t.error instanceof O3a?r.error(s0e({title:`Failed to parse ${e}: ${t.error.reason}`,subtitle:t.error.mark.snippet})):r.error("Failed to parse file: "+e);break;case Wp.STRUCTURE_VALIDATION:for(let i of t.error.issues)for(let{title:n,subtitle:a}of o_B(i))r.error(s0e({title:n,subtitle:a,breadcrumbs:[e,...i.path]}));break;case Wp.FAILED_TO_LOAD_DEPENDENCY:r.error("Failed to load dependency: "+t.dependencyName);break;case Wp.DEPENDENCY_NOT_LISTED:r.error(`Dependency is not listed in ${rUo}: `+t.dependencyName);break;case Wp.EXPORT_PACKAGE_HAS_DEFINITIONS:r.error("Exported package contains API definitions: "+t.pathToPackage);break;case Wp.EXPORTING_PACKAGE_MARKER_OTHER_KEYS:r.error(`${t.pathOfPackageMarker} has an export so it cannot define other keys.`);break;case Wp.JSONSCHEMA_VALIDATION:if(t.error.error!=null){let i=t.error.error.instancePath.split("/").filter(n=>n!=="").map(ZBh);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(s0e({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(ZBh);i.keyword==="required"&&i.params?.missingProperty?n.push(i.params.missingProperty):i.keyword==="additionalProperties"&&i.params?.additionalProperty&&n.push(i.params.additionalProperty),r.debug(s0e({title:i.message??"Unknown error",breadcrumbs:[e,...n]}))}break;default:vt(t)}}function o_B(e){switch(e.code){case wi.invalid_type:return[{title:"Incorrect type",subtitle:`Expected ${Rt.underline(e.expected)} but received ${Rt.underline(e.received)}`}];case wi.unrecognized_keys:return e.keys.map(t=>({title:"Unexpected key",subtitle:`Encountered unexpected key ${Rt.underline(t)}`}));case wi.invalid_enum_value:return[{title:"Unrecognized value",subtitle:`Allowed values: ${e.options.map(t=>Rt.underline(t)).join(", ")}`}];case wi.invalid_union:case wi.invalid_arguments:case wi.invalid_return_type:case wi.invalid_date:case wi.invalid_string:case wi.too_small:case wi.too_big:case wi.invalid_intersection_types:case wi.not_multiple_of:case wi.custom:default:return[{title:e.message}]}}var kBh=require("fs/promises");async function eIh(e,t){let r=[];for(let i of await m4(e,t))r.push(await u_B({relativeFilepath:Xf(e,i),absoluteFilepath:i}));return r}async function u_B({relativeFilepath:e,absoluteFilepath:t}){return{relativeFilepath:e,absoluteFilepath:t,fileContents:(await(0,kBh.readFile)(t)).toString()}}async function tIh(e){let t={},r={};function i(n){try{t[n.relativeFilepath]={defaultUrl:void 0,contents:qi.load(n.fileContents,{schema:qi.CORE_SCHEMA}),rawContents:n.fileContents}}catch(a){r[n.relativeFilepath]={type:Wp.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 M2c=ue(i7i(),1);var iCh=require("fs"),ksa=require("fs/promises");var nCh=require("os"),aCh=ue(require("path"),1),oCh=require("stream/promises");var rIh=ue(require("events"),1),wx=ue(require("fs"),1);var s_B=wx.default.writev,T$i=Symbol("_autoClose"),N8t=Symbol("_close"),c$a=Symbol("_ended"),tj=Symbol("_fd"),PZc=Symbol("_finished"),WUi=Symbol("_flags"),jZc=Symbol("_flush"),MZc=Symbol("_handleChunk"),DZc=Symbol("_makeBuf"),f$a=Symbol("_mode"),Kmu=Symbol("_needDrain"),Vsa=Symbol("_onerror"),Wsa=Symbol("_onopen"),wZc=Symbol("_onread"),Usa=Symbol("_onwrite"),R$i=Symbol("_open"),z8t=Symbol("_path"),q$i=Symbol("_pos"),oXt=Symbol("_queue"),Lsa=Symbol("_read"),EZc=Symbol("_readSize"),VUi=Symbol("_reading"),l$a=Symbol("_remain"),SZc=Symbol("_size"),Jmu=Symbol("_write"),dgn=Symbol("_writing"),$mu=Symbol("_defaultFlag"),pgn=Symbol("_errored"),_gn=class extends aR{[pgn]=!1;[tj];[z8t];[EZc];[VUi]=!1;[SZc];[l$a];[T$i];constructor(t,r){if(r=r||{},super(r),this.readable=!0,this.writable=!1,typeof t!="string")throw new TypeError("path must be a string");this[pgn]=!1,this[tj]=typeof r.fd=="number"?r.fd:void 0,this[z8t]=t,this[EZc]=r.readSize||16*1024*1024,this[VUi]=!1,this[SZc]=typeof r.size=="number"?r.size:1/0,this[l$a]=this[SZc],this[T$i]=typeof r.autoClose=="boolean"?r.autoClose:!0,typeof this[tj]=="number"?this[Lsa]():this[R$i]()}get fd(){return this[tj]}get path(){return this[z8t]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[R$i](){wx.default.open(this[z8t],"r",(t,r)=>this[Wsa](t,r))}[Wsa](t,r){t?this[Vsa](t):(this[tj]=r,this.emit("open",r),this[Lsa]())}[DZc](){return Buffer.allocUnsafe(Math.min(this[EZc],this[l$a]))}[Lsa](){if(!this[VUi]){this[VUi]=!0;let t=this[DZc]();if(t.length===0)return process.nextTick(()=>this[wZc](null,0,t));wx.default.read(this[tj],t,0,t.length,null,(r,i,n)=>this[wZc](r,i,n))}}[wZc](t,r,i){this[VUi]=!1,t?this[Vsa](t):this[MZc](r,i)&&this[Lsa]()}[N8t](){if(this[T$i]&&typeof this[tj]=="number"){let t=this[tj];this[tj]=void 0,wx.default.close(t,r=>r?this.emit("error",r):this.emit("close"))}}[Vsa](t){this[VUi]=!0,this[N8t](),this.emit("error",t)}[MZc](t,r){let i=!1;return this[l$a]-=t,t>0&&(i=super.write(t<r.length?r.subarray(0,t):r)),(t===0||this[l$a]<=0)&&(i=!1,this[N8t](),super.end()),i}emit(t,...r){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[tj]=="number"&&this[Lsa](),!1;case"error":return this[pgn]?!1:(this[pgn]=!0,super.emit(t,...r));default:return super.emit(t,...r)}}},Ymu=class extends _gn{[R$i](){let t=!0;try{this[Wsa](null,wx.default.openSync(this[z8t],"r")),t=!1}finally{t&&this[N8t]()}}[Lsa](){let t=!0;try{if(!this[VUi]){this[VUi]=!0;do{let r=this[DZc](),i=r.length===0?0:wx.default.readSync(this[tj],r,0,r.length,null);if(!this[MZc](i,r))break}while(!0);this[VUi]=!1}t=!1}finally{t&&this[N8t]()}}[N8t](){if(this[T$i]&&typeof this[tj]=="number"){let t=this[tj];this[tj]=void 0,wx.default.closeSync(t),this.emit("close")}}},GUi=class extends rIh.default{readable=!1;writable=!0;[pgn]=!1;[dgn]=!1;[c$a]=!1;[oXt]=[];[Kmu]=!1;[z8t];[f$a];[T$i];[tj];[$mu];[WUi];[PZc]=!1;[q$i];constructor(t,r){r=r||{},super(r),this[z8t]=t,this[tj]=typeof r.fd=="number"?r.fd:void 0,this[f$a]=r.mode===void 0?438:r.mode,this[q$i]=typeof r.start=="number"?r.start:void 0,this[T$i]=typeof r.autoClose=="boolean"?r.autoClose:!0;let i=this[q$i]!==void 0?"r+":"w";this[$mu]=r.flags===void 0,this[WUi]=r.flags===void 0?i:r.flags,this[tj]===void 0&&this[R$i]()}emit(t,...r){if(t==="error"){if(this[pgn])return!1;this[pgn]=!0}return super.emit(t,...r)}get fd(){return this[tj]}get path(){return this[z8t]}[Vsa](t){this[N8t](),this[dgn]=!0,this.emit("error",t)}[R$i](){wx.default.open(this[z8t],this[WUi],this[f$a],(t,r)=>this[Wsa](t,r))}[Wsa](t,r){this[$mu]&&this[WUi]==="r+"&&t&&t.code==="ENOENT"?(this[WUi]="w",this[R$i]()):t?this[Vsa](t):(this[tj]=r,this.emit("open",r),this[dgn]||this[jZc]())}end(t,r){return t&&this.write(t,r),this[c$a]=!0,!this[dgn]&&!this[oXt].length&&typeof this[tj]=="number"&&this[Usa](null,0),this}write(t,r){return typeof t=="string"&&(t=Buffer.from(t,r)),this[c$a]?(this.emit("error",new Error("write() after end()")),!1):this[tj]===void 0||this[dgn]||this[oXt].length?(this[oXt].push(t),this[Kmu]=!0,!1):(this[dgn]=!0,this[Jmu](t),!0)}[Jmu](t){wx.default.write(this[tj],t,0,t.length,this[q$i],(r,i)=>this[Usa](r,i))}[Usa](t,r){t?this[Vsa](t):(this[q$i]!==void 0&&typeof r=="number"&&(this[q$i]+=r),this[oXt].length?this[jZc]():(this[dgn]=!1,this[c$a]&&!this[PZc]?(this[PZc]=!0,this[N8t](),this.emit("finish")):this[Kmu]&&(this[Kmu]=!1,this.emit("drain"))))}[jZc](){if(this[oXt].length===0)this[c$a]&&this[Usa](null,0);else if(this[oXt].length===1)this[Jmu](this[oXt].pop());else{let t=this[oXt];this[oXt]=[],s_B(this[tj],t,this[q$i],(r,i)=>this[Usa](r,i))}}[N8t](){if(this[T$i]&&typeof this[tj]=="number"){let t=this[tj];this[tj]=void 0,wx.default.close(t,r=>r?this.emit("error",r):this.emit("close"))}}},Gsa=class extends GUi{[R$i](){let t;if(this[$mu]&&this[WUi]==="r+")try{t=wx.default.openSync(this[z8t],this[WUi],this[f$a])}catch(r){if(r?.code==="ENOENT")return this[WUi]="w",this[R$i]();throw r}else t=wx.default.openSync(this[z8t],this[WUi],this[f$a]);this[Wsa](null,t)}[N8t](){if(this[T$i]&&typeof this[tj]=="number"){let t=this[tj];this[tj]=void 0,wx.default.closeSync(t),this.emit("close")}}[Jmu](t){let r=!0;try{this[Usa](null,wx.default.writeSync(this[tj],t,0,t.length,this[q$i])),r=!1}finally{if(r)try{this[N8t]()}catch{}}}};var o2c=ue(require("path"),1);var Pgn=ue(require("fs"),1),hAu=require("path");var c_B=new Map([["C","cwd"],["f","file"],["z","gzip"],["P","preservePaths"],["U","unlink"],["strip-components","strip"],["stripComponents","strip"],["keep-newer","newer"],["keepNewer","newer"],["keep-newer-files","newer"],["keepNewerFiles","newer"],["k","keep"],["keep-existing","keep"],["keepExisting","keep"],["m","noMtime"],["no-mtime","noMtime"],["p","preserveOwner"],["L","follow"],["h","follow"],["onentry","onReadEntry"]]),iIh=e=>!!e.sync&&!!e.file,nIh=e=>!e.sync&&!!e.file,aIh=e=>!!e.sync&&!e.file,oIh=e=>!e.sync&&!e.file;var uIh=e=>!!e.file;var l_B=e=>{let t=c_B.get(e);return t||e},d$a=(e={})=>{if(!e)return{};let t={};for(let[r,i]of Object.entries(e)){let n=l_B(r);t[n]=i}return t.chmod===void 0&&t.noChmod===!1&&(t.chmod=!0),delete t.noChmod,t};var uXt=(e,t,r,i,n)=>Object.assign((a=[],o,c)=>{Array.isArray(a)&&(o=a,a={}),typeof o=="function"&&(c=o,o=void 0),o?o=Array.from(o):o=[];let d=d$a(a);if(n?.(d,o),iIh(d)){if(typeof c=="function")throw new TypeError("callback not supported for sync tar functions");return e(d,o)}else if(nIh(d)){let s=t(d,o),u=c||void 0;return u?s.then(()=>u(),u):s}else if(aIh(d)){if(typeof c=="function")throw new TypeError("callback not supported for sync tar functions");return r(d,o)}else if(oIh(d)){if(typeof c=="function")throw new TypeError("callback only supported with file option");return i(d,o)}else throw new Error("impossible options??")},{syncFile:e,asyncFile:t,syncNoFile:r,asyncNoFile:i,validate:n});var PIh=require("events");var Xmu=ue(require("assert"),1),z$i=require("buffer");var cIh=ue(require("zlib"),1);var sIh=ue(require("zlib"),1),f_B=sIh.default.constants||{ZLIB_VERNUM:4736},dSe=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},f_B));var d_B=z$i.Buffer.concat,lIh=Object.getOwnPropertyDescriptor(z$i.Buffer,"concat"),p_B=e=>e,IZc=lIh?.writable===!0||lIh?.set!==void 0?e=>{z$i.Buffer.concat=e?p_B:d_B}:e=>{},hgn=Symbol("_superWrite"),xsa=class extends Error{code;errno;constructor(t,r){super("zlib: "+t.message,{cause:t}),this.code=t.code,this.errno=t.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+t.message,Error.captureStackTrace(this,r??this.constructor)}get name(){return"ZlibError"}},CZc=Symbol("flushFlag"),p$a=class extends aR{#e=!1;#t=!1;#r;#i;#n;#a;#o;get sawError(){return this.#e}get handle(){return this.#a}get flushFlag(){return this.#r}constructor(t,r){if(!t||typeof t!="object")throw new TypeError("invalid options for ZlibBase constructor");if(super(t),this.#r=t.flush??0,this.#i=t.finishFlush??0,this.#n=t.fullFlushFlag??0,typeof cIh[r]!="function")throw new TypeError("Compression method not supported: "+r);try{this.#a=new cIh[r](t)}catch(i){throw new xsa(i,this.constructor)}this.#o=i=>{this.#e||(this.#e=!0,this.close(),this.emit("error",i))},this.#a?.on("error",i=>this.#o(new xsa(i))),this.once("end",()=>this.close)}close(){this.#a&&(this.#a.close(),this.#a=void 0,this.emit("close"))}reset(){if(!this.#e)return(0,Xmu.default)(this.#a,"zlib binding closed"),this.#a.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#n),this.write(Object.assign(z$i.Buffer.alloc(0),{[CZc]:t})))}end(t,r,i){return typeof t=="function"&&(i=t,r=void 0,t=void 0),typeof r=="function"&&(i=r,r=void 0),t&&(r?this.write(t,r):this.write(t)),this.flush(this.#i),this.#t=!0,super.end(i)}get ended(){return this.#t}[hgn](t){return super.write(t)}write(t,r,i){if(typeof r=="function"&&(i=r,r="utf8"),typeof t=="string"&&(t=z$i.Buffer.from(t,r)),this.#e)return;(0,Xmu.default)(this.#a,"zlib binding closed");let n=this.#a._handle,a=n.close;n.close=()=>{};let o=this.#a.close;this.#a.close=()=>{},IZc(!0);let c;try{let s=typeof t[CZc]=="number"?t[CZc]:this.#r;c=this.#a._processChunk(t,s),IZc(!1)}catch(s){IZc(!1),this.#o(new xsa(s,this.write))}finally{this.#a&&(this.#a._handle=n,n.close=a,this.#a.close=o,this.#a.removeAllListeners("error"))}this.#a&&this.#a.on("error",s=>this.#o(new xsa(s,this.write)));let d;if(c)if(Array.isArray(c)&&c.length>0){let s=c[0];d=this[hgn](z$i.Buffer.from(s));for(let u=1;u<c.length;u++)d=this[hgn](c[u])}else d=this[hgn](z$i.Buffer.from(c));return i&&i(),d}},Zmu=class extends p$a{#e;#t;constructor(t,r){t=t||{},t.flush=t.flush||dSe.Z_NO_FLUSH,t.finishFlush=t.finishFlush||dSe.Z_FINISH,t.fullFlushFlag=dSe.Z_FULL_FLUSH,super(t,r),this.#e=t.level,this.#t=t.strategy}params(t,r){if(!this.sawError){if(!this.handle)throw new Error("cannot switch params when binding is closed");if(!this.handle.params)throw new Error("not supported in this implementation");if(this.#e!==t||this.#t!==r){this.flush(dSe.Z_SYNC_FLUSH),(0,Xmu.default)(this.handle,"zlib binding closed");let i=this.handle.flush;this.handle.flush=(n,a)=>{typeof n=="function"&&(a=n,n=this.flushFlag),this.flush(n),a?.()};try{this.handle.params(t,r)}finally{this.handle.flush=i}this.handle&&(this.#e=t,this.#t=r)}}}};var kmu=class extends Zmu{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[hgn](t){return this.#e?(this.#e=!1,t[9]=255,super[hgn](t)):super[hgn](t)}};var eAu=class extends Zmu{constructor(t){super(t,"Unzip")}},tAu=class extends p$a{constructor(t,r){t=t||{},t.flush=t.flush||dSe.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||dSe.BROTLI_OPERATION_FINISH,t.fullFlushFlag=dSe.BROTLI_OPERATION_FLUSH,super(t,r)}},rAu=class extends tAu{constructor(t){super(t,"BrotliCompress")}},iAu=class extends tAu{constructor(t){super(t,"BrotliDecompress")}},nAu=class extends p$a{constructor(t,r){t=t||{},t.flush=t.flush||dSe.ZSTD_e_continue,t.finishFlush=t.finishFlush||dSe.ZSTD_e_end,t.fullFlushFlag=dSe.ZSTD_e_flush,super(t,r)}},aAu=class extends nAu{constructor(t){super(t,"ZstdCompress")}},oAu=class extends nAu{constructor(t){super(t,"ZstdDecompress")}};var vgn=require("path");var fIh=(e,t)=>{if(Number.isSafeInteger(e))e<0?y_B(e,t):h_B(e,t);else throw Error("cannot encode number outside of javascript safe integer range");return t},h_B=(e,t)=>{t[0]=128;for(var r=t.length;r>1;r--)t[r-1]=e&255,e=Math.floor(e/256)},y_B=(e,t)=>{t[0]=255;var r=!1;e=e*-1;for(var i=t.length;i>1;i--){var n=e&255;e=Math.floor(e/256),r?t[i-1]=pIh(n):n===0?t[i-1]=0:(r=!0,t[i-1]=_Ih(n))}},dIh=e=>{let t=e[0],r=t===128?v_B(e.subarray(1,e.length)):t===255?b_B(e):null;if(r===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(r))throw Error("parsed number outside of javascript safe integer range");return r},b_B=e=>{for(var t=e.length,r=0,i=!1,n=t-1;n>-1;n--){var a=Number(e[n]),o;i?o=pIh(a):a===0?o=a:(i=!0,o=_Ih(a)),o!==0&&(r-=o*Math.pow(256,t-n-1))}return r},v_B=e=>{for(var t=e.length,r=0,i=t-1;i>-1;i--){var n=Number(e[i]);n!==0&&(r+=n*Math.pow(256,t-i-1))}return r},pIh=e=>(255^e)&255,_Ih=e=>(255^e)+1&255;var uAu=e=>sAu.has(e);var sAu=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]),hIh=new Map(Array.from(sAu).map(e=>[e[1],e[0]]));var hge=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#e="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,r=0,i,n){Buffer.isBuffer(t)?this.decode(t,r||0,i,n):t&&this.#t(t)}decode(t,r,i,n){if(r||(r=0),!t||!(t.length>=r+512))throw new Error("need 512 bytes for header");this.path=i?.path??ygn(t,r,100),this.mode=i?.mode??n?.mode??N$i(t,r+100,8),this.uid=i?.uid??n?.uid??N$i(t,r+108,8),this.gid=i?.gid??n?.gid??N$i(t,r+116,8),this.size=i?.size??n?.size??N$i(t,r+124,12),this.mtime=i?.mtime??n?.mtime??qZc(t,r+136,12),this.cksum=N$i(t,r+148,12),n&&this.#t(n,!0),i&&this.#t(i);let a=ygn(t,r+156,1);if(uAu(a)&&(this.#e=a||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=ygn(t,r+157,100),t.subarray(r+257,r+265).toString()==="ustar\x0000")if(this.uname=i?.uname??n?.uname??ygn(t,r+265,32),this.gname=i?.gname??n?.gname??ygn(t,r+297,32),this.devmaj=i?.devmaj??n?.devmaj??N$i(t,r+329,8)??0,this.devmin=i?.devmin??n?.devmin??N$i(t,r+337,8)??0,t[r+475]!==0){let c=ygn(t,r+345,155);this.path=c+"/"+this.path}else{let c=ygn(t,r+345,130);c&&(this.path=c+"/"+this.path),this.atime=i?.atime??n?.atime??qZc(t,r+476,12),this.ctime=i?.ctime??n?.ctime??qZc(t,r+488,12)}let o=256;for(let c=r;c<r+148;c++)o+=t[c];for(let c=r+156;c<r+512;c++)o+=t[c];this.cksumValid=o===this.cksum,this.cksum===void 0&&o===256&&(this.nullBlock=!0)}#t(t,r=!1){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([i,n])=>!(n==null||i==="path"&&r||i==="linkpath"&&r||i==="global"))))}encode(t,r=0){if(t||(t=this.block=Buffer.alloc(512)),this.#e==="Unsupported"&&(this.#e="0"),!(t.length>=r+512))throw new Error("need 512 bytes for header");let i=this.ctime||this.atime?130:155,n=O_B(this.path||"",i),a=n[0],o=n[1];this.needPax=!!n[2],this.needPax=bgn(t,r,100,a)||this.needPax,this.needPax=F$i(t,r+100,8,this.mode)||this.needPax,this.needPax=F$i(t,r+108,8,this.uid)||this.needPax,this.needPax=F$i(t,r+116,8,this.gid)||this.needPax,this.needPax=F$i(t,r+124,12,this.size)||this.needPax,this.needPax=TZc(t,r+136,12,this.mtime)||this.needPax,t[r+156]=this.#e.charCodeAt(0),this.needPax=bgn(t,r+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",r+257,8),this.needPax=bgn(t,r+265,32,this.uname)||this.needPax,this.needPax=bgn(t,r+297,32,this.gname)||this.needPax,this.needPax=F$i(t,r+329,8,this.devmaj)||this.needPax,this.needPax=F$i(t,r+337,8,this.devmin)||this.needPax,this.needPax=bgn(t,r+345,i,o)||this.needPax,t[r+475]!==0?this.needPax=bgn(t,r+345,155,o)||this.needPax:(this.needPax=bgn(t,r+345,130,o)||this.needPax,this.needPax=TZc(t,r+476,12,this.atime)||this.needPax,this.needPax=TZc(t,r+488,12,this.ctime)||this.needPax);let c=256;for(let d=r;d<r+148;d++)c+=t[d];for(let d=r+156;d<r+512;d++)c+=t[d];return this.cksum=c,F$i(t,r+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:sAu.get(this.#e)}get typeKey(){return this.#e}set type(t){let r=String(hIh.get(t));if(uAu(r)||r==="Unsupported")this.#e=r;else if(uAu(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},O_B=(e,t)=>{let i=e,n="",a,o=vgn.posix.parse(e).root||".";if(Buffer.byteLength(i)<100)a=[i,n,!1];else{n=vgn.posix.dirname(i),i=vgn.posix.basename(i);do Buffer.byteLength(i)<=100&&Buffer.byteLength(n)<=t?a=[i,n,!1]:Buffer.byteLength(i)>100&&Buffer.byteLength(n)<=t?a=[i.slice(0,99),n,!0]:(i=vgn.posix.join(vgn.posix.basename(n),i),n=vgn.posix.dirname(n));while(n!==o&&a===void 0);a||(a=[e.slice(0,99),"",!0])}return a},ygn=(e,t,r)=>e.subarray(t,t+r).toString("utf8").replace(/\0.*/,""),qZc=(e,t,r)=>m_B(N$i(e,t,r)),m_B=e=>e===void 0?void 0:new Date(e*1e3),N$i=(e,t,r)=>Number(e[t])&128?dIh(e.subarray(t,t+r)):P_B(e,t,r),A_B=e=>isNaN(e)?void 0:e,P_B=(e,t,r)=>A_B(parseInt(e.subarray(t,t+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),j_B={12:8589934591,8:2097151},F$i=(e,t,r,i)=>i===void 0?!1:i>j_B[r]||i<0?(fIh(i,e.subarray(t,t+r)),!0):(w_B(e,t,r,i),!1),w_B=(e,t,r,i)=>e.write(E_B(i,r),t,r,"ascii"),E_B=(e,t)=>S_B(Math.floor(e).toString(8),t),S_B=(e,t)=>(e.length===t-1?e:new Array(t-e.length-1).join("0")+e+" ")+"\0",TZc=(e,t,r,i)=>i===void 0?!1:F$i(e,t,r,i.getTime()/1e3),M_B=new Array(156).join("\0"),bgn=(e,t,r,i)=>i===void 0?!1:(e.write(i+M_B,t,r,"utf8"),i.length!==Buffer.byteLength(i)||i.length>r);var bIh=require("path");var Q$i=class e{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(t,r=!1){this.atime=t.atime,this.charset=t.charset,this.comment=t.comment,this.ctime=t.ctime,this.dev=t.dev,this.gid=t.gid,this.global=r,this.gname=t.gname,this.ino=t.ino,this.linkpath=t.linkpath,this.mtime=t.mtime,this.nlink=t.nlink,this.path=t.path,this.size=t.size,this.uid=t.uid,this.uname=t.uname}encode(){let t=this.encodeBody();if(t==="")return Buffer.allocUnsafe(0);let r=Buffer.byteLength(t),i=512*Math.ceil(1+r/512),n=Buffer.allocUnsafe(i);for(let a=0;a<512;a++)n[a]=0;new hge({path:("PaxHeader/"+(0,bIh.basename)(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:r,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(n),n.write(t,512,r,"utf8");for(let a=r+512;a<n.length;a++)n[a]=0;return n}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(t){if(this[t]===void 0)return"";let r=this[t],i=r instanceof Date?r.getTime()/1e3:r,n=" "+(t==="dev"||t==="ino"||t==="nlink"?"SCHILY.":"")+t+"="+i+`
@@ -1941,7 +1941,7 @@ The generated documentation will replace this placeholder page with complete API
1941
1941
  - Class and function references
1942
1942
  - Type annotations and signatures
1943
1943
  - Docstring content
1944
- `;return this.parsedDocsConfig.pages[He.of(o)]=d,{id:this.#e.get(c),type:"page",slug:a.get(),title:i,icon:void 0,hidden:!1,viewers:void 0,orphaned:void 0,pageId:c,authed:void 0,noindex:!0,featureFlags:void 0,availability:void 0}}async toPageNode({item:t,parentSlug:r,hideChildren:i,parentAvailability:n}){let a=Ft.PageId(this.toRelativeFilepath(t.absolutePath)),o=r.apply({urlSlug:t.slug??cS(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?Ft.PageId(o):void 0,d=this.#e.get(c??`${t}/section`),s=i.apply({urlSlug:r.slug??cS(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,l=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:l,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(p=>this.toNavigationChild({prefix:d,item:p,parentSlug:s,hideChildren:l,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 Gfn(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 Zgn(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:Ft.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??cS(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??cS(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):qG.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(us),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:qG.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 Gfn(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:qG.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function awB(e,t){let r=e?.launch??"github";if(e?.github==null)return{url:void 0,launch:r};let{owner:i,repo:n,branch:a="main",host:o="https://github.com"}=e.github;return{url:`${qx(o)}/${i}/${n}/blob/${a}/fern/${t}?plain=1`,launch:r}}function owB(e){switch(e){case"beta":return Ft.V1.NavigationV1Availability.Beta;case"deprecated":return Ft.V1.NavigationV1Availability.Deprecated;case"ga":return Ft.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return Ft.V1.NavigationV1Availability.Stable;default:vt(e)}}async function BL(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof jS?t:null))).filter(us)}async function ftl(e,t,r){if(e instanceof hSe){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof jS))return;let i=await e.getIntermediateRepresentation({context:t,audiences:r,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1,logWarnings:!1});return Cx({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 uc={};Yt(uc,{AlgoliaSearchIndex:()=>NQh,ApiDefinitionId:()=>nUh,ApiId:()=>sUh,Availability:()=>PUh,DocsConfigId:()=>cUh,EndpointId:()=>fUh,EndpointPathLiteral:()=>mUh,EnvironmentId:()=>lUh,FileId:()=>yUh,HttpMethod:()=>AUh,IndexSegmentId:()=>FQh,JqString:()=>vUh,OrgId:()=>oUh,PageId:()=>hUh,PayloadLocation:()=>YUh,PropertyKey:()=>gUh,PullRequestState:()=>xUh,RoleId:()=>OUh,TokenId:()=>uUh,TypeId:()=>_Uh,Url:()=>bUh,VersionId:()=>aUh,WebSocketId:()=>dUh,WebhookId:()=>pUh,algolia:()=>dtl,api:()=>Atl,commons:()=>Ptl,diff:()=>jUh,docs:()=>Ctl,generators:()=>Ttl,git:()=>Rtl,navigation:()=>Ftl,sdks:()=>Utl,snippets:()=>JUh,snippetsFactory:()=>$Uh,templates:()=>Ltl,tokens:()=>XUh});var dtl={};Yt(dtl,{AlgoliaSearchIndex:()=>NQh,IndexSegmentId:()=>FQh});function NQh(e){return e}function FQh(e){return e}var Atl={};Yt(Atl,{latest:()=>htl,v1:()=>mtl});var htl={};Yt(htl,{AuthSchemeId:()=>QQh,WebhookHttpMethod:()=>WQh,auth:()=>ptl,commons:()=>UQh,endpoint:()=>LQh,type_:()=>VQh,webhook:()=>_tl,websocket:()=>GQh});var ptl={};Yt(ptl,{AuthSchemeId:()=>QQh});function QQh(e){return e}var UQh={};var LQh={};var VQh={};var _tl={};Yt(_tl,{WebhookHttpMethod:()=>WQh});var WQh={Get:"GET",Post:"POST"};var GQh={};var mtl={};Yt(mtl,{SubpackageId:()=>eUh,WebSocketMessageId:()=>tUh,WebSocketMessageOrigin:()=>rUh,WebhookHttpMethod:()=>iUh,commons:()=>Otl,db:()=>ytl,read:()=>vtl,register:()=>gtl});var ytl={};Yt(ytl,{endpoint:()=>xQh});var xQh={};var vtl={};Yt(vtl,{SupportedLanguage:()=>HQh,endpoint:()=>btl,type_:()=>KQh,webhook:()=>JQh,websocket:()=>$Qh});var btl={};Yt(btl,{SupportedLanguage:()=>HQh});var HQh={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby",Csharp:"csharp"};var KQh={};var JQh={};var $Qh={};var gtl={};Yt(gtl,{SourceId:()=>uwB,endpoint:()=>YQh,type_:()=>XQh,webhook:()=>ZQh,websocket:()=>kQh});var YQh={};var XQh={};var ZQh={};var kQh={};function uwB(e){return e}var Otl={};Yt(Otl,{SubpackageId:()=>eUh,WebSocketMessageId:()=>tUh,WebSocketMessageOrigin:()=>rUh,WebhookHttpMethod:()=>iUh});function eUh(e){return e}function tUh(e){return e}var rUh={Client:"client",Server:"server"};var iUh={Get:"GET",Post:"POST"};var Ptl={};Yt(Ptl,{ApiDefinitionId:()=>nUh,ApiId:()=>sUh,Availability:()=>PUh,DocsConfigId:()=>cUh,EndpointId:()=>fUh,EndpointPathLiteral:()=>mUh,EnvironmentId:()=>lUh,FileId:()=>yUh,HttpMethod:()=>AUh,JqString:()=>vUh,OrgId:()=>oUh,PageId:()=>hUh,PropertyKey:()=>gUh,RoleId:()=>OUh,TokenId:()=>uUh,TypeId:()=>_Uh,Url:()=>bUh,VersionId:()=>aUh,WebSocketId:()=>dUh,WebhookId:()=>pUh});function nUh(e){return e}function aUh(e){return e}function oUh(e){return e}function uUh(e){return e}function sUh(e){return e}function cUh(e){return e}function lUh(e){return e}function fUh(e){return e}function dUh(e){return e}function pUh(e){return e}function _Uh(e){return e}function hUh(e){return e}function yUh(e){return e}function bUh(e){return e}function vUh(e){return e}function gUh(e){return e}function OUh(e){return e}function mUh(e){return e}var AUh={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var PUh={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var jUh={};var Ctl={};Yt(Ctl,{latest:()=>Etl,v1:()=>Btl,v2:()=>Itl});var Etl={};Yt(Etl,{Layout:()=>EUh,MdxEngine:()=>swB,TwitterCardSetting:()=>SUh,commons:()=>wUh,frontmatter:()=>jtl,seo:()=>wtl});var swB={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var wUh={};var jtl={};Yt(jtl,{Layout:()=>EUh});var EUh={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var wtl={};Yt(wtl,{TwitterCardSetting:()=>SUh});var SUh={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var Btl={};Yt(Btl,{commons:()=>Dtl,db:()=>MUh,read:()=>DUh,write:()=>Stl});var MUh={};var DUh={};var Stl={};Yt(Stl,{DocsRegistrationId:()=>lwB,FilePath:()=>cwB});function cwB(e){return e}function lwB(e){return e}var Dtl={};Yt(Dtl,{ContentAlignment:()=>qUh,FontDisplay:()=>FUh,FontStyle:()=>NUh,HeaderPosition:()=>TUh,JsScriptStrategy:()=>zUh,ProgrammingLanguage:()=>BUh,SearchbarPlacement:()=>IUh,TabsPlacement:()=>CUh,TwitterCardSetting:()=>RUh,commons:()=>Mtl});var Mtl={};Yt(Mtl,{ContentAlignment:()=>qUh,FontDisplay:()=>FUh,FontStyle:()=>NUh,HeaderPosition:()=>TUh,JsScriptStrategy:()=>zUh,ProgrammingLanguage:()=>BUh,SearchbarPlacement:()=>IUh,TabsPlacement:()=>CUh,TwitterCardSetting:()=>RUh});var BUh={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 IUh={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var CUh={Header:"HEADER",Sidebar:"SIDEBAR"};var qUh={Center:"CENTER",Left:"LEFT"};var TUh={Fixed:"FIXED",Absolute:"ABSOLUTE"};var RUh={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var zUh={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var NUh={Normal:"normal",Italic:"italic"};var FUh={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var Itl={};Yt(Itl,{read:()=>QUh,write:()=>UUh});var QUh={};var UUh={};var Ttl={};Yt(Ttl,{ChangelogEntryType:()=>VUh,GeneratorId:()=>fwB,GeneratorLanguage:()=>dwB,ReleaseType:()=>WUh,cli:()=>LUh,commons:()=>qtl,versions:()=>GUh});var LUh={};var qtl={};Yt(qtl,{ChangelogEntryType:()=>VUh,ReleaseType:()=>WUh});var VUh={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var WUh={Ga:"GA",Rc:"RC"};var GUh={};function fwB(e){return e}var dwB={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var Rtl={};Yt(Rtl,{PullRequestState:()=>xUh});var xUh={Open:"open",Closed:"closed",Merged:"merged"};var Ftl={};Yt(Ftl,{latest:()=>ztl,v1:()=>Ntl});var ztl={};Yt(ztl,{NodeId:()=>hwB,ProductId:()=>ywB,Slug:()=>pwB,TabId:()=>_wB});function pwB(e){return e}function _wB(e){return e}function hwB(e){return e}function ywB(e){return e}var Ntl={};Yt(Ntl,{NavigationV1Availability:()=>mwB,NodeId:()=>gwB,ProductId:()=>OwB,Slug:()=>bwB,TabId:()=>vwB});function bwB(e){return e}function vwB(e){return e}function gwB(e){return e}function OwB(e){return e}var mwB={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var Utl={};Yt(Utl,{Language:()=>HUh,VersionBump:()=>KUh,versions:()=>Qtl});var Qtl={};Yt(Qtl,{Language:()=>HUh,VersionBump:()=>KUh});var HUh={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var KUh={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var JUh={};var $Uh={};var Ltl={};Yt(Ltl,{PayloadLocation:()=>YUh});var YUh={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var XUh={};var a0u=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};function Ho(e){return e!=null}var kUh=ue(l4a(),1);var ZUh=["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 jXt(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,kUh.default)(e,{special:ZUh}).replace(/V\s(\d)/g,"V$1")}function e4h({endpoints:e,webhookEndpoints:t}){let r={};return Object.values({...e,...t}).forEach(i=>{let n=[];i.namespace?.forEach(a=>{let o=[...n,a],c=uc.api.v1.SubpackageId(o.join("."));r[c]={id:c,name:a,displayName:jXt(a)},n.push(a)})}),r}var o0u=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 t4h(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var mo=class extends o0u{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 ${t4h(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 mo{},DY=class extends IC{seenSchemas;constructor(t){super(t),this.seenSchemas=new Set(t.seenSchemas)}};var r4h="x-fern-base-path",i4h="x-fern-availability",u0u="x-fern-sdk-group-name",n4h="x-fern-global-headers",a4h="x-fern-sdk-method-name";var o4h="x-fern-webhook",u4h="x-fern-access-token-locator",s4h="x-fern-basic",c4h="x-fern-username-variable-name",l4h="x-fern-password-variable-name",f4h="x-fern-bearer",d4h="x-fern-token-variable-name",p4h="x-fern-header",_4h="x-fern-header-variable-name",h4h="x-fern-server-name",y4h="x-fern-examples";var s0u=class extends mo{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[h4h]}convert(){if(this.serverName!=null)return this.serverName}};var c0u=class extends mo{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 s0u({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:uc.EnvironmentId(t),baseUrl:this.url}}};function yYi(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 c0u({input:c,context:r,accessPath:i,pathId:["servers",`${d}`]}));return[...n,...o]}function tg(e){return typeof e=="object"&&Ho(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:(tg(n)&&(n=IL(n,t,r)),n)}function l0u(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return tg(r)?IL(r,t,void 0):r}var uLh=ue(bM());var f0u=class extends mo{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[s4h];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var d0u=class extends mo{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[l4h]}convert(){return this.passwordVariableName}};var p0u=class extends mo{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[c4h]}convert(){return this.usernameVariableName}};var _0u=class extends mo{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[f4h];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var h0u=class extends mo{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[d4h]}convert(){return this.tokenVariableName}};function b4h(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var v4h="x-bearer-format",g4h="x-code-samples",O4h="x-codeSamples";var y0u=class extends mo{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[v4h]}convert(){return this.bearerFormat}};var b0u=class extends mo{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[p4h];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var v0u=class extends mo{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[_4h]}convert(){return this.headerVariableName}};function m4h(e){return e.type==="apiKey"}var Gca=class extends mo{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){m4h(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new b0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new v0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new y0u({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 g0u(e){return e}function O0u(e){return e==="__proto__"}function m0u(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function xca(e){return typeof e=="string"||typeof e=="symbol"?e:Object.is(e?.valueOf?.(),-0)?"-0":String(e)}function LYa(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e))return e.map(LYa).join(",");let t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function A0u(e){if(Array.isArray(e))return e.map(xca);if(typeof e=="symbol")return[e];e=LYa(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 VYa(e,t,r){if(e==null)return r;switch(typeof t){case"string":{if(O0u(t))return r;let i=e[t];return i===void 0?m0u(t)?VYa(e,A0u(t),r):r:i}case"number":case"symbol":{typeof t=="number"&&(t=xca(t));let i=e[t];return i===void 0?r:i}default:{if(Array.isArray(t))return AwB(e,t,r);if(Object.is(t?.valueOf(),-0)?t="-0":t=String(t),O0u(t))return r;let i=e[t];return i===void 0?r:i}}}function AwB(e,t,r){if(t.length===0)return r;let i=e;for(let n=0;n<t.length;n++){if(i==null||O0u(t[n]))return r;i=i[t[n]]}return i===void 0?r:i}function A4h(e){return function(t){return VYa(t,e)}}function P4h(e){return e!==null&&(typeof e=="object"||typeof e=="function")}function P0u(e){return e==null||typeof e!="object"&&typeof e!="function"}function Vtl(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function Gtl(e,t,r){return typeof r!="function"?Gtl(e,t,()=>{}):Wtl(e,t,function i(n,a,o,c,d,s){let u=r(n,a,o,c,d,s);return u!==void 0?!!u:Wtl(n,a,i,s)},new Map)}function Wtl(e,t,r,i){if(t===e)return!0;switch(typeof t){case"object":return PwB(e,t,r,i);case"function":return Object.keys(t).length>0?Wtl(e,{...t},r,i):Vtl(e,t);default:return P4h(e)?typeof t=="string"?t==="":!0:Vtl(e,t)}}function PwB(e,t,r,i){if(t==null)return!0;if(Array.isArray(t))return j4h(e,t,r,i);if(t instanceof Map)return jwB(e,t,r,i);if(t instanceof Set)return wwB(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(!P0u(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 jwB(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 j4h(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 wwB(e,t,r,i){return t.size===0?!0:e instanceof Set?j4h([...e],[...t],r,i):!1}function j0u(e,t){return Gtl(e,t,()=>{})}function w4h(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function w0u(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}var E4h="[object RegExp]",E0u="[object String]",S0u="[object Number]",M0u="[object Boolean]",D0u="[object Arguments]",S4h="[object Symbol]",M4h="[object Date]",D4h="[object Map]",B4h="[object Set]",I4h="[object Array]";var C4h="[object ArrayBuffer]",q4h="[object Object]";var T4h="[object DataView]",R4h="[object Uint8Array]",z4h="[object Uint8ClampedArray]",N4h="[object Uint16Array]",F4h="[object Uint32Array]";var Q4h="[object Int8Array]",U4h="[object Int16Array]",L4h="[object Int32Array]";var V4h="[object Float32Array]",W4h="[object Float64Array]";function G4h(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function x4h(e,t){return bYi(e,void 0,e,new Map,t)}function bYi(e,t,r,i=new Map,n=void 0){let a=n?.(e,t,r,i);if(a!==void 0)return a;if(P0u(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]=bYi(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,bYi(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(bYi(c,void 0,r,i,n));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(e))return e.subarray();if(G4h(e)){let o=new(Object.getPrototypeOf(e)).constructor(e.length);i.set(e,o);for(let c=0;c<e.length;c++)o[c]=bYi(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),k8t(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),k8t(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),k8t(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,k8t(o,e,r,i,n),o}if(e instanceof Boolean){let o=new Boolean(e.valueOf());return i.set(e,o),k8t(o,e,r,i,n),o}if(e instanceof Number){let o=new Number(e.valueOf());return i.set(e,o),k8t(o,e,r,i,n),o}if(e instanceof String){let o=new String(e.valueOf());return i.set(e,o),k8t(o,e,r,i,n),o}if(typeof e=="object"&&EwB(e)){let o=Object.create(Object.getPrototypeOf(e));return i.set(e,o),k8t(o,e,r,i,n),o}return e}function k8t(e,t,r=e,i,n){let a=[...Object.keys(t),...w4h(t)];for(let o=0;o<a.length;o++){let c=a[o],d=Object.getOwnPropertyDescriptor(e,c);(d==null||d.writable)&&(e[c]=bYi(t[c],c,r,i,n))}}function EwB(e){switch(w0u(e)){case D0u:case I4h:case C4h:case T4h:case M0u:case M4h:case V4h:case W4h:case Q4h:case U4h:case L4h:case D4h:case S0u:case q4h:case E4h:case B4h:case E0u:case S4h:case R4h:case z4h:case N4h:case F4h:return!0;default:return!1}}function H4h(e){return bYi(e,void 0,e,new Map,void 0)}function K4h(e){return e=H4h(e),t=>j0u(t,e)}function J4h(e,t){return x4h(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 S0u:case E0u:case M0u:{let c=new e.constructor(e?.valueOf());return k8t(c,e),c}case D0u:{let c={};return k8t(c,e),c.length=e.length,c[Symbol.iterator]=e[Symbol.iterator],c}default:return}})}function $4h(e){return J4h(e)}var SwB=/^(?:0|[1-9]\d*)$/;function Y4h(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 SwB.test(e)}}function X4h(e){return e!==null&&typeof e=="object"&&w0u(e)==="[object Arguments]"}function Z4h(e,t){let r;if(Array.isArray(t)?r=t:typeof t=="string"&&m0u(t)&&e?.[t]==null?r=A0u(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)||X4h(i))&&Y4h(a)&&a<i.length))return!1;i=i[a]}return!0}function k4h(e,t){switch(typeof e){case"object":{Object.is(e?.valueOf(),-0)&&(e="-0");break}case"number":{e=xca(e);break}}return t=$4h(t),function(r){let i=VYa(r,e);return i===void 0?Z4h(r,e):t===void 0?i===void 0:j0u(i,t)}}function eLh(e){if(e==null)return g0u;switch(typeof e){case"function":return e;case"object":return Array.isArray(e)&&e.length===2?k4h(e[0],e[1]):K4h(e);case"string":case"symbol":case"number":return A4h(e)}}function tLh(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 B0u(e,t=g0u){return e==null?{}:tLh(e,eLh(t))}function rLh(e){return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}var MwB=new RegExp("\\p{Lu}?\\p{Ll}+|[0-9]+|\\p{Lu}+(?!\\p{Ll})|\\p{Emoji_Presentation}|\\p{Extended_Pictographic}|\\p{L}+","gu");function iLh(e){return Array.from(e.match(MwB)??[])}function nLh(e){let t=iLh(e);if(t.length===0)return"";let[r,...i]=t;return`${r.toLowerCase()}${i.map(n=>rLh(n)).join("")}`}function aLh(e){return typeof e!="string"&&(e=LYa(e)),e.replace(/['\u2019]/g,"")}function eWt(e){return nLh(aLh(e))}function ij(e){if(e!=null)return Array.isArray(e)?e:[e]}function I0u({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`${DwB(o)}${BwB(e)}.${IwB(i,n,a,c)}`}function DwB(e){return e?"webhook_":"endpoint_"}function BwB(e){return e!=null?ij(e)?.map(t=>eWt(t)).join("/"):""}function IwB(e,t,r,i){return e||t||eWt(r??"")||eWt(i??"")}function oLh(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var C0u=class extends mo{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[u4h],this.accessTokenLocator!=null&&(oLh(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 q0u=class extends mo{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 Gca({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new C0u({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=I0u({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:uc.EndpointId(r),accessTokenLocator:uc.JqString(t),headerName:this.headerAuthNode?.convert()?.headerWireValue,tokenPrefix:this.headerAuthNode?.convert()?.prefix}}}}};var Hca=class extends mo{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 f0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicUsernameVariableNameNode=new p0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new d0u({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 _0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new h0u({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":{b4h(this.input)?(this.authScheme="header",this.headerAuthNode=new Gca({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 q0u({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 uLh.UnreachableCaseError(this.authScheme);return}}};var Kca=class extends mo{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(i=>{let n=l0u(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 Hca({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(Ho))}};var T0u=class extends mo{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[r4h],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 sLh(e){return"required"in e&&typeof e.required=="boolean"?e.required:!1}function cLh(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function Jca(e,t){return e==null?void 0:Object.entries(e).map(([i,n])=>ij(n.convert())?.map(o=>((t!=null&&!t.includes(i)||t==null&&!sLh(n))&&(o=cLh(o,o.type==="enum"?o.default:void 0)),{key:uc.PropertyKey(i),valueShape:o,description:n.description,availability:n.availability?.convert()})).filter(Ho)).filter(Ho).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(o=>[...a,o]):[[...a]]),[[]])}function R0u(e,t){return tg(e)?IL(e,t,void 0):e}function vYi(e,t){return e!=null&&e!==""?e:t!=null&&t!==""?t:void 0}function lLh(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 fLh(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 dLh=ue(bM());var xtl=["decimal","decimal128","double-int","double","float","sf-decimal"],Htl=["int16","int32","int64","int8","sf-integer","uint8"],Ktl=["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"],Jtl=["beta","pre-release","in-development","generally-available","deprecated"];function CC(e,t){return tg(e)?IL(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var ESe=class extends mo{availability;constructor(t){super(t),this.safeParse()}parse(){if(CC(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[i4h];r!=null&&(Jtl.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${Jtl.join(", ")}. Received: ${r}`,path:this.accessPath}),this.availability=void 0))}}convert(){switch(this.availability){case"beta":case"pre-release":return uc.Availability.Beta;case"in-development":return uc.Availability.InDevelopment;case"generally-available":return uc.Availability.GenerallyAvailable;case"deprecated":return uc.Availability.Deprecated;case void 0:return;default:new dLh.UnreachableCaseError(this.availability);return}}};var N0u=ue(bM());function pLh(e){return typeof e=="object"&&e!=null&&"language"in e}function _Lh(e){return typeof e=="object"&&e!=null&&"sdk"in e}function hLh(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function yLh(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function z0u(e){return typeof e=="object"&&e!=null&&"event"in e}function $tl(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(z0u)}function gYi(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function bLh(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var F0u=class extends mo{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[y4h]}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 gYi(o)?[n,{type:"filenameWithData",filename:o.filename,data:uc.FileId(o.data)}]:o!=null?[n,{type:"filename",value:o}]:void 0;case"files":{if(Array.isArray(o)){if(o.every(c=>gYi(c)))return[n,{type:"filenamesWithData",value:o.map(c=>({filename:c.filename,data:uc.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 N0u.UnreachableCaseError(a.multipartType);return}}).filter(Ho))};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=bLh(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 N0u.UnreachableCaseError(n.contentType);break}let o;switch(i.contentType){case"application/json":{hLh(r.response)&&(o={type:"json",value:r.response.body});break}case"text/event-stream":{$tl(r.response)&&(o={type:"sse",value:r.response.stream.map(l=>({event:l.event,data:l.data}))});break}case"application/octet-stream":!$tl(r.response)&&yLh(r.response)&&(o={type:"stream",value:r.response.stream});break;case void 0:break;default:new N0u.UnreachableCaseError(i.contentType);break}let c={};r["code-samples"]?.forEach(l=>{pLh(l)?l.language!=null&&(c[l.language]??=[],c[l.language]?.push({name:l.name,language:l.language,install:l.install,code:l.code,generated:!1,description:l.docs})):_Lh(l)&&l.sdk!=null&&(c[l.sdk]??=[],c[l.sdk]?.push({name:l.name,language:l.sdk,install:void 0,code:l.code,generated:!1,description:l.docs}))});let d=Object.fromEntries(Object.entries(r["path-parameters"]??{}).map(([l,p])=>[uc.PropertyKey(l),p])),s=Object.fromEntries(Object.entries(r["query-parameters"]??{}).map(([l,p])=>[uc.PropertyKey(l),p])),u=Object.fromEntries(Object.entries(r.headers??{}).map(([l,p])=>[uc.PropertyKey(l),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 WYa=class extends mo{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[u0u]}convert(){if(this.groupName==null)return;let t;return Array.isArray(this.groupName)?t=this.groupName:t=[this.groupName],t.map(r=>uc.api.v1.SubpackageId(eWt(r)))}};var Q0u=class extends mo{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[a4h]}convert(){return this.sdkMethodName}};var U0u=class extends mo{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[o4h]}convert(){return this.isWebhook}};var L0u=class extends mo{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[g4h]??[],...this.input[O4h]??[]],this.codeSamples.forEach(t=>{[...Object.values(uc.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 kgn=ue(bM());function Ytl(e,t){return tg(e)?IL(e,t,void 0):e}function vLh(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 TF="",wXt=class extends mo{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&&(gYi(n)||typeof n=="string");case"files":return t&&Array.isArray(n)&&n.every(a=>gYi(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new kgn.UnreachableCaseError(i.multipartType),t}},!0)}parse(){let t=this.shapes.requestBody?.schema?.example({includeOptionals:!1,override:void 0});this.resolvedRequestInput=Ytl(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=Ytl(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 kgn.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(z0u)){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 kgn.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 gYi(n)?[r,{type:"filenameWithData",filename:n.filename,data:uc.FileId(n.data)}]:[r,{type:"filename",value:n}];case"files":{if(Array.isArray(n)){if(n.every(a=>gYi(a)))return[r,{type:"filenamesWithData",value:n.map(a=>({filename:a.filename,data:uc.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 kgn.UnreachableCaseError(i.multipartType);return}}).filter(Ho))};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 kgn.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 kgn.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(Ho));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(Ho));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:vLh(this.path,i??{}),responseStatusCode:this.responseStatusCode,name:this.name!=null?jXt(this.name):this.summary!=null?jXt(this.summary):void 0,description:this.convertDescription(),pathParameters:i,queryParameters:n,headers:a,requestBody:t,responseBody:r,snippets:void 0}}};function gLh(e,t){return tg(e)?IL(e,t,void 0):e}var CLh=ue(bM());var OLh="#/components/schemas/";function $ca(e){if(e.$ref.startsWith(OLh))return e.$ref.replace(OLh,"")}function d4i(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}function OYi(e){return typeof e.type=="string"&&e.type==="array"}function mLh(e){return e.type==="boolean"}function ALh(e){return e.type==="integer"}function mYi(e){return!Array.isArray(e.type)&&!OYi(e)}function PLh(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||mYi(t)||OYi(t))}function jLh(e){return"nullable"in e&&typeof e.nullable=="boolean"}function wLh(e){return e.type==="null"}function ELh(e){return e.type==="number"}function Xtl(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function SLh(e){return e.type==="string"}var V0u=class extends DY{item;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.item=new hw({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 ij(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 W0u=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 ESe({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 G0u=class extends DY{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 hw({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName})}).filter(Ho)}convert(){if(this.typeNodes==null)return;let i=this.typeNodes.map(n=>ij(n.convert())?.map(o=>({displayName:n.name,shape:o,description:n.description,availability:n.availability?.convert()}))).filter(Ho).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(d4i).filter(Ho):i}example(t){return this.nullable?null:this.typeNodes?.[0]?.example(t)}};function x0u(e){return e!=null&&e.length>0?e:[void 0]}var Yca=class extends DY{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 hw({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 hw({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(tg(t))return $ca(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([i,n])=>[i,new hw({input:n,context:this.context,accessPath:this.accessPath,pathId:["allOf",r.toString(),"properties",i],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))}}).filter(Ho))),this.description=this.input.description}convertProperties(){if(this.properties!=null)return Jca(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}}}]:ij(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(Ho)}convert(){let t=this.convertProperties();if(t==null)return;let r=this.convertExtraProperties();return t.flatMap(i=>x0u(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=>uc.TypeId(a)),properties:i,extraProperties:n}))}example({includeOptionals:t}){let r={...this.properties};return this.input.allOf?.forEach(i=>{let n=CC(i,this.context.document);n!=null&&(r={...r,...Object.fromEntries(Object.entries(n.properties??{}).map(([a,o])=>[a,new hw({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 H0u=class extends DY{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=>CC(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>CC(t,this.context.document)?.type!=="null"?new hw({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0).filter(Ho);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=CC({$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 hw({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(Ho);return this.isNullable&&n!=null?n.map(d4i).filter(Ho):n}let t=0,r=this.discriminated&&this.discriminant!=null&&this.discriminatedMapping!=null?{type:"discriminatedUnion",discriminant:uc.PropertyKey(this.discriminant),variants:Object.entries(this.discriminatedMapping).flatMap(([n,a])=>ij(a.convert())?.map(c=>{if(!(c==null||c.type!=="object"))return{discriminantValue:n,displayName:a.name??jXt(n),availability:a.availability?.convert(),description:a.description,...c}}).filter(Ho)).filter(Ho)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(n=>ij(n.convert())?.map(o=>{if(o==null)return;t+=1;let c=o.type==="object"?jXt(`${this.schemaName??"Variant"} ${t}`):void 0;return{displayName:n.name??(o.type==="alias"&&o.value.type==="id"?jXt(o.value.id):c),shape:o,description:n.description,availability:n.availability?.convert()}}).filter(Ho)).filter(Ho)}:void 0,i=this.isNullable?d4i(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 K0u=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 AYi=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(tg(r)){let n=CC(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(Ho),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 MLh=ue(bM());function CwB(e){return Htl.includes(e)}var J0u=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&&(CwB(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${Htl.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 MLh.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 $0u=class extends IC{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return d4i({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var DLh=ue(bM());function qwB(e){return xtl.includes(e)}var Y0u=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&&(qwB(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${xtl.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 DLh.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 BLh=ue(bM());function TwB(e){return Ktl.includes(e)}var X0u=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 BLh.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&&(TwB(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${Ktl.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new AYi({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 ILh=ue(bM());var Z0u=class extends IC{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,ILh.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var eOn=class extends DY{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=$ca(this.input);let t=CC(this.input,this.context.document);t?.enum!=null&&mYi(t)&&(this.maybeEnumConverterNode=new AYi({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:uc.TypeId(this.schemaId),default:this.maybeEnumConverterNode?.default!=null?{type:"enum",value:this.maybeEnumConverterNode.default}:void 0}}}example(t){let r=CC(this.input,this.context.document);if(r!=null)return new hw({input:r,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName}).example(t)}};var hw=class e extends DY{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 ESe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),mYi(this.input)&&jLh(this.input)&&(this.nullable=this.input.nullable!=null?this.input.nullable:this.nullable),tg(this.input)){let t=$ca(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 eOn({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 W0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(PLh(this.input))this.typeShapeNode=new G0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(mYi(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new H0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(Xtl(this.input)&&this.input.allOf!=null)this.typeShapeNode=new Yca({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(mYi(this.input)&&this.input.enum!=null)this.typeShapeNode=new AYi({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":Xtl(this.input)&&(this.typeShapeNode=new Yca({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"array":OYi(this.input)&&(this.typeShapeNode=new V0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"boolean":mLh(this.input)&&(this.typeShapeNode=new K0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"integer":ALh(this.input)&&(this.typeShapeNode=new J0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"number":ELh(this.input)&&(this.typeShapeNode=new Y0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"string":SLh(this.input)&&(this.typeShapeNode=new X0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"null":wLh(this.input)&&(this.typeShapeNode=new $0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case void 0:break;default:new CLh.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 Yca({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 Z0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),!tg(this.input)&&(!OYi(this.input)&&this.input==null||OYi(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=ij(t)?.map(i=>this.nullable?d4i(i):i).filter(Ho);return Array.isArray(t)&&t.length>1?r:r?.[0]}example(t){return this.availability?.availability!=="deprecated"?this.typeShapeNode?.example(t):void 0}};function PYi(e){if(e!=null)return Jca(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(Ho))}var EXt=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;tg(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 ESe({input:r,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new hw({input:r,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:t});let i=gLh(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 qLh(e,t){return tg(e)?IL(e,t,void 0):e}var Ztl=ue(bM());function k0u(e){let{uniqueId:t,type:r,contextTypes:i,description:n,availability:a}=e;i[uc.TypeId(t)]={name:t,shape:r,description:n,availability:a}}var TLh=ue(fnc(),1),Xca=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=TLh.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 RwB(e){return typeof e.securitySchemes=="object"&&e.securitySchemes!=null}var ewu=class extends mo{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 hw({input:r,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:new Set,nullable:void 0,schemaName:t})]))),RwB(this.input)&&this.input.securitySchemes!=null&&(this.securitySchemes=Object.fromEntries(Object.entries(this.input.securitySchemes??{}).map(([t,r],i)=>{let n;if(tg(r)?n=l0u(r.$ref,this.context.document):n=r,n!=null)return[t,new Hca({input:n,context:this.context,accessPath:this.accessPath,pathId:["securitySchemes",`${i}`]})]}).filter(Ho)))}convert(){return{auths:this.securitySchemes!=null?Object.fromEntries(Object.entries(this.securitySchemes??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[uc.api.latest.AuthSchemeId(t),i]}).filter(Ho)):void 0,types:this.typeSchemas!=null?Object.fromEntries(Object.entries(this.typeSchemas).map(([t,r])=>{let i=r.name??t,n=ij(r.convert());return n==null?[t,void 0]:[uc.TypeId(t),{name:i,shape:n[0],description:r.description,availability:void 0}]}).filter(([t,r])=>Ho(r))):void 0}}};var twu=class extends hw{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=CC(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${tg(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=CC(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 rwu=class extends mo{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=CC(this.input.schema,this.context.document);this.availability=new ESe({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=tg(this.input.schema)?new eOn({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=Xca.parse(t);n?.containsJSON()?(this.contentType="json",this.schema=this.schema??new hw({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 twu({input:o,context:this.context,accessPath:this.accessPath,pathId:`schema.${a}`,seenSchemas:new Set,nullable:void 0,schemaName:a})]}).filter(Ho))):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?{[TF]:{value:this.input.example}}:{},...this.input.examples},r!=null&&Object.keys(this.examples).length===0&&(this.examples={[TF]:{value:r}})}convertJsonLike(){let t=this.schema?.convert();return t==null?void 0:ij(t)?.map(i=>{let n=i.type;switch(n){case"object":case"alias":return i;case"enum":case"undiscriminatedUnion":case"discriminatedUnion":{let a=eWt([this.method,this.path,this.contentType,"request"].join("_"));return k0u({uniqueId:a,type:i,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:uc.TypeId(a),default:i.type==="enum"&&i.default!=null?{type:"enum",value:i.default}:void 0}}}case void 0:return;default:new Ztl.UnreachableCaseError(n);return}}).filter(Ho)}convert(){if(this.schema instanceof eOn)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:uc.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:uc.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"property":{let a=ij(n.convert()),o=n.multipartType;return a?.map(c=>({type:o,key:uc.PropertyKey(i),contentType:n.contentType,exploded:void 0,valueShape:c,description:n.description,availability:n.availability?.convert()}))}case void 0:return[];default:return new Ztl.UnreachableCaseError(n.multipartType),[]}}).filter(Ho).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 iwu=class extends mo{description;requestBodiesByContentType;constructor(t){super(t),this.safeParse(t)}parse({method:t,path:r}){let i=qLh(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 rwu({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])=>ij(r.convert())?.map(n=>({description:this.description,contentType:t,body:n}))).filter(Ho)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>ij(t.convert())?.map(i=>{if(!(i.type!=="alias"&&i.type!=="object"))return{description:this.description,shape:i}})).filter(Ho)}webhookExample(){return{payload:this.requestBodiesByContentType?.["application/json"]?.schema?.example({includeOptionals:!0,override:void 0})}}};var RLh={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 zLh(e,t){if(tg(e)){let r=IL(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var nwu=ue(bM());var NLh="application/json";var FLh="application/octet-stream";function QLh(e,t){return e===t||t===TF||e===TF}var GYa=class extends mo{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)QLh(c,a)&&(i.add(c),this.examples?.push(new wXt({input:{requestExample:o,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,vYi(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(l=>new wXt({input:{requestExample:u,responseExample:l},context:this.context,accessPath:this.accessPath,pathId:s!=null&&s!==""?["examples",s]:"examples"},this.path,this.statusCode,vYi(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 wXt({input:{requestExample:s,responseExample:u},context:this.context,accessPath:this.accessPath,pathId:d!=null&&d!==""?["examples",d]:"examples"},this.path,this.statusCode,vYi(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 wXt({input:{requestExample:o,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,vYi(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[TF];if(a!=null)for(let o of a)this.examples?.push(new wXt({input:{requestExample:n,responseExample:o},context:this.context,accessPath:this.accessPath,pathId:i!=null&&i!==""?["examples",i]:"examples"},this.path,this.statusCode,vYi(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=Xca.parse(t);if(c?.isJSON()||c?.isEventStream())this.contentType=NLh,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 hw({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=FLh,this.contentSubtype=CC(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 hw({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=B0u(this.input.examples,c=>[c])),this.input.example!=null&&Object.keys(r).length===0&&(r[TF]??=[],r[TF]=[{value:this.input.example}]);let i=CC(this.input.schema,this.context.document);if(i!=null&&(i.examples!=null&&Object.keys(r).length===0&&(r=B0u(i.examples,c=>[c])),i.example!=null&&Object.keys(r).length===0&&(r[TF]??=[],r[TF]?.push({value:i.example}))),Object.keys(r).length===0){let c=this.schema?.example({includeOptionals:!0,override:void 0});r[TF]??=[],r[TF]?.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!==TF).map(([d,s])=>[c,d,s]));let o=Object.entries(r).filter(([c,d])=>!n.has(c)&&Ho(d)&&c!==TF);Object.keys(r).every(c=>c===TF)||this.matchExamplesByIndex(a,o),!n.has(TF)&&this.examples.length===0&&this.addGlobalFallbackExample(this.requests,r),this.examples.length===0&&(this.examples=void 0)}convertStreamingFormat(){switch(this.streamingFormat){case"json":return ij(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new nwu.UnreachableCaseError(this.streamingFormat);return}}convertJsonLike(){return ij(this.schema?.convert())?.map(r=>{let i=r.type;switch(i){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":{let n=eWt([this.method,this.path,this.statusCode,"response"].join("_"));return k0u({uniqueId:n,type:r,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:uc.TypeId(n),default:r.type==="enum"&&r.default!=null?{type:"enum",value:r.default}:void 0}}}case"object":return r;default:new nwu.UnreachableCaseError(i);return}}).filter(Ho)}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 nwu.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?this.convertJsonLike():void 0}};var xYa=class extends mo{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=zLh(this.input,this.context.document);if(r==null){this.context.errors.error({message:tg(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 EXt({input:n,context:this.context,accessPath:this.accessPath,pathId:"headers",parameterName:i})}),r.content==null?(this.responses??=[],this.responses.push(new GYa({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 GYa({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(Ho)}};var awu=class extends mo{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 xYa({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 xYa({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 x0u(PYi(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(Ho))})))}).filter(Ho)}convertResponseObjectToErrors(){return Object.entries(this.errorsByStatusCode??{}).flatMap(([t,r])=>r.responses?.flatMap(i=>{let n=i.schema,a=ij(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??RLh[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(Ho)})).filter(Ho)})).filter(Ho)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var jYi=class extends mo{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 wXt({input:{requestExample:t,responseExample:void 0},context:this.context,accessPath:this.accessPath,pathId:"examples"},this.path,200,vYi(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 ESe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=yYi(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new U0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((i,n)=>{if(tg(i)){let a=R0u(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 EXt({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 EXt({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 EXt({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 L0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new iwu({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 awu({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 Kca({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespaces=[new WYa({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 WYa({input:{[u0u]:i},context:this.context,accessPath:this.accessPath,pathId:["tags",`${n}`]})));let r=new Q0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointIds=this.namespaces.map(i=>I0u({namespace:ij(i?.groupName),path:this.path,method:this.method,sdkMethodName:r.sdkMethodName,operationId:this.input.operationId,displayName:this.displayName,isWebhook:this.isWebhook})).filter(Ho),this.xFernExamplesNode=new F0u({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(Ho)}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:uc.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(Ho),n=fLh(this.xFernExamplesNode?.convert(),[...i??[],...t?.flatMap(u=>u.examples)??[]])?.map(u=>({...u,snippets:lLh(u.snippets,this.redocExamplesNode?.convert())}));if(this.isWebhook)return this.endpointIds.map((u,l)=>{if(!(this.method!=="POST"&&this.method!=="GET"))return{id:uc.WebhookId(u),description:this.description,availability:this.availability?.convert(),displayName:this.displayName,operationId:this.operationId,namespace:this.namespaces?.[l]?.convert(),method:this.method,path:this.convertPathToPathParts()?.map(p=>p.value.toString())??[],queryParameters:PYi(this.queryParameters)?.flat(),headers:PYi(this.requestHeaders)?.flat(),payloads:this.requests?.convertToWebhookPayload(),examples:[this.requests?.webhookExample()].filter(Ho)}}).filter(Ho);let a=this.servers?.map(u=>u.convert()).filter(Ho),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(Ho);return this.endpointIds.map((u,l)=>({id:uc.EndpointId(u),description:this.description,availability:this.availability?.convert(),namespace:this.namespaces?.[l]?.convert()?.map(p=>uc.api.v1.SubpackageId(p)),displayName:this.displayName,operationId:this.operationId,method:this.method,path:o,auth:c?.map(p=>uc.api.latest.AuthSchemeId(p)),defaultEnvironment:a?.[0]?.id,environments:a,pathParameters:PYi(this.pathParameters)?.flat(),queryParameters:PYi(this.queryParameters)?.flat(),requestHeaders:PYi(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 Zca=class extends mo{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=yYi(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 jYi({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 jYi({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 jYi({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 jYi({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 jYi({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(Ho)}};function owu(e){return"payloads"in e}var uwu=class extends mo{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 Zca({input:a,context:this.context,accessPath:this.accessPath,pathId:n,servers:yYi(t,a.servers,this.context,this.accessPath),globalAuth:r,basePath:i,isWebhook:void 0})}).filter(Ho)}convert(){if(this.paths==null)return;let t={},r={};return this.paths.forEach(i=>{let n=i.convert();n?.forEach(a=>{owu(a)?r[uc.WebhookId(a.id)]=a:t[uc.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var swu=class extends mo{globalHeaders;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[n4h]?.map(r=>{let{header:i,...n}=r;return(n.optional!=null&&!n.optional||R0u(n,this.context.document)?.required)&&(this.requiredProperties??=[],this.requiredProperties?.push(i)),[i,new EXt({input:n,context:this.context,accessPath:this.accessPath,pathId:this.pathId,parameterName:i})]});t!=null&&(this.globalHeaders=Object.fromEntries(t))}convert(){return Jca(this.globalHeaders,this.requiredProperties)?.flat()}};function ULh(e,t){if(tg(e)){let r=IL(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var cwu=class extends mo{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=ULh(a,this.context.document);if(o!=null)return new Zca({input:o,context:this.context,accessPath:this.accessPath,pathId:n,servers:t,globalAuth:r,basePath:i,isWebhook:!0})}).filter(Ho)}convert(){return this.webhooks?.reduce((t,r)=>(r.convert()?.forEach(i=>{owu(i)&&(t[uc.WebhookId(i.id)]=i)}),t),{})}};var lwu=class extends mo{paths;webhooks;components;auth;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){let t=yYi(void 0,this.input.servers,this.context,this.accessPath);this.input.security!=null&&(this.auth=new Kca({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"}));let r=new T0u({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 uwu({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 cwu({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 ewu({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"})),this.globalHeaders=new swu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=Tve(),{webhookEndpoints:r,endpoints:i}=this.paths?.convert()??{},n={...this.webhooks?.convert()??{},...r??{}},a=e4h({endpoints:i,webhookEndpoints:n}),{types:o,auths:c}=this.components?.convert()??{};return{id:uc.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 ktl(e,t){if(e instanceof hSe){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof jS))return;let r=new V8t(e.absoluteFilePath),i=await bSe({context:t,specs:e.specs}),n=await r.loadDocuments({context:t,specs:i,loadAiExamples:!0}),a;for(let o of n){if(o.type!=="openapi")continue;let c={document:o.value,logger:t.logger,errors:new a0u,generatedTypes:{}},d=new lwu({input:o.value,context:c,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=p$n(a,d.convert())}return a}var nKh=ue(rrl(),1),aKh=ue(Zwu(),1),ASu=require("fs/promises"),oKh=ue(require("http"),1),uKh=ue(require("path"),1);var G5h=require("events"),iEu=ue(require("fs"),1),lOn=ue(require("path"),1);var E5h=ue(require("os"),1),S5h=300,IYi=20,_Xa=1e7,M5h=E5h.default.platform();var iqB=M5h==="darwin",Ail=M5h==="win32",CYi=iqB||Ail,D5h=3e3,B5h=2e4,Pil=1250;var BXt;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(BXt||(BXt={}));var cOn;(function(e){e.CHANGE="change",e.RENAME="rename"})(cOn||(cOn={}));var hXa;(function(e){e.CHANGE="change",e.ERROR="error"})(hXa||(hXa={}));var rf;(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"})(rf||(rf={}));var zx;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(zx||(zx={}));var nqB=(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 O=Date.now(),A=O-d,j=O-s,M=A>=t||j>=a;return[O,M]},l=O=>{if(s=O,!o)return;let A=o;o=void 0,e.apply(void 0,A)},p=()=>{g(0)},_=()=>{c&&(p(),l(Date.now()))},h=O=>{if(s=O,i)return l(O)},y=O=>{if(n&&o)return l(O);o=void 0},b=()=>{c=void 0;let[O,A]=u();return A?y(O):v(O)},v=O=>{let A=O-d,j=O-s,M=t-A,w=a-j,D=Math.min(M,w);return g(D)},g=O=>{c&&clearTimeout(c),!(O<=0)&&(c=setTimeout(b,O))},m=(...O)=>{let[A,j]=u(),M=!!c;if(o=O,d=A,(j||!c)&&g(t),j)return M?l(A):h(A)};return m.cancel=p,m.flush=_,m},kwu=nqB;var Sil=ue(require("fs"),1),tEu=ue(require("path"),1);var dm=ue(require("fs"),1),CL=require("util");var _4i=(e,t)=>function(...i){return e.apply(void 0,i).catch(t)},IXt=(e,t)=>function(...i){try{return e.apply(void 0,i)}catch(n){return t(n)}};var jil=ue(require("process"),1),I5h=jil.default.getuid?!jil.default.getuid():!1,C5h=1e4,qY=()=>{};var yXa={isChangeErrorOk:e=>{if(!yXa.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!I5h&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!yXa.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(!yXa.isNodeError(e))throw e;if(!yXa.isChangeErrorOk(e))throw e}},qC=yXa;var wil=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=C5h,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()}}}}},q5h=new wil;var h4i=(e,t)=>function(i){return function n(...a){return q5h.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)})}},y4i=(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 aqB={attempt:{chmod:_4i((0,CL.promisify)(dm.default.chmod),qC.onChangeError),chown:_4i((0,CL.promisify)(dm.default.chown),qC.onChangeError),close:_4i((0,CL.promisify)(dm.default.close),qY),fsync:_4i((0,CL.promisify)(dm.default.fsync),qY),mkdir:_4i((0,CL.promisify)(dm.default.mkdir),qY),realpath:_4i((0,CL.promisify)(dm.default.realpath),qY),stat:_4i((0,CL.promisify)(dm.default.stat),qY),unlink:_4i((0,CL.promisify)(dm.default.unlink),qY),chmodSync:IXt(dm.default.chmodSync,qC.onChangeError),chownSync:IXt(dm.default.chownSync,qC.onChangeError),closeSync:IXt(dm.default.closeSync,qY),existsSync:IXt(dm.default.existsSync,qY),fsyncSync:IXt(dm.default.fsync,qY),mkdirSync:IXt(dm.default.mkdirSync,qY),realpathSync:IXt(dm.default.realpathSync,qY),statSync:IXt(dm.default.statSync,qY),unlinkSync:IXt(dm.default.unlinkSync,qY)},retry:{close:h4i((0,CL.promisify)(dm.default.close),qC.isRetriableError),fsync:h4i((0,CL.promisify)(dm.default.fsync),qC.isRetriableError),open:h4i((0,CL.promisify)(dm.default.open),qC.isRetriableError),readFile:h4i((0,CL.promisify)(dm.default.readFile),qC.isRetriableError),rename:h4i((0,CL.promisify)(dm.default.rename),qC.isRetriableError),stat:h4i((0,CL.promisify)(dm.default.stat),qC.isRetriableError),write:h4i((0,CL.promisify)(dm.default.write),qC.isRetriableError),writeFile:h4i((0,CL.promisify)(dm.default.writeFile),qC.isRetriableError),closeSync:y4i(dm.default.closeSync,qC.isRetriableError),fsyncSync:y4i(dm.default.fsyncSync,qC.isRetriableError),openSync:y4i(dm.default.openSync,qC.isRetriableError),readFileSync:y4i(dm.default.readFileSync,qC.isRetriableError),renameSync:y4i(dm.default.renameSync,qC.isRetriableError),statSync:y4i(dm.default.statSync,qC.isRetriableError),writeSync:y4i(dm.default.writeSync,qC.isRetriableError),writeFileSync:y4i(dm.default.writeFileSync,qC.isRetriableError)}},T5h=aqB;var eEu=ue(require("fs"),1),bXa=ue(require("path"),1);var Eil=()=>{};var oqB=()=>{let e=Eil,t=Eil,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}},R5h=oqB;var uqB=()=>{let{promise:e,resolve:t,isPending:r}=R5h(),i=0,n=()=>{i+=1},a=()=>{i-=1,!i&&t()};return(()=>{n(),queueMicrotask(a)})(),{promise:e,isPending:r,increment:n,decrement:a}},z5h=uqB;var N5h={then:e=>{e()}};var F5h=e=>Array.isArray(e)?e:[e],Q5h=e=>typeof e=="function";var sqB=(e,t)=>{let r=t?.followSymlinks??!1,i=t?.depth??1/0,n=t?.limit??1/0,a=t?.ignore??[],o=F5h(a).map(W=>Q5h(W)?W:x=>W.test(x)),c=W=>o.some(x=>x(W)),d=t?.signal??{aborted:!1},s=t?.onDirents||(()=>{}),u=[],l=new Set,p={},_=[],h=new Set,y={},b=[],v=new Set,g={},m={},O=new Set,A={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},j={directories:u,directoriesNames:l,directoriesNamesToPaths:p,files:_,filesNames:h,filesNamesToPaths:y,symlinks:b,symlinksNames:v,symlinksNamesToPaths:g,map:m},{promise:M,increment:w,decrement:D}=z5h(),B=0,T=(W,x,Ee,se)=>{O.has(x)||B>=n||(B+=1,W.directories.push(x),W.directoriesNames.add(Ee),u.push(x),l.add(Ee),p.propertyIsEnumerable(Ee)||(p[Ee]=[]),p[Ee].push(x),O.add(x),!(se>=i)&&(B>=n||$(x,se+1)))},R=(W,x,Ee)=>{O.has(x)||B>=n||(B+=1,W.files.push(x),W.filesNames.add(Ee),_.push(x),h.add(Ee),y.propertyIsEnumerable(Ee)||(y[Ee]=[]),y[Ee].push(x),O.add(x))},q=(W,x,Ee,se)=>{O.has(x)||B>=n||(B+=1,W.symlinks.push(x),W.symlinksNames.add(Ee),b.push(x),v.add(Ee),g.propertyIsEnumerable(Ee)||(g[Ee]=[]),g[Ee].push(x),O.add(x),r&&(se>=i||B>=n||de(x,se+1)))},z=(W,x,Ee,se,Oe)=>{d.aborted||c(x)||(se.isDirectory()?T(W,x,Ee,Oe):se.isFile()?R(W,x,Ee):se.isSymbolicLink()&&q(W,x,Ee,Oe))},N=(W,x,Ee,se)=>{if(d.aborted)return;let Oe=x===bXa.default.sep?"":bXa.default.sep,Fe=Ee.name,ae=`${x}${Oe}${Fe}`;c(ae)||(Ee.isDirectory()?T(W,ae,Fe,se):Ee.isFile()?R(W,ae,Fe):Ee.isSymbolicLink()&&q(W,ae,Fe,se))},H=(W,x,Ee,se)=>{for(let Oe=0,Fe=Ee.length;Oe<Fe;Oe++)N(W,x,Ee[Oe],se)},$=(W,x)=>{d.aborted||x>i||B>=n||(w(),eEu.default.readdir(W,{withFileTypes:!0},(Ee,se)=>{if(Ee||d.aborted||!se.length)return D();(s(se)||N5h).then(()=>{let Fe=m[W]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};H(Fe,W,se,x),D()})}))},de=(W,x)=>{w(),eEu.default.realpath(W,(Ee,se)=>{if(Ee||d.aborted)return D();eEu.default.stat(se,(Oe,Fe)=>{if(Oe||d.aborted)return D();let ae=bXa.default.basename(se),re=m[W]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};z(re,se,ae,Fe,x),D()})})};return(async(W,x=1)=>(W=bXa.default.normalize(W),O.add(W),$(W,x),await M,d.aborted?A:j))(e)},U5h=sqB;var CXt={lang:{debounce:kwu,attempt:e=>{try{return e()}catch(t){return CXt.lang.castError(t)}},castArray:e=>CXt.lang.isArray(e)?e:[e],castError:e=>CXt.lang.isError(e)?e:CXt.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(CXt.lang.isNaN(e))return CXt.lang.isNaN(t);if(CXt.lang.isPrimitive(e)||CXt.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(tEu.default.sep).length-1),getRealPath:(e,t)=>{try{return t?Sil.default.realpathSync.native(e):Sil.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===tEu.default.sep&&t.length-e.length>tEu.default.sep.length,poll:(e,t=B5h)=>T5h.retry.stat(t)(e,{bigint:!0}).catch(CXt.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 U5h(e,{depth:r,limit:i,ignore:t,signal:n});return[o.directories,o.files]}}}},Gp=CXt;var rEu=ue(require("path"),1);var Mil=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||Gp.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=S5h){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]),l=this.eventsDeduplicate([...s,...u]);this.onTargetEvents(l)},o=Gp.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===rf.CHANGE&&c===rf.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===rf.ADD_DIR?await this.eventsPopulateAddDir(t,n,r,i):o===rf.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??IYi:Math.min(1,this.options.depth??IYi),o=this.options.limit??_Xa,[c,d]=await Gp.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())Gp.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(rf.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!CYi&&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(rf.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(rf.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(rEu.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(rf.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(rEu.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(rf.UNLINK_DIR,t))}onTargetEvent(t){let[r,i]=t;r===rf.ADD?this.onTargetAdd(i):r===rf.ADD_DIR?this.onTargetAddDir(i):r===rf.CHANGE?this.onTargetChange(i):r===rf.UNLINK?this.onTargetUnlink(i):r===rf.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=cOn.CHANGE,r){if(this.watcher.isClosed())return;let i=rEu.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){Ail&&t.code==="EPERM"?this.onWatcherChange(cOn.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(hXa.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(hXa.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(cOn.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&CYi&&this.options.native!==!1?this.options.depth??IYi:Math.min(1,this.options.depth??IYi),i=this.options.limit??_Xa,[n,a]=await Gp.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(cOn.CHANGE,c,t)}))}}},L5h=Mil;var Nx={interval:100,intervalId:void 0,fns:new Map,init:()=>{Nx.intervalId||(Nx.intervalId=setInterval(Nx.resolve,Nx.interval))},reset:()=>{Nx.intervalId&&(clearInterval(Nx.intervalId),delete Nx.intervalId)},add:(e,t)=>{Nx.fns.set(e,Date.now()+t),Nx.init()},remove:e=>{Nx.fns.delete(e)},resolve:()=>{if(!Nx.fns.size)return Nx.reset();let e=Date.now();for(let[t,r]of Nx.fns)r>=e||(Nx.remove(t),t())}},vXa=Nx;var gXa=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=Pil){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{let l=this._watcher._poller.paths.find(i||-1,p=>p!==n);if(l&&l!==n){if(Gp.fs.getRealPath(n,!0)===l)return;this._watcher.event(a.rename,l,n)}else this._watcher.event(a.add,n)};if(!i)return c();let d=()=>{o.add.delete(i),vXa.remove(s)},s=()=>{d(),c()};vXa.add(s,r);let u=()=>{let l=o.unlink.get(i);if(!l)return;d();let p=l();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=Pil){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),vXa.remove(s)},s=()=>{d(),c()};vXa.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,rf.ADD,BXt.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,rf.ADD_DIR,BXt.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,rf.UNLINK,BXt.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,rf.UNLINK_DIR,BXt.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}}};gXa.DIR_EVENTS={add:rf.ADD_DIR,rename:rf.RENAME_DIR,unlink:rf.UNLINK_DIR};gXa.FILE_EVENTS={add:rf.ADD,change:rf.CHANGE,rename:rf.RENAME,unlink:rf.UNLINK};var V5h=gXa;var Dil=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(Gp.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let i=this.map.get(t);if(Gp.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(Gp.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(Gp.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let i=this.map.get(t);return Gp.lang.isSet(i)?i.has(r):i===r}return!1}set(t,r){if(this.map.has(t)){let i=this.map.get(t);Gp.lang.isSet(i)?i.add(r):i!==r&&this.map.set(t,new Set([i,r]))}else this.map.set(t,r);return this}},Bil=Dil;var Iil=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}},W5h=Iil;var Cil=class{constructor(){this.inos={},this.paths=new Bil,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 Gp.fs.poll(t,r);if(!(!i||!(i.isFile()||i.isDirectory())))return new W5h(i)}reset(){this.inos={},this.paths=new Bil,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,rf.ADD,n),[rf.ADD];if(n.isDirectory())return this.updateIno(t,rf.ADD_DIR,n),[rf.ADD_DIR]}else if(i&&!n){if(i.isFile())return this.updateIno(t,rf.UNLINK,i),[rf.UNLINK];if(i.isDirectory())return this.updateIno(t,rf.UNLINK_DIR,i),[rf.UNLINK_DIR]}else if(i&&n){if(i.isFile()){if(n.isFile())return i.ino===n.ino&&!i.size&&!n.size?[]:(this.updateIno(t,rf.CHANGE,n),[rf.CHANGE]);if(n.isDirectory())return this.updateIno(t,rf.UNLINK,i),this.updateIno(t,rf.ADD_DIR,n),[rf.UNLINK,rf.ADD_DIR]}else if(i.isDirectory()){if(n.isFile())return this.updateIno(t,rf.UNLINK_DIR,i),this.updateIno(t,rf.ADD,n),[rf.UNLINK_DIR,rf.ADD];if(n.isDirectory())return i.ino===n.ino?[]:(this.updateIno(t,rf.UNLINK_DIR,i),this.updateIno(t,rf.ADD_DIR,n),[rf.UNLINK_DIR,rf.ADD_DIR])}}return[]}updateIno(t,r,i){let n=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=i.isFile()?BXt.FILE:BXt.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)}}},qil=Cil;var Til=class e extends G5h.EventEmitter{constructor(t,r,i){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(zx.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(n=>this.on(zx.CLOSE,n)),this._readyWait=new Promise(n=>this.on(zx.READY,n)),this._locker=new V5h(this),this._roots=new Set,this._poller=new qil,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&&(Gp.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(zx.CLOSE))}error(t){if(this.isClosed())return!1;let r=Gp.lang.castError(t);return this.emit(zx.ERROR,r)}event(t,r,i){return this.isClosed()?!1:(this.emit(zx.ALL,t,r,i),this.emit(t,r,i))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(zx.READY))}pollerExists(t,r){for(let i of this._pollers)if(i.targetPath===t&&Gp.lang.isShallowEqual(i.options,r))return!0;return!1}subwatcherExists(t,r){for(let i of this._subwatchers)if(i.targetPath===t&&Gp.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)Gp.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 L5h(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=Gp.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=lOn.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??IYi))&&u.handler===i&&(!u.filePath||u.filePath===n)&&u.options.ignore===r.ignore&&!!u.options.native==!!r.native&&(!r.recursive||u.options.recursive&&CYi&&u.options.native!==!1)))return!0;if(!CYi)break;let s=lOn.default.dirname(t);if(o===s)break;o=s}return!1}async watchDirectories(t,r,i,n,a){if(this.isClosed())return;t=Gp.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||CYi&&r.native!==!1?r:{...r,recursive:!1},u={watcher:iEu.default.watch(c,d),handler:i,options:r,folderPath:c,filePath:n},l=o=await this.watcherAdd(u,a);if(this._roots.has(n||c)){let _={...r,ignoreInitial:!0,recursive:!1},h=lOn.default.dirname(c),y=c;await this.watchDirectories([h],_,i,y,l)}}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||CYi&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,i,n,a));{r={...r,recursive:!0};let o=r.depth??IYi,c=r.limit??_Xa,[d]=await Gp.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=Gp.fs.getDepth(t);for(let l of d){let p=Gp.fs.getDepth(l),_=Math.max(0,o-(p-u)),h={...r,depth:_};await this.watchDirectories([l],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(zx.CLOSE,d),o.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(n),this.removeListener(zx.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=lOn.default.dirname(t);return this.watchDirectory(n,r,i,t)}async watchPollingOnce(t,r,i){if(this.isClosed())return;let n=!1,a=new qil,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 Gp.lang.noop;if(this.pollerExists(t,r))return Gp.lang.noop;let n={...r,interval:r.pollingInterval??D5h},a={targetPath:t,options:r},o=()=>{this._pollers.add(a),this.on(zx.CLOSE,c),iEu.default.watchFile(t,n,i)},c=()=>{this._pollers.delete(a),this.removeListener(zx.CLOSE,c),iEu.default.unwatchFile(t,i)};return Gp.lang.attempt(o),()=>Gp.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=Gp.lang.uniq(t).sort(),t.every((a,o)=>t.every((c,d)=>d===o||!Gp.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=lOn.default.resolve(t),this.isIgnored(t,r.ignore)))return;let n=await Gp.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=lOn.default.dirname(t);return(await Gp.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,i):this.watchUnknownTarget(t,r,i)}}async watch(t,r,i=Gp.lang.noop){if(Gp.lang.isFunction(t))return this.watch([],{},t);if(Gp.lang.isUndefined(t))return this.watch([],r,i);if(Gp.lang.isFunction(r))return this.watch(t,{},r);if(Gp.lang.isUndefined(r))return this.watch(t,{},i);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let n=Gp.lang.castArray(t);n.forEach(a=>this._roots.add(a)),await this.watchPaths(n,r,i),!this.isClosed()&&(i!==Gp.lang.noop&&this.on(zx.ALL,i),r.readdirMap=void 0,this.ready())}},nEu=Til;uru();var _la=require("fs/promises"),x5h=require("os"),H5h=ue(require("path"),1),cqB=".fern",lqB="logs";function fqB(){return"cli@3.47.4"}var OXa=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=Tt(Sr.of((0,x5h.homedir)()),He.of(cqB)),r=Tt(t,He.of(lqB));await mi(r)||await(0,_la.mkdir)(r,{recursive:!0});let n=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=Tt(r,He.of(n));let a=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${H5h.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
1944
+ `;return this.parsedDocsConfig.pages[He.of(o)]=d,{id:this.#e.get(c),type:"page",slug:a.get(),title:i,icon:void 0,hidden:!1,viewers:void 0,orphaned:void 0,pageId:c,authed:void 0,noindex:!0,featureFlags:void 0,availability:void 0}}async toPageNode({item:t,parentSlug:r,hideChildren:i,parentAvailability:n}){let a=Ft.PageId(this.toRelativeFilepath(t.absolutePath)),o=r.apply({urlSlug:t.slug??cS(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?Ft.PageId(o):void 0,d=this.#e.get(c??`${t}/section`),s=i.apply({urlSlug:r.slug??cS(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,l=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:l,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(p=>this.toNavigationChild({prefix:d,item:p,parentSlug:s,hideChildren:l,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 Gfn(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 Zgn(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:Ft.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??cS(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??cS(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):qG.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(us),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:qG.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 Gfn(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:qG.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function awB(e,t){let r=e?.launch??"github";if(e?.github==null)return{url:void 0,launch:r};let{owner:i,repo:n,branch:a="main",host:o="https://github.com"}=e.github;return{url:`${qx(o)}/${i}/${n}/blob/${a}/fern/${t}?plain=1`,launch:r}}function owB(e){switch(e){case"beta":return Ft.V1.NavigationV1Availability.Beta;case"deprecated":return Ft.V1.NavigationV1Availability.Deprecated;case"ga":return Ft.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return Ft.V1.NavigationV1Availability.Stable;default:vt(e)}}async function BL(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof jS?t:null))).filter(us)}async function ftl(e,t,r){if(e instanceof hSe){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof jS))return;let i=await e.getIntermediateRepresentation({context:t,audiences:r,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1,logWarnings:!1});return Cx({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 uc={};Yt(uc,{AlgoliaSearchIndex:()=>NQh,ApiDefinitionId:()=>nUh,ApiId:()=>sUh,Availability:()=>PUh,DocsConfigId:()=>cUh,EndpointId:()=>fUh,EndpointPathLiteral:()=>mUh,EnvironmentId:()=>lUh,FileId:()=>yUh,HttpMethod:()=>AUh,IndexSegmentId:()=>FQh,JqString:()=>vUh,OrgId:()=>oUh,PageId:()=>hUh,PayloadLocation:()=>YUh,PropertyKey:()=>gUh,PullRequestState:()=>xUh,RoleId:()=>OUh,TokenId:()=>uUh,TypeId:()=>_Uh,Url:()=>bUh,VersionId:()=>aUh,WebSocketId:()=>dUh,WebhookId:()=>pUh,algolia:()=>dtl,api:()=>Atl,commons:()=>Ptl,diff:()=>jUh,docs:()=>Ctl,generators:()=>Ttl,git:()=>Rtl,navigation:()=>Ftl,sdks:()=>Utl,snippets:()=>JUh,snippetsFactory:()=>$Uh,templates:()=>Ltl,tokens:()=>XUh});var dtl={};Yt(dtl,{AlgoliaSearchIndex:()=>NQh,IndexSegmentId:()=>FQh});function NQh(e){return e}function FQh(e){return e}var Atl={};Yt(Atl,{latest:()=>htl,v1:()=>mtl});var htl={};Yt(htl,{AuthSchemeId:()=>QQh,WebhookHttpMethod:()=>WQh,auth:()=>ptl,commons:()=>UQh,endpoint:()=>LQh,type_:()=>VQh,webhook:()=>_tl,websocket:()=>GQh});var ptl={};Yt(ptl,{AuthSchemeId:()=>QQh});function QQh(e){return e}var UQh={};var LQh={};var VQh={};var _tl={};Yt(_tl,{WebhookHttpMethod:()=>WQh});var WQh={Get:"GET",Post:"POST"};var GQh={};var mtl={};Yt(mtl,{SubpackageId:()=>eUh,WebSocketMessageId:()=>tUh,WebSocketMessageOrigin:()=>rUh,WebhookHttpMethod:()=>iUh,commons:()=>Otl,db:()=>ytl,read:()=>vtl,register:()=>gtl});var ytl={};Yt(ytl,{endpoint:()=>xQh});var xQh={};var vtl={};Yt(vtl,{SupportedLanguage:()=>HQh,endpoint:()=>btl,type_:()=>KQh,webhook:()=>JQh,websocket:()=>$Qh});var btl={};Yt(btl,{SupportedLanguage:()=>HQh});var HQh={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby",Csharp:"csharp"};var KQh={};var JQh={};var $Qh={};var gtl={};Yt(gtl,{SourceId:()=>uwB,endpoint:()=>YQh,type_:()=>XQh,webhook:()=>ZQh,websocket:()=>kQh});var YQh={};var XQh={};var ZQh={};var kQh={};function uwB(e){return e}var Otl={};Yt(Otl,{SubpackageId:()=>eUh,WebSocketMessageId:()=>tUh,WebSocketMessageOrigin:()=>rUh,WebhookHttpMethod:()=>iUh});function eUh(e){return e}function tUh(e){return e}var rUh={Client:"client",Server:"server"};var iUh={Get:"GET",Post:"POST"};var Ptl={};Yt(Ptl,{ApiDefinitionId:()=>nUh,ApiId:()=>sUh,Availability:()=>PUh,DocsConfigId:()=>cUh,EndpointId:()=>fUh,EndpointPathLiteral:()=>mUh,EnvironmentId:()=>lUh,FileId:()=>yUh,HttpMethod:()=>AUh,JqString:()=>vUh,OrgId:()=>oUh,PageId:()=>hUh,PropertyKey:()=>gUh,RoleId:()=>OUh,TokenId:()=>uUh,TypeId:()=>_Uh,Url:()=>bUh,VersionId:()=>aUh,WebSocketId:()=>dUh,WebhookId:()=>pUh});function nUh(e){return e}function aUh(e){return e}function oUh(e){return e}function uUh(e){return e}function sUh(e){return e}function cUh(e){return e}function lUh(e){return e}function fUh(e){return e}function dUh(e){return e}function pUh(e){return e}function _Uh(e){return e}function hUh(e){return e}function yUh(e){return e}function bUh(e){return e}function vUh(e){return e}function gUh(e){return e}function OUh(e){return e}function mUh(e){return e}var AUh={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var PUh={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var jUh={};var Ctl={};Yt(Ctl,{latest:()=>Etl,v1:()=>Btl,v2:()=>Itl});var Etl={};Yt(Etl,{Layout:()=>EUh,MdxEngine:()=>swB,TwitterCardSetting:()=>SUh,commons:()=>wUh,frontmatter:()=>jtl,seo:()=>wtl});var swB={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var wUh={};var jtl={};Yt(jtl,{Layout:()=>EUh});var EUh={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var wtl={};Yt(wtl,{TwitterCardSetting:()=>SUh});var SUh={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var Btl={};Yt(Btl,{commons:()=>Dtl,db:()=>MUh,read:()=>DUh,write:()=>Stl});var MUh={};var DUh={};var Stl={};Yt(Stl,{DocsRegistrationId:()=>lwB,FilePath:()=>cwB});function cwB(e){return e}function lwB(e){return e}var Dtl={};Yt(Dtl,{ContentAlignment:()=>qUh,FontDisplay:()=>FUh,FontStyle:()=>NUh,HeaderPosition:()=>TUh,JsScriptStrategy:()=>zUh,ProgrammingLanguage:()=>BUh,SearchbarPlacement:()=>IUh,TabsPlacement:()=>CUh,TwitterCardSetting:()=>RUh,commons:()=>Mtl});var Mtl={};Yt(Mtl,{ContentAlignment:()=>qUh,FontDisplay:()=>FUh,FontStyle:()=>NUh,HeaderPosition:()=>TUh,JsScriptStrategy:()=>zUh,ProgrammingLanguage:()=>BUh,SearchbarPlacement:()=>IUh,TabsPlacement:()=>CUh,TwitterCardSetting:()=>RUh});var BUh={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 IUh={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var CUh={Header:"HEADER",Sidebar:"SIDEBAR"};var qUh={Center:"CENTER",Left:"LEFT"};var TUh={Fixed:"FIXED",Absolute:"ABSOLUTE"};var RUh={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var zUh={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var NUh={Normal:"normal",Italic:"italic"};var FUh={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var Itl={};Yt(Itl,{read:()=>QUh,write:()=>UUh});var QUh={};var UUh={};var Ttl={};Yt(Ttl,{ChangelogEntryType:()=>VUh,GeneratorId:()=>fwB,GeneratorLanguage:()=>dwB,ReleaseType:()=>WUh,cli:()=>LUh,commons:()=>qtl,versions:()=>GUh});var LUh={};var qtl={};Yt(qtl,{ChangelogEntryType:()=>VUh,ReleaseType:()=>WUh});var VUh={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var WUh={Ga:"GA",Rc:"RC"};var GUh={};function fwB(e){return e}var dwB={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var Rtl={};Yt(Rtl,{PullRequestState:()=>xUh});var xUh={Open:"open",Closed:"closed",Merged:"merged"};var Ftl={};Yt(Ftl,{latest:()=>ztl,v1:()=>Ntl});var ztl={};Yt(ztl,{NodeId:()=>hwB,ProductId:()=>ywB,Slug:()=>pwB,TabId:()=>_wB});function pwB(e){return e}function _wB(e){return e}function hwB(e){return e}function ywB(e){return e}var Ntl={};Yt(Ntl,{NavigationV1Availability:()=>mwB,NodeId:()=>gwB,ProductId:()=>OwB,Slug:()=>bwB,TabId:()=>vwB});function bwB(e){return e}function vwB(e){return e}function gwB(e){return e}function OwB(e){return e}var mwB={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var Utl={};Yt(Utl,{Language:()=>HUh,VersionBump:()=>KUh,versions:()=>Qtl});var Qtl={};Yt(Qtl,{Language:()=>HUh,VersionBump:()=>KUh});var HUh={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var KUh={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var JUh={};var $Uh={};var Ltl={};Yt(Ltl,{PayloadLocation:()=>YUh});var YUh={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var XUh={};var a0u=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};function Ho(e){return e!=null}var kUh=ue(l4a(),1);var ZUh=["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 jXt(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,kUh.default)(e,{special:ZUh}).replace(/V\s(\d)/g,"V$1")}function e4h({endpoints:e,webhookEndpoints:t}){let r={};return Object.values({...e,...t}).forEach(i=>{let n=[];i.namespace?.forEach(a=>{let o=[...n,a],c=uc.api.v1.SubpackageId(o.join("."));r[c]={id:c,name:a,displayName:jXt(a)},n.push(a)})}),r}var o0u=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 t4h(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var mo=class extends o0u{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 ${t4h(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 mo{},DY=class extends IC{seenSchemas;constructor(t){super(t),this.seenSchemas=new Set(t.seenSchemas)}};var r4h="x-fern-base-path",i4h="x-fern-availability",u0u="x-fern-sdk-group-name",n4h="x-fern-global-headers",a4h="x-fern-sdk-method-name";var o4h="x-fern-webhook",u4h="x-fern-access-token-locator",s4h="x-fern-basic",c4h="x-fern-username-variable-name",l4h="x-fern-password-variable-name",f4h="x-fern-bearer",d4h="x-fern-token-variable-name",p4h="x-fern-header",_4h="x-fern-header-variable-name",h4h="x-fern-server-name",y4h="x-fern-examples";var s0u=class extends mo{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[h4h]}convert(){if(this.serverName!=null)return this.serverName}};var c0u=class extends mo{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 s0u({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:uc.EnvironmentId(t),baseUrl:this.url}}};function yYi(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 c0u({input:c,context:r,accessPath:i,pathId:["servers",`${d}`]}));return[...n,...o]}function tg(e){return typeof e=="object"&&Ho(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:(tg(n)&&(n=IL(n,t,r)),n)}function l0u(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return tg(r)?IL(r,t,void 0):r}var uLh=ue(bM());var f0u=class extends mo{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[s4h];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var d0u=class extends mo{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[l4h]}convert(){return this.passwordVariableName}};var p0u=class extends mo{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[c4h]}convert(){return this.usernameVariableName}};var _0u=class extends mo{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[f4h];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var h0u=class extends mo{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[d4h]}convert(){return this.tokenVariableName}};function b4h(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var v4h="x-bearer-format",g4h="x-code-samples",O4h="x-codeSamples";var y0u=class extends mo{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[v4h]}convert(){return this.bearerFormat}};var b0u=class extends mo{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[p4h];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var v0u=class extends mo{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[_4h]}convert(){return this.headerVariableName}};function m4h(e){return e.type==="apiKey"}var Gca=class extends mo{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){m4h(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new b0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new v0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new y0u({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 g0u(e){return e}function O0u(e){return e==="__proto__"}function m0u(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function xca(e){return typeof e=="string"||typeof e=="symbol"?e:Object.is(e?.valueOf?.(),-0)?"-0":String(e)}function LYa(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e))return e.map(LYa).join(",");let t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function A0u(e){if(Array.isArray(e))return e.map(xca);if(typeof e=="symbol")return[e];e=LYa(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 VYa(e,t,r){if(e==null)return r;switch(typeof t){case"string":{if(O0u(t))return r;let i=e[t];return i===void 0?m0u(t)?VYa(e,A0u(t),r):r:i}case"number":case"symbol":{typeof t=="number"&&(t=xca(t));let i=e[t];return i===void 0?r:i}default:{if(Array.isArray(t))return AwB(e,t,r);if(Object.is(t?.valueOf(),-0)?t="-0":t=String(t),O0u(t))return r;let i=e[t];return i===void 0?r:i}}}function AwB(e,t,r){if(t.length===0)return r;let i=e;for(let n=0;n<t.length;n++){if(i==null||O0u(t[n]))return r;i=i[t[n]]}return i===void 0?r:i}function A4h(e){return function(t){return VYa(t,e)}}function P4h(e){return e!==null&&(typeof e=="object"||typeof e=="function")}function P0u(e){return e==null||typeof e!="object"&&typeof e!="function"}function Vtl(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function Gtl(e,t,r){return typeof r!="function"?Gtl(e,t,()=>{}):Wtl(e,t,function i(n,a,o,c,d,s){let u=r(n,a,o,c,d,s);return u!==void 0?!!u:Wtl(n,a,i,s)},new Map)}function Wtl(e,t,r,i){if(t===e)return!0;switch(typeof t){case"object":return PwB(e,t,r,i);case"function":return Object.keys(t).length>0?Wtl(e,{...t},r,i):Vtl(e,t);default:return P4h(e)?typeof t=="string"?t==="":!0:Vtl(e,t)}}function PwB(e,t,r,i){if(t==null)return!0;if(Array.isArray(t))return j4h(e,t,r,i);if(t instanceof Map)return jwB(e,t,r,i);if(t instanceof Set)return wwB(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(!P0u(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 jwB(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 j4h(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 wwB(e,t,r,i){return t.size===0?!0:e instanceof Set?j4h([...e],[...t],r,i):!1}function j0u(e,t){return Gtl(e,t,()=>{})}function w4h(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function w0u(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}var E4h="[object RegExp]",E0u="[object String]",S0u="[object Number]",M0u="[object Boolean]",D0u="[object Arguments]",S4h="[object Symbol]",M4h="[object Date]",D4h="[object Map]",B4h="[object Set]",I4h="[object Array]";var C4h="[object ArrayBuffer]",q4h="[object Object]";var T4h="[object DataView]",R4h="[object Uint8Array]",z4h="[object Uint8ClampedArray]",N4h="[object Uint16Array]",F4h="[object Uint32Array]";var Q4h="[object Int8Array]",U4h="[object Int16Array]",L4h="[object Int32Array]";var V4h="[object Float32Array]",W4h="[object Float64Array]";function G4h(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function x4h(e,t){return bYi(e,void 0,e,new Map,t)}function bYi(e,t,r,i=new Map,n=void 0){let a=n?.(e,t,r,i);if(a!==void 0)return a;if(P0u(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]=bYi(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,bYi(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(bYi(c,void 0,r,i,n));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(e))return e.subarray();if(G4h(e)){let o=new(Object.getPrototypeOf(e)).constructor(e.length);i.set(e,o);for(let c=0;c<e.length;c++)o[c]=bYi(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),k8t(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),k8t(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),k8t(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,k8t(o,e,r,i,n),o}if(e instanceof Boolean){let o=new Boolean(e.valueOf());return i.set(e,o),k8t(o,e,r,i,n),o}if(e instanceof Number){let o=new Number(e.valueOf());return i.set(e,o),k8t(o,e,r,i,n),o}if(e instanceof String){let o=new String(e.valueOf());return i.set(e,o),k8t(o,e,r,i,n),o}if(typeof e=="object"&&EwB(e)){let o=Object.create(Object.getPrototypeOf(e));return i.set(e,o),k8t(o,e,r,i,n),o}return e}function k8t(e,t,r=e,i,n){let a=[...Object.keys(t),...w4h(t)];for(let o=0;o<a.length;o++){let c=a[o],d=Object.getOwnPropertyDescriptor(e,c);(d==null||d.writable)&&(e[c]=bYi(t[c],c,r,i,n))}}function EwB(e){switch(w0u(e)){case D0u:case I4h:case C4h:case T4h:case M0u:case M4h:case V4h:case W4h:case Q4h:case U4h:case L4h:case D4h:case S0u:case q4h:case E4h:case B4h:case E0u:case S4h:case R4h:case z4h:case N4h:case F4h:return!0;default:return!1}}function H4h(e){return bYi(e,void 0,e,new Map,void 0)}function K4h(e){return e=H4h(e),t=>j0u(t,e)}function J4h(e,t){return x4h(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 S0u:case E0u:case M0u:{let c=new e.constructor(e?.valueOf());return k8t(c,e),c}case D0u:{let c={};return k8t(c,e),c.length=e.length,c[Symbol.iterator]=e[Symbol.iterator],c}default:return}})}function $4h(e){return J4h(e)}var SwB=/^(?:0|[1-9]\d*)$/;function Y4h(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 SwB.test(e)}}function X4h(e){return e!==null&&typeof e=="object"&&w0u(e)==="[object Arguments]"}function Z4h(e,t){let r;if(Array.isArray(t)?r=t:typeof t=="string"&&m0u(t)&&e?.[t]==null?r=A0u(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)||X4h(i))&&Y4h(a)&&a<i.length))return!1;i=i[a]}return!0}function k4h(e,t){switch(typeof e){case"object":{Object.is(e?.valueOf(),-0)&&(e="-0");break}case"number":{e=xca(e);break}}return t=$4h(t),function(r){let i=VYa(r,e);return i===void 0?Z4h(r,e):t===void 0?i===void 0:j0u(i,t)}}function eLh(e){if(e==null)return g0u;switch(typeof e){case"function":return e;case"object":return Array.isArray(e)&&e.length===2?k4h(e[0],e[1]):K4h(e);case"string":case"symbol":case"number":return A4h(e)}}function tLh(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 B0u(e,t=g0u){return e==null?{}:tLh(e,eLh(t))}function rLh(e){return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}var MwB=new RegExp("\\p{Lu}?\\p{Ll}+|[0-9]+|\\p{Lu}+(?!\\p{Ll})|\\p{Emoji_Presentation}|\\p{Extended_Pictographic}|\\p{L}+","gu");function iLh(e){return Array.from(e.match(MwB)??[])}function nLh(e){let t=iLh(e);if(t.length===0)return"";let[r,...i]=t;return`${r.toLowerCase()}${i.map(n=>rLh(n)).join("")}`}function aLh(e){return typeof e!="string"&&(e=LYa(e)),e.replace(/['\u2019]/g,"")}function eWt(e){return nLh(aLh(e))}function ij(e){if(e!=null)return Array.isArray(e)?e:[e]}function I0u({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`${DwB(o)}${BwB(e)}.${IwB(i,n,a,c)}`}function DwB(e){return e?"webhook_":"endpoint_"}function BwB(e){return e!=null?ij(e)?.map(t=>eWt(t)).join("/"):""}function IwB(e,t,r,i){return e||t||eWt(r??"")||eWt(i??"")}function oLh(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var C0u=class extends mo{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[u4h],this.accessTokenLocator!=null&&(oLh(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 q0u=class extends mo{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 Gca({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new C0u({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=I0u({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:uc.EndpointId(r),accessTokenLocator:uc.JqString(t),headerName:this.headerAuthNode?.convert()?.headerWireValue,tokenPrefix:this.headerAuthNode?.convert()?.prefix}}}}};var Hca=class extends mo{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 f0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicUsernameVariableNameNode=new p0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new d0u({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 _0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new h0u({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":{b4h(this.input)?(this.authScheme="header",this.headerAuthNode=new Gca({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 q0u({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 uLh.UnreachableCaseError(this.authScheme);return}}};var Kca=class extends mo{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(i=>{let n=l0u(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 Hca({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(Ho))}};var T0u=class extends mo{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[r4h],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 sLh(e){return"required"in e&&typeof e.required=="boolean"?e.required:!1}function cLh(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function Jca(e,t){return e==null?void 0:Object.entries(e).map(([i,n])=>ij(n.convert())?.map(o=>((t!=null&&!t.includes(i)||t==null&&!sLh(n))&&(o=cLh(o,o.type==="enum"?o.default:void 0)),{key:uc.PropertyKey(i),valueShape:o,description:n.description,availability:n.availability?.convert()})).filter(Ho)).filter(Ho).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(o=>[...a,o]):[[...a]]),[[]])}function R0u(e,t){return tg(e)?IL(e,t,void 0):e}function vYi(e,t){return e!=null&&e!==""?e:t!=null&&t!==""?t:void 0}function lLh(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 fLh(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 dLh=ue(bM());var xtl=["decimal","decimal128","double-int","double","float","sf-decimal"],Htl=["int16","int32","int64","int8","sf-integer","uint8"],Ktl=["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"],Jtl=["beta","pre-release","in-development","generally-available","deprecated"];function CC(e,t){return tg(e)?IL(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var ESe=class extends mo{availability;constructor(t){super(t),this.safeParse()}parse(){if(CC(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[i4h];r!=null&&(Jtl.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${Jtl.join(", ")}. Received: ${r}`,path:this.accessPath}),this.availability=void 0))}}convert(){switch(this.availability){case"beta":case"pre-release":return uc.Availability.Beta;case"in-development":return uc.Availability.InDevelopment;case"generally-available":return uc.Availability.GenerallyAvailable;case"deprecated":return uc.Availability.Deprecated;case void 0:return;default:new dLh.UnreachableCaseError(this.availability);return}}};var N0u=ue(bM());function pLh(e){return typeof e=="object"&&e!=null&&"language"in e}function _Lh(e){return typeof e=="object"&&e!=null&&"sdk"in e}function hLh(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function yLh(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function z0u(e){return typeof e=="object"&&e!=null&&"event"in e}function $tl(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(z0u)}function gYi(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function bLh(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var F0u=class extends mo{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[y4h]}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 gYi(o)?[n,{type:"filenameWithData",filename:o.filename,data:uc.FileId(o.data)}]:o!=null?[n,{type:"filename",value:o}]:void 0;case"files":{if(Array.isArray(o)){if(o.every(c=>gYi(c)))return[n,{type:"filenamesWithData",value:o.map(c=>({filename:c.filename,data:uc.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 N0u.UnreachableCaseError(a.multipartType);return}}).filter(Ho))};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=bLh(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 N0u.UnreachableCaseError(n.contentType);break}let o;switch(i.contentType){case"application/json":{hLh(r.response)&&(o={type:"json",value:r.response.body});break}case"text/event-stream":{$tl(r.response)&&(o={type:"sse",value:r.response.stream.map(l=>({event:l.event,data:l.data}))});break}case"application/octet-stream":!$tl(r.response)&&yLh(r.response)&&(o={type:"stream",value:r.response.stream});break;case void 0:break;default:new N0u.UnreachableCaseError(i.contentType);break}let c={};r["code-samples"]?.forEach(l=>{pLh(l)?l.language!=null&&(c[l.language]??=[],c[l.language]?.push({name:l.name,language:l.language,install:l.install,code:l.code,generated:!1,description:l.docs})):_Lh(l)&&l.sdk!=null&&(c[l.sdk]??=[],c[l.sdk]?.push({name:l.name,language:l.sdk,install:void 0,code:l.code,generated:!1,description:l.docs}))});let d=Object.fromEntries(Object.entries(r["path-parameters"]??{}).map(([l,p])=>[uc.PropertyKey(l),p])),s=Object.fromEntries(Object.entries(r["query-parameters"]??{}).map(([l,p])=>[uc.PropertyKey(l),p])),u=Object.fromEntries(Object.entries(r.headers??{}).map(([l,p])=>[uc.PropertyKey(l),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 WYa=class extends mo{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[u0u]}convert(){if(this.groupName==null)return;let t;return Array.isArray(this.groupName)?t=this.groupName:t=[this.groupName],t.map(r=>uc.api.v1.SubpackageId(eWt(r)))}};var Q0u=class extends mo{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[a4h]}convert(){return this.sdkMethodName}};var U0u=class extends mo{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[o4h]}convert(){return this.isWebhook}};var L0u=class extends mo{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[g4h]??[],...this.input[O4h]??[]],this.codeSamples.forEach(t=>{[...Object.values(uc.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 kgn=ue(bM());function Ytl(e,t){return tg(e)?IL(e,t,void 0):e}function vLh(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 TF="",wXt=class extends mo{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&&(gYi(n)||typeof n=="string");case"files":return t&&Array.isArray(n)&&n.every(a=>gYi(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new kgn.UnreachableCaseError(i.multipartType),t}},!0)}parse(){let t=this.shapes.requestBody?.schema?.example({includeOptionals:!1,override:void 0});this.resolvedRequestInput=Ytl(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=Ytl(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 kgn.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(z0u)){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 kgn.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 gYi(n)?[r,{type:"filenameWithData",filename:n.filename,data:uc.FileId(n.data)}]:[r,{type:"filename",value:n}];case"files":{if(Array.isArray(n)){if(n.every(a=>gYi(a)))return[r,{type:"filenamesWithData",value:n.map(a=>({filename:a.filename,data:uc.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 kgn.UnreachableCaseError(i.multipartType);return}}).filter(Ho))};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 kgn.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 kgn.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(Ho));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(Ho));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:vLh(this.path,i??{}),responseStatusCode:this.responseStatusCode,name:this.name!=null?jXt(this.name):this.summary!=null?jXt(this.summary):void 0,description:this.convertDescription(),pathParameters:i,queryParameters:n,headers:a,requestBody:t,responseBody:r,snippets:void 0}}};function gLh(e,t){return tg(e)?IL(e,t,void 0):e}var CLh=ue(bM());var OLh="#/components/schemas/";function $ca(e){if(e.$ref.startsWith(OLh))return e.$ref.replace(OLh,"")}function d4i(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}function OYi(e){return typeof e.type=="string"&&e.type==="array"}function mLh(e){return e.type==="boolean"}function ALh(e){return e.type==="integer"}function mYi(e){return!Array.isArray(e.type)&&!OYi(e)}function PLh(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||mYi(t)||OYi(t))}function jLh(e){return"nullable"in e&&typeof e.nullable=="boolean"}function wLh(e){return e.type==="null"}function ELh(e){return e.type==="number"}function Xtl(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function SLh(e){return e.type==="string"}var V0u=class extends DY{item;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.item=new hw({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 ij(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 W0u=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 ESe({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 G0u=class extends DY{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 hw({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName})}).filter(Ho)}convert(){if(this.typeNodes==null)return;let i=this.typeNodes.map(n=>ij(n.convert())?.map(o=>({displayName:n.name,shape:o,description:n.description,availability:n.availability?.convert()}))).filter(Ho).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(d4i).filter(Ho):i}example(t){return this.nullable?null:this.typeNodes?.[0]?.example(t)}};function x0u(e){return e!=null&&e.length>0?e:[void 0]}var Yca=class extends DY{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 hw({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 hw({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(tg(t))return $ca(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([i,n])=>[i,new hw({input:n,context:this.context,accessPath:this.accessPath,pathId:["allOf",r.toString(),"properties",i],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))}}).filter(Ho))),this.description=this.input.description}convertProperties(){if(this.properties!=null)return Jca(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}}}]:ij(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(Ho)}convert(){let t=this.convertProperties();if(t==null)return;let r=this.convertExtraProperties();return t.flatMap(i=>x0u(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=>uc.TypeId(a)),properties:i,extraProperties:n}))}example({includeOptionals:t}){let r={...this.properties};return this.input.allOf?.forEach(i=>{let n=CC(i,this.context.document);n!=null&&(r={...r,...Object.fromEntries(Object.entries(n.properties??{}).map(([a,o])=>[a,new hw({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 H0u=class extends DY{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=>CC(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>CC(t,this.context.document)?.type!=="null"?new hw({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0).filter(Ho);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=CC({$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 hw({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(Ho);return this.isNullable&&n!=null?n.map(d4i).filter(Ho):n}let t=0,r=this.discriminated&&this.discriminant!=null&&this.discriminatedMapping!=null?{type:"discriminatedUnion",discriminant:uc.PropertyKey(this.discriminant),variants:Object.entries(this.discriminatedMapping).flatMap(([n,a])=>ij(a.convert())?.map(c=>{if(!(c==null||c.type!=="object"))return{discriminantValue:n,displayName:a.name??jXt(n),availability:a.availability?.convert(),description:a.description,...c}}).filter(Ho)).filter(Ho)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(n=>ij(n.convert())?.map(o=>{if(o==null)return;t+=1;let c=o.type==="object"?jXt(`${this.schemaName??"Variant"} ${t}`):void 0;return{displayName:n.name??(o.type==="alias"&&o.value.type==="id"?jXt(o.value.id):c),shape:o,description:n.description,availability:n.availability?.convert()}}).filter(Ho)).filter(Ho)}:void 0,i=this.isNullable?d4i(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 K0u=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 AYi=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(tg(r)){let n=CC(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(Ho),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 MLh=ue(bM());function CwB(e){return Htl.includes(e)}var J0u=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&&(CwB(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${Htl.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 MLh.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 $0u=class extends IC{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return d4i({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var DLh=ue(bM());function qwB(e){return xtl.includes(e)}var Y0u=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&&(qwB(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${xtl.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 DLh.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 BLh=ue(bM());function TwB(e){return Ktl.includes(e)}var X0u=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 BLh.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&&(TwB(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${Ktl.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new AYi({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 ILh=ue(bM());var Z0u=class extends IC{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,ILh.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var eOn=class extends DY{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=$ca(this.input);let t=CC(this.input,this.context.document);t?.enum!=null&&mYi(t)&&(this.maybeEnumConverterNode=new AYi({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:uc.TypeId(this.schemaId),default:this.maybeEnumConverterNode?.default!=null?{type:"enum",value:this.maybeEnumConverterNode.default}:void 0}}}example(t){let r=CC(this.input,this.context.document);if(r!=null)return new hw({input:r,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName}).example(t)}};var hw=class e extends DY{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 ESe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),mYi(this.input)&&jLh(this.input)&&(this.nullable=this.input.nullable!=null?this.input.nullable:this.nullable),tg(this.input)){let t=$ca(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 eOn({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 W0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(PLh(this.input))this.typeShapeNode=new G0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(mYi(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new H0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(Xtl(this.input)&&this.input.allOf!=null)this.typeShapeNode=new Yca({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(mYi(this.input)&&this.input.enum!=null)this.typeShapeNode=new AYi({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":Xtl(this.input)&&(this.typeShapeNode=new Yca({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"array":OYi(this.input)&&(this.typeShapeNode=new V0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"boolean":mLh(this.input)&&(this.typeShapeNode=new K0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"integer":ALh(this.input)&&(this.typeShapeNode=new J0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"number":ELh(this.input)&&(this.typeShapeNode=new Y0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"string":SLh(this.input)&&(this.typeShapeNode=new X0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"null":wLh(this.input)&&(this.typeShapeNode=new $0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case void 0:break;default:new CLh.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 Yca({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 Z0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),!tg(this.input)&&(!OYi(this.input)&&this.input==null||OYi(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=ij(t)?.map(i=>this.nullable?d4i(i):i).filter(Ho);return Array.isArray(t)&&t.length>1?r:r?.[0]}example(t){return this.availability?.availability!=="deprecated"?this.typeShapeNode?.example(t):void 0}};function PYi(e){if(e!=null)return Jca(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(Ho))}var EXt=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;tg(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 ESe({input:r,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new hw({input:r,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:t});let i=gLh(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 qLh(e,t){return tg(e)?IL(e,t,void 0):e}var Ztl=ue(bM());function k0u(e){let{uniqueId:t,type:r,contextTypes:i,description:n,availability:a}=e;i[uc.TypeId(t)]={name:t,shape:r,description:n,availability:a}}var TLh=ue(fnc(),1),Xca=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=TLh.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 RwB(e){return typeof e.securitySchemes=="object"&&e.securitySchemes!=null}var ewu=class extends mo{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 hw({input:r,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:new Set,nullable:void 0,schemaName:t})]))),RwB(this.input)&&this.input.securitySchemes!=null&&(this.securitySchemes=Object.fromEntries(Object.entries(this.input.securitySchemes??{}).map(([t,r],i)=>{let n;if(tg(r)?n=l0u(r.$ref,this.context.document):n=r,n!=null)return[t,new Hca({input:n,context:this.context,accessPath:this.accessPath,pathId:["securitySchemes",`${i}`]})]}).filter(Ho)))}convert(){return{auths:this.securitySchemes!=null?Object.fromEntries(Object.entries(this.securitySchemes??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[uc.api.latest.AuthSchemeId(t),i]}).filter(Ho)):void 0,types:this.typeSchemas!=null?Object.fromEntries(Object.entries(this.typeSchemas).map(([t,r])=>{let i=r.name??t,n=ij(r.convert());return n==null?[t,void 0]:[uc.TypeId(t),{name:i,shape:n[0],description:r.description,availability:void 0}]}).filter(([t,r])=>Ho(r))):void 0}}};var twu=class extends hw{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=CC(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${tg(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=CC(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 rwu=class extends mo{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=CC(this.input.schema,this.context.document);this.availability=new ESe({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=tg(this.input.schema)?new eOn({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=Xca.parse(t);n?.containsJSON()?(this.contentType="json",this.schema=this.schema??new hw({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 twu({input:o,context:this.context,accessPath:this.accessPath,pathId:`schema.${a}`,seenSchemas:new Set,nullable:void 0,schemaName:a})]}).filter(Ho))):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?{[TF]:{value:this.input.example}}:{},...this.input.examples},r!=null&&Object.keys(this.examples).length===0&&(this.examples={[TF]:{value:r}})}convertJsonLike(){let t=this.schema?.convert();return t==null?void 0:ij(t)?.map(i=>{let n=i.type;switch(n){case"object":case"alias":return i;case"enum":case"undiscriminatedUnion":case"discriminatedUnion":{let a=eWt([this.method,this.path,this.contentType,"request"].join("_"));return k0u({uniqueId:a,type:i,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:uc.TypeId(a),default:i.type==="enum"&&i.default!=null?{type:"enum",value:i.default}:void 0}}}case void 0:return;default:new Ztl.UnreachableCaseError(n);return}}).filter(Ho)}convert(){if(this.schema instanceof eOn)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:uc.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:uc.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"property":{let a=ij(n.convert()),o=n.multipartType;return a?.map(c=>({type:o,key:uc.PropertyKey(i),contentType:n.contentType,exploded:void 0,valueShape:c,description:n.description,availability:n.availability?.convert()}))}case void 0:return[];default:return new Ztl.UnreachableCaseError(n.multipartType),[]}}).filter(Ho).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 iwu=class extends mo{description;requestBodiesByContentType;constructor(t){super(t),this.safeParse(t)}parse({method:t,path:r}){let i=qLh(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 rwu({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])=>ij(r.convert())?.map(n=>({description:this.description,contentType:t,body:n}))).filter(Ho)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>ij(t.convert())?.map(i=>{if(!(i.type!=="alias"&&i.type!=="object"))return{description:this.description,shape:i}})).filter(Ho)}webhookExample(){return{payload:this.requestBodiesByContentType?.["application/json"]?.schema?.example({includeOptionals:!0,override:void 0})}}};var RLh={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 zLh(e,t){if(tg(e)){let r=IL(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var nwu=ue(bM());var NLh="application/json";var FLh="application/octet-stream";function QLh(e,t){return e===t||t===TF||e===TF}var GYa=class extends mo{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)QLh(c,a)&&(i.add(c),this.examples?.push(new wXt({input:{requestExample:o,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,vYi(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(l=>new wXt({input:{requestExample:u,responseExample:l},context:this.context,accessPath:this.accessPath,pathId:s!=null&&s!==""?["examples",s]:"examples"},this.path,this.statusCode,vYi(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 wXt({input:{requestExample:s,responseExample:u},context:this.context,accessPath:this.accessPath,pathId:d!=null&&d!==""?["examples",d]:"examples"},this.path,this.statusCode,vYi(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 wXt({input:{requestExample:o,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,vYi(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[TF];if(a!=null)for(let o of a)this.examples?.push(new wXt({input:{requestExample:n,responseExample:o},context:this.context,accessPath:this.accessPath,pathId:i!=null&&i!==""?["examples",i]:"examples"},this.path,this.statusCode,vYi(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=Xca.parse(t);if(c?.isJSON()||c?.isEventStream())this.contentType=NLh,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 hw({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=FLh,this.contentSubtype=CC(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 hw({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=B0u(this.input.examples,c=>[c])),this.input.example!=null&&Object.keys(r).length===0&&(r[TF]??=[],r[TF]=[{value:this.input.example}]);let i=CC(this.input.schema,this.context.document);if(i!=null&&(i.examples!=null&&Object.keys(r).length===0&&(r=B0u(i.examples,c=>[c])),i.example!=null&&Object.keys(r).length===0&&(r[TF]??=[],r[TF]?.push({value:i.example}))),Object.keys(r).length===0){let c=this.schema?.example({includeOptionals:!0,override:void 0});r[TF]??=[],r[TF]?.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!==TF).map(([d,s])=>[c,d,s]));let o=Object.entries(r).filter(([c,d])=>!n.has(c)&&Ho(d)&&c!==TF);Object.keys(r).every(c=>c===TF)||this.matchExamplesByIndex(a,o),!n.has(TF)&&this.examples.length===0&&this.addGlobalFallbackExample(this.requests,r),this.examples.length===0&&(this.examples=void 0)}convertStreamingFormat(){switch(this.streamingFormat){case"json":return ij(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new nwu.UnreachableCaseError(this.streamingFormat);return}}convertJsonLike(){return ij(this.schema?.convert())?.map(r=>{let i=r.type;switch(i){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":{let n=eWt([this.method,this.path,this.statusCode,"response"].join("_"));return k0u({uniqueId:n,type:r,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:uc.TypeId(n),default:r.type==="enum"&&r.default!=null?{type:"enum",value:r.default}:void 0}}}case"object":return r;default:new nwu.UnreachableCaseError(i);return}}).filter(Ho)}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 nwu.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?this.convertJsonLike():void 0}};var xYa=class extends mo{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=zLh(this.input,this.context.document);if(r==null){this.context.errors.error({message:tg(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 EXt({input:n,context:this.context,accessPath:this.accessPath,pathId:"headers",parameterName:i})}),r.content==null?(this.responses??=[],this.responses.push(new GYa({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 GYa({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(Ho)}};var awu=class extends mo{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 xYa({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 xYa({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 x0u(PYi(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(Ho))})))}).filter(Ho)}convertResponseObjectToErrors(){return Object.entries(this.errorsByStatusCode??{}).flatMap(([t,r])=>r.responses?.flatMap(i=>{let n=i.schema,a=ij(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??RLh[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(Ho)})).filter(Ho)})).filter(Ho)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var jYi=class extends mo{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 wXt({input:{requestExample:t,responseExample:void 0},context:this.context,accessPath:this.accessPath,pathId:"examples"},this.path,200,vYi(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 ESe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=yYi(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new U0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((i,n)=>{if(tg(i)){let a=R0u(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 EXt({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 EXt({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 EXt({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 L0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new iwu({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 awu({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 Kca({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespaces=[new WYa({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 WYa({input:{[u0u]:i},context:this.context,accessPath:this.accessPath,pathId:["tags",`${n}`]})));let r=new Q0u({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointIds=this.namespaces.map(i=>I0u({namespace:ij(i?.groupName),path:this.path,method:this.method,sdkMethodName:r.sdkMethodName,operationId:this.input.operationId,displayName:this.displayName,isWebhook:this.isWebhook})).filter(Ho),this.xFernExamplesNode=new F0u({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(Ho)}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:uc.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(Ho),n=fLh(this.xFernExamplesNode?.convert(),[...i??[],...t?.flatMap(u=>u.examples)??[]])?.map(u=>({...u,snippets:lLh(u.snippets,this.redocExamplesNode?.convert())}));if(this.isWebhook)return this.endpointIds.map((u,l)=>{if(!(this.method!=="POST"&&this.method!=="GET"))return{id:uc.WebhookId(u),description:this.description,availability:this.availability?.convert(),displayName:this.displayName,operationId:this.operationId,namespace:this.namespaces?.[l]?.convert(),method:this.method,path:this.convertPathToPathParts()?.map(p=>p.value.toString())??[],queryParameters:PYi(this.queryParameters)?.flat(),headers:PYi(this.requestHeaders)?.flat(),payloads:this.requests?.convertToWebhookPayload(),examples:[this.requests?.webhookExample()].filter(Ho)}}).filter(Ho);let a=this.servers?.map(u=>u.convert()).filter(Ho),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(Ho);return this.endpointIds.map((u,l)=>({id:uc.EndpointId(u),description:this.description,availability:this.availability?.convert(),namespace:this.namespaces?.[l]?.convert()?.map(p=>uc.api.v1.SubpackageId(p)),displayName:this.displayName,operationId:this.operationId,method:this.method,path:o,auth:c?.map(p=>uc.api.latest.AuthSchemeId(p)),defaultEnvironment:a?.[0]?.id,environments:a,pathParameters:PYi(this.pathParameters)?.flat(),queryParameters:PYi(this.queryParameters)?.flat(),requestHeaders:PYi(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 Zca=class extends mo{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=yYi(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 jYi({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 jYi({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 jYi({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 jYi({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 jYi({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(Ho)}};function owu(e){return"payloads"in e}var uwu=class extends mo{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 Zca({input:a,context:this.context,accessPath:this.accessPath,pathId:n,servers:yYi(t,a.servers,this.context,this.accessPath),globalAuth:r,basePath:i,isWebhook:void 0})}).filter(Ho)}convert(){if(this.paths==null)return;let t={},r={};return this.paths.forEach(i=>{let n=i.convert();n?.forEach(a=>{owu(a)?r[uc.WebhookId(a.id)]=a:t[uc.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var swu=class extends mo{globalHeaders;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[n4h]?.map(r=>{let{header:i,...n}=r;return(n.optional!=null&&!n.optional||R0u(n,this.context.document)?.required)&&(this.requiredProperties??=[],this.requiredProperties?.push(i)),[i,new EXt({input:n,context:this.context,accessPath:this.accessPath,pathId:this.pathId,parameterName:i})]});t!=null&&(this.globalHeaders=Object.fromEntries(t))}convert(){return Jca(this.globalHeaders,this.requiredProperties)?.flat()}};function ULh(e,t){if(tg(e)){let r=IL(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var cwu=class extends mo{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=ULh(a,this.context.document);if(o!=null)return new Zca({input:o,context:this.context,accessPath:this.accessPath,pathId:n,servers:t,globalAuth:r,basePath:i,isWebhook:!0})}).filter(Ho)}convert(){return this.webhooks?.reduce((t,r)=>(r.convert()?.forEach(i=>{owu(i)&&(t[uc.WebhookId(i.id)]=i)}),t),{})}};var lwu=class extends mo{paths;webhooks;components;auth;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){let t=yYi(void 0,this.input.servers,this.context,this.accessPath);this.input.security!=null&&(this.auth=new Kca({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"}));let r=new T0u({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 uwu({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 cwu({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 ewu({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"})),this.globalHeaders=new swu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=Tve(),{webhookEndpoints:r,endpoints:i}=this.paths?.convert()??{},n={...this.webhooks?.convert()??{},...r??{}},a=e4h({endpoints:i,webhookEndpoints:n}),{types:o,auths:c}=this.components?.convert()??{};return{id:uc.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 ktl(e,t){if(e instanceof hSe){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof jS))return;let r=new V8t(e.absoluteFilePath),i=await bSe({context:t,specs:e.specs}),n=await r.loadDocuments({context:t,specs:i,loadAiExamples:!0}),a;for(let o of n){if(o.type!=="openapi")continue;let c={document:o.value,logger:t.logger,errors:new a0u,generatedTypes:{}},d=new lwu({input:o.value,context:c,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=p$n(a,d.convert())}return a}var nKh=ue(rrl(),1),aKh=ue(Zwu(),1),ASu=require("fs/promises"),oKh=ue(require("http"),1),uKh=ue(require("path"),1);var G5h=require("events"),iEu=ue(require("fs"),1),lOn=ue(require("path"),1);var E5h=ue(require("os"),1),S5h=300,IYi=20,_Xa=1e7,M5h=E5h.default.platform();var iqB=M5h==="darwin",Ail=M5h==="win32",CYi=iqB||Ail,D5h=3e3,B5h=2e4,Pil=1250;var BXt;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(BXt||(BXt={}));var cOn;(function(e){e.CHANGE="change",e.RENAME="rename"})(cOn||(cOn={}));var hXa;(function(e){e.CHANGE="change",e.ERROR="error"})(hXa||(hXa={}));var rf;(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"})(rf||(rf={}));var zx;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(zx||(zx={}));var nqB=(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 O=Date.now(),A=O-d,j=O-s,M=A>=t||j>=a;return[O,M]},l=O=>{if(s=O,!o)return;let A=o;o=void 0,e.apply(void 0,A)},p=()=>{g(0)},_=()=>{c&&(p(),l(Date.now()))},h=O=>{if(s=O,i)return l(O)},y=O=>{if(n&&o)return l(O);o=void 0},b=()=>{c=void 0;let[O,A]=u();return A?y(O):v(O)},v=O=>{let A=O-d,j=O-s,M=t-A,w=a-j,D=Math.min(M,w);return g(D)},g=O=>{c&&clearTimeout(c),!(O<=0)&&(c=setTimeout(b,O))},m=(...O)=>{let[A,j]=u(),M=!!c;if(o=O,d=A,(j||!c)&&g(t),j)return M?l(A):h(A)};return m.cancel=p,m.flush=_,m},kwu=nqB;var Sil=ue(require("fs"),1),tEu=ue(require("path"),1);var dm=ue(require("fs"),1),CL=require("util");var _4i=(e,t)=>function(...i){return e.apply(void 0,i).catch(t)},IXt=(e,t)=>function(...i){try{return e.apply(void 0,i)}catch(n){return t(n)}};var jil=ue(require("process"),1),I5h=jil.default.getuid?!jil.default.getuid():!1,C5h=1e4,qY=()=>{};var yXa={isChangeErrorOk:e=>{if(!yXa.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!I5h&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!yXa.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(!yXa.isNodeError(e))throw e;if(!yXa.isChangeErrorOk(e))throw e}},qC=yXa;var wil=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=C5h,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()}}}}},q5h=new wil;var h4i=(e,t)=>function(i){return function n(...a){return q5h.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)})}},y4i=(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 aqB={attempt:{chmod:_4i((0,CL.promisify)(dm.default.chmod),qC.onChangeError),chown:_4i((0,CL.promisify)(dm.default.chown),qC.onChangeError),close:_4i((0,CL.promisify)(dm.default.close),qY),fsync:_4i((0,CL.promisify)(dm.default.fsync),qY),mkdir:_4i((0,CL.promisify)(dm.default.mkdir),qY),realpath:_4i((0,CL.promisify)(dm.default.realpath),qY),stat:_4i((0,CL.promisify)(dm.default.stat),qY),unlink:_4i((0,CL.promisify)(dm.default.unlink),qY),chmodSync:IXt(dm.default.chmodSync,qC.onChangeError),chownSync:IXt(dm.default.chownSync,qC.onChangeError),closeSync:IXt(dm.default.closeSync,qY),existsSync:IXt(dm.default.existsSync,qY),fsyncSync:IXt(dm.default.fsync,qY),mkdirSync:IXt(dm.default.mkdirSync,qY),realpathSync:IXt(dm.default.realpathSync,qY),statSync:IXt(dm.default.statSync,qY),unlinkSync:IXt(dm.default.unlinkSync,qY)},retry:{close:h4i((0,CL.promisify)(dm.default.close),qC.isRetriableError),fsync:h4i((0,CL.promisify)(dm.default.fsync),qC.isRetriableError),open:h4i((0,CL.promisify)(dm.default.open),qC.isRetriableError),readFile:h4i((0,CL.promisify)(dm.default.readFile),qC.isRetriableError),rename:h4i((0,CL.promisify)(dm.default.rename),qC.isRetriableError),stat:h4i((0,CL.promisify)(dm.default.stat),qC.isRetriableError),write:h4i((0,CL.promisify)(dm.default.write),qC.isRetriableError),writeFile:h4i((0,CL.promisify)(dm.default.writeFile),qC.isRetriableError),closeSync:y4i(dm.default.closeSync,qC.isRetriableError),fsyncSync:y4i(dm.default.fsyncSync,qC.isRetriableError),openSync:y4i(dm.default.openSync,qC.isRetriableError),readFileSync:y4i(dm.default.readFileSync,qC.isRetriableError),renameSync:y4i(dm.default.renameSync,qC.isRetriableError),statSync:y4i(dm.default.statSync,qC.isRetriableError),writeSync:y4i(dm.default.writeSync,qC.isRetriableError),writeFileSync:y4i(dm.default.writeFileSync,qC.isRetriableError)}},T5h=aqB;var eEu=ue(require("fs"),1),bXa=ue(require("path"),1);var Eil=()=>{};var oqB=()=>{let e=Eil,t=Eil,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}},R5h=oqB;var uqB=()=>{let{promise:e,resolve:t,isPending:r}=R5h(),i=0,n=()=>{i+=1},a=()=>{i-=1,!i&&t()};return(()=>{n(),queueMicrotask(a)})(),{promise:e,isPending:r,increment:n,decrement:a}},z5h=uqB;var N5h={then:e=>{e()}};var F5h=e=>Array.isArray(e)?e:[e],Q5h=e=>typeof e=="function";var sqB=(e,t)=>{let r=t?.followSymlinks??!1,i=t?.depth??1/0,n=t?.limit??1/0,a=t?.ignore??[],o=F5h(a).map(W=>Q5h(W)?W:x=>W.test(x)),c=W=>o.some(x=>x(W)),d=t?.signal??{aborted:!1},s=t?.onDirents||(()=>{}),u=[],l=new Set,p={},_=[],h=new Set,y={},b=[],v=new Set,g={},m={},O=new Set,A={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},j={directories:u,directoriesNames:l,directoriesNamesToPaths:p,files:_,filesNames:h,filesNamesToPaths:y,symlinks:b,symlinksNames:v,symlinksNamesToPaths:g,map:m},{promise:M,increment:w,decrement:D}=z5h(),B=0,T=(W,x,Ee,se)=>{O.has(x)||B>=n||(B+=1,W.directories.push(x),W.directoriesNames.add(Ee),u.push(x),l.add(Ee),p.propertyIsEnumerable(Ee)||(p[Ee]=[]),p[Ee].push(x),O.add(x),!(se>=i)&&(B>=n||$(x,se+1)))},R=(W,x,Ee)=>{O.has(x)||B>=n||(B+=1,W.files.push(x),W.filesNames.add(Ee),_.push(x),h.add(Ee),y.propertyIsEnumerable(Ee)||(y[Ee]=[]),y[Ee].push(x),O.add(x))},q=(W,x,Ee,se)=>{O.has(x)||B>=n||(B+=1,W.symlinks.push(x),W.symlinksNames.add(Ee),b.push(x),v.add(Ee),g.propertyIsEnumerable(Ee)||(g[Ee]=[]),g[Ee].push(x),O.add(x),r&&(se>=i||B>=n||de(x,se+1)))},z=(W,x,Ee,se,Oe)=>{d.aborted||c(x)||(se.isDirectory()?T(W,x,Ee,Oe):se.isFile()?R(W,x,Ee):se.isSymbolicLink()&&q(W,x,Ee,Oe))},N=(W,x,Ee,se)=>{if(d.aborted)return;let Oe=x===bXa.default.sep?"":bXa.default.sep,Fe=Ee.name,ae=`${x}${Oe}${Fe}`;c(ae)||(Ee.isDirectory()?T(W,ae,Fe,se):Ee.isFile()?R(W,ae,Fe):Ee.isSymbolicLink()&&q(W,ae,Fe,se))},H=(W,x,Ee,se)=>{for(let Oe=0,Fe=Ee.length;Oe<Fe;Oe++)N(W,x,Ee[Oe],se)},$=(W,x)=>{d.aborted||x>i||B>=n||(w(),eEu.default.readdir(W,{withFileTypes:!0},(Ee,se)=>{if(Ee||d.aborted||!se.length)return D();(s(se)||N5h).then(()=>{let Fe=m[W]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};H(Fe,W,se,x),D()})}))},de=(W,x)=>{w(),eEu.default.realpath(W,(Ee,se)=>{if(Ee||d.aborted)return D();eEu.default.stat(se,(Oe,Fe)=>{if(Oe||d.aborted)return D();let ae=bXa.default.basename(se),re=m[W]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};z(re,se,ae,Fe,x),D()})})};return(async(W,x=1)=>(W=bXa.default.normalize(W),O.add(W),$(W,x),await M,d.aborted?A:j))(e)},U5h=sqB;var CXt={lang:{debounce:kwu,attempt:e=>{try{return e()}catch(t){return CXt.lang.castError(t)}},castArray:e=>CXt.lang.isArray(e)?e:[e],castError:e=>CXt.lang.isError(e)?e:CXt.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(CXt.lang.isNaN(e))return CXt.lang.isNaN(t);if(CXt.lang.isPrimitive(e)||CXt.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(tEu.default.sep).length-1),getRealPath:(e,t)=>{try{return t?Sil.default.realpathSync.native(e):Sil.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===tEu.default.sep&&t.length-e.length>tEu.default.sep.length,poll:(e,t=B5h)=>T5h.retry.stat(t)(e,{bigint:!0}).catch(CXt.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 U5h(e,{depth:r,limit:i,ignore:t,signal:n});return[o.directories,o.files]}}}},Gp=CXt;var rEu=ue(require("path"),1);var Mil=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||Gp.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=S5h){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]),l=this.eventsDeduplicate([...s,...u]);this.onTargetEvents(l)},o=Gp.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===rf.CHANGE&&c===rf.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===rf.ADD_DIR?await this.eventsPopulateAddDir(t,n,r,i):o===rf.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??IYi:Math.min(1,this.options.depth??IYi),o=this.options.limit??_Xa,[c,d]=await Gp.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())Gp.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(rf.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!CYi&&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(rf.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(rf.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(rEu.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(rf.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(rEu.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(rf.UNLINK_DIR,t))}onTargetEvent(t){let[r,i]=t;r===rf.ADD?this.onTargetAdd(i):r===rf.ADD_DIR?this.onTargetAddDir(i):r===rf.CHANGE?this.onTargetChange(i):r===rf.UNLINK?this.onTargetUnlink(i):r===rf.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=cOn.CHANGE,r){if(this.watcher.isClosed())return;let i=rEu.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){Ail&&t.code==="EPERM"?this.onWatcherChange(cOn.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(hXa.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(hXa.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(cOn.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&CYi&&this.options.native!==!1?this.options.depth??IYi:Math.min(1,this.options.depth??IYi),i=this.options.limit??_Xa,[n,a]=await Gp.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(cOn.CHANGE,c,t)}))}}},L5h=Mil;var Nx={interval:100,intervalId:void 0,fns:new Map,init:()=>{Nx.intervalId||(Nx.intervalId=setInterval(Nx.resolve,Nx.interval))},reset:()=>{Nx.intervalId&&(clearInterval(Nx.intervalId),delete Nx.intervalId)},add:(e,t)=>{Nx.fns.set(e,Date.now()+t),Nx.init()},remove:e=>{Nx.fns.delete(e)},resolve:()=>{if(!Nx.fns.size)return Nx.reset();let e=Date.now();for(let[t,r]of Nx.fns)r>=e||(Nx.remove(t),t())}},vXa=Nx;var gXa=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=Pil){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{let l=this._watcher._poller.paths.find(i||-1,p=>p!==n);if(l&&l!==n){if(Gp.fs.getRealPath(n,!0)===l)return;this._watcher.event(a.rename,l,n)}else this._watcher.event(a.add,n)};if(!i)return c();let d=()=>{o.add.delete(i),vXa.remove(s)},s=()=>{d(),c()};vXa.add(s,r);let u=()=>{let l=o.unlink.get(i);if(!l)return;d();let p=l();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=Pil){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),vXa.remove(s)},s=()=>{d(),c()};vXa.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,rf.ADD,BXt.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,rf.ADD_DIR,BXt.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,rf.UNLINK,BXt.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,rf.UNLINK_DIR,BXt.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}}};gXa.DIR_EVENTS={add:rf.ADD_DIR,rename:rf.RENAME_DIR,unlink:rf.UNLINK_DIR};gXa.FILE_EVENTS={add:rf.ADD,change:rf.CHANGE,rename:rf.RENAME,unlink:rf.UNLINK};var V5h=gXa;var Dil=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(Gp.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let i=this.map.get(t);if(Gp.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(Gp.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(Gp.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let i=this.map.get(t);return Gp.lang.isSet(i)?i.has(r):i===r}return!1}set(t,r){if(this.map.has(t)){let i=this.map.get(t);Gp.lang.isSet(i)?i.add(r):i!==r&&this.map.set(t,new Set([i,r]))}else this.map.set(t,r);return this}},Bil=Dil;var Iil=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}},W5h=Iil;var Cil=class{constructor(){this.inos={},this.paths=new Bil,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 Gp.fs.poll(t,r);if(!(!i||!(i.isFile()||i.isDirectory())))return new W5h(i)}reset(){this.inos={},this.paths=new Bil,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,rf.ADD,n),[rf.ADD];if(n.isDirectory())return this.updateIno(t,rf.ADD_DIR,n),[rf.ADD_DIR]}else if(i&&!n){if(i.isFile())return this.updateIno(t,rf.UNLINK,i),[rf.UNLINK];if(i.isDirectory())return this.updateIno(t,rf.UNLINK_DIR,i),[rf.UNLINK_DIR]}else if(i&&n){if(i.isFile()){if(n.isFile())return i.ino===n.ino&&!i.size&&!n.size?[]:(this.updateIno(t,rf.CHANGE,n),[rf.CHANGE]);if(n.isDirectory())return this.updateIno(t,rf.UNLINK,i),this.updateIno(t,rf.ADD_DIR,n),[rf.UNLINK,rf.ADD_DIR]}else if(i.isDirectory()){if(n.isFile())return this.updateIno(t,rf.UNLINK_DIR,i),this.updateIno(t,rf.ADD,n),[rf.UNLINK_DIR,rf.ADD];if(n.isDirectory())return i.ino===n.ino?[]:(this.updateIno(t,rf.UNLINK_DIR,i),this.updateIno(t,rf.ADD_DIR,n),[rf.UNLINK_DIR,rf.ADD_DIR])}}return[]}updateIno(t,r,i){let n=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=i.isFile()?BXt.FILE:BXt.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)}}},qil=Cil;var Til=class e extends G5h.EventEmitter{constructor(t,r,i){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(zx.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(n=>this.on(zx.CLOSE,n)),this._readyWait=new Promise(n=>this.on(zx.READY,n)),this._locker=new V5h(this),this._roots=new Set,this._poller=new qil,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&&(Gp.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(zx.CLOSE))}error(t){if(this.isClosed())return!1;let r=Gp.lang.castError(t);return this.emit(zx.ERROR,r)}event(t,r,i){return this.isClosed()?!1:(this.emit(zx.ALL,t,r,i),this.emit(t,r,i))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(zx.READY))}pollerExists(t,r){for(let i of this._pollers)if(i.targetPath===t&&Gp.lang.isShallowEqual(i.options,r))return!0;return!1}subwatcherExists(t,r){for(let i of this._subwatchers)if(i.targetPath===t&&Gp.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)Gp.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 L5h(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=Gp.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=lOn.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??IYi))&&u.handler===i&&(!u.filePath||u.filePath===n)&&u.options.ignore===r.ignore&&!!u.options.native==!!r.native&&(!r.recursive||u.options.recursive&&CYi&&u.options.native!==!1)))return!0;if(!CYi)break;let s=lOn.default.dirname(t);if(o===s)break;o=s}return!1}async watchDirectories(t,r,i,n,a){if(this.isClosed())return;t=Gp.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||CYi&&r.native!==!1?r:{...r,recursive:!1},u={watcher:iEu.default.watch(c,d),handler:i,options:r,folderPath:c,filePath:n},l=o=await this.watcherAdd(u,a);if(this._roots.has(n||c)){let _={...r,ignoreInitial:!0,recursive:!1},h=lOn.default.dirname(c),y=c;await this.watchDirectories([h],_,i,y,l)}}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||CYi&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,i,n,a));{r={...r,recursive:!0};let o=r.depth??IYi,c=r.limit??_Xa,[d]=await Gp.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=Gp.fs.getDepth(t);for(let l of d){let p=Gp.fs.getDepth(l),_=Math.max(0,o-(p-u)),h={...r,depth:_};await this.watchDirectories([l],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(zx.CLOSE,d),o.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(n),this.removeListener(zx.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=lOn.default.dirname(t);return this.watchDirectory(n,r,i,t)}async watchPollingOnce(t,r,i){if(this.isClosed())return;let n=!1,a=new qil,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 Gp.lang.noop;if(this.pollerExists(t,r))return Gp.lang.noop;let n={...r,interval:r.pollingInterval??D5h},a={targetPath:t,options:r},o=()=>{this._pollers.add(a),this.on(zx.CLOSE,c),iEu.default.watchFile(t,n,i)},c=()=>{this._pollers.delete(a),this.removeListener(zx.CLOSE,c),iEu.default.unwatchFile(t,i)};return Gp.lang.attempt(o),()=>Gp.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=Gp.lang.uniq(t).sort(),t.every((a,o)=>t.every((c,d)=>d===o||!Gp.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=lOn.default.resolve(t),this.isIgnored(t,r.ignore)))return;let n=await Gp.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=lOn.default.dirname(t);return(await Gp.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,i):this.watchUnknownTarget(t,r,i)}}async watch(t,r,i=Gp.lang.noop){if(Gp.lang.isFunction(t))return this.watch([],{},t);if(Gp.lang.isUndefined(t))return this.watch([],r,i);if(Gp.lang.isFunction(r))return this.watch(t,{},r);if(Gp.lang.isUndefined(r))return this.watch(t,{},i);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let n=Gp.lang.castArray(t);n.forEach(a=>this._roots.add(a)),await this.watchPaths(n,r,i),!this.isClosed()&&(i!==Gp.lang.noop&&this.on(zx.ALL,i),r.readdirMap=void 0,this.ready())}},nEu=Til;uru();var _la=require("fs/promises"),x5h=require("os"),H5h=ue(require("path"),1),cqB=".fern",lqB="logs";function fqB(){return"cli@3.47.6"}var OXa=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=Tt(Sr.of((0,x5h.homedir)()),He.of(cqB)),r=Tt(t,He.of(lqB));await mi(r)||await(0,_la.mkdir)(r,{recursive:!0});let n=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=Tt(r,He.of(n));let a=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${H5h.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
1945
1945
  `);await(0,_la.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)+`
1946
1946
  `;try{await(0,_la.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:fqB(),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 ual=ue(Wil(),1),F7h=ue($Eu(),1),TY=require("fs/promises"),Q7h=require("os"),U7h=ue(j4(),1),L7h=ue(z7h(),1),dSu=process.platform==="win32",oal=Rt.cyan("[docs]:"),IzB="etag",CzB=23,N7h=e=>e.padEnd(CzB," "),qzB="preview",TzB="app-preview",RzB="bundle",zzB=".next",NzB="standalone",FzB=".fern",QzB="packages/fern-docs/bundle/.next/server/instrumentation.js",UzB=".npmrc",LzB=".pnpmfile.cjs",VzB="pnpm-workspace.yaml",WzB='Cannot find matching keyid: {"signatures":';function GzB(){return Tt(Sr.of((0,Q7h.homedir)()),He.of(FzB))}function Ila({app:e=!1}){return Tt(GzB(),He.of(e?TzB:qzB))}function LYi({app:e=!1}){return Tt(Ila({app:e}),He.of(e?zzB:RzB))}function GXa({app:e=!1}){return Tt(LYi({app:e}),He.of(NzB))}function xzB({app:e=!1}){return Tt(GXa({app:e}),He.of(QzB))}function HzB({app:e=!1}){return Tt(GXa({app:e}),He.of(VzB))}function KzB({app:e=!1}){return Tt(GXa({app:e}),He.of(LzB))}function JzB({app:e=!1}){return Tt(GXa({app:e}),He.of(UzB))}function bOn(e){return new Error(`${e}. Please reach out to support@buildwithfern.com.`)}function $zB({app:e=!1}){return Tt(Ila({app:e}),He.of(IzB))}var YzB=`module.exports = {
1947
1947
  hooks: {