fern-api 0.66.17 → 0.66.19

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 +4 -4
  2. package/package.json +1 -1
package/cli.cjs CHANGED
@@ -1709,7 +1709,7 @@ ${DQp.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&Ifc(th
1709
1709
  `+Xtn.default.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?Xtn.default.cyan(zQp(t,this.opt.mask)):Xtn.default.italic(Xtn.default.dim("[hidden]")):this.opt.mask?zQp(t,this.opt.mask):Xtn.default.italic(Xtn.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 KGo=ui(z8(),1),oKp=ui(Ddc(),1),uKp=ui(wAe(),1);var J3a=class extends R8{_run(t){this.done=t,this.editorResult=new uKp.Subject;let r=AH(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"?KGo.default.dim("Received"):KGo.default.dim("Press <enter> to launch your preferred editor."),t&&(r=KGo.default.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),(0,oKp.editAsync)(this.currentText,this.endExternalEditor.bind(this),{postfix:this.opt.postfix??".txt"})}endExternalEditor(t,r){this.rl.resume(),t?this.editorResult.error(t):this.editorResult.next(r)}onEnd(t){this.editorResult.unsubscribe(),this.lineSubscription.unsubscribe(),this.answer=t.value,this.status="answered",this.render(),this.screen.done(),this.done(this.answer)}onError(t){this.render(t.isValid)}};var dKp=require("stream");var lKp=ui(require("readline"),1),fKp=ui(cKp(),1),arn=class{constructor(t){this.rl||=lKp.default.createInterface(KXD(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 KXD(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 fKp.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var K3a=class extends arn{constructor(t={}){super(t),this.log=new dKp.Writable({write:(r,i,n)=>{this.writeLog(r),n()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return q3a(this.rl,this.bottomBar.split(`
1710
1710
  `).length),this}updateBottomBar(t){return q3a(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+`
1711
1711
  `}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&&jGo(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var yM=ui(wAe(),1),hKp=ui(XFa(),1);var YGo=ui(wAe(),1),pKp=ui(XFa(),1),XGo=function(e,t,r){return typeof e[t]!="function"?(0,YGo.of)(e):(0,YGo.from)((0,pKp.default)(e[t])(r).then(i=>(e[t]=i,e)))};var _Kp={set:(e,t="",r)=>{let i=e;t.split(".").forEach((n,a,u)=>{n==="__proto__"||n==="constructor"||(a===u.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((u,l)=>u!=null?u[l]:u,e),n=i(/[,[\]]+?/)||i(/[,.[\]]+?/);return n===void 0||n===e?r:n}},sHn=class extends arn{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,yM.from)(t):(0,yM.isObservable)(t)?i=t:Object.values(t).every(n=>typeof n=="object"&&!Array.isArray(n)&&n!=null)?i=(0,yM.from)(Object.entries(t).map(([n,a])=>({name:n,...a}))):i=(0,yM.from)([t]),this.process=i.pipe((0,yM.concatMap)(this.processQuestion.bind(this)),(0,yM.publish)()),this.process.connect(),this.process.pipe((0,yM.reduce)((n,a)=>(_Kp.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,yM.defer)(()=>(0,yM.of)(t).pipe((0,yM.concatMap)(this.setDefaultType.bind(this)),(0,yM.concatMap)(this.filterIfRunnable.bind(this)),(0,yM.concatMap)(()=>XGo(t,"message",this.answers)),(0,yM.concatMap)(()=>XGo(t,"default",this.answers)),(0,yM.concatMap)(()=>XGo(t,"choices",this.answers)),(0,yM.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,yM.defer)(()=>(0,yM.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,yM.defer)(()=>(0,yM.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&_Kp.get(this.answers,t.name)!==void 0)return yM.EMPTY;if(t.when===!1)return yM.EMPTY;if(typeof t.when!="function")return(0,yM.of)(t);let{answers:r}=this;return(0,yM.defer)(()=>(0,yM.from)((0,hKp.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,yM.filter)(i=>i!=null)))}};function yKp(e){let t=function(r,i){let n;try{n=new sHn(t.prompts,e)}catch(u){return Promise.reject(u)}let a=n.run(r,i);return a.ui=n,a};return t.prompts={},t.registerPrompt=function(r,i){return t.prompts[r]=i,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",C3a),this.registerPrompt("input",Ytn),this.registerPrompt("number",B3a),this.registerPrompt("confirm",I3a),this.registerPrompt("rawlist",z3a),this.registerPrompt("expand",R3a),this.registerPrompt("checkbox",x3a),this.registerPrompt("password",N3a),this.registerPrompt("editor",J3a)},t.restoreDefaultPrompts(),t}var Mdc=yKp();function XXD(e,t){Mdc.registerPrompt(e,t)}function ZXD(){Mdc.restoreDefaultPrompts()}var kXD={prompt:Mdc,ui:{BottomBar:K3a,Prompt:sHn},createPromptModule:yKp,registerPrompt:XXD,restoreDefaultPrompts:ZXD,Separator:Loe},ZGo=kXD;var OHn=require("path"),YYp=require("fs"),XYp=require("readline"),mYp="posthog-node";function IeE(e,{organization:t,projectId:r,prefix:i,severityAllowList:n=["error"]}={}){return a=>{if(!(n==="*"||n.includes(a.level)))return a;a.tags||(a.tags={});let l=a.tags[OQo.POSTHOG_ID_TAG];if(l===void 0)return a;let d=e.options.host??"https://us.i.posthog.com",s=new URL(`/project/${e.apiKey}/person/${l}`,d).toString();a.tags["PostHog Person URL"]=s;let o=a.exception?.values||[],c=o.map(g=>({...g,stacktrace:g.stacktrace?{...g.stacktrace,type:"raw",frames:(g.stacktrace.frames||[]).map(O=>({...O,platform:"node:javascript"}))}:void 0})),b={$exception_message:o[0]?.value||a.message,$exception_type:o[0]?.type,$exception_personURL:s,$exception_level:a.level,$exception_list:c,$sentry_event_id:a.event_id,$sentry_exception:a.exception,$sentry_exception_message:o[0]?.value||a.message,$sentry_exception_type:o[0]?.type,$sentry_tags:a.tags};return t&&r&&(b.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+a.event_id),e.capture({event:"$exception",distinctId:l,properties:b}),a}}var OQo=class{constructor(t,r,i,n){this.name=mYp,this.name=mYp,this.setupOnce=function(a,u){let l=u()?.getClient()?.getDsn()?.projectId;a(IeE(t,{organization:r,projectId:l,prefix:i,severityAllowList:n}))}}};OQo.POSTHOG_ID_TAG="posthog_distinct_id";var hQo="0123456789abcdef",mQo=class e{constructor(t){this.bytes=t}static ofInner(t){if(t.length!==16)throw new TypeError("not 128-bit length");return new e(t)}static fromFieldsV7(t,r,i,n){if(!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||!Number.isInteger(n)||t<0||r<0||i<0||n<0||t>0xffffffffffff||r>4095||i>1073741823||n>4294967295)throw new RangeError("invalid field value");let a=new Uint8Array(16);return a[0]=t/2**40,a[1]=t/2**32,a[2]=t/2**24,a[3]=t/2**16,a[4]=t/2**8,a[5]=t,a[6]=112|r>>>8,a[7]=r,a[8]=128|i>>>24,a[9]=i>>>16,a[10]=i>>>8,a[11]=i,a[12]=n>>>24,a[13]=n>>>16,a[14]=n>>>8,a[15]=n,new e(a)}static parse(t){let r;switch(t.length){case 32:r=/^[0-9a-f]{32}$/i.exec(t)?.[0];break;case 36:r=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break;case 38:r=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(t)?.slice(1,6).join("");break;case 45:r=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break}if(r){let i=new Uint8Array(16);for(let n=0;n<16;n+=4){let a=parseInt(r.substring(2*n,2*n+8),16);i[n+0]=a>>>24,i[n+1]=a>>>16,i[n+2]=a>>>8,i[n+3]=a}return new e(i)}else throw new SyntaxError("could not parse UUID string")}toString(){let t="";for(let r=0;r<this.bytes.length;r++)t+=hQo.charAt(this.bytes[r]>>>4),t+=hQo.charAt(this.bytes[r]&15),(r===3||r===5||r===7||r===9)&&(t+="-");return t}toHex(){let t="";for(let r=0;r<this.bytes.length;r++)t+=hQo.charAt(this.bytes[r]>>>4),t+=hQo.charAt(this.bytes[r]&15);return t}toJSON(){return this.toString()}getVariant(){let t=this.bytes[8]>>>4;if(t<0)throw new Error("unreachable");if(t<=7)return this.bytes.every(r=>r===0)?"NIL":"VAR_0";if(t<=11)return"VAR_10";if(t<=13)return"VAR_110";if(t<=15)return this.bytes.every(r=>r===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new e(this.bytes.slice(0))}equals(t){return this.compareTo(t)===0}compareTo(t){for(let r=0;r<16;r++){let i=this.bytes[r]-t.bytes[r];if(i!==0)return Math.sign(i)}return 0}},vpc=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??zeE()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(t,r){let i=this.generateOrAbortCore(t,r);return i===void 0&&(this.timestamp=0,i=this.generateOrAbortCore(t,r)),i}generateOrAbortCore(t,r){if(!Number.isInteger(t)||t<1||t>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(r<0||r>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(t>this.timestamp)this.timestamp=t,this.resetCounter();else if(t+r>=this.timestamp)this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter());else return;return mQo.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=this.random.nextUint32()*1024+(this.random.nextUint32()&1023)}generateV4(){let t=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return t[6]=64|t[6]>>>4,t[8]=128|t[8]>>>2,mQo.ofInner(t)}},zeE=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),PYp,bpc=()=>ReE().toString(),ReE=()=>(PYp||(PYp=new vpc)).generate();function xeE(e,t){let r=!1;return Object.assign(i=>{let a=global.process.listeners("uncaughtException").filter(u=>u.name!=="domainUncaughtExceptionClear"&&u._posthogErrorHandler!==!0).length===0;e(i,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&a&&(r=!0,t())},{_posthogErrorHandler:!0})}function NeE(e,t){global.process.on("uncaughtException",xeE(e,t))}function FeE(e){global.process.on("unhandledRejection",t=>{e(t,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var yQo,jYp,vQo;function LeE(e){let t=globalThis._posthogChunkIds;if(!t)return console.error("No chunk id map found"),{};let r=Object.keys(t);return vQo&&r.length===jYp||(jYp=r.length,vQo=r.reduce((i,n)=>{yQo||(yQo={});let a=yQo[n];if(a)i[a[0]]=a[1];else{let u=e(n);for(let l=u.length-1;l>=0;l--){let s=u[l]?.filename,o=t[n];if(s&&o){i[s]=o,yQo[n]=[s,o];break}}}return i},{})),vQo}function UeE(e){return typeof Event<"u"&&ZYp(e,Event)}function VeE(e){return kYp(e,"Object")}function Dpc(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return ZYp(e,Error)}}function ZYp(e,t){try{return e instanceof t}catch{return!1}}function WeE(e){return kYp(e,"ErrorEvent")}function kYp(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}async function HeE(e,t,r,i){let a=i&&i.mechanism||{handled:!0,type:"generic"},u=eXp(a,r,i);return{$exception_list:await Promise.all(u.map(async s=>{let o=await XeE(e,t,s);return o.value=o.value||"",o.type=o.type||"Error",o.mechanism=a,o}))}}function eXp(e,t,r){let i=$eE(e,t,r);return i.cause?[i,...eXp(e,i.cause,r)]:[i]}function $eE(e,t,r){if(Dpc(t))return t;if(e.synthetic=!0,VeE(t)){let n=GeE(t);if(n)return n;let a=QeE(t),u=r?.syntheticException||new Error(a);return u.message=a,u}let i=r?.syntheticException||new Error(t);return i.message=`${t}`,i}function GeE(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(Dpc(r))return r}}function QeE(e){if("name"in e&&typeof e.name=="string"){let i=`'${e.name}' captured as exception`;return"message"in e&&typeof e.message=="string"&&(i+=` with message '${e.message}'`),i}else if("message"in e&&typeof e.message=="string")return e.message;let t=KeE(e);if(WeE(e))return`Event \`ErrorEvent\` captured as exception with message \`${e.message}\``;let r=JeE(e);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${t}`}function JeE(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{}}function KeE(e,t=40){let r=Object.keys(YeE(e));r.sort();let i=r[0];if(!i)return"[object has no keys]";if(i.length>=t)return wYp(i,t);for(let n=r.length;n>0;n--){let a=r.slice(0,n).join(", ");if(!(a.length>t))return n===r.length?a:wYp(a,t)}return""}function wYp(e,t=0){return typeof e!="string"||t===0||e.length<=t?e:`${e.slice(0,t)}...`}function YeE(e){return Dpc(e)?{message:e.message,name:e.name,stack:e.stack,...SYp(e)}:UeE(e)?{type:e.type,target:DYp(e.target),currentTarget:DYp(e.currentTarget),...SYp(e)}:e}function SYp(e){if(typeof e=="object"&&e!==null){let t={};for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t}else return{}}function DYp(e){try{return Object.prototype.toString.call(e)}catch{return"<unknown>"}}async function XeE(e,t,r){let i={type:r.name||r.constructor.name,value:r.message},n=ZeE(e,r);for(let a of t)n=await a(n);return n.length&&(i.stacktrace={frames:n,type:"raw"}),i}function ZeE(e,t){return keE(e(t.stack||"",1),e)}function keE(e,t){let r=LeE(t);return e.forEach(i=>{i.filename&&(i.chunk_id=r[i.filename])}),e}var etE=2e3,vHn=class e{static async captureException(t,r,i,n,a){let u={...a};n||(u.$process_person_profile=!1);let l=await HeE(this.stackParser,this.frameModifiers,r,i);t.capture({event:"$exception",distinctId:n||bpc(),properties:{...l,...u}})}constructor(t,r){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this.startAutocaptureIfEnabled()}startAutocaptureIfEnabled(){this.isEnabled()&&(NeE(this.onException.bind(this),this.onFatalError.bind(this)),FeE(this.onException.bind(this)))}onException(t,r){e.captureException(this.client,t,r)}async onFatalError(){await this.client.shutdown(etE)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}};function ttE(e=process.argv[1]?(0,OHn.dirname)(process.argv[1]):process.cwd(),t=OHn.sep==="\\"){let r=t?EYp(e):e;return i=>{if(!i)return;let n=t?EYp(i):i,{dir:a,base:u,ext:l}=OHn.posix.parse(n);(l===".js"||l===".mjs"||l===".cjs")&&(u=u.slice(0,l.length*-1));let d=decodeURIComponent(u);a||(a=".");let s=a.lastIndexOf("/node_modules");if(s>-1)return`${a.slice(s+14).replace(/\//g,".")}:${d}`;if(a.startsWith(r)){let o=a.slice(r.length+1).replace(/\//g,".");return o?`${o}:${d}`:d}return d}}function EYp(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var PQo=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)}}},gQo=new PQo(25),tXp=new PQo(20),Epc=7,rtE=1e3,itE=1e4;async function ntE(e){let t={};for(let n=e.length-1;n>=0;n--){let a=e[n],u=a?.filename;if(!a||typeof u!="string"||typeof a.lineno!="number"||stE(u)||ctE(a))continue;t[u]||(t[u]=[]),t[u].push(a.lineno)}let r=Object.keys(t);if(r.length==0)return e;let i=[];for(let n of r){if(tXp.get(n))continue;let a=t[n];if(!a)continue;a.sort((d,s)=>d-s);let u=ftE(a);if(u.every(d=>ltE(n,d)))continue;let l=dtE(gQo,n,{});i.push(atE(n,u,l))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&otE(e,gQo),gQo.reduce(),e}function atE(e,t,r){return new Promise(i=>{let n=(0,YYp.createReadStream)(e),a=(0,XYp.createInterface)({input:n});function u(){n.destroy(),i()}let l=0,d=0,s=t[d];if(s===void 0){u();return}let o=s[0],c=s[1];function b(){tXp.set(e,1),a.close(),a.removeAllListeners(),u()}n.on("error",b),a.on("error",b),a.on("close",u),a.on("line",g=>{if(l++,!(l<o)&&(r[l]=ptE(g,0),l>=c)){if(d===t.length-1){a.close(),a.removeAllListeners();return}d++;let O=t[d];if(O===void 0){a.close(),a.removeAllListeners();return}o=O[0],c=O[1]}})})}function otE(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;utE(r.lineno,r,i)}}function utE(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=rXp(e);n<e;n++){let a=r[n];if(a===void 0){MYp(t);return}t.pre_context.push(a)}if(r[e]===void 0){MYp(t);return}t.context_line=r[e];let i=iXp(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 MYp(e){delete e.pre_context,delete e.context_line,delete e.post_context}function stE(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function ctE(e){return e.lineno!==void 0&&e.lineno>itE||e.colno!==void 0&&e.colno>rtE}function ltE(e,t){let r=gQo.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 ftE(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=AYp(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+Epc:(n.push(i),i=AYp(a)),t++}return n}function AYp(e){return[rXp(e),iXp(e)]}function rXp(e){return Math.max(1,e-Epc)}function iXp(e){return e+Epc}function dtE(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function ptE(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}var _tE="4.18.0",Goe;(function(e){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.DecideEndpointWasHit="decide_endpoint_was_hit",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config"})(Goe||(Goe={}));var qYp;(function(e){e.Left="left",e.Right="right",e.Center="center"})(qYp||(qYp={}));var TYp;(function(e){e.Button="button",e.Tab="tab",e.Selector="selector"})(TYp||(TYp={}));var CYp;(function(e){e.Popover="popover",e.API="api",e.Widget="widget"})(CYp||(CYp={}));var BYp;(function(e){e.Html="html",e.Text="text"})(BYp||(BYp={}));var IYp;(function(e){e.Number="number",e.Emoji="emoji"})(IYp||(IYp={}));var zYp;(function(e){e.Open="open",e.MultipleChoice="multiple_choice",e.SingleChoice="single_choice",e.Rating="rating",e.Link="link"})(zYp||(zYp={}));var RYp;(function(e){e.NextQuestion="next_question",e.End="end",e.ResponseBased="response_based",e.SpecificQuestion="specific_question"})(RYp||(RYp={}));var xYp;(function(e){e.Regex="regex",e.NotRegex="not_regex",e.Exact="exact",e.IsNot="is_not",e.Icontains="icontains",e.NotIcontains="not_icontains"})(xYp||(xYp={}));var NYp;(function(e){e.Contains="contains",e.Exact="exact",e.Regex="regex"})(NYp||(NYp={}));var htE=e=>{if("flags"in e){let t=vtE(e.flags),r=btE(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}else{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([n,a])=>[n,nXp(a)])),i=Object.fromEntries(Object.entries(t).map(([n,a])=>[n,ytE(n,a,r[n])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}};function ytE(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 vtE=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,Mpc(r)]).filter(([,t])=>t!==void 0)),btE=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?nXp(i):void 0]}))},Mpc=e=>e===void 0?void 0:e.variant??e.enabled,nXp=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}},gtE=1,OtE=new Set(["61be3dd8","96f6df5f","8cfdba9b","bf027177","e59430a8","7fa5500b","569798e9","04809ff7","0ebc61a5","32de7f98","3beeb69a","12d34ad9","733853ec","0645bb64","5dcbee21","b1f95fa3","2189e408","82b460c2","3a8cc979","29ef8843","2cdbf767","38084b54","50f9f8de","41d0df91","5c236689","c11aedd3","ada46672","f4331ee1","42fed62a","c957462c","d62f705a","e0162666","01b3e5cf","441cef7f","bb9cafee","8f348eb0","b2553f3a","97469d7d","39f21a76","03706dcc","27d50569","307584a7","6433e92e","150c7fbb","49f57f22","3772f65b","01eb8256","3c9e9234","f853c7f7","c0ac4b67","cd609d40","10ca9b1a","8a87f11b","8e8e5216","1f6b63b3","db7943dd","79b7164c","07f78e33","2d21b6fd","952db5ee","a7d3b43f","1924dd9c","84e1b8f6","dff631b6","c5aa8a79","fa133a95","498a4508","24748755","98f3d658","21bbda67","7dbfed69","be3ec24c","fc80b8e2","75cc0998"]),mtE="utf8";function PtE(e,t){if(!e||typeof e!="string"||jtE(e))throw new Error(t)}function jtE(e){return e.trim().length===0}function wtE(e){return e?.replace(/\/+$/,"")}async function StE(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 FYp(){return new Date().getTime()}function hpc(){return new Date().toISOString()}function jQo(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}function DtE(){return typeof fetch<"u"?fetch:typeof globalThis.fetch<"u"?globalThis.fetch:void 0}function EtE(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24);return(t>>>0).toString(16).padStart(8,"0")}function MtE(e,t=0,r){let i=EtE(e);return r?.has(i)?!1:parseInt(i,16)/4294967295<t}function LYp(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var a7a=String.fromCharCode,UYp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bQo={};function AtE(e,t){if(!bQo[e]){bQo[e]={};for(let r=0;r<e.length;r++)bQo[e][e.charAt(r)]=r}return bQo[e][t]}var hHn={compressToBase64:function(e){if(e==null)return"";let t=hHn._compress(e,6,function(r){return UYp.charAt(r)});switch(t.length%4){default:case 0:return t;case 1:return t+"===";case 2:return t+"==";case 3:return t+"="}},decompressFromBase64:function(e){return e==null?"":e==""?null:hHn._decompress(e.length,32,function(t){return AtE(UYp,e.charAt(t))})},compress:function(e){return hHn._compress(e,16,function(t){return a7a(t)})},_compress:function(e,t,r){if(e==null)return"";let i={},n={},a=[],u,l,d="",s="",o="",c=2,b=3,g=2,O=0,m=0,w;for(w=0;w<e.length;w+=1)if(d=e.charAt(w),Object.prototype.hasOwnProperty.call(i,d)||(i[d]=b++,n[d]=!0),s=o+d,Object.prototype.hasOwnProperty.call(i,s))o=s;else{if(Object.prototype.hasOwnProperty.call(n,o)){if(o.charCodeAt(0)<256){for(u=0;u<g;u++)O=O<<1,m==t-1?(m=0,a.push(r(O)),O=0):m++;for(l=o.charCodeAt(0),u=0;u<8;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}else{for(l=1,u=0;u<g;u++)O=O<<1|l,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=0;for(l=o.charCodeAt(0),u=0;u<16;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}c--,c==0&&(c=Math.pow(2,g),g++),delete n[o]}else for(l=i[o],u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;c--,c==0&&(c=Math.pow(2,g),g++),i[s]=b++,o=String(d)}if(o!==""){if(Object.prototype.hasOwnProperty.call(n,o)){if(o.charCodeAt(0)<256){for(u=0;u<g;u++)O=O<<1,m==t-1?(m=0,a.push(r(O)),O=0):m++;for(l=o.charCodeAt(0),u=0;u<8;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}else{for(l=1,u=0;u<g;u++)O=O<<1|l,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=0;for(l=o.charCodeAt(0),u=0;u<16;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}c--,c==0&&(c=Math.pow(2,g),g++),delete n[o]}else for(l=i[o],u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;c--,c==0&&(c=Math.pow(2,g),g++)}for(l=2,u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;for(;;)if(O=O<<1,m==t-1){a.push(r(O));break}else m++;return a.join("")},decompress:function(e){return e==null?"":e==""?null:hHn._decompress(e.length,32768,function(t){return e.charCodeAt(t)})},_decompress:function(e,t,r){let i=[],n=[],a={val:r(0),position:t,index:1},u=4,l=4,d=3,s="",o,c,b,g,O,m,w;for(o=0;o<3;o+=1)i[o]=o;for(b=0,O=Math.pow(2,2),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;w=a7a(b);break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;w=a7a(b);break;case 2:return""}for(i[3]=w,c=w,n.push(w);;){if(a.index>e)return"";for(b=0,O=Math.pow(2,d),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(w=b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=a7a(b),w=l-1,u--;break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=a7a(b),w=l-1,u--;break;case 2:return n.join("")}if(u==0&&(u=Math.pow(2,d),d++),i[w])s=i[w];else if(w===l)s=c+c.charAt(0);else return null;n.push(s),i[l++]=c+s.charAt(0),u--,c=s,u==0&&(u=Math.pow(2,d),d++)}}},gpc=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)}},bHn=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()}},o7a=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function VYp(e){if(e instanceof bHn){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 ypc(e){return typeof e=="object"&&(e instanceof bHn||e instanceof o7a)}function WYp(e){return typeof e=="object"&&e instanceof bHn&&e.status===413}var Opc;(function(e){e.FeatureFlags="feature_flags",e.Recordings="recordings"})(Opc||(Opc={}));var mpc=class{constructor(t,r){this.flushPromise=null,this.shutdownPromise=null,this.pendingPromises={},this._events=new gpc,this._isInitialized=!1,PtE(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=wtE(r?.host||"https://us.i.posthog.com"),this.flushAt=r?.flushAt?Math.max(r?.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,r?.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,r?.maxQueueSize??1e3),this.flushInterval=r?.flushInterval??1e4,this.captureMode=r?.captureMode||"json",this.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:ypc},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._initPromise=Promise.resolve(),this._isInitialized=!0}logMsgIfDebug(t){this.isDebug&&t()}wrap(t){if(this.disabled){this.logMsgIfDebug(()=>console.warn("[PostHog] The client is disabled"));return}if(this._isInitialized)return t();this._initPromise.then(()=>t())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(Goe.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(Goe.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(Goe.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(i,n)=>console.log("PostHog Debug",i,n));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(t){return{distinct_id:t.distinct_id,event:t.event,properties:{...t.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(t){let r=bpc();return this.pendingPromises[r]=t,t.catch(()=>{}).finally(()=>{delete this.pendingPromises[r]}),t}identifyStateless(t,r,i){this.wrap(()=>{let n={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",n,i)})}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,u){this.wrap(()=>{let l=this.buildPayload({distinct_id:a||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:i||{},...u||{}}});this.enqueue("capture",l,n)})}async 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.logMsgIfDebug(()=>console.error("Remote config could not be loaded",n)),this._events.emit("error",n)})}async getDecide(t,r={},i={},n={},a={}){await this._initPromise;let l=MtE(this.apiKey,gtE,OtE)?`${this.host}/flags/?v=2`:`${this.host}/decide/?v=4`,d={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify({token:this.apiKey,distinct_id:t,groups:r,person_properties:i,group_properties:n,...a})};return this.logMsgIfDebug(()=>console.log("PostHog Debug","Decide URL",l)),this.fetchWithRetry(l,d,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(s=>s.json()).then(s=>htE(s)).catch(s=>{this._events.emit("error",s)})}async getFeatureFlagStateless(t,r,i={},n={},a={},u){await this._initPromise;let l=await this.getFeatureFlagDetailStateless(t,r,i,n,a,u);if(l===void 0)return{response:void 0,requestId:void 0};let d=Mpc(l.response);return d===void 0&&(d=!1),{response:d,requestId:l.requestId}}async getFeatureFlagDetailStateless(t,r,i={},n={},a={},u){await this._initPromise;let l=await this.getFeatureFlagDetailsStateless(r,i,n,a,u,[t]);return l===void 0?void 0:{response:l.flags[t],requestId:l.requestId}}async getFeatureFlagPayloadStateless(t,r,i={},n={},a={},u){await this._initPromise;let l=await this.getFeatureFlagPayloadsStateless(r,i,n,a,u,[t]);if(!l)return;let d=l[t];return d===void 0?null:d}async getFeatureFlagPayloadsStateless(t,r={},i={},n={},a,u){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a,u)).payloads}async getFeatureFlagsStateless(t,r={},i={},n={},a,u){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a,u)}async getFeatureFlagsAndPayloadsStateless(t,r={},i={},n={},a,u){await this._initPromise;let l=await this.getFeatureFlagDetailsStateless(t,r,i,n,a,u);return l?{flags:l.featureFlags,payloads:l.featureFlagPayloads,requestId:l.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(t,r={},i={},n={},a,u){await this._initPromise;let l={};(a??this.disableGeoip)&&(l.geoip_disable=!0),u&&(l.flag_keys_to_evaluate=u);let d=await this.getDecide(t,r,i,n,l);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(Opc.FeatureFlags)?(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.logMsgIfDebug(()=>console.log("PostHog Debug","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 u=`Surveys API could not be loaded: ${a.status}`,l=new Error(u);this.logMsgIfDebug(()=>console.error(l)),this._events.emit("error",new Error(u));return}return a.json()}).catch(a=>{this.logMsgIfDebug(()=>console.error("Surveys API could not be loaded",a)),this._events.emit("error",a)}))?.surveys;return n&&this.logMsgIfDebug(()=>console.log("PostHog Debug","Surveys fetched from API: ",JSON.stringify(n))),n??[]}get props(){return this._props||(this._props=this.getPersistedProperty(Goe.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(Goe.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(Goe.Props,this.props)})}enqueue(t,r,i){this.wrap(()=>{if(this.optedOut){this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");return}let n=this.prepareMessage(t,r,i),a=this.getPersistedProperty(Goe.Queue)||[];a.length>=this.maxQueueSize&&(a.shift(),this.logMsgIfDebug(()=>console.info("Queue is full, the oldest event is dropped."))),a.push({message:n}),this.setPersistedProperty(Goe.Queue,a),this._events.emit(t,n),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=jQo(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,i){if(this.disabled){this.logMsgIfDebug(()=>console.warn("[PostHog] The client is disabled"));return}if(this._isInitialized||await this._initPromise,this.optedOut){this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");return}let n={api_key:this.apiKey,batch:[this.prepareMessage(t,r,i)],sent_at:hpc()};this.historicalMigration&&(n.historical_migration=!0);let a=JSON.stringify(n),u=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${FYp()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,l=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(hHn.compressToBase64(a))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:a};try{await this.fetchWithRetry(u,l)}catch(d){this._events.emit("error",d)}}prepareMessage(t,r,i){let n={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:i?.timestamp?i?.timestamp:hpc(),uuid:i?.uuid?i.uuid:bpc()};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 VYp(t)})}async flush(){let t=LYp([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),LYp([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(Goe.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(b=>b.message),u=()=>{let g=(this.getPersistedProperty(Goe.Queue)||[]).slice(n.length);this.setPersistedProperty(Goe.Queue,g),t=g},l={api_key:this.apiKey,batch:a,sent_at:hpc()};this.historicalMigration&&(l.historical_migration=!0);let d=JSON.stringify(l),s=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${FYp()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,o=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(hHn.compressToBase64(d))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:d},c={retryCheck:b=>WYp(b)?!1:ypc(b)};try{await this.fetchWithRetry(s,o,c)}catch(b){if(WYp(b)&&a.length>1){this.maxBatchSize=Math.max(1,Math.floor(a.length/2)),this.logMsgIfDebug(()=>console.warn(`Received 413 when sending batch of size ${a.length}, reducing batch size to ${this.maxBatchSize}`));continue}throw b instanceof o7a||u(),this._events.emit("error",b),b}u(),r.push(...a)}this._events.emit("flush",r)}async fetchWithRetry(t,r,i,n){var a;(a=AbortSignal).timeout??(a.timeout=function(s){let o=new AbortController;return setTimeout(()=>o.abort(),s),o.signal});let u=r.body?r.body:"",l=-1;try{l=Buffer.byteLength(u,mtE)}catch{l=new TextEncoder().encode(u).length}return await StE(async()=>{let d=null;try{d=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(o){throw new o7a(o)}if(!(r.mode==="no-cors")&&(d.status<200||d.status>=400))throw new bHn(d,l);return d},{...this._retryOptions,...i})}async _shutdown(t=3e4){await this._initPromise;let r=!1;this.clearFlushTimer();let i=async()=>{try{for(await Promise.all(Object.values(this.pendingPromises));!((this.getPersistedProperty(Goe.Queue)||[]).length===0||(await this.flush(),r)););}catch(n){if(!ypc(n))throw n;await VYp(n)}};return Promise.race([new Promise((n,a)=>{jQo(()=>{this.logMsgIfDebug(()=>console.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.logMsgIfDebug(()=>console.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}},Ppc=DtE();if(!Ppc){let e=OYp();Ppc=async(t,r)=>{let i=await e.request({url:t,headers:r.headers,method:r.method.toLowerCase(),data:r.body,signal:r.signal,validateStatus:()=>!0});return{status:i.status,text:async()=>i.data,json:async()=>i.data}}}var aXp=Ppc,wQo=class{constructor(t){this.factory=t}async getValue(){return this.value!==void 0?this.value:(this.initializationPromise===void 0&&(this.initializationPromise=(async()=>{try{let t=await this.factory();return this.value=t,t}finally{this.initializationPromise=void 0}})()),this.initializationPromise)}isInitialized(){return this.value!==void 0}async waitForInitialization(){this.isInitialized()||await this.getValue()}},oXp=new wQo(async()=>{try{return await import("crypto")}catch{return}});async function qtE(){return await oXp.getValue()}var TtE=new wQo(async()=>{if(typeof globalThis.crypto?.subtle<"u")return globalThis.crypto.subtle;try{let e=await oXp.getValue();if(e?.webcrypto?.subtle)return e.webcrypto.subtle}catch{}});async function CtE(){return await TtE.getValue()}async function BtE(e){let t=await qtE();if(t)return t.createHash("sha1").update(e).digest("hex");let r=await CtE();if(r){let i=await r.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(i)).map(a=>a.toString(16).padStart(2,"0")).join("")}throw new Error("No crypto implementation available. Tried Node Crypto API and Web SubtleCrypto API")}var ItE=60*1e3,ztE=1152921504606847e3,RtE=["is_not"],yHn=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},x8=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},jpc=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:i,timeout:n,host:a,customHeaders:u,...l}){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=l.fetch||aXp,this.onError=l.onError,this.customHeaders=u,this.onLoad=l.onLoad,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,i={},n={},a={}){await this.loadFeatureFlags();let u,l;if(!this.loadedSuccessfullyOnce)return u;for(let d of this.featureFlags)if(t===d.key){l=d;break}if(l!==void 0)try{u=await this.computeFlagLocally(l,r,i,n,a),this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${u}`))}catch(d){d instanceof x8?this.logMsgIfDebug(()=>console.debug(`InconclusiveMatchError when computing flag locally: ${t}: ${d}`)):d instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${d}`))}return u}async computeFeatureFlagPayloadLocally(t,r){await this.loadFeatureFlags();let i;if(this.loadedSuccessfullyOnce){if(typeof r=="boolean"?i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]:typeof r=="string"&&(i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]),i==null)return null;try{return JSON.parse(i)}catch{return i}}}async getAllFlagsAndPayloads(t,r={},i={},n={}){await this.loadFeatureFlags();let a={},u={},l=this.featureFlags.length==0;return await Promise.all(this.featureFlags.map(async d=>{try{let s=await this.computeFlagLocally(d,t,r,i,n);a[d.key]=s;let o=await this.computeFeatureFlagPayloadLocally(d.key,s);o&&(u[d.key]=o)}catch(s){s instanceof x8||s instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${d.key}: ${s}`)),l=!0}})),{response:a,payloads:u,fallbackToDecide:l}}async computeFlagLocally(t,r,i={},n={},a={}){if(t.ensure_experience_continuity)throw new x8("Flag has experience continuity enabled");if(!t.active)return!1;let l=(t.filters||{}).aggregation_group_type_index;if(l!=null){let d=this.groupTypeMapping[String(l)];if(!d)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${l} for feature flag ${t.key}`)),new x8("Flag has unknown group type index");if(!(d in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let s=a[d];return await this.matchFeatureFlagProperties(t,i[d],s)}else return await this.matchFeatureFlagProperties(t,r,n)}async matchFeatureFlagProperties(t,r,i){let n=t.filters||{},a=n.groups||[],u=!1,l,d=[...a].sort((s,o)=>{let c=!!s.variant,b=!!o.variant;return c&&b?0:c?-1:b?1:0});for(let s of d)try{if(await this.isConditionMatch(t,r,s,i)){let o=s.variant,c=n.multivariate?.variants||[];o&&c.some(b=>b.key===o)?l=o:l=await this.getMatchingVariant(t,r)||!0;break}}catch(o){if(o instanceof x8)u=!0;else throw o}if(l!==void 0)return l;if(u)throw new x8("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,i,n){let a=i.rollout_percentage,u=l=>{this.logMsgIfDebug(()=>console.warn(l))};if((i.properties||[]).length>0){for(let l of i.properties){let d=l.type,s=!1;if(d==="cohort"?s=sXp(l,n,this.cohorts,this.debugMode):s=uXp(l,n,u),!s)return!1}if(a==null)return!0}return!(a!=null&&await HYp(t.key,r)>a/100)}async getMatchingVariant(t,r){let i=await HYp(t.key,r,"variant"),n=this.variantLookupTable(t).find(a=>i>=a.valueMin&&i<a.valueMax);if(n)return n.key}variantLookupTable(t){let r=[],i=0,n=0;return((t.filters||{}).multivariate?.variants||[]).forEach(l=>{n=i+l.rollout_percentage/100,r.push({valueMin:i,valueMax:n,key:l.key}),i=n}),r}async loadFeatureFlags(t=!1){(!this.loadedSuccessfullyOnce||t)&&await this._loadFeatureFlags()}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(ItE,this.pollingInterval*2**this.backOffCount):this.pollingInterval}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this._loadFeatureFlags(),this.getPollingInterval());try{let t=await this._requestFeatureFlagDefinitions();if(!t)return;switch(t.status){case 401:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new yHn(`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 yHn(`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 yHn(`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 r=await t.json()??{};if(!("flags"in r)){this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(r)}`));return}this.featureFlags=r.flags??[],this.featureFlagsByKey=this.featureFlags.reduce((i,n)=>(i[n.key]=n,i),{}),this.groupTypeMapping=r.group_type_mapping||{},this.cohorts=r.cohorts||{},this.loadedSuccessfullyOnce=!0,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.onLoad?.(this.featureFlags.length);break}default:return}}catch(t){t instanceof yHn&&this.onError?.(t)}}getPersonalApiKeyRequestOptions(t="GET"){return{method:t,headers:{...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`}}}async _requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions(),i=null;if(this.timeout&&typeof this.timeout=="number"){let n=new AbortController;i=jQo(()=>{n.abort()},this.timeout),r.signal=n.signal}try{return await this.fetch(t,r)}finally{clearTimeout(i)}}stopPoller(){clearTimeout(this.poller)}_requestRemoteConfigPayload(t){let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config/`,i=this.getPersonalApiKeyRequestOptions(),n=null;if(this.timeout&&typeof this.timeout=="number"){let a=new AbortController;n=jQo(()=>{a.abort()},this.timeout),i.signal=a.signal}try{return this.fetch(r,i)}finally{clearTimeout(n)}}};async function HYp(e,t,r=""){let i=await BtE(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/ztE}function uXp(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 x8("Operator is_not_set is not supported")}else throw new x8(`Property ${i} not found in propertyValues`);let u=t[i];if(u==null&&!RtE.includes(a))return r&&r(`Property ${i} cannot have a value of null/undefined with the ${a} operator`),!1;function l(s,o){return Array.isArray(s)?s.map(c=>String(c).toLowerCase()).includes(String(o).toLowerCase()):String(s).toLowerCase()===String(o).toLowerCase()}function d(s,o,c){if(c==="gt")return s>o;if(c==="gte")return s>=o;if(c==="lt")return s<o;if(c==="lte")return s<=o;throw new Error(`Invalid operator: ${c}`)}switch(a){case"exact":return l(n,u);case"is_not":return!l(n,u);case"is_set":return i in t;case"icontains":return String(u).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(u).toLowerCase().includes(String(n).toLowerCase());case"regex":return $Yp(String(n))&&String(u).match(String(n))!==null;case"not_regex":return $Yp(String(n))&&String(u).match(String(n))===null;case"gt":case"gte":case"lt":case"lte":{let s=typeof n=="number"?n:null;if(typeof n=="string")try{s=parseFloat(n)}catch{}return s!=null&&u!=null?typeof u=="string"?d(u,String(n),a):d(u,s,a):d(String(u),String(n),a)}case"is_date_after":case"is_date_before":{let s=xtE(String(n));if(s==null&&(s=GYp(n)),s==null)throw new x8(`Invalid date: ${n}`);let o=GYp(u);return["is_date_before"].includes(a)?o<s:o>s}default:throw new x8(`Unknown operator: ${a}`)}}function sXp(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new x8("can't match cohort without a given cohort property value");let a=r[n];return cXp(a,t,r,i)}function cXp(e,t,r,i=!1){if(!e)return!0;let n=e.type,a=e.values;if(!a||a.length===0)return!0;let u=!1;if("values"in a[0]){for(let l of a)try{let d=cXp(l,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof x8)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new x8("Can't match cohort without a given cohort property value");return n==="AND"}else{for(let l of a)try{let d;l.type==="cohort"?d=sXp(l,t,r,i):d=uXp(l,t);let s=l.negation||!1;if(n==="AND"){if(!d&&!s||d&&s)return!1}else if(d&&!s||!d&&s)return!0}catch(d){if(d instanceof x8)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new x8("can't match cohort without a given cohort property value");return n==="AND"}}function $Yp(e){try{return new RegExp(e),!0}catch{return!1}}function GYp(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 x8(`${e} is in an invalid date format`)}else throw new x8(`The date provided ${e} must be a string, number, or date object`)}function xtE(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(r){if(!r.groups)return null;let n=parseInt(r.groups.number);if(n>=1e4)return null;let a=r.groups.interval;if(a=="h")i.setUTCHours(i.getUTCHours()-n);else if(a=="d")i.setUTCDate(i.getUTCDate()-n);else if(a=="w")i.setUTCDate(i.getUTCDate()-n*7);else if(a=="m")i.setUTCMonth(i.getUTCMonth()-n);else if(a=="y")i.setUTCFullYear(i.getUTCFullYear()-n);else return null;return i}else return null}var wpc=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},NtE=100,QYp=30*1e3,FtE=50*1e3,Spc=class extends mpc{constructor(t,r={}){if(super(t,r),this._memoryStorage=new wpc,this.options=r,this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,NtE):QYp,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.');this.featureFlagsPoller=new jpc({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:i=>{this._events.emit("error",i)},onLoad:i=>{this._events.emit("localEvaluationFlagsLoaded",i)},customHeaders:this.getCustomHeaders()})}this.errorTracking=new vHn(this,r),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||FtE}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):aXp(t,r)}getLibraryVersion(){return _tE}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.logMsgIfDebug(()=>console.warn("Called capture() with a string as the first argument when an object was expected."));let{distinctId:r,event:i,properties:n,groups:a,sendFeatureFlags:u,timestamp:l,disableGeoip:d,uuid:s}=t,o=g=>{super.captureStateless(r,i,g,{timestamp:l,disableGeoip:d,uuid:s})},c=async(g,O,m)=>(await super.getFeatureFlagsStateless(g,O,void 0,void 0,m)).flags,b=Promise.resolve().then(async()=>{if(u)return await c(r,a,d);if(i==="$feature_flag_called")return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let g={};for(let[O,m]of Object.entries(a||{}))g[O]=String(m);return await this.getAllFlags(r,{groups:g,disableGeoip:d,onlyEvaluateLocally:!0})}return{}}).then(g=>{let O={};if(g)for(let[w,E]of Object.entries(g))O[`$feature/${w}`]=E;let m=Object.keys(g||{}).filter(w=>g?.[w]!==!1).sort();return m.length>0&&(O.$active_feature_flags=m),O}).catch(()=>({})).then(g=>{o({...g,...n,$groups:a})});this.addPendingPromise(b)}async captureImmediate(t){typeof t=="string"&&this.logMsgIfDebug(()=>console.warn("Called capture() with a string as the first argument when an object was expected."));let{distinctId:r,event:i,properties:n,groups:a,sendFeatureFlags:u,timestamp:l,disableGeoip:d,uuid:s}=t,o=g=>super.captureStatelessImmediate(r,i,g,{timestamp:l,disableGeoip:d,uuid:s}),c=async(g,O,m)=>(await super.getFeatureFlagsStateless(g,O,void 0,void 0,m)).flags;await Promise.resolve().then(async()=>{if(u)return await c(r,a,d);if(i==="$feature_flag_called")return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let g={};for(let[O,m]of Object.entries(a||{}))g[O]=String(m);return await this.getAllFlags(r,{groups:g,disableGeoip:d,onlyEvaluateLocally:!0})}return{}}).then(g=>{let O={};if(g)for(let[w,E]of Object.entries(g))O[`$feature/${w}`]=E;let m=Object.keys(g||{}).filter(w=>g?.[w]!==!1).sort();return m.length>0&&(O.$active_feature_flags=m),O}).catch(()=>({})).then(g=>{o({...g,...n,$groups:a})})}identify({distinctId:t,properties:r,disableGeoip:i}){let n=r?.$set_once;delete r?.$set_once;let a=r?.$set||r;super.identifyStateless(t,{$set:a,$set_once:n},{disableGeoip:i})}async identifyImmediate({distinctId:t,properties:r,disableGeoip:i}){let n=r?.$set_once;delete r?.$set_once;let a=r?.$set||r;await super.identifyStatelessImmediate(t,{$set:a,$set_once:n},{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=QYp){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:u,sendFeatureFlagEvents:l,personProperties:d,groupProperties:s}=i||{},o=this.addLocalPersonAndGroupProperties(r,n,d,s);d=o.allPersonProperties,s=o.allGroupProperties,u==null&&(u=!1),l==null&&(l=!0);let c=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,d,s),b=c!==void 0,g,O;if(!b&&!u){let w=await super.getFeatureFlagDetailStateless(t,r,n,d,s,a);if(w===void 0)return;O=w.response,c=Mpc(O),g=w?.requestId}let m=`${t}_${c}`;return l&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(m))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(m):this.distinctIdHasSentFlagCalls[r]=[m],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:c,$feature_flag_id:O?.metadata?.id,$feature_flag_version:O?.metadata?.version,$feature_flag_reason:O?.reason?.description??O?.reason?.code,locally_evaluated:b,[`$feature/${t}`]:c,$feature_flag_request_id:g},groups:n,disableGeoip:a})),c}async getFeatureFlagPayload(t,r,i,n){let{groups:a,disableGeoip:u}=n||{},{onlyEvaluateLocally:l,sendFeatureFlagEvents:d,personProperties:s,groupProperties:o}=n||{},c=this.addLocalPersonAndGroupProperties(r,a,s,o);s=c.allPersonProperties,o=c.allGroupProperties;let b;return this.featureFlagsPoller!==void 0&&(i||(i=await this.getFeatureFlag(t,r,{...n,onlyEvaluateLocally:!0,sendFeatureFlagEvents:!1})),i&&(b=await this.featureFlagsPoller?.computeFeatureFlagPayloadLocally(t,i))),l==null&&(l=!1),d==null&&(d=!0),l==null&&(l=!1),!(b!==void 0)&&!l&&(b=await super.getFeatureFlagPayloadStateless(t,r,a,s,o,u)),b}async getRemoteConfigPayload(t){return(await this.featureFlagsPoller?._requestRemoteConfigPayload(t))?.json()}async isFeatureEnabled(t,r,i){let n=await this.getFeatureFlag(t,r,i);if(n!==void 0)return!!n||!1}async getAllFlags(t,r){return(await this.getAllFlagsAndPayloads(t,r)).featureFlags||{}}async getAllFlagsAndPayloads(t,r){let{groups:i,disableGeoip:n}=r||{},{onlyEvaluateLocally:a,personProperties:u,groupProperties:l}=r||{},d=this.addLocalPersonAndGroupProperties(t,i,u,l);u=d.allPersonProperties,l=d.allGroupProperties,a==null&&(a=!1);let s=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,u,l),o={},c={},b=!0;if(s&&(o=s.response,c=s.payloads,b=s.fallbackToDecide),b&&!a){let g=await super.getFeatureFlagsAndPayloadsStateless(t,i,u,l,n);o={...o,...g.flags||{}},c={...c,...g.payloads||{}}}return{featureFlags:o,featureFlagPayloads:c}}groupIdentify({groupType:t,groupKey:r,properties:i,distinctId:n,disableGeoip:a}){super.groupIdentifyStateless(t,r,i,{disableGeoip:a},n)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}async _shutdown(t){return this.featureFlagsPoller?.stopPoller(),super._shutdown(t)}addLocalPersonAndGroupProperties(t,r,i,n){let a={distinct_id:t,...i||{}},u={};if(r)for(let l of Object.keys(r))u[l]={$group_key:r[l],...n?.[l]||{}};return{allPersonProperties:a,allGroupProperties:u}}captureException(t,r,i){let n=new Error("PostHog syntheticException");vHn.captureException(this,t,{syntheticException:n},r,i)}},JYp=/\(error: (.*)\)/,lXp=50,fXp="?";function LtE(e){let t=/^\s*[-]{4,}$/,r=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;return i=>{let n=i.match(r);if(n){let a,u,l,d,s;if(n[1]){l=n[1];let b=l.lastIndexOf(".");if(l[b-1]==="."&&b--,b>0){a=l.slice(0,b),u=l.slice(b+1);let g=a.indexOf(".Module");g>0&&(l=l.slice(g+1),a=a.slice(0,g))}d=void 0}u&&(d=a,s=u),u==="<anonymous>"&&(s=void 0,l=void 0),l===void 0&&(s=s||fXp,l=d?`${d}.${s}`:s);let o=n[2]?.startsWith("file://")?n[2].slice(7):n[2],c=n[5]==="native";return o?.match(/\/[A-Z]:/)&&(o=o.slice(1)),!o&&n[5]&&!c&&(o=n[5]),{filename:o?decodeURI(o):void 0,module:e?e(o):void 0,function:l,lineno:KYp(n[3]),colno:KYp(n[4]),in_app:UtE(o||"",c),platform:"node:javascript"}}if(i.match(t))return{filename:i,platform:"node:javascript"}}}function UtE(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 KYp(e){return parseInt(e||"",10)||void 0}function VtE(e){return[90,LtE(e)]}function WtE(e){let r=[VtE(e)].sort((i,n)=>i[0]-n[0]).map(i=>i[1]);return(i,n=0)=>{let a=[],u=i.split(`
1712
- `);for(let l=n;l<u.length;l++){let d=u[l];if(d.length>1024)continue;let s=JYp.test(d)?d.replace(JYp,"$1"):d;if(!s.match(/\S*Error: /)){for(let o of r){let c=o(s);if(c){a.push(c);break}}if(a.length>=lXp)break}}return HtE(a)}}function HtE(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,lXp).map(r=>({...r,filename:r.filename||$tE(t).filename,function:r.function||fXp}))}function $tE(e){return e[e.length-1]||{}}vHn.stackParser=WtE(ttE());vHn.frameModifiers=[ntE];var gHn=class extends Spc{getLibraryId(){return"posthog-node"}};var SQo=class{posthog;constructor({posthogApiKey:t}){this.posthog=new gHn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.66.17",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var u7a=class{async sendEvent(){}async identify(){}async flush(){}};var mHn=require("fs/promises"),hXp=require("os"),yXp=require("path");var dXp=ui(require("crypto")),EQo=new Uint8Array(256),DQo=EQo.length;function Apc(){return DQo>EQo.length-16&&(dXp.default.randomFillSync(EQo),DQo=0),EQo.slice(DQo,DQo+=16)}var CH=[];for(let e=0;e<256;++e)CH.push((e+256).toString(16).slice(1));function pXp(e,t=0){return CH[e[t+0]]+CH[e[t+1]]+CH[e[t+2]]+CH[e[t+3]]+"-"+CH[e[t+4]]+CH[e[t+5]]+"-"+CH[e[t+6]]+CH[e[t+7]]+"-"+CH[e[t+8]]+CH[e[t+9]]+"-"+CH[e[t+10]]+CH[e[t+11]]+CH[e[t+12]]+CH[e[t+13]]+CH[e[t+14]]+CH[e[t+15]]}var _Xp=ui(require("crypto")),qpc={randomUUID:_Xp.default.randomUUID};function GtE(e,t,r){if(qpc.randomUUID&&!t&&!e)return qpc.randomUUID();e=e||{};let i=e.random||(e.rng||Apc)();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 pXp(i)}var Qoe=GtE;var QtE="id",JtE=".fern",s7a=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new gHn(r),this.userId=t==null?void 0:hoc(t)}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"0.66.17",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Eu(Fc.of((0,hXp.homedir)()),Ia.of(JtE),Ia.of(QtE));await jf(t)||(await(0,mHn.mkdir)((0,yXp.dirname)(t),{recursive:!0}),await(0,mHn.writeFile)(t,Qoe())),this.persistedDistinctId=(await(0,mHn.readFile)(t)).toString()}return this.persistedDistinctId}};var Tpc;async function PHn(){return Tpc==null&&(Tpc=await KtE()),Tpc}async function KtE(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new u7a;let r=await WLo();return r!=null?new s7a({token:r,posthogApiKey:e}):await bVn()!=null?new SQo({posthogApiKey:e}):new s7a({token:void 0,posthogApiKey:e})}catch{return new u7a}}function c7a(e,t){return function(){return e.apply(t,arguments)}}var{toString:YtE}=Object.prototype,{getPrototypeOf:Bpc}=Object,{iterator:AQo,toStringTag:bXp}=Symbol,qQo=(e=>t=>{let r=YtE.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),MGt=e=>(e=e.toLowerCase(),t=>qQo(t)===e),TQo=e=>t=>typeof t===e,{isArray:jHn}=Array,l7a=TQo("undefined");function XtE(e){return e!==null&&!l7a(e)&&e.constructor!==null&&!l7a(e.constructor)&&Joe(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var gXp=MGt("ArrayBuffer");function ZtE(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&gXp(e.buffer),t}var ktE=TQo("string"),Joe=TQo("function"),OXp=TQo("number"),CQo=e=>e!==null&&typeof e=="object",erE=e=>e===!0||e===!1,MQo=e=>{if(qQo(e)!=="object")return!1;let t=Bpc(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(bXp in e)&&!(AQo in e)},trE=MGt("Date"),rrE=MGt("File"),irE=MGt("Blob"),nrE=MGt("FileList"),arE=e=>CQo(e)&&Joe(e.pipe),orE=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Joe(e.append)&&((t=qQo(e))==="formdata"||t==="object"&&Joe(e.toString)&&e.toString()==="[object FormData]"))},urE=MGt("URLSearchParams"),[srE,crE,lrE,frE]=["ReadableStream","Request","Response","Headers"].map(MGt),drE=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function f7a(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),jHn(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{let a=r?Object.getOwnPropertyNames(e):Object.keys(e),u=a.length,l;for(i=0;i<u;i++)l=a[i],t.call(null,e[l],l,e)}}function mXp(e,t){t=t.toLowerCase();let r=Object.keys(e),i=r.length,n;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}var frn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,PXp=e=>!l7a(e)&&e!==frn;function Cpc(){let{caseless:e}=PXp(this)&&this||{},t={},r=(i,n)=>{let a=e&&mXp(t,n)||n;MQo(t[a])&&MQo(i)?t[a]=Cpc(t[a],i):MQo(i)?t[a]=Cpc({},i):jHn(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&f7a(arguments[i],r);return t}var prE=(e,t,r,{allOwnKeys:i}={})=>(f7a(t,(n,a)=>{r&&Joe(n)?e[a]=c7a(n,r):e[a]=n},{allOwnKeys:i}),e),_rE=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),hrE=(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)},yrE=(e,t,r,i)=>{let n,a,u,l={};if(t=t||{},e==null)return t;do{for(n=Object.getOwnPropertyNames(e),a=n.length;a-- >0;)u=n[a],(!i||i(u,e,t))&&!l[u]&&(t[u]=e[u],l[u]=!0);e=r!==!1&&Bpc(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},vrE=(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},brE=e=>{if(!e)return null;if(jHn(e))return e;let t=e.length;if(!OXp(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},grE=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Bpc(Uint8Array)),OrE=(e,t)=>{let i=(e&&e[AQo]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},mrE=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},PrE=MGt("HTMLFormElement"),jrE=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),vXp=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),wrE=MGt("RegExp"),jXp=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};f7a(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},SrE=e=>{jXp(e,(t,r)=>{if(Joe(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(Joe(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+"'")})}})},DrE=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return jHn(e)?i(e):i(String(e).split(t)),r},ErE=()=>{},MrE=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function ArE(e){return!!(e&&Joe(e.append)&&e[bXp]==="FormData"&&e[AQo])}var qrE=e=>{let t=new Array(10),r=(i,n)=>{if(CQo(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=jHn(i)?[]:{};return f7a(i,(u,l)=>{let d=r(u,n+1);!l7a(d)&&(a[l]=d)}),t[n]=void 0,a}}return i};return r(e,0)},TrE=MGt("AsyncFunction"),CrE=e=>e&&(CQo(e)||Joe(e))&&Joe(e.then)&&Joe(e.catch),wXp=((e,t)=>e?setImmediate:t?((r,i)=>(frn.addEventListener("message",({source:n,data:a})=>{n===frn&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),frn.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",Joe(frn.postMessage)),BrE=typeof queueMicrotask<"u"?queueMicrotask.bind(frn):typeof process<"u"&&process.nextTick||wXp,IrE=e=>e!=null&&Joe(e[AQo]),ss={isArray:jHn,isArrayBuffer:gXp,isBuffer:XtE,isFormData:orE,isArrayBufferView:ZtE,isString:ktE,isNumber:OXp,isBoolean:erE,isObject:CQo,isPlainObject:MQo,isReadableStream:srE,isRequest:crE,isResponse:lrE,isHeaders:frE,isUndefined:l7a,isDate:trE,isFile:rrE,isBlob:irE,isRegExp:wrE,isFunction:Joe,isStream:arE,isURLSearchParams:urE,isTypedArray:grE,isFileList:nrE,forEach:f7a,merge:Cpc,extend:prE,trim:drE,stripBOM:_rE,inherits:hrE,toFlatObject:yrE,kindOf:qQo,kindOfTest:MGt,endsWith:vrE,toArray:brE,forEachEntry:OrE,matchAll:mrE,isHTMLForm:PrE,hasOwnProperty:vXp,hasOwnProp:vXp,reduceDescriptors:jXp,freezeMethods:SrE,toObjectSet:DrE,toCamelCase:jrE,noop:ErE,toFiniteNumber:MrE,findKey:mXp,global:frn,isContextDefined:PXp,isSpecCompliantForm:ArE,toJSONObject:qrE,isAsyncFn:TrE,isThenable:CrE,setImmediate:wXp,asap:BrE,isIterable:IrE};function wHn(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)}ss.inherits(wHn,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:ss.toJSONObject(this.config),code:this.code,status:this.status}}});var SXp=wHn.prototype,DXp={};["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=>{DXp[e]={value:e}});Object.defineProperties(wHn,DXp);Object.defineProperty(SXp,"isAxiosError",{value:!0});wHn.from=(e,t,r,i,n,a)=>{let u=Object.create(SXp);return ss.toFlatObject(e,u,function(d){return d!==Error.prototype},l=>l!=="isAxiosError"),wHn.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var Qp=wHn;var EXp=ui(kGo(),1),BQo=EXp.default;function Ipc(e){return ss.isPlainObject(e)||ss.isArray(e)}function AXp(e){return ss.endsWith(e,"[]")?e.slice(0,-2):e}function MXp(e,t,r){return e?e.concat(t).map(function(n,a){return n=AXp(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function zrE(e){return ss.isArray(e)&&!e.some(Ipc)}var RrE=ss.toFlatObject(ss,{},null,function(t){return/^is[A-Z]/.test(t)});function xrE(e,t,r){if(!ss.isObject(e))throw new TypeError("target must be an object");t=t||new(BQo||FormData),r=ss.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,w){return!ss.isUndefined(w[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&ss.isSpecCompliantForm(t);if(!ss.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(ss.isDate(O))return O.toISOString();if(ss.isBoolean(O))return O.toString();if(!d&&ss.isBlob(O))throw new Qp("Blob is not supported. Use a Buffer instead.");return ss.isArrayBuffer(O)||ss.isTypedArray(O)?d&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,w){let E=O;if(O&&!w&&typeof O=="object"){if(ss.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(ss.isArray(O)&&zrE(O)||(ss.isFileList(O)||ss.endsWith(m,"[]"))&&(E=ss.toArray(O)))return m=AXp(m),E.forEach(function(M,D){!(ss.isUndefined(M)||M===null)&&t.append(u===!0?MXp([m],D,a):u===null?m:m+"[]",s(M))}),!1}return Ipc(O)?!0:(t.append(MXp(w,m,a),s(O)),!1)}let c=[],b=Object.assign(RrE,{defaultVisitor:o,convertValue:s,isVisitable:Ipc});function g(O,m){if(!ss.isUndefined(O)){if(c.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));c.push(O),ss.forEach(O,function(E,q){(!(ss.isUndefined(E)||E===null)&&n.call(t,E,ss.isString(q)?q.trim():q,m,b))===!0&&g(E,m?m.concat(q):[q])}),c.pop()}}if(!ss.isObject(e))throw new TypeError("data must be an object");return g(e),t}var ZRi=xrE;function qXp(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function TXp(e,t){this._pairs=[],e&&ZRi(e,this,t)}var CXp=TXp.prototype;CXp.append=function(t,r){this._pairs.push([t,r])};CXp.toString=function(t){let r=t?function(i){return t.call(this,i,qXp)}:qXp;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var BXp=TXp;function NrE(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function drn(e,t,r){if(!t)return e;let i=r&&r.encode||NrE;ss.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=ss.isURLSearchParams(t)?t.toString():new BXp(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var zpc=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){ss.forEach(this.handlers,function(i){i!==null&&t(i)})}},Rpc=zpc;var SHn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var xXp=ui(require("crypto"),1);var IXp=ui(require("url"),1),zXp=IXp.default.URLSearchParams;var xpc="abcdefghijklmnopqrstuvwxyz",RXp="0123456789",NXp={DIGIT:RXp,ALPHA:xpc,ALPHA_DIGIT:xpc+xpc.toUpperCase()+RXp},FrE=(e=16,t=NXp.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);xXp.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},FXp={isNode:!0,classes:{URLSearchParams:zXp,FormData:BQo,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:NXp,generateString:FrE,protocols:["http","https","file","data"]};var Lpc={};Po(Lpc,{hasBrowserEnv:()=>Fpc,hasStandardBrowserEnv:()=>LrE,hasStandardBrowserWebWorkerEnv:()=>UrE,navigator:()=>Npc,origin:()=>VrE});var Fpc=typeof window<"u"&&typeof document<"u",Npc=typeof navigator=="object"&&navigator||void 0,LrE=Fpc&&(!Npc||["ReactNative","NativeScript","NS"].indexOf(Npc.product)<0),UrE=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",VrE=Fpc&&window.location.href||"http://localhost";var NA={...Lpc,...FXp};function Upc(e,t){return ZRi(e,new NA.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return NA.isNode&&ss.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function WrE(e){return ss.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function HrE(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 $rE(e){function t(r,i,n,a){let u=r[a++];if(u==="__proto__")return!0;let l=Number.isFinite(+u),d=a>=r.length;return u=!u&&ss.isArray(n)?n.length:u,d?(ss.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!l):((!n[u]||!ss.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&ss.isArray(n[u])&&(n[u]=HrE(n[u])),!l)}if(ss.isFormData(e)&&ss.isFunction(e.entries)){let r={};return ss.forEachEntry(e,(i,n)=>{t(WrE(i),n,r,0)}),r}return null}var IQo=$rE;function GrE(e,t,r){if(ss.isString(e))try{return(t||JSON.parse)(e),ss.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var Vpc={transitional:SHn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=ss.isObject(t);if(a&&ss.isHTMLForm(t)&&(t=new FormData(t)),ss.isFormData(t))return n?JSON.stringify(IQo(t)):t;if(ss.isArrayBuffer(t)||ss.isBuffer(t)||ss.isStream(t)||ss.isFile(t)||ss.isBlob(t)||ss.isReadableStream(t))return t;if(ss.isArrayBufferView(t))return t.buffer;if(ss.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return Upc(t,this.formSerializer).toString();if((l=ss.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return ZRi(l?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),GrE(t)):t}],transformResponse:[function(t){let r=this.transitional||Vpc.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(ss.isResponse(t)||ss.isReadableStream(t))return t;if(t&&ss.isString(t)&&(i&&!this.responseType||n)){let u=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t)}catch(l){if(u)throw l.name==="SyntaxError"?Qp.from(l,Qp.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:NA.classes.FormData,Blob:NA.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ss.forEach(["delete","get","head","post","put","patch"],e=>{Vpc.headers[e]={}});var DHn=Vpc;var QrE=ss.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"]),LXp=e=>{let t={},r,i,n;return e&&e.split(`
1712
+ `);for(let l=n;l<u.length;l++){let d=u[l];if(d.length>1024)continue;let s=JYp.test(d)?d.replace(JYp,"$1"):d;if(!s.match(/\S*Error: /)){for(let o of r){let c=o(s);if(c){a.push(c);break}}if(a.length>=lXp)break}}return HtE(a)}}function HtE(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,lXp).map(r=>({...r,filename:r.filename||$tE(t).filename,function:r.function||fXp}))}function $tE(e){return e[e.length-1]||{}}vHn.stackParser=WtE(ttE());vHn.frameModifiers=[ntE];var gHn=class extends Spc{getLibraryId(){return"posthog-node"}};var SQo=class{posthog;constructor({posthogApiKey:t}){this.posthog=new gHn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.66.19",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var u7a=class{async sendEvent(){}async identify(){}async flush(){}};var mHn=require("fs/promises"),hXp=require("os"),yXp=require("path");var dXp=ui(require("crypto")),EQo=new Uint8Array(256),DQo=EQo.length;function Apc(){return DQo>EQo.length-16&&(dXp.default.randomFillSync(EQo),DQo=0),EQo.slice(DQo,DQo+=16)}var CH=[];for(let e=0;e<256;++e)CH.push((e+256).toString(16).slice(1));function pXp(e,t=0){return CH[e[t+0]]+CH[e[t+1]]+CH[e[t+2]]+CH[e[t+3]]+"-"+CH[e[t+4]]+CH[e[t+5]]+"-"+CH[e[t+6]]+CH[e[t+7]]+"-"+CH[e[t+8]]+CH[e[t+9]]+"-"+CH[e[t+10]]+CH[e[t+11]]+CH[e[t+12]]+CH[e[t+13]]+CH[e[t+14]]+CH[e[t+15]]}var _Xp=ui(require("crypto")),qpc={randomUUID:_Xp.default.randomUUID};function GtE(e,t,r){if(qpc.randomUUID&&!t&&!e)return qpc.randomUUID();e=e||{};let i=e.random||(e.rng||Apc)();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 pXp(i)}var Qoe=GtE;var QtE="id",JtE=".fern",s7a=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new gHn(r),this.userId=t==null?void 0:hoc(t)}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"0.66.19",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Eu(Fc.of((0,hXp.homedir)()),Ia.of(JtE),Ia.of(QtE));await jf(t)||(await(0,mHn.mkdir)((0,yXp.dirname)(t),{recursive:!0}),await(0,mHn.writeFile)(t,Qoe())),this.persistedDistinctId=(await(0,mHn.readFile)(t)).toString()}return this.persistedDistinctId}};var Tpc;async function PHn(){return Tpc==null&&(Tpc=await KtE()),Tpc}async function KtE(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new u7a;let r=await WLo();return r!=null?new s7a({token:r,posthogApiKey:e}):await bVn()!=null?new SQo({posthogApiKey:e}):new s7a({token:void 0,posthogApiKey:e})}catch{return new u7a}}function c7a(e,t){return function(){return e.apply(t,arguments)}}var{toString:YtE}=Object.prototype,{getPrototypeOf:Bpc}=Object,{iterator:AQo,toStringTag:bXp}=Symbol,qQo=(e=>t=>{let r=YtE.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),MGt=e=>(e=e.toLowerCase(),t=>qQo(t)===e),TQo=e=>t=>typeof t===e,{isArray:jHn}=Array,l7a=TQo("undefined");function XtE(e){return e!==null&&!l7a(e)&&e.constructor!==null&&!l7a(e.constructor)&&Joe(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var gXp=MGt("ArrayBuffer");function ZtE(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&gXp(e.buffer),t}var ktE=TQo("string"),Joe=TQo("function"),OXp=TQo("number"),CQo=e=>e!==null&&typeof e=="object",erE=e=>e===!0||e===!1,MQo=e=>{if(qQo(e)!=="object")return!1;let t=Bpc(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(bXp in e)&&!(AQo in e)},trE=MGt("Date"),rrE=MGt("File"),irE=MGt("Blob"),nrE=MGt("FileList"),arE=e=>CQo(e)&&Joe(e.pipe),orE=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Joe(e.append)&&((t=qQo(e))==="formdata"||t==="object"&&Joe(e.toString)&&e.toString()==="[object FormData]"))},urE=MGt("URLSearchParams"),[srE,crE,lrE,frE]=["ReadableStream","Request","Response","Headers"].map(MGt),drE=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function f7a(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),jHn(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{let a=r?Object.getOwnPropertyNames(e):Object.keys(e),u=a.length,l;for(i=0;i<u;i++)l=a[i],t.call(null,e[l],l,e)}}function mXp(e,t){t=t.toLowerCase();let r=Object.keys(e),i=r.length,n;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}var frn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,PXp=e=>!l7a(e)&&e!==frn;function Cpc(){let{caseless:e}=PXp(this)&&this||{},t={},r=(i,n)=>{let a=e&&mXp(t,n)||n;MQo(t[a])&&MQo(i)?t[a]=Cpc(t[a],i):MQo(i)?t[a]=Cpc({},i):jHn(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&f7a(arguments[i],r);return t}var prE=(e,t,r,{allOwnKeys:i}={})=>(f7a(t,(n,a)=>{r&&Joe(n)?e[a]=c7a(n,r):e[a]=n},{allOwnKeys:i}),e),_rE=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),hrE=(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)},yrE=(e,t,r,i)=>{let n,a,u,l={};if(t=t||{},e==null)return t;do{for(n=Object.getOwnPropertyNames(e),a=n.length;a-- >0;)u=n[a],(!i||i(u,e,t))&&!l[u]&&(t[u]=e[u],l[u]=!0);e=r!==!1&&Bpc(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},vrE=(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},brE=e=>{if(!e)return null;if(jHn(e))return e;let t=e.length;if(!OXp(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},grE=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Bpc(Uint8Array)),OrE=(e,t)=>{let i=(e&&e[AQo]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},mrE=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},PrE=MGt("HTMLFormElement"),jrE=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),vXp=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),wrE=MGt("RegExp"),jXp=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};f7a(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},SrE=e=>{jXp(e,(t,r)=>{if(Joe(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(Joe(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+"'")})}})},DrE=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return jHn(e)?i(e):i(String(e).split(t)),r},ErE=()=>{},MrE=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function ArE(e){return!!(e&&Joe(e.append)&&e[bXp]==="FormData"&&e[AQo])}var qrE=e=>{let t=new Array(10),r=(i,n)=>{if(CQo(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=jHn(i)?[]:{};return f7a(i,(u,l)=>{let d=r(u,n+1);!l7a(d)&&(a[l]=d)}),t[n]=void 0,a}}return i};return r(e,0)},TrE=MGt("AsyncFunction"),CrE=e=>e&&(CQo(e)||Joe(e))&&Joe(e.then)&&Joe(e.catch),wXp=((e,t)=>e?setImmediate:t?((r,i)=>(frn.addEventListener("message",({source:n,data:a})=>{n===frn&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),frn.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",Joe(frn.postMessage)),BrE=typeof queueMicrotask<"u"?queueMicrotask.bind(frn):typeof process<"u"&&process.nextTick||wXp,IrE=e=>e!=null&&Joe(e[AQo]),ss={isArray:jHn,isArrayBuffer:gXp,isBuffer:XtE,isFormData:orE,isArrayBufferView:ZtE,isString:ktE,isNumber:OXp,isBoolean:erE,isObject:CQo,isPlainObject:MQo,isReadableStream:srE,isRequest:crE,isResponse:lrE,isHeaders:frE,isUndefined:l7a,isDate:trE,isFile:rrE,isBlob:irE,isRegExp:wrE,isFunction:Joe,isStream:arE,isURLSearchParams:urE,isTypedArray:grE,isFileList:nrE,forEach:f7a,merge:Cpc,extend:prE,trim:drE,stripBOM:_rE,inherits:hrE,toFlatObject:yrE,kindOf:qQo,kindOfTest:MGt,endsWith:vrE,toArray:brE,forEachEntry:OrE,matchAll:mrE,isHTMLForm:PrE,hasOwnProperty:vXp,hasOwnProp:vXp,reduceDescriptors:jXp,freezeMethods:SrE,toObjectSet:DrE,toCamelCase:jrE,noop:ErE,toFiniteNumber:MrE,findKey:mXp,global:frn,isContextDefined:PXp,isSpecCompliantForm:ArE,toJSONObject:qrE,isAsyncFn:TrE,isThenable:CrE,setImmediate:wXp,asap:BrE,isIterable:IrE};function wHn(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)}ss.inherits(wHn,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:ss.toJSONObject(this.config),code:this.code,status:this.status}}});var SXp=wHn.prototype,DXp={};["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=>{DXp[e]={value:e}});Object.defineProperties(wHn,DXp);Object.defineProperty(SXp,"isAxiosError",{value:!0});wHn.from=(e,t,r,i,n,a)=>{let u=Object.create(SXp);return ss.toFlatObject(e,u,function(d){return d!==Error.prototype},l=>l!=="isAxiosError"),wHn.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var Qp=wHn;var EXp=ui(kGo(),1),BQo=EXp.default;function Ipc(e){return ss.isPlainObject(e)||ss.isArray(e)}function AXp(e){return ss.endsWith(e,"[]")?e.slice(0,-2):e}function MXp(e,t,r){return e?e.concat(t).map(function(n,a){return n=AXp(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function zrE(e){return ss.isArray(e)&&!e.some(Ipc)}var RrE=ss.toFlatObject(ss,{},null,function(t){return/^is[A-Z]/.test(t)});function xrE(e,t,r){if(!ss.isObject(e))throw new TypeError("target must be an object");t=t||new(BQo||FormData),r=ss.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,w){return!ss.isUndefined(w[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&ss.isSpecCompliantForm(t);if(!ss.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(ss.isDate(O))return O.toISOString();if(ss.isBoolean(O))return O.toString();if(!d&&ss.isBlob(O))throw new Qp("Blob is not supported. Use a Buffer instead.");return ss.isArrayBuffer(O)||ss.isTypedArray(O)?d&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,w){let E=O;if(O&&!w&&typeof O=="object"){if(ss.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(ss.isArray(O)&&zrE(O)||(ss.isFileList(O)||ss.endsWith(m,"[]"))&&(E=ss.toArray(O)))return m=AXp(m),E.forEach(function(M,D){!(ss.isUndefined(M)||M===null)&&t.append(u===!0?MXp([m],D,a):u===null?m:m+"[]",s(M))}),!1}return Ipc(O)?!0:(t.append(MXp(w,m,a),s(O)),!1)}let c=[],b=Object.assign(RrE,{defaultVisitor:o,convertValue:s,isVisitable:Ipc});function g(O,m){if(!ss.isUndefined(O)){if(c.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));c.push(O),ss.forEach(O,function(E,q){(!(ss.isUndefined(E)||E===null)&&n.call(t,E,ss.isString(q)?q.trim():q,m,b))===!0&&g(E,m?m.concat(q):[q])}),c.pop()}}if(!ss.isObject(e))throw new TypeError("data must be an object");return g(e),t}var ZRi=xrE;function qXp(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function TXp(e,t){this._pairs=[],e&&ZRi(e,this,t)}var CXp=TXp.prototype;CXp.append=function(t,r){this._pairs.push([t,r])};CXp.toString=function(t){let r=t?function(i){return t.call(this,i,qXp)}:qXp;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var BXp=TXp;function NrE(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function drn(e,t,r){if(!t)return e;let i=r&&r.encode||NrE;ss.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=ss.isURLSearchParams(t)?t.toString():new BXp(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var zpc=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){ss.forEach(this.handlers,function(i){i!==null&&t(i)})}},Rpc=zpc;var SHn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var xXp=ui(require("crypto"),1);var IXp=ui(require("url"),1),zXp=IXp.default.URLSearchParams;var xpc="abcdefghijklmnopqrstuvwxyz",RXp="0123456789",NXp={DIGIT:RXp,ALPHA:xpc,ALPHA_DIGIT:xpc+xpc.toUpperCase()+RXp},FrE=(e=16,t=NXp.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);xXp.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},FXp={isNode:!0,classes:{URLSearchParams:zXp,FormData:BQo,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:NXp,generateString:FrE,protocols:["http","https","file","data"]};var Lpc={};Po(Lpc,{hasBrowserEnv:()=>Fpc,hasStandardBrowserEnv:()=>LrE,hasStandardBrowserWebWorkerEnv:()=>UrE,navigator:()=>Npc,origin:()=>VrE});var Fpc=typeof window<"u"&&typeof document<"u",Npc=typeof navigator=="object"&&navigator||void 0,LrE=Fpc&&(!Npc||["ReactNative","NativeScript","NS"].indexOf(Npc.product)<0),UrE=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",VrE=Fpc&&window.location.href||"http://localhost";var NA={...Lpc,...FXp};function Upc(e,t){return ZRi(e,new NA.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return NA.isNode&&ss.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function WrE(e){return ss.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function HrE(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 $rE(e){function t(r,i,n,a){let u=r[a++];if(u==="__proto__")return!0;let l=Number.isFinite(+u),d=a>=r.length;return u=!u&&ss.isArray(n)?n.length:u,d?(ss.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!l):((!n[u]||!ss.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&ss.isArray(n[u])&&(n[u]=HrE(n[u])),!l)}if(ss.isFormData(e)&&ss.isFunction(e.entries)){let r={};return ss.forEachEntry(e,(i,n)=>{t(WrE(i),n,r,0)}),r}return null}var IQo=$rE;function GrE(e,t,r){if(ss.isString(e))try{return(t||JSON.parse)(e),ss.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var Vpc={transitional:SHn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=ss.isObject(t);if(a&&ss.isHTMLForm(t)&&(t=new FormData(t)),ss.isFormData(t))return n?JSON.stringify(IQo(t)):t;if(ss.isArrayBuffer(t)||ss.isBuffer(t)||ss.isStream(t)||ss.isFile(t)||ss.isBlob(t)||ss.isReadableStream(t))return t;if(ss.isArrayBufferView(t))return t.buffer;if(ss.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return Upc(t,this.formSerializer).toString();if((l=ss.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return ZRi(l?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),GrE(t)):t}],transformResponse:[function(t){let r=this.transitional||Vpc.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(ss.isResponse(t)||ss.isReadableStream(t))return t;if(t&&ss.isString(t)&&(i&&!this.responseType||n)){let u=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t)}catch(l){if(u)throw l.name==="SyntaxError"?Qp.from(l,Qp.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:NA.classes.FormData,Blob:NA.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ss.forEach(["delete","get","head","post","put","patch"],e=>{Vpc.headers[e]={}});var DHn=Vpc;var QrE=ss.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"]),LXp=e=>{let t={},r,i,n;return e&&e.split(`
1713
1713
  `).forEach(function(u){n=u.indexOf(":"),r=u.substring(0,n).trim().toLowerCase(),i=u.substring(n+1).trim(),!(!r||t[r]&&QrE[r])&&(r==="set-cookie"?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t};var UXp=Symbol("internals");function d7a(e){return e&&String(e).trim().toLowerCase()}function zQo(e){return e===!1||e==null?e:ss.isArray(e)?e.map(zQo):String(e)}function JrE(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 KrE=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function Wpc(e,t,r,i,n){if(ss.isFunction(i))return i.call(this,t,r);if(n&&(t=r),!!ss.isString(t)){if(ss.isString(i))return t.indexOf(i)!==-1;if(ss.isRegExp(i))return i.test(t)}}function YrE(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,i)=>r.toUpperCase()+i)}function XrE(e,t){let r=ss.toCamelCase(" "+t);["get","set","has"].forEach(i=>{Object.defineProperty(e,i+r,{value:function(n,a,u){return this[i].call(this,t,n,a,u)},configurable:!0})})}var EHn=class{constructor(t){t&&this.set(t)}set(t,r,i){let n=this;function a(l,d,s){let o=d7a(d);if(!o)throw new Error("header name must be a non-empty string");let c=ss.findKey(n,o);(!c||n[c]===void 0||s===!0||s===void 0&&n[c]!==!1)&&(n[c||d]=zQo(l))}let u=(l,d)=>ss.forEach(l,(s,o)=>a(s,o,d));if(ss.isPlainObject(t)||t instanceof this.constructor)u(t,r);else if(ss.isString(t)&&(t=t.trim())&&!KrE(t))u(LXp(t),r);else if(ss.isObject(t)&&ss.isIterable(t)){let l={},d,s;for(let o of t){if(!ss.isArray(o))throw TypeError("Object iterator must return a key-value pair");l[s=o[0]]=(d=l[s])?ss.isArray(d)?[...d,o[1]]:[d,o[1]]:o[1]}u(l,r)}else t!=null&&a(r,t,i);return this}get(t,r){if(t=d7a(t),t){let i=ss.findKey(this,t);if(i){let n=this[i];if(!r)return n;if(r===!0)return JrE(n);if(ss.isFunction(r))return r.call(this,n,i);if(ss.isRegExp(r))return r.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=d7a(t),t){let i=ss.findKey(this,t);return!!(i&&this[i]!==void 0&&(!r||Wpc(this,this[i],i,r)))}return!1}delete(t,r){let i=this,n=!1;function a(u){if(u=d7a(u),u){let l=ss.findKey(i,u);l&&(!r||Wpc(i,i[l],l,r))&&(delete i[l],n=!0)}}return ss.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||Wpc(this,this[a],a,t,!0))&&(delete this[a],n=!0)}return n}normalize(t){let r=this,i={};return ss.forEach(this,(n,a)=>{let u=ss.findKey(i,a);if(u){r[u]=zQo(n),delete r[a];return}let l=t?YrE(a):String(a).trim();l!==a&&delete r[a],r[l]=zQo(n),i[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return ss.forEach(this,(i,n)=>{i!=null&&i!==!1&&(r[n]=t&&ss.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(`
1714
1714
  `)}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[UXp]=this[UXp]={accessors:{}}).accessors,n=this.prototype;function a(u){let l=d7a(u);i[l]||(XrE(n,u),i[l]=!0)}return ss.isArray(t)?t.forEach(a):a(t),this}};EHn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);ss.reduceDescriptors(EHn.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(i){this[r]=i}}});ss.freezeMethods(EHn);var Kx=EHn;function p7a(e,t){let r=this||DHn,i=t||r,n=Kx.from(i.headers),a=i.data;return ss.forEach(e,function(l){a=l.call(r,a,n.normalize(),t?t.status:void 0)}),n.normalize(),a}function _7a(e){return!!(e&&e.__CANCEL__)}function VXp(e,t,r){Qp.call(this,e??"canceled",Qp.ERR_CANCELED,t,r),this.name="CanceledError"}ss.inherits(VXp,Qp,{__CANCEL__:!0});var DAe=VXp;function war(e,t,r){let i=r.config.validateStatus;!r.status||!i||i(r.status)?e(r):t(new Qp("Request failed with status code "+r.status,[Qp.ERR_BAD_REQUEST,Qp.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function Hpc(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function $pc(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function prn(e,t,r){let i=!Hpc(t);return e&&(i||r==!1)?$pc(e,t):t}var nZp=ui(Y3a(),1),aZp=ui(require("http"),1),oZp=ui(require("https"),1),uZp=ui(require("util"),1),sZp=ui($dc(),1),ZOi=ui(require("zlib"),1);var _rn="1.10.0";function h7a(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var ZrE=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function Gpc(e,t,r){let i=r&&r.Blob||NA.classes.Blob,n=h7a(e);if(t===void 0&&i&&(t=!0),n==="data"){e=n.length?e.slice(n.length+1):e;let a=ZrE.exec(e);if(!a)throw new Qp("Invalid URL",Qp.ERR_INVALID_URL);let u=a[1],l=a[2],d=a[3],s=Buffer.from(decodeURIComponent(d),l?"base64":"utf8");if(t){if(!i)throw new Qp("Blob is not supported",Qp.ERR_NOT_SUPPORT);return new i([s],{type:u})}return s}throw new Qp("Unsupported protocol "+n,Qp.ERR_NOT_SUPPORT)}var yrn=ui(require("stream"),1);var WXp=ui(require("stream"),1);var Qpc=Symbol("internals"),Jpc=class extends WXp.default.Transform{constructor(t){t=ss.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(i,n)=>!ss.isUndefined(n[i])),super({readableHighWaterMark:t.chunkSize});let r=this[Qpc]={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[Qpc];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,i){let n=this[Qpc],a=n.maxRate,u=this.readableHighWaterMark,l=n.timeWindow,d=1e3/l,s=a/d,o=n.minChunkSize!==!1?Math.max(n.minChunkSize,s*.01):0,c=(g,O)=>{let m=Buffer.byteLength(g);n.bytesSeen+=m,n.bytes+=m,n.isCaptured&&this.emit("progress",n.bytesSeen),this.push(g)?process.nextTick(O):n.onReadCallback=()=>{n.onReadCallback=null,process.nextTick(O)}},b=(g,O)=>{let m=Buffer.byteLength(g),w=null,E=u,q,M=0;if(a){let D=Date.now();(!n.ts||(M=D-n.ts)>=l)&&(n.ts=D,q=s-n.bytes,n.bytes=q<0?-q:0,M=0),q=s-n.bytes}if(a){if(q<=0)return setTimeout(()=>{O(null,g)},l-M);q<E&&(E=q)}E&&m>E&&m-E>o&&(w=g.subarray(E),g=g.subarray(0,E)),c(g,w?()=>{process.nextTick(O,null,w)}:O)};b(t,function g(O,m){if(O)return i(O);m?b(m,g):i(null)})}},Kpc=Jpc;var cZp=require("events");var $Xp=ui(require("util"),1),GXp=require("stream");var{asyncIterator:HXp}=Symbol,krE=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[HXp]?yield*e[HXp]():yield e},RQo=krE;var eiE=NA.ALPHABET.ALPHA_DIGIT+"-_",y7a=typeof TextEncoder=="function"?new TextEncoder:new $Xp.default.TextEncoder,hrn=`\r
1715
1715
  `,tiE=y7a.encode(hrn),riE=2,Ypc=class{constructor(t,r){let{escapeName:i}=this.constructor,n=ss.isString(r),a=`Content-Disposition: form-data; name="${i(t)}"${!n&&r.name?`; filename="${i(r.name)}"`:""}${hrn}`;n?r=y7a.encode(String(r).replace(/\r?\n|\r\n?/g,hrn)):a+=`Content-Type: ${r.type||"application/octet-stream"}${hrn}`,this.headers=y7a.encode(a+hrn),this.contentLength=n?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+riE,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;ss.isTypedArray(t)?yield t:yield*RQo(t),yield tiE}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},iiE=(e,t,r)=>{let{tag:i="form-data-boundary",size:n=25,boundary:a=i+"-"+NA.generateString(n,eiE)}=r||{};if(!ss.isFormData(e))throw TypeError("FormData instance required");if(a.length<1||a.length>70)throw Error("boundary must be 10-70 characters long");let u=y7a.encode("--"+a+hrn),l=y7a.encode("--"+a+"--"+hrn),d=l.byteLength,s=Array.from(e.entries()).map(([c,b])=>{let g=new Ypc(c,b);return d+=g.size,g});d+=u.byteLength*s.length,d=ss.toFiniteNumber(d);let o={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(d)&&(o["Content-Length"]=d),t&&t(o),GXp.Readable.from(async function*(){for(let c of s)yield u,yield*c.encode();yield l}())},QXp=iiE;var JXp=ui(require("stream"),1),Xpc=class extends JXp.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)}},KXp=Xpc;var niE=(e,t)=>ss.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,YXp=niE;function aiE(e,t){e=e||10;let r=new Array(e),i=new Array(e),n=0,a=0,u;return t=t!==void 0?t:1e3,function(d){let s=Date.now(),o=i[a];u||(u=s),r[n]=d,i[n]=s;let c=a,b=0;for(;c!==n;)b+=r[c++],c=c%e;if(n=(n+1)%e,n===a&&(a=(a+1)%e),s-u<t)return;let g=o&&s-o;return g?Math.round(b*1e3/g):void 0}}var XXp=aiE;function oiE(e,t){let r=0,i=1e3/t,n,a,u=(s,o=Date.now())=>{r=o,n=null,a&&(clearTimeout(a),a=null),e.apply(null,s)};return[(...s)=>{let o=Date.now(),c=o-r;c>=i?u(s,o):(n=s,a||(a=setTimeout(()=>{a=null,u(n)},i-c)))},()=>n&&u(n)]}var ZXp=oiE;var XOi=(e,t,r=3)=>{let i=0,n=XXp(50,250);return ZXp(a=>{let u=a.loaded,l=a.lengthComputable?a.total:void 0,d=u-i,s=n(d),o=u<=l;i=u;let c={loaded:u,total:l,progress:l?u/l:void 0,bytes:d,rate:s||void 0,estimated:s&&l&&o?(l-u)/s:void 0,event:a,lengthComputable:l!=null,[t?"download":"upload"]:!0};e(c)},r)},MHn=(e,t)=>{let r=e!=null;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},AHn=e=>(...t)=>ss.asap(()=>e(...t));var kXp={flush:ZOi.default.constants.Z_SYNC_FLUSH,finishFlush:ZOi.default.constants.Z_SYNC_FLUSH},uiE={flush:ZOi.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:ZOi.default.constants.BROTLI_OPERATION_FLUSH},eZp=ss.isFunction(ZOi.default.createBrotliDecompress),{http:siE,https:ciE}=sZp.default,liE=/https:?/,tZp=NA.protocols.map(e=>e+":"),rZp=(e,[t,r])=>(e.on("end",r).on("error",r),t);function fiE(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function lZp(e,t,r){let i=t;if(!i&&i!==!1){let n=nZp.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){lZp(a,t,a.href)}}var diE=typeof process<"u"&&ss.kindOf(process)==="process",piE=e=>new Promise((t,r)=>{let i,n,a=(d,s)=>{n||(n=!0,i&&i(d,s))},u=d=>{a(d),t(d)},l=d=>{a(d,!0),r(d)};e(u,l,d=>i=d).catch(l)}),_iE=({address:e,family:t})=>{if(!ss.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},iZp=(e,t)=>_iE(ss.isObject(e)?e:{address:e,family:t}),fZp=diE&&function(t){return piE(async function(i,n,a){let{data:u,lookup:l,family:d}=t,{responseType:s,responseEncoding:o}=t,c=t.method.toUpperCase(),b,g=!1,O;if(l){let Oe=YXp(l,Ue=>ss.isArray(Ue)?Ue:[Ue]);l=(Ue,bt,De)=>{Oe(Ue,bt,(Te,Rt,Pe)=>{if(Te)return De(Te);let ot=ss.isArray(Rt)?Rt.map(at=>iZp(at)):[iZp(Rt,Pe)];bt.all?De(Te,ot):De(Te,ot[0].address,ot[0].family)})}}let m=new cZp.EventEmitter,w=()=>{t.cancelToken&&t.cancelToken.unsubscribe(E),t.signal&&t.signal.removeEventListener("abort",E),m.removeAllListeners()};a((Oe,Ue)=>{b=!0,Ue&&(g=!0,w())});function E(Oe){m.emit("abort",!Oe||Oe.type?new DAe(null,t,O):Oe)}m.once("abort",n),(t.cancelToken||t.signal)&&(t.cancelToken&&t.cancelToken.subscribe(E),t.signal&&(t.signal.aborted?E():t.signal.addEventListener("abort",E)));let q=prn(t.baseURL,t.url,t.allowAbsoluteUrls),M=new URL(q,NA.hasBrowserEnv?NA.origin:void 0),D=M.protocol||tZp[0];if(D==="data:"){let Oe;if(c!=="GET")return war(i,n,{status:405,statusText:"method not allowed",headers:{},config:t});try{Oe=Gpc(t.url,s==="blob",{Blob:t.env&&t.env.Blob})}catch(Ue){throw Qp.from(Ue,Qp.ERR_BAD_REQUEST,t)}return s==="text"?(Oe=Oe.toString(o),(!o||o==="utf8")&&(Oe=ss.stripBOM(Oe))):s==="stream"&&(Oe=yrn.default.Readable.from(Oe)),war(i,n,{data:Oe,status:200,statusText:"OK",headers:new Kx,config:t})}if(tZp.indexOf(D)===-1)return n(new Qp("Unsupported protocol "+D,Qp.ERR_BAD_REQUEST,t));let C=Kx.from(t.headers).normalize();C.set("User-Agent","axios/"+_rn,!1);let{onUploadProgress:R,onDownloadProgress:G}=t,I=t.maxRate,L,V;if(ss.isSpecCompliantForm(u)){let Oe=C.getContentType(/boundary=([-_\w\d]{10,70})/i);u=QXp(u,Ue=>{C.set(Ue)},{tag:`axios-${_rn}-boundary`,boundary:Oe&&Oe[1]||void 0})}else if(ss.isFormData(u)&&ss.isFunction(u.getHeaders)){if(C.set(u.getHeaders()),!C.hasContentLength())try{let Oe=await uZp.default.promisify(u.getLength).call(u);Number.isFinite(Oe)&&Oe>=0&&C.setContentLength(Oe)}catch{}}else if(ss.isBlob(u)||ss.isFile(u))u.size&&C.setContentType(u.type||"application/octet-stream"),C.setContentLength(u.size||0),u=yrn.default.Readable.from(RQo(u));else if(u&&!ss.isStream(u)){if(!Buffer.isBuffer(u))if(ss.isArrayBuffer(u))u=Buffer.from(new Uint8Array(u));else if(ss.isString(u))u=Buffer.from(u,"utf-8");else return n(new Qp("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",Qp.ERR_BAD_REQUEST,t));if(C.setContentLength(u.length,!1),t.maxBodyLength>-1&&u.length>t.maxBodyLength)return n(new Qp("Request body larger than maxBodyLength limit",Qp.ERR_BAD_REQUEST,t))}let Y=ss.toFiniteNumber(C.getContentLength());ss.isArray(I)?(L=I[0],V=I[1]):L=V=I,u&&(R||L)&&(ss.isStream(u)||(u=yrn.default.Readable.from(u,{objectMode:!1})),u=yrn.default.pipeline([u,new Kpc({maxRate:ss.toFiniteNumber(L)})],ss.noop),R&&u.on("progress",rZp(u,MHn(Y,XOi(AHn(R),!1,3)))));let K;if(t.auth){let Oe=t.auth.username||"",Ue=t.auth.password||"";K=Oe+":"+Ue}if(!K&&M.username){let Oe=M.username,Ue=M.password;K=Oe+":"+Ue}K&&C.delete("authorization");let X;try{X=drn(M.pathname+M.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch(Oe){let Ue=new Error(Oe.message);return Ue.config=t,Ue.url=t.url,Ue.exists=!0,n(Ue)}C.set("Accept-Encoding","gzip, compress, deflate"+(eZp?", br":""),!1);let oe={path:X,method:c,headers:C.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:K,protocol:D,family:d,beforeRedirect:fiE,beforeRedirects:{}};!ss.isUndefined(l)&&(oe.lookup=l),t.socketPath?oe.socketPath=t.socketPath:(oe.hostname=M.hostname.startsWith("[")?M.hostname.slice(1,-1):M.hostname,oe.port=M.port,lZp(oe,t.proxy,D+"//"+M.hostname+(M.port?":"+M.port:"")+oe.path));let pe,de=liE.test(oe.protocol);if(oe.agent=de?t.httpsAgent:t.httpAgent,t.transport?pe=t.transport:t.maxRedirects===0?pe=de?oZp.default:aZp.default:(t.maxRedirects&&(oe.maxRedirects=t.maxRedirects),t.beforeRedirect&&(oe.beforeRedirects.config=t.beforeRedirect),pe=de?ciE:siE),t.maxBodyLength>-1?oe.maxBodyLength=t.maxBodyLength:oe.maxBodyLength=1/0,t.insecureHTTPParser&&(oe.insecureHTTPParser=t.insecureHTTPParser),O=pe.request(oe,function(Ue){if(O.destroyed)return;let bt=[Ue],De=+Ue.headers["content-length"];if(G||V){let at=new Kpc({maxRate:ss.toFiniteNumber(V)});G&&at.on("progress",rZp(at,MHn(De,XOi(AHn(G),!0,3)))),bt.push(at)}let Te=Ue,Rt=Ue.req||O;if(t.decompress!==!1&&Ue.headers["content-encoding"])switch((c==="HEAD"||Ue.statusCode===204)&&delete Ue.headers["content-encoding"],(Ue.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":bt.push(ZOi.default.createUnzip(kXp)),delete Ue.headers["content-encoding"];break;case"deflate":bt.push(new KXp),bt.push(ZOi.default.createUnzip(kXp)),delete Ue.headers["content-encoding"];break;case"br":eZp&&(bt.push(ZOi.default.createBrotliDecompress(uiE)),delete Ue.headers["content-encoding"])}Te=bt.length>1?yrn.default.pipeline(bt,ss.noop):bt[0];let Pe=yrn.default.finished(Te,()=>{Pe(),w()}),ot={status:Ue.statusCode,statusText:Ue.statusMessage,headers:new Kx(Ue.headers),config:t,request:Rt};if(s==="stream")ot.data=Te,war(i,n,ot);else{let at=[],me=0;Te.on("data",function(St){at.push(St),me+=St.length,t.maxContentLength>-1&&me>t.maxContentLength&&(g=!0,Te.destroy(),n(new Qp("maxContentLength size of "+t.maxContentLength+" exceeded",Qp.ERR_BAD_RESPONSE,t,Rt)))}),Te.on("aborted",function(){if(g)return;let St=new Qp("stream has been aborted",Qp.ERR_BAD_RESPONSE,t,Rt);Te.destroy(St),n(St)}),Te.on("error",function(St){O.destroyed||n(Qp.from(St,null,t,Rt))}),Te.on("end",function(){try{let St=at.length===1?at[0]:Buffer.concat(at);s!=="arraybuffer"&&(St=St.toString(o),(!o||o==="utf8")&&(St=ss.stripBOM(St))),ot.data=St}catch(St){return n(Qp.from(St,null,t,ot.request,ot))}war(i,n,ot)})}m.once("abort",at=>{Te.destroyed||(Te.emit("error",at),Te.destroy())})}),m.once("abort",Oe=>{n(Oe),O.destroy(Oe)}),O.on("error",function(Ue){n(Qp.from(Ue,null,t,O))}),O.on("socket",function(Ue){Ue.setKeepAlive(!0,1e3*60)}),t.timeout){let Oe=parseInt(t.timeout,10);if(Number.isNaN(Oe)){n(new Qp("error trying to parse `config.timeout` to int",Qp.ERR_BAD_OPTION_VALUE,t,O));return}O.setTimeout(Oe,function(){if(b)return;let bt=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",De=t.transitional||SHn;t.timeoutErrorMessage&&(bt=t.timeoutErrorMessage),n(new Qp(bt,De.clarifyTimeoutError?Qp.ETIMEDOUT:Qp.ECONNABORTED,t,O)),E()})}if(ss.isStream(u)){let Oe=!1,Ue=!1;u.on("end",()=>{Oe=!0}),u.once("error",bt=>{Ue=!0,O.destroy(bt)}),u.on("close",()=>{!Oe&&!Ue&&E(new DAe("Request stream has been aborted",t,O))}),u.pipe(O)}else O.end(u)})};var dZp=NA.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,NA.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(NA.origin),NA.navigator&&/(msie|trident)/i.test(NA.navigator.userAgent)):()=>!0;var pZp=NA.hasStandardBrowserEnv?{write(e,t,r,i,n,a){let u=[e+"="+encodeURIComponent(t)];ss.isNumber(r)&&u.push("expires="+new Date(r).toGMTString()),ss.isString(i)&&u.push("path="+i),ss.isString(n)&&u.push("domain="+n),a===!0&&u.push("secure"),document.cookie=u.join("; ")},read(e){let t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};var _Zp=e=>e instanceof Kx?{...e}:e;function AGt(e,t){t=t||{};let r={};function i(s,o,c,b){return ss.isPlainObject(s)&&ss.isPlainObject(o)?ss.merge.call({caseless:b},s,o):ss.isPlainObject(o)?ss.merge({},o):ss.isArray(o)?o.slice():o}function n(s,o,c,b){if(ss.isUndefined(o)){if(!ss.isUndefined(s))return i(void 0,s,c,b)}else return i(s,o,c,b)}function a(s,o){if(!ss.isUndefined(o))return i(void 0,o)}function u(s,o){if(ss.isUndefined(o)){if(!ss.isUndefined(s))return i(void 0,s)}else return i(void 0,o)}function l(s,o,c){if(c in t)return i(s,o);if(c in e)return i(void 0,s)}let d={url:a,method:a,data:a,baseURL:u,transformRequest:u,transformResponse:u,paramsSerializer:u,timeout:u,timeoutMessage:u,withCredentials:u,withXSRFToken:u,adapter:u,responseType:u,xsrfCookieName:u,xsrfHeaderName:u,onUploadProgress:u,onDownloadProgress:u,decompress:u,maxContentLength:u,maxBodyLength:u,beforeRedirect:u,transport:u,httpAgent:u,httpsAgent:u,cancelToken:u,socketPath:u,responseEncoding:u,validateStatus:l,headers:(s,o,c)=>n(_Zp(s),_Zp(o),c,!0)};return ss.forEach(Object.keys(Object.assign({},e,t)),function(o){let c=d[o]||n,b=c(e[o],t[o],o);ss.isUndefined(b)&&c!==l||(r[o]=b)}),r}var xQo=e=>{let t=AGt({},e),{data:r,withXSRFToken:i,xsrfHeaderName:n,xsrfCookieName:a,headers:u,auth:l}=t;t.headers=u=Kx.from(u),t.url=drn(prn(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),l&&u.set("Authorization","Basic "+btoa((l.username||"")+":"+(l.password?unescape(encodeURIComponent(l.password)):"")));let d;if(ss.isFormData(r)){if(NA.hasStandardBrowserEnv||NA.hasStandardBrowserWebWorkerEnv)u.setContentType(void 0);else if((d=u.getContentType())!==!1){let[s,...o]=d?d.split(";").map(c=>c.trim()).filter(Boolean):[];u.setContentType([s||"multipart/form-data",...o].join("; "))}}if(NA.hasStandardBrowserEnv&&(i&&ss.isFunction(i)&&(i=i(t)),i||i!==!1&&dZp(t.url))){let s=n&&a&&pZp.read(a);s&&u.set(n,s)}return t};var hiE=typeof XMLHttpRequest<"u",hZp=hiE&&function(e){return new Promise(function(r,i){let n=xQo(e),a=n.data,u=Kx.from(n.headers).normalize(),{responseType:l,onUploadProgress:d,onDownloadProgress:s}=n,o,c,b,g,O;function m(){g&&g(),O&&O(),n.cancelToken&&n.cancelToken.unsubscribe(o),n.signal&&n.signal.removeEventListener("abort",o)}let w=new XMLHttpRequest;w.open(n.method.toUpperCase(),n.url,!0),w.timeout=n.timeout;function E(){if(!w)return;let M=Kx.from("getAllResponseHeaders"in w&&w.getAllResponseHeaders()),C={data:!l||l==="text"||l==="json"?w.responseText:w.response,status:w.status,statusText:w.statusText,headers:M,config:e,request:w};war(function(G){r(G),m()},function(G){i(G),m()},C),w=null}"onloadend"in w?w.onloadend=E:w.onreadystatechange=function(){!w||w.readyState!==4||w.status===0&&!(w.responseURL&&w.responseURL.indexOf("file:")===0)||setTimeout(E)},w.onabort=function(){w&&(i(new Qp("Request aborted",Qp.ECONNABORTED,e,w)),w=null)},w.onerror=function(){i(new Qp("Network Error",Qp.ERR_NETWORK,e,w)),w=null},w.ontimeout=function(){let D=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded",C=n.transitional||SHn;n.timeoutErrorMessage&&(D=n.timeoutErrorMessage),i(new Qp(D,C.clarifyTimeoutError?Qp.ETIMEDOUT:Qp.ECONNABORTED,e,w)),w=null},a===void 0&&u.setContentType(null),"setRequestHeader"in w&&ss.forEach(u.toJSON(),function(D,C){w.setRequestHeader(C,D)}),ss.isUndefined(n.withCredentials)||(w.withCredentials=!!n.withCredentials),l&&l!=="json"&&(w.responseType=n.responseType),s&&([b,O]=XOi(s,!0),w.addEventListener("progress",b)),d&&w.upload&&([c,g]=XOi(d),w.upload.addEventListener("progress",c),w.upload.addEventListener("loadend",g)),(n.cancelToken||n.signal)&&(o=M=>{w&&(i(!M||M.type?new DAe(null,e,w):M),w.abort(),w=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));let q=h7a(n.url);if(q&&NA.protocols.indexOf(q)===-1){i(new Qp("Unsupported protocol "+q+":",Qp.ERR_BAD_REQUEST,e));return}w.send(a||null)})};var yiE=(e,t)=>{let{length:r}=e=e?e.filter(Boolean):[];if(t||r){let i=new AbortController,n,a=function(s){if(!n){n=!0,l();let o=s instanceof Error?s:this.reason;i.abort(o instanceof Qp?o:new DAe(o instanceof Error?o.message:o))}},u=t&&setTimeout(()=>{u=null,a(new Qp(`timeout ${t} of ms exceeded`,Qp.ETIMEDOUT))},t),l=()=>{e&&(u&&clearTimeout(u),u=null,e.forEach(s=>{s.unsubscribe?s.unsubscribe(a):s.removeEventListener("abort",a)}),e=null)};e.forEach(s=>s.addEventListener("abort",a));let{signal:d}=i;return d.unsubscribe=()=>ss.asap(l),d}},yZp=yiE;var viE=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},biE=async function*(e,t){for await(let r of giE(e))yield*viE(r,t)},giE=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()}},Zpc=(e,t,r,i)=>{let n=biE(e,t),a=0,u,l=d=>{u||(u=!0,i&&i(d))};return new ReadableStream({async pull(d){try{let{done:s,value:o}=await n.next();if(s){l(),d.close();return}let c=o.byteLength;if(r){let b=a+=c;r(b)}d.enqueue(new Uint8Array(o))}catch(s){throw l(s),s}},cancel(d){return l(d),n.return()}},{highWaterMark:2})};var FQo=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",bZp=FQo&&typeof ReadableStream=="function",OiE=FQo&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),gZp=(e,...t)=>{try{return!!e(...t)}catch{return!1}},miE=bZp&&gZp(()=>{let e=!1,t=new Request(NA.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),vZp=64*1024,kpc=bZp&&gZp(()=>ss.isReadableStream(new Response("").body)),NQo={stream:kpc&&(e=>e.body)};FQo&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!NQo[t]&&(NQo[t]=ss.isFunction(e[t])?r=>r[t]():(r,i)=>{throw new Qp(`Response type '${t}' is not supported`,Qp.ERR_NOT_SUPPORT,i)})})})(new Response);var PiE=async e=>{if(e==null)return 0;if(ss.isBlob(e))return e.size;if(ss.isSpecCompliantForm(e))return(await new Request(NA.origin,{method:"POST",body:e}).arrayBuffer()).byteLength;if(ss.isArrayBufferView(e)||ss.isArrayBuffer(e))return e.byteLength;if(ss.isURLSearchParams(e)&&(e=e+""),ss.isString(e))return(await OiE(e)).byteLength},jiE=async(e,t)=>{let r=ss.toFiniteNumber(e.getContentLength());return r??PiE(t)},OZp=FQo&&(async e=>{let{url:t,method:r,data:i,signal:n,cancelToken:a,timeout:u,onDownloadProgress:l,onUploadProgress:d,responseType:s,headers:o,withCredentials:c="same-origin",fetchOptions:b}=xQo(e);s=s?(s+"").toLowerCase():"text";let g=yZp([n,a&&a.toAbortSignal()],u),O,m=g&&g.unsubscribe&&(()=>{g.unsubscribe()}),w;try{if(d&&miE&&r!=="get"&&r!=="head"&&(w=await jiE(o,i))!==0){let C=new Request(t,{method:"POST",body:i,duplex:"half"}),R;if(ss.isFormData(i)&&(R=C.headers.get("content-type"))&&o.setContentType(R),C.body){let[G,I]=MHn(w,XOi(AHn(d)));i=Zpc(C.body,vZp,G,I)}}ss.isString(c)||(c=c?"include":"omit");let E="credentials"in Request.prototype;O=new Request(t,{...b,signal:g,method:r.toUpperCase(),headers:o.normalize().toJSON(),body:i,duplex:"half",credentials:E?c:void 0});let q=await fetch(O,b),M=kpc&&(s==="stream"||s==="response");if(kpc&&(l||M&&m)){let C={};["status","statusText","headers"].forEach(L=>{C[L]=q[L]});let R=ss.toFiniteNumber(q.headers.get("content-length")),[G,I]=l&&MHn(R,XOi(AHn(l),!0))||[];q=new Response(Zpc(q.body,vZp,G,()=>{I&&I(),m&&m()}),C)}s=s||"text";let D=await NQo[ss.findKey(NQo,s)||"text"](q,e);return!M&&m&&m(),await new Promise((C,R)=>{war(C,R,{data:D,headers:Kx.from(q.headers),status:q.status,statusText:q.statusText,config:e,request:O})})}catch(E){throw m&&m(),E&&E.name==="TypeError"&&/Load failed|fetch/i.test(E.message)?Object.assign(new Qp("Network Error",Qp.ERR_NETWORK,e,O),{cause:E.cause||E}):Qp.from(E,E&&E.code,e,O)}});var e_c={http:fZp,xhr:hZp,fetch:OZp};ss.forEach(e_c,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var mZp=e=>`- ${e}`,wiE=e=>ss.isFunction(e)||e===null||e===!1,LQo={getAdapter:e=>{e=ss.isArray(e)?e:[e];let{length:t}=e,r,i,n={};for(let a=0;a<t;a++){r=e[a];let u;if(i=r,!wiE(r)&&(i=e_c[(u=String(r)).toLowerCase()],i===void 0))throw new Qp(`Unknown adapter '${u}'`);if(i)break;n[u||"#"+a]=i}if(!i){let a=Object.entries(n).map(([l,d])=>`adapter ${l} `+(d===!1?"is not supported by the environment":"is not available in the build")),u=t?a.length>1?`since :
@@ -1911,7 +1911,7 @@ For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides
1911
1911
  2. your cache path is incorrectly configured (which is: ${this.puppeteer.configuration.cacheDirectory}).
1912
1912
  For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides/configuration.`)}}return n.executablePath}};q8a=new WeakMap;var ptu=class extends KQn{constructor(t){super(t,"chrome")}launch(t={}){var r;return((r=t.headless)!==null&&r!==void 0?r:!0)===!0&&(!this.puppeteer.configuration.logLevel||this.puppeteer.configuration.logLevel==="warn")&&!process.env.PUPPETEER_DISABLE_HEADLESS_WARNING&&console.warn(["\x1B[1m\x1B[43m\x1B[30m","Puppeteer old Headless deprecation warning:\x1B[0m\x1B[33m"," In the near feature `headless: true` will default to the new Headless mode"," for Chrome instead of the old Headless implementation. For more"," information, please see https://developer.chrome.com/articles/new-headless/.",' Consider opting in early by passing `headless: "new"` to `puppeteer.launch()`',` If you encounter any bugs, please report them to https://github.com/puppeteer/puppeteer/issues/new/choose.\x1B[0m
1913
1913
  `].join(`
1914
- `)),super.launch(t)}async computeLaunchArguments(t={}){let{ignoreDefaultArgs:r=!1,args:i=[],pipe:n=!1,debuggingPort:a,channel:u,executablePath:l}=t,d=[];r?Array.isArray(r)?d.push(...this.defaultArgs(t).filter(g=>!r.includes(g))):d.push(...i):d.push(...this.defaultArgs(t)),d.some(g=>g.startsWith("--remote-debugging-"))||(n?(Zc(!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,o=d.findIndex(g=>g.startsWith("--user-data-dir"));o<0&&(s=!0,d.push(`--user-data-dir=${await(0,tb_.mkdtemp)(this.getProfilePath())}`),o=d.length-1);let c=d[o].split("=",2)[1];Zc(typeof c=="string","`--user-data-dir` is malformed");let b=l;return b||(Zc(u||!this.puppeteer._isPuppeteerCore,"An `executablePath` or `channel` must be specified for `puppeteer-core`"),b=this.executablePath(u)),{executablePath:b,args:d,isTempUserDataDir:s,userDataDir:c}}async cleanUserDataDir(t,r){if(r.isTemp)try{await vQn(t)}catch(i){throw X0(i),i}}defaultArgs(t={}){let r=["--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-component-update","--disable-default-apps","--disable-dev-shm-usage","--disable-extensions","--disable-features=Translate,BackForwardCache,AcceptCHFrame,MediaRouter,OptimizationHints","--disable-hang-monitor","--disable-ipc-flooding-protection","--disable-popup-blocking","--disable-prompt-on-repost","--disable-renderer-backgrounding","--disable-sync","--enable-automation","--enable-blink-features=IdleDetection","--enable-features=NetworkServiceInProcess2","--export-tagged-pdf","--force-color-profile=srgb","--metrics-recording-only","--no-first-run","--password-store=basic","--use-mock-keychain"],{devtools:i=!1,headless:n=!i,args:a=[],userDataDir:u}=t;return u&&r.push(`--user-data-dir=${rb_.default.resolve(u)}`),i&&r.push("--auto-open-devtools-for-tabs"),n&&r.push(n==="new"?"--headless=new":"--headless","--hide-scrollbars","--mute-audio"),a.every(l=>l.startsWith("-"))&&r.push("about:blank"),r.push(...a),r}executablePath(t){return t?neu({browser:Pq.CHROME,channel:aAE(t)}):this.resolveExecutablePath()}};function aAE(e){switch(e){case"chrome":return c7.STABLE;case"chrome-dev":return c7.DEV;case"chrome-beta":return c7.BETA;case"chrome-canary":return c7.CANARY}}var FPc=ui(require("fs"),1),tnn=require("fs/promises"),ib_=ui(require("os"),1),_tu=ui(require("path"),1);eB();FA();var htu=class extends KQn{constructor(t){super(t,"firefox")}async computeLaunchArguments(t={}){let{ignoreDefaultArgs:r=!1,args:i=[],executablePath:n,pipe:a=!1,extraPrefsFirefox:u={},debuggingPort:l=null}=t,d=[];r?Array.isArray(r)?d.push(...this.defaultArgs(t).filter(g=>!r.includes(g))):d.push(...i):d.push(...this.defaultArgs(t)),d.some(g=>g.startsWith("--remote-debugging-"))||(a&&Zc(l===null,"Browser should be launched with either pipe or debugging port - not both."),d.push(`--remote-debugging-port=${l||0}`));let s,o=!0,c=d.findIndex(g=>["-profile","--profile"].includes(g));if(c!==-1){if(s=d[c+1],!s||!FPc.default.existsSync(s))throw new Error(`Firefox profile not found at '${s}'`);o=!1}else s=await(0,tnn.mkdtemp)(this.getProfilePath()),d.push("--profile"),d.push(s);await LOc(Pq.FIREFOX,{path:s,preferences:u});let b;return this.puppeteer._isPuppeteerCore||n?(Zc(n,"An `executablePath` must be specified for `puppeteer-core`"),b=n):b=this.executablePath(),{isTempUserDataDir:o,userDataDir:s,args:d,executablePath:b}}async cleanUserDataDir(t,r){if(r.isTemp)try{await vQn(t)}catch(i){throw X0(i),i}else try{await(0,tnn.unlink)(_tu.default.join(t,"user.js"));let i=_tu.default.join(t,"prefs.js.puppeteer");if(FPc.default.existsSync(i)){let n=_tu.default.join(t,"prefs.js");await(0,tnn.unlink)(n),await(0,tnn.rename)(i,n)}}catch(i){X0(i)}}executablePath(){if(this.puppeteer.browserRevision==="latest"){let r=this.puppeteer.createBrowserFetcher({product:this.product,path:this.puppeteer.defaultDownloadPath}).localRevisions();r[0]&&(this.actualBrowserRevision=r[0])}return this.resolveExecutablePath()}defaultArgs(t={}){let{devtools:r=!1,headless:i=!r,args:n=[],userDataDir:a=null}=t,u=["--no-remote"];switch(ib_.default.platform()){case"darwin":u.push("--foreground");break;case"win32":u.push("--wait-for-browser");break}return a&&(u.push("--profile"),u.push(a)),i&&u.push("--headless"),r&&u.push("--devtools"),n.every(l=>l.startsWith("-"))&&u.push("about:blank"),u.push(...n),u}};var nb_=require("path");var C8a=Object.freeze({chromium:"1108766",firefox:"latest"});var LPc=function(e,t,r,i,n){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?n.call(e,r):n?n.value=r:t.set(e,r),r},uQt=function(e,t,r,i){if(r==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?i:r==="a"?i.call(e):i?i.value:t.get(e)},YQn,Fmi,I8a,B8a,XQn=class extends S2a{constructor(t){let{configuration:r,...i}=t;switch(super(i),YQn.add(this),Fmi.set(this,void 0),I8a.set(this,void 0),this.configuration={},r&&(this.configuration=r),this.configuration.defaultProduct){case"firefox":this.defaultBrowserRevision=C8a.firefox;break;default:this.configuration.defaultProduct="chrome",this.defaultBrowserRevision=C8a.chromium;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.createBrowserFetcher=this.createBrowserFetcher.bind(this)}connect(t){return super.connect(t)}launch(t={}){let{product:r=this.defaultProduct}=t;return LPc(this,I8a,r,"f"),uQt(this,YQn,"a",B8a).launch(t)}executablePath(t){return uQt(this,YQn,"a",B8a).executablePath(t)}get browserRevision(){var t,r,i;return(i=(r=(t=uQt(this,Fmi,"f"))===null||t===void 0?void 0:t.getActualBrowserRevision())!==null&&r!==void 0?r:this.configuration.browserRevision)!==null&&i!==void 0?i:this.defaultBrowserRevision}get defaultDownloadPath(){var t;return(t=this.configuration.downloadPath)!==null&&t!==void 0?t:(0,nb_.join)(this.configuration.cacheDirectory,this.product)}get lastLaunchedProduct(){var t;return(t=uQt(this,I8a,"f"))!==null&&t!==void 0?t:this.defaultProduct}get defaultProduct(){var t;return(t=this.configuration.defaultProduct)!==null&&t!==void 0?t:"chrome"}get product(){return uQt(this,YQn,"a",B8a).product}defaultArgs(t={}){return uQt(this,YQn,"a",B8a).defaultArgs(t)}createBrowserFetcher(t={}){var r;let i=this.defaultDownloadPath;if(!t.path&&i&&(t.path=i),!t.path)throw new Error("A `path` must be specified for `puppeteer-core`.");return!("useMacOSARMBinary"in t)&&(!((r=this.configuration.experiments)===null||r===void 0)&&r.macArmChromiumEnabled)&&(t.useMacOSARMBinary=!0),!("host"in t)&&this.configuration.downloadHost&&(t.host=this.configuration.downloadHost),!("product"in t)&&this.configuration.defaultProduct&&(t.product=this.configuration.defaultProduct),new Qko(t)}};Fmi=new WeakMap,I8a=new WeakMap,YQn=new WeakSet,B8a=function(){if(uQt(this,Fmi,"f")&&uQt(this,Fmi,"f").product===this.lastLaunchedProduct)return uQt(this,Fmi,"f");switch(this.lastLaunchedProduct){case"chrome":this.defaultBrowserRevision=C8a.chromium,LPc(this,Fmi,new ptu(this),"f");break;case"firefox":this.defaultBrowserRevision=C8a.firefox,LPc(this,Fmi,new htu(this),"f");break;default:throw new Error(`Unknown product: ${uQt(this,I8a,"f")}`)}return uQt(this,Fmi,"f")};h0c();V6a();var oAE=new XQn({isPuppeteerCore:!0}),{connect:k45,createBrowserFetcher:e25,defaultArgs:t25,executablePath:r25,launch:i25}=oAE;var Bg_=require("os"),Ig_=require("path"),zg_=ui(Cg_(),1);function CCE(e){switch(e){case"chrome":case"firefox":return!0;default:return!1}}var Rg_=()=>{var e,t,r,i,n,a,u,l,d,s,o,c,b,g,O,m,w,E,q,M,D,C,R,G,I,L,V,Y,K,X,oe,pe,de,Oe,Ue,bt,De;let Te=(0,zg_.cosmiconfigSync)("puppeteer").search(),Rt=Te?Te.config:{};if(Rt.defaultProduct=(i=(r=(t=(e=process.env.PUPPETEER_PRODUCT)!==null&&e!==void 0?e:process.env.npm_config_puppeteer_product)!==null&&t!==void 0?t:process.env.npm_package_config_puppeteer_product)!==null&&r!==void 0?r:Rt.defaultProduct)!==null&&i!==void 0?i:"chrome",Rt.executablePath=(u=(a=(n=process.env.PUPPETEER_EXECUTABLE_PATH)!==null&&n!==void 0?n:process.env.npm_config_puppeteer_executable_path)!==null&&a!==void 0?a:process.env.npm_package_config_puppeteer_executable_path)!==null&&u!==void 0?u:Rt.executablePath,Rt.executablePath&&(Rt.skipDownload=!0),Rt.skipDownload=!!((b=(c=(o=(s=(d=(l=process.env.PUPPETEER_SKIP_DOWNLOAD)!==null&&l!==void 0?l:process.env.npm_config_puppeteer_skip_download)!==null&&d!==void 0?d:process.env.npm_package_config_puppeteer_skip_download)!==null&&s!==void 0?s:process.env.PUPPETEER_SKIP_CHROMIUM_DOWNLOAD)!==null&&o!==void 0?o:process.env.npm_config_puppeteer_skip_chromium_download)!==null&&c!==void 0?c:process.env.npm_package_config_puppeteer_skip_chromium_download)!==null&&b!==void 0?b:Rt.skipDownload),Rt.skipDownload||(Rt.browserRevision=(w=(m=(O=(g=process.env.PUPPETEER_CHROMIUM_REVISION)!==null&&g!==void 0?g:process.env.PUPPETEER_BROWSER_REVISION)!==null&&O!==void 0?O:process.env.npm_config_puppeteer_browser_revision)!==null&&m!==void 0?m:process.env.npm_package_config_puppeteer_browser_revision)!==null&&w!==void 0?w:Rt.browserRevision,Rt.downloadHost=(M=(q=(E=process.env.PUPPETEER_DOWNLOAD_HOST)!==null&&E!==void 0?E:process.env.npm_config_puppeteer_download_host)!==null&&q!==void 0?q:process.env.npm_package_config_puppeteer_download_host)!==null&&M!==void 0?M:Rt.downloadHost,Rt.downloadPath=(R=(C=(D=process.env.PUPPETEER_DOWNLOAD_PATH)!==null&&D!==void 0?D:process.env.npm_config_puppeteer_download_path)!==null&&C!==void 0?C:process.env.npm_package_config_puppeteer_download_path)!==null&&R!==void 0?R:Rt.downloadPath),Rt.cacheDirectory=(V=(L=(I=(G=process.env.PUPPETEER_CACHE_DIR)!==null&&G!==void 0?G:process.env.npm_config_puppeteer_cache_dir)!==null&&I!==void 0?I:process.env.npm_package_config_puppeteer_cache_dir)!==null&&L!==void 0?L:Rt.cacheDirectory)!==null&&V!==void 0?V:(0,Ig_.join)((0,Bg_.homedir)(),".cache","puppeteer"),Rt.temporaryDirectory=(X=(K=(Y=process.env.PUPPETEER_TMP_DIR)!==null&&Y!==void 0?Y:process.env.npm_config_puppeteer_tmp_dir)!==null&&K!==void 0?K:process.env.npm_package_config_puppeteer_tmp_dir)!==null&&X!==void 0?X:Rt.temporaryDirectory,(oe=Rt.experiments)!==null&&oe!==void 0||(Rt.experiments={}),Rt.experiments.macArmChromiumEnabled=!!((Oe=(de=(pe=process.env.PUPPETEER_EXPERIMENTAL_CHROMIUM_MAC_ARM)!==null&&pe!==void 0?pe:process.env.npm_config_puppeteer_experimental_chromium_mac_arm)!==null&&de!==void 0?de:process.env.npm_package_config_puppeteer_experimental_chromium_mac_arm)!==null&&Oe!==void 0?Oe:Rt.experiments.macArmChromiumEnabled),Rt.logLevel=(De=(bt=(Ue=process.env.PUPPETEER_LOGLEVEL)!==null&&Ue!==void 0?Ue:process.env.npm_config_LOGLEVEL)!==null&&bt!==void 0?bt:process.env.npm_package_config_LOGLEVEL)!==null&&De!==void 0?De:Rt.logLevel,!CCE(Rt.defaultProduct))throw new Error(`Unsupported product ${Rt.defaultProduct}`);return Rt};var BCE=Rg_(),ICE=new XQn({isPuppeteerCore:!1,configuration:BCE}),{connect:d85,createBrowserFetcher:p85,defaultArgs:_85,executablePath:h85,launch:xg_}=ICE;var zCE="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",RCE={"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 K8a(e,t=3,r=1e3,i=2){try{return await e()}catch(n){if(t>0)return await new Promise(a=>setTimeout(a,r)),K8a(e,t-1,r*i,i);throw n}}async function Ng_(){try{return await xg_({headless:"new",ignoreHTTPSErrors:!0})}catch{throw new Error("Could not create a Puppeteer instance")}}async function xCE(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(RCE),await r.setUserAgent(zCE),await r.setJavaScriptEnabled(!0),await K8a(()=>r.goto(t.toString(),{waitUntil:"networkidle2",timeout:3e4}));let i=await K8a(()=>r.content());return await r.close(),i}catch{throw new Error("Failed to download page from Puppeteer")}}async function NCE(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 Qjc({url:e,browser:t}){try{let r;if(t?r=await xCE(t,e):r=await K8a(()=>NCE(e)),r)return r;throw new Error("An unknown error occurred.")}catch{throw new Error(`Error retrieving HTML for ${e.toString()}`)}}async function Fg_(e){try{let t=await K8a(()=>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 FCE=["png","jpeg","jpg","webp","avif","svg","ico","jfif","pjpeg","pjp","svgz","bmp"];async function Lg_(e){if(!e)return{success:!1,data:void 0};if(e.startsWith("data:image/"))return{success:!0,data:[e,e]};let t=(0,aJn.join)(process.cwd(),"fern");try{let r=await LCE(e,(0,aJn.join)(t,"images"));return r=r.replace(t,""),{success:!0,data:[e,r]}}catch{return{success:!1,data:void 0}}}async function LCE(e,t){let r=VCE(e),i=(0,aJn.join)(t,r);if(!UCE(r))throw new Error(`${r} - file extension not supported`);if((0,Ntu.existsSync)(i))return i;try{(0,Ntu.mkdirSync)((0,aJn.dirname)(i),{recursive:!0})}catch{throw new Error(`${i} - failed to create directory`)}try{let n=await Fg_(e);return nc_(i,n),i}catch{throw new Error(`${i}: failed to download file from source`)}}function UCE(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&&!FCE.includes(i))}function VCE(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 WCE(e){let t=[];return Vf(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 Ug_(e,t){let r=w$n(e),i=WCE(r);if(i!=null){let n=await Promise.all(i.map(async a=>{let u=await Lg_(a.properties.src);return u.success&&u.data?u.data[1]:""}));t.push(...n)}for(let n=t.length-1;n>=0;n--)t[n]||t.splice(n,1)}var Vg_=28;async function Wg_(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 Ug_(a,r)))}let i=[...new Set(r).values()];if(i.length!==0){if(i.length===1&&i[0]!=null){let n=Ia.of(nJ(i[0]));return{light:n,dark:n,height:Vg_}}if(i[0]!=null&&i[1]!=null){let n=Ia.of(nJ(i[0])),a=Ia.of(nJ(i[1]));return{light:n,dark:a,height:Vg_}}}}var Ftu=class extends jrn{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:z7a});let i=await this.getHastForUrl(this.url),n=_l_(i)??[];if(n.length===0)this.logger.debug("No tabs found on the page");else{this.logger.debug(`Found ${n.length} tabs:`);for(let o of n)this.logger.debug(` - Tab: ${o.name} (${o.url})`)}for(let o of n){let c=await this.scrapeTab({name:o.name,url:o.url});if(!c)continue;let b=r.getNavigationBuilder({tabId:this.kebabCaseWithoutEmojis(o.name),tabConfig:{slug:o.url,displayName:o.name}}),g=Eu(this.absolutePathToFernDirectory,Ia.of(this.kebabCaseWithoutEmojis(o.name)));await this.downloadMarkdownPages({absolutePathToOutputDirectory:g,sections:c});let O=await this.getNavigationItems({absolutePathToOutputDirectory:g,sections:c});for(let m of O)b.addItem({item:m})}let a=await Ng_(),u=await Wg_(this.url,a);u!=null&&r.setLogo({logo:u});let l=await Nn_(i);r.setTitle({title:l});let d=await In_(i);if(d!=null){let o=await this.getAndCreateAssetsDirectory(),c=await fetch(d);if(c.ok){let b=Buffer.from(await c.arrayBuffer()),g=Eu(o,Ia.of("favicon"));await(0,vNi.writeFile)(g,new Uint8Array(b)),r.setFavicon({favicon:hae(this.absolutePathToFernDirectory,g)})}}let s=await yl_(i);r.setColors({colors:s}),a&&await a.close(),r.build({outputDirectory:this.absolutePathToFernDirectory})}async getAndCreateAssetsDirectory(){let t=Eu(this.absolutePathToFernDirectory,Ia.of("assets"));return await(0,vNi.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=fl_(n);if(!a){this.logger.debug(`No sidebar element found for tab: ${t} (${r})`);return}let u=dl_(a);return this.logger.debug(`Successfully scraped tab: ${t}`),u}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 Qjc({url:t});return w$n(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,vNi.mkdir)(n,{recursive:!0}),await Promise.all(i.pages.filter(a=>a.type==="page").map(async a=>{let u=new URL(a.slug.toString(),this.url);this.logger.debug(`Fetching page: ${u.toString()}`);let l=await Qjc({url:u}),d=await ll_({logger:this.logger,html:l,url:u});if(d.success&&d.data){let s=this.getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:n,page:a.slug});await(0,vNi.writeFile)(s,d.data.mdx),d.data.images.imageURLs.length>0&&(this.logger.debug(`Found ${d.data.images.imageURLs.length} images to download for ${u.toString()}`),await Promise.all(Object.entries(d.data.images.imageURLToFilename).map(async([o,c])=>{try{let b=await fetch(o);if(!b.ok){this.logger.warn(`Failed to download image ${o}, status: ${b.status}`);return}let g=Buffer.from(await b.arrayBuffer()),O=Eu(n,Ia.of(c)),m=Rd(O);await(0,vNi.mkdir)(m,{recursive:!0}),await(0,vNi.writeFile)(O,new Uint8Array(g)),this.logger.debug(`Saved image to ${O}`)}catch(b){this.logger.warn(`Error downloading image ${o}: ${b}`)}})))}else this.logger.warn(`Failed to parse page ${u.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}),u={section:n.group,contents:[],slug:this.kebabCaseWithoutEmojis(n.group)};for(let l of n.pages)if(l.type==="page")u.contents.push({page:l.page,path:hae(this.absolutePathToFernDirectory,this.getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:a,page:l.slug}))});else{let d=await this.getNavigationItems({absolutePathToOutputDirectory:a,sections:[l]});u.contents.push(...d)}i.push(u)}return i}getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:t,page:r}){return Eu(t,Ia.of(`${this.kebabCaseWithoutEmojis(r.split("/").pop()||r)}.mdx`))}getAbsolutePathToOutputDirectoryForSection({absolutePathToOutputDirectory:t,section:r}){return Eu(t,Ia.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 Hg_=require("fs/promises");async function Jjc({readmeUrl:e,outputPath:t,taskContext:r,versionOfCli:i,organization:n}){let a=new wrn;a.setInstance({companyName:n}),await new Ftu({url:e,context:r,builder:a,absolutePathToFernDirectory:Eu(Fc.of(process.cwd()),Ia.of("fern"))}).import({args:{},builder:a}),await a.build({outputDirectory:t}),await(0,Hg_.writeFile)(Eu(Fc.of(t),Ia.of(KW),Ia.of(lae)),JSON.stringify({version:i,organization:n},void 0,4))}var Kjc=async({readmeUrl:e,organization:t,taskContext:r,versionOfCli:i})=>{if(!e||!fki(e)){r.failAndThrow("Provide a URL to a readme-generated site");return}let n=Fc.of(_I());await Jjc({readmeUrl:e,outputPath:n,taskContext:r,versionOfCli:i,organization:t})};var $g_="0.0.0";var Gg_={[Bh.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,qB(e)])),[Bh.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"]),[Bh.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"]),[Bh.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"]),[Bh.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"]),[Bh.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"]),[Bh.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"]),[Bh.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"]),[Bh.GenerationLanguage.SWIFT]:new Set([])};var $CE=["go","ruby"];function iee({generationLanguage:e,keywords:t,smartCasing:r}){let i={generateName:(n,a)=>{let u=c=>({unsafeName:c,safeName:GCE({name:c,keywords:QCE({generationLanguage:e,keywords:t})})}),l=S_(n),d=qB(l),s=TZi(n),o=EZi(l);return r&&(!YCE(o)&&(e==null||$CE.includes(e))&&(l=o.map((c,b)=>{if(b>0){let g=Ltu(c);if(g!=null)return g;if(Utu(c))return c.toUpperCase()}return c}).join(""),d=qB(o.map((c,b)=>{let g=Ltu(c);return g??(Utu(c)?c.toUpperCase():b===0?qB(c):c)}).join(""))),s=n.split(" ").map(c=>c.split(/(\d+)/).map(TZi).join("")).join("_")),{originalName:n,camelCase:u(a?.casingOverrides?.camel??l),snakeCase:u(a?.casingOverrides?.snake??s),screamingSnakeCase:u(a?.casingOverrides?.["screaming-snake"]??s.toUpperCase()),pascalCase:u(a?.casingOverrides?.pascal??d)}},generateNameAndWireValue:({name:n,wireValue:a,opts:u})=>({name:i.generateName(n,u),wireValue:a})};return i}function GCE({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":KCE(e)?"_"+e:e}function QCE({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return Gg_[e]}var JCE=/^[0-9]/;function KCE(e){return JCE.test(e)}function YCE(e){return e.some((t,r)=>{if(r===0)return!1;let i=e[r-1];if(i==null)return!1;let n=Ltu(i)!=null||Utu(i),a=Ltu(t)!=null||Utu(t);return n&&a})}function Ltu(e){return ZCE.get(e.toUpperCase())}function Utu(e){return XCE.has(e.toUpperCase())}var XCE=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"]),ZCE=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]);function Yjc({rawApiFileSchema:e,casingsGenerator:t}){if(e.auth==null)return{docs:void 0,requirement:toe.All,schemes:[]};let r=typeof e.auth!="string"?e.auth.docs:void 0;return Ren(e.auth,{single:i=>{let n=Qg_({reference:i,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t});return{docs:r,requirement:toe.All,schemes:[n]}},any:({any:i})=>({docs:r,requirement:toe.Any,schemes:i.map(n=>Qg_({reference:n,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t}))})})}function Qg_({reference:e,authSchemeDeclarations:t,casingsGenerator:r}){let i=(a,u)=>{let l=t?.[a];if(l==null)throw new Error("Unknown auth scheme: "+a);return mNa(l,{header:d=>BA.header({docs:u,name:r.generateNameAndWireValue({name:d.name??a,wireValue:d.header}),valueType:Xc.primitive({v1:ny.String,v2:Td.string({default:void 0,validation:void 0})}),prefix:d.prefix,headerEnvVar:d.env}),basic:d=>Jg_({casingsGenerator:r,docs:u,rawScheme:d}),tokenBearer:d=>Vtu({casingsGenerator:r,docs:u,rawScheme:d}),inferredBearer(d){return Vtu({casingsGenerator:r,docs:u,rawScheme:void 0})},oauth:d=>Vtu({casingsGenerator:r,docs:u,rawScheme:void 0})})},n=typeof e=="string"?e:e.scheme;switch(n){case"bearer":case"oauth":return Vtu({casingsGenerator:r,docs:void 0,rawScheme:void 0});case"basic":return Jg_({casingsGenerator:r,docs:void 0,rawScheme:void 0});default:return i(n,typeof e!="string"?e.docs:void 0)}}function Vtu({casingsGenerator:e,docs:t,rawScheme:r}){return BA.bearer({docs:t,token:e.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function Jg_({casingsGenerator:e,docs:t,rawScheme:r}){return BA.basic({docs:t,username:e.generateName(r?.username?.name??"username"),usernameEnvVar:r?.username?.env,password:e.generateName(r?.password?.name??"password"),passwordEnvVar:r?.password?.env})}function WF(e){let t=eBE(e),{value:r,done:i}=Xjc(t,"{");return i?{head:r,parts:[]}:{head:r,parts:[...kCE(t)]}}function*kCE(e){let t;do{let{value:r}=Xjc(e,"}"),i=Xjc(e,"{");t=i.done,yield{pathParameter:r,tail:i.value}}while(!t)}function*eBE(e){for(let t of e)yield t}function Xjc(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 Y8a({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:Krr(i,{singleBaseUrl:()=>$R.singleBaseUrl(tBE({environments:t,casingsGenerator:r})),multipleBaseUrls:n=>$R.multipleBaseUrls(rBE({baseUrls:Object.keys(n.urls),environments:t,casingsGenerator:r}))})},audiences:{...Object.fromEntries(Object.entries(t).map(([n,a])=>[n,Krr(a,{singleBaseUrl:u=>[...typeof u=="string"?[]:u.audiences??[]],multipleBaseUrls:u=>[...u.audiences??[]]})]))}}}function tBE({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,i])=>Krr(i,{singleBaseUrl:n=>({docs:typeof n=="string"?void 0:n.docs,id:r,name:t.generateName(r),url:Kg_(typeof n=="string"?n:n.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function rBE({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(i=>({id:i,name:r.generateName(i)})),environments:Object.entries(t).map(([i,n])=>Krr(n,{multipleBaseUrls:a=>({docs:a.docs,id:i,name:r.generateName(i),urls:_d(a.urls,u=>Kg_(u))}),singleBaseUrl:()=>{throw new Error(`Environment ${i} does not have multiple base URLs`)}}))}}function Kg_(e){return e.endsWith("/")?e.slice(0,-1):e}function X8a(e){let t=2166136261;function r(n,a){if(typeof n=="object"&&n!=null){if(a>64){i("[MaxDepthExceeded]");return}if(Array.isArray(n)){i("[");for(let u=0;u<n.length;u++)u>0&&i(","),r(n[u],a+1);i("]")}else i("{"),Object.keys(n).sort().forEach((l,d)=>{d>0&&i(","),i(l),i(":"),r(n[l],a+1)}),i("}")}else i(String(n))}function i(n){for(let a=0;a<n.length;a++){let u=n.charCodeAt(a);t^=u,t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24),t>>>=0}}return r(e,0),t.toString(16)}function lor({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 Yg_({fieldName:e,containerType:t,maxDepth:r,currentDepth:i,typeDeclarations:n,skipOptionalProperties:a}){if(i>=r)return dor({containerType:t});switch(t.type){case"list":{let u=OT({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?dor({containerType:t}):{type:"success",example:Wm.list({list:[u.example,u.example],itemType:t.list}),jsonExample:[u.jsonExample,u.jsonExample]}}case"literal":return{type:"success",example:Wm.literal({literal:t.literal._visit({boolean:u=>Vd.boolean(u),string:u=>Vd.string({original:u}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:t.literal._visit({boolean:u=>u,string:u=>u,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":{if(a)return dor({containerType:t});let u=OT({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?dor({containerType:t}):{type:"success",example:Wm.optional({optional:u.example,valueType:t.optional}),jsonExample:u.jsonExample}}case"nullable":{if(a)return dor({containerType:t});let u=OT({fieldName:e,typeReference:t.nullable,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?dor({containerType:t}):{type:"success",example:Wm.nullable({nullable:u.example,valueType:t.nullable}),jsonExample:u.jsonExample}}case"set":{let u=OT({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?dor({containerType:t}):{type:"success",example:Wm.set({set:[u.example],itemType:t.set}),jsonExample:[u.jsonExample]}}case"map":{let u=OT({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a}),l=OT({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"||l.type==="failure"?dor({containerType:t}):{type:"success",example:Wm.map({map:[{key:u.example,value:l.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[u.jsonExample]:l.jsonExample}}}default:So(t)}}function dor({containerType:e}){switch(e.type){case"list":return{type:"success",example:Wm.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:Wm.literal({literal:e.literal._visit({boolean:t=>Vd.boolean(t),string:t=>Vd.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:Wm.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"nullable":return{type:"success",example:Wm.nullable({nullable:void 0,valueType:e.nullable}),jsonExample:void 0};case"set":return{type:"success",example:Wm.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:Wm.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:So(e)}}function Zg_({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":return uBE({fieldName:e,default_:iBE(t.v2),validation:nBE(t.v2)});case"BASE_64":return{type:"success",example:Vd.base64(Ch.BASE64),jsonExample:Ch.BASE64};case"BOOLEAN":return{type:"success",example:Vd.boolean(Ch.BOOLEAN),jsonExample:Ch.BOOLEAN};case"DATE":return{type:"success",example:Vd.date(Ch.DATE),jsonExample:Ch.DATE};case"DATE_TIME":return{type:"success",example:Vd.datetime({datetime:new Date(Ch.DATE_TIME),raw:Ch.DATE_TIME}),jsonExample:Ch.DATE_TIME};case"DOUBLE":return sBE({fieldName:e,validation:aBE(t.v2)});case"FLOAT":return{type:"success",example:Vd.float(Ch.FLOAT),jsonExample:Ch.FLOAT};case"INTEGER":return cBE({fieldName:e,validation:oBE(t.v2)});case"UINT_64":return{type:"success",example:Vd.uint64(Ch.INT64),jsonExample:Ch.INT64};case"UINT":return{type:"success",example:Vd.uint(Ch.UINT),jsonExample:Ch.UINT};case"BIG_INTEGER":return{type:"success",example:Vd.bigInteger(Ch.INT64.toString()),jsonExample:`${Ch.INT64}`};case"LONG":return{type:"success",example:Vd.long(Ch.INT64),jsonExample:Ch.INT64};case"UUID":return{type:"success",example:Vd.uuid(Ch.UUID),jsonExample:Ch.UUID};default:So(t.v1)}}function iBE(e){if(e?.type==="string")return e.default}function nBE(e){if(e?.type==="string")return e.validation}function aBE(e){if(e?.type==="double")return e.validation}function oBE(e){if(e?.type==="integer")return e.validation}function Xg_(e){if(e<=Ch.SAMPLE_STRINGS.length){let t=Ch.SAMPLE_STRINGS[e-1];if(t)return t;throw new Error(`Unexpected undefined value in SAMPLE_STRINGS at index ${e-1}`)}return Ch.SAMPLE_STRINGS[Ch.SAMPLE_STRINGS.length-1]+".".repeat(e-Ch.SAMPLE_STRINGS.length)}function uBE({fieldName:e,default_:t,validation:r}){if(t!=null)return{type:"success",example:Vd.string({original:t}),jsonExample:t};if(r){let n=r.minLength,a=r.maxLength;if(n){let u=Xg_(n);return{type:"success",example:Vd.string({original:u}),jsonExample:u}}else if(a!=null&&a<10){let u=Xg_(a);return{type:"success",example:Vd.string({original:u}),jsonExample:u}}}let i=e??Ch.STRING;return{type:"success",example:Vd.string({original:i}),jsonExample:i}}function sBE({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:Vd.double(r),jsonExample:r};if(i)return{type:"success",example:Vd.double(i),jsonExample:i}}return{type:"success",example:Vd.double(Ch.DOUBLE),jsonExample:Ch.DOUBLE}}function cBE({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:Vd.integer(r),jsonExample:r};if(i)return{type:"success",example:Vd.integer(i),jsonExample:i}}return{type:"success",example:Vd.integer(Ch.INT),jsonExample:Ch.INT}}function oJn({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let u=OT({fieldName:e,typeDeclarations:t,typeReference:r.shape.aliasOf,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure")return u;let{example:l,jsonExample:d}=u;return{type:"success",example:l1.alias({value:l}),jsonExample:d}}case"enum":{let u=r.shape.values[0];return u==null?{type:"failure",message:"No enum values present"}:{type:"success",example:l1.enum({value:u.name}),jsonExample:u.name.wireValue}}case"object":{let u={},l=[];if((r.shape.extendedProperties==null||r.shape.extendedProperties.length===0)&&r.shape.extends!=null)for(let c of r.shape.extends){let b=t[c.typeId];if(b==null)continue;let g=oJn({fieldName:e,typeDeclaration:b,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});g!=null&&g.type==="success"&&g.example.type==="object"&&(Object.assign(u,g.jsonExample),l.push(...g.example.properties))}let d=lBE({fieldName:e,typeDeclaration:r,objectTypeDeclaration:r.shape,typeDeclarations:t,currentDepth:n,maxDepth:i,skipOptionalProperties:a});if(d.type==="failure")return d;let{example:s,jsonExample:o}=d;return{type:"success",example:l1.object({properties:[...l,...s.properties]}),jsonExample:Object.assign({},u,o)}}case"undiscriminatedUnion":{let u=0;for(let l of r.shape.members){let d=OT({fieldName:e,typeReference:l.type,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});if(d.type==="failure"){++u;continue}let{example:s,jsonExample:o}=d;return{type:"success",example:l1.undiscriminatedUnion({index:u,singleUnionType:s}),jsonExample:o}}break}case"union":{let u=r.shape.discriminant,l={};if(r.shape.baseProperties!=null)for(let d of r.shape.baseProperties){let s=OT({fieldName:d.name.wireValue,typeReference:d.valueType,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});s.type==="success"&&(l[d.name.wireValue]=s.jsonExample)}for(let d of r.shape.types){let s=d.shape._visit({noProperties:()=>({type:"success",example:l1.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:J3.noProperties()}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,...l}}),samePropertiesAsObject:o=>{let c=t[o.typeId];if(c==null)return{type:"failure",message:`Failed to find type declaration with id ${o.typeId}`};let b=oJn({currentDepth:n,maxDepth:i,fieldName:e,typeDeclaration:c,typeDeclarations:t,skipOptionalProperties:a});if(b==null)return{type:"failure",message:"Failed to generate example for type reference"};if(b.type==="failure")return b;let{example:g,jsonExample:O}=b;return{type:"success",example:l1.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:J3.samePropertiesAsObject({typeId:c.name.typeId,object:g.type==="object"?g:{properties:[]}})}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,...typeof O=="object"?O:{},...l}}},singleProperty:o=>{let c=OT({currentDepth:n+1,maxDepth:i,fieldName:e,typeReference:o.type,typeDeclarations:t,skipOptionalProperties:a});if(c.type==="failure")return c;let{example:b,jsonExample:g}=c;return{type:"success",example:l1.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:J3.singleProperty(b)}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,[o.name.wireValue]:g,...l}}},_other:()=>{throw new Error("Encountered unknown union type")}});if(s.type!=="failure")return s}}}return{type:"failure",message:"Failed to generate example for type reference"}}function lBE({fieldName:e,typeDeclaration:t,objectTypeDeclaration:r,typeDeclarations:i,maxDepth:n,currentDepth:a,skipOptionalProperties:u}){let l={},d=[];for(let s of[...r.properties??[],...r.extendedProperties??[]]){let o=OT({fieldName:s.name.wireValue,typeReference:s.valueType,typeDeclarations:i,currentDepth:a+1,maxDepth:n,skipOptionalProperties:u});if(o.type==="failure"&&!lor({typeDeclarations:i,typeReference:s.valueType}))return{type:"failure",message:`Failed to generate required property ${s.name.wireValue} b/c ${o.message}`};if(o.type==="failure")continue;let{example:c,jsonExample:b}=o;d.push({name:s.name,originalTypeDeclaration:t.name,value:c}),l[s.name.wireValue]=b}return{type:"success",example:l1.object({properties:d}),jsonExample:l}}function OT({fieldName:e,typeReference:t,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){if(n>i)return{type:"failure",message:"Exceeded max depth"};switch(t.type){case"named":{let u=r[t.typeId];if(u==null)return{type:"failure",message:`Failed to find type declaration with id ${t.typeId}`};let l=oJn({fieldName:e,typeDeclaration:u,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(l==null)return{type:"failure",message:"Failed to generate example for type declaration"};if(l.type==="failure")return l;let{example:d,jsonExample:s}=l;return{type:"success",example:{jsonExample:s,shape:ay.named({shape:d,typeName:u.name})},jsonExample:s}}case"container":{let u=Yg_({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure"){let{example:s,jsonExample:o}=dor({containerType:t.container});return{type:"success",example:{jsonExample:o,shape:ay.container(s)},jsonExample:o}}let{example:l,jsonExample:d}=u;return{type:"success",example:{jsonExample:d,shape:ay.container(l)},jsonExample:d}}case"primitive":{let{jsonExample:u,example:l}=Zg_({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:u,shape:ay.primitive(l)},jsonExample:u}}case"unknown":{let u={key:"value"};return{type:"success",example:{jsonExample:u,shape:ay.unknown(u)},jsonExample:u}}}}function snn(e,t){let r=[];for(let i of e){let n=OT({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 uJn(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&lor({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=OT({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 Wtu(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&lor({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=OT({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?q8.exploded():q8.single(),value:n.example})}return{type:"success",example:r,jsonExample:void 0}}var Zjc=Xc.primitive({v1:ny.String,v2:Td.string({default:void 0,validation:void 0})});function Z8a({ir:e,endpoint:t,service:r,typeDeclarations:i,skipOptionalRequestProperties:n,generationResponse:a}){let u={name:void 0,endpointHeaders:[],endpointPathParameters:[],queryParameters:[],servicePathParameters:[],serviceHeaders:[],rootPathParameters:[],request:void 0,response:gC.ok(NB.body(void 0)),docs:void 0},l=snn(t.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(l.type==="failure")return l;u.endpointPathParameters=l.example;let d=snn(r.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(d.type==="failure")return d;u.servicePathParameters=d.example;let s=snn(e.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(s.type==="failure")return s;u.rootPathParameters=s.example;let o=Wtu(t.queryParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:10});if(o.type==="failure")return o;u.queryParameters=o.example;let c=uJn(t.headers,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(c.type==="failure")return c;u.endpointHeaders=c.example;let b=uJn(r.headers,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(b.type==="failure")return b;if(u.serviceHeaders=b.example,t.requestBody!=null)switch(t.requestBody.type){case"bytes":return{type:"failure",message:"Bytes request unsupported"};case"fileUpload":return{type:"failure",message:"File upload unsupported"};case"inlinedRequestBody":{let g={},O=[];if(t.requestBody.extends!=null)for(let m of t.requestBody.extends){let w=i[m.typeId];if(w==null)throw new Error(`Failed to find extended type declaration with id ${m.typeId}`);let E=oJn({typeDeclaration:w,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});E!=null&&E.type==="success"&&Object.assign(g,E.jsonExample)}for(let m of[...t.requestBody.properties??[],...t.requestBody.extendedProperties??[]]){let w=OT({fieldName:m.name.wireValue,typeReference:m.valueType,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});if(w.type==="failure"&&!lor({typeDeclarations:i,typeReference:m.valueType}))return{type:"failure",message:`Failed to generate required property ${m.name.wireValue} b/c ${w.message}`};if(w.type==="failure")continue;let{example:E,jsonExample:q}=w;O.push({name:m.name,originalTypeDeclaration:void 0,value:E}),g[m.name.wireValue]=q}u.request=MJ.inlinedRequestBody({jsonExample:g,properties:O});break}case"reference":{let g=OT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:n});if(g.type==="failure")return g;let{example:O}=g;u.request=MJ.reference(O);break}default:So(t.requestBody)}if(a.type==="success"&&t.response?.body!=null)switch(t.response.body.type){case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":{let g=OT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.responseBodyType,skipOptionalProperties:!1});if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=gC.ok(NB.body({...O,jsonExample:m}));break}case"streamParameter":{let g;switch(t.response.body.nonStreamResponse.type){case"bytes":return{type:"failure",message:"Bytes unsupported"};case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":g=OT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.nonStreamResponse.value.responseBodyType,skipOptionalProperties:!1});break;case"text":g=OT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:Zjc,skipOptionalProperties:!1});break;default:So(t.response.body.nonStreamResponse)}if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=gC.ok(NB.body({...O,jsonExample:m}));break}case"streaming":{let g;switch(t.response.body.value.type){case"sse":{if(g=OT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=gC.ok(NB.sse([{data:{...O,jsonExample:m},event:""}]));break}case"json":{if(g=OT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=gC.ok(NB.stream([{...O,jsonExample:m}]));break}case"text":{if(g=OT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:Zjc,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=gC.ok(NB.stream([{...O,jsonExample:m}]));break}default:So(t.response.body.value)}break}case"text":{let g=OT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:Zjc,skipOptionalProperties:!1});if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=gC.ok(NB.body({...O,jsonExample:m}));break}case"bytes":return{type:"failure",message:"Bytes unsupported"};default:So(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)u.response=gC.error({body:void 0,error:a.declaration.name});else{let g=OT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:a.declaration.type,skipOptionalProperties:n});if(g.type==="failure")return g;let{example:O}=g;u.response=gC.error({body:O,error:a.declaration.name})}try{return{type:"success",example:{id:X8a(u),url:fBE(t,u),...u},jsonExample:void 0}}catch(g){return{type:"failure",message:`Parse failure with exceptions ${g}`}}}function fBE(e,t){let r={};[...t.rootPathParameters,...t.servicePathParameters,...t.endpointPathParameters].forEach(n=>{let a=n.value.jsonExample,u=typeof a=="string"?a:JSON.stringify(a);r[n.name.originalName]=u});let i=e.fullPath.head+e.fullPath.parts.map(n=>encodeURIComponent(`${r[n.pathParameter]}`)+n.tail).join("");return i.startsWith("/")||i===""?i:`/${i}`}function kjc({ir:e,channel:t,typeDeclarations:r,skipOptionalRequestProperties:i}){let n={name:void 0,pathParameters:[],headers:[],queryParameters:[],messages:[],docs:void 0},a=snn(t.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(a.type==="failure")return a;n.pathParameters.push(...a.example);let u=snn(e.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(u.type==="failure")return u;n.pathParameters.push(...u.example);let l=Wtu(t.queryParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:10});if(l.type==="failure")return l;n.queryParameters=l.example;let d=uJn(t.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(d.type==="failure")return d;n.headers.push(...d.example);let s=uJn(e.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(s.type==="failure")return s;n.headers.push(...s.example);let c=t.messages.filter(O=>O.origin==="client")[0];if(c!=null){let O=kg_({message:c,typeDeclarations:r,skipOptionalRequestProperties:i});O!=null&&n.messages.push({type:c.type,body:O})}let g=t.messages.filter(O=>O.origin==="server")[0];if(g!=null){let O=kg_({message:g,typeDeclarations:r,skipOptionalRequestProperties:i});O!=null&&n.messages.push({type:g.type,body:O})}return{type:"success",example:{...n,url:dBE(t,n)},jsonExample:void 0}}function kg_({message:e,typeDeclarations:t,skipOptionalRequestProperties:r}){if(e.body.type==="inlinedBody")return;let i=OT({currentDepth:0,maxDepth:10,typeDeclarations:t,typeReference:e.body.bodyType,skipOptionalProperties:r});if(i.type==="success")return hAe.reference(i.example)}function dBE(e,t){let r={};[...t.pathParameters].forEach(n=>{let a=n.value.jsonExample,u=typeof a=="string"?a:JSON.stringify(a);r[n.name.originalName]=u});let i=e.path.head+e.path.parts.map(n=>encodeURIComponent(`${r[n.pathParameter]}`)+n.tail).join("");return i.startsWith("/")||i===""?i:`/${i}`}function sJn(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{},i=Object.values(t)[0],n=Object.values(r)[0];return{userExample:i,autoExample:n}}function bNi(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{};return{userExamples:t,autoExamples:r}}function eO_({ir:e,endpoint:t,skipOptionalRequestProperties:r}){let i=e.types,n={pathParameters:{},queryParameters:{},headers:{}};for(let u of t.pathParameters){let{userExample:l,autoExample:d}=sJn(u.v2Examples);l!==void 0?n.pathParameters[u.name.originalName]=l:d!==void 0&&(n.pathParameters[u.name.originalName]=d)}for(let u of t.queryParameters){let{userExample:l,autoExample:d}=sJn(u.v2Examples);if(l!==void 0)n.queryParameters[u.name.name.originalName]=l;else if(d!==void 0){if(r&&lor({typeReference:u.valueType,typeDeclarations:i}))continue;n.queryParameters[u.name.name.originalName]=d}}let a=[...t.headers,...e.headers,...e.idempotencyHeaders];for(let u of a){let{userExample:l,autoExample:d}=sJn(u.v2Examples);if(l!==void 0)n.headers[u.name.wireValue]=l;else if(d!==void 0){if(r&&lor({typeReference:u.valueType,typeDeclarations:i}))continue;n.headers[u.name.wireValue]=d}}return n}function tO_({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let{pathParameters:i,queryParameters:n,headers:a}=eO_({endpoint:e,ir:t,skipOptionalRequestProperties:r}),u={},l={},d={endpoint:{method:e.method,path:pBE(e)},baseUrl:void 0,environment:e.baseUrl,auth:void 0,pathParameters:i,queryParameters:n,headers:a,requestBody:void 0,docs:void 0};if(e.requestBody!=null)switch(e.requestBody.type){case"bytes":break;case"fileUpload":{let{userExamples:s,autoExamples:o}=bNi(e.requestBody.v2Examples);for(let[c,b]of Object.entries(s))u[c]={...d,requestBody:b};for(let[c,b]of Object.entries(o))l[c]={...d,requestBody:b};break}case"inlinedRequestBody":{let{userExamples:s,autoExamples:o}=bNi(e.requestBody.v2Examples);for(let[c,b]of Object.entries(s))u[c]={...d,requestBody:b};for(let[c,b]of Object.entries(o))l[c]={...d,requestBody:b};break}case"reference":{let{userExamples:s,autoExamples:o}=bNi(e.requestBody.v2Examples);for(let[c,b]of Object.entries(s))u[c]={...d,requestBody:b};for(let[c,b]of Object.entries(o))l[c]={...d,requestBody:b};break}default:So(e.requestBody)}return{userRequestExamples:u,autoRequestExamples:l,baseExample:d}}function pBE(e){let t={};[...e.pathParameters,...e.allPathParameters].forEach(i=>{let{userExample:n,autoExample:a}=sJn(i.v2Examples),u=n??a,l;u==null?l=i.name.originalName:l=typeof u=="string"?u:JSON.stringify(u),t[i.name.originalName]=l});let r=e.fullPath.head+e.fullPath.parts.map(i=>encodeURIComponent(`${t[i.pathParameter]}`)+i.tail).join("");return r.startsWith("/")||r===""?r:`/${r}`}function Htu({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:m4.json(k8a(null))}}:{userResponseExamples:{},autoResponseExamples:{},baseExample:a};switch(r.body.type){case"bytes":break;case"fileDownload":break;case"text":{let u=r.body,{userExamples:l,autoExamples:d}=bNi(u.v2Examples);for(let[s,o]of Object.entries(l)){let c=e.source?.type==="openrpc"?k8a(o):o;i[s]={...a,body:m4.json(c)}}for(let[s,o]of Object.entries(d)){let c=e.source?.type==="openrpc"?k8a(o):o;n[s]={...a,body:m4.json(c)}}break}case"json":{let u=r.body.value;if(u.type==="response"){let{userExamples:l,autoExamples:d}=bNi(u.v2Examples);for(let[s,o]of Object.entries(l)){let c=e.source?.type==="openrpc"?k8a(o):o;i[s]={...a,body:m4.json(c)}}for(let[s,o]of Object.entries(d)){let c=e.source?.type==="openrpc"?k8a(o):o;n[s]={...a,body:m4.json(c)}}}break}case"streaming":{let u=r.body.value;if(u.type==="json"){let{userExamples:l,autoExamples:d}=bNi(u.v2Examples);for(let[s,o]of Object.entries(l))i[s]={...a,body:m4.stream([o])};for(let[s,o]of Object.entries(d))n[s]={...a,body:m4.stream([o])}}break}case"streamParameter":break;default:So(r.body)}return{userResponseExamples:i,autoResponseExamples:n,baseExample:a}}function k8a(e,t=1){return{id:t,jsonrpc:"2.0",result:e}}var cJn=(e,t,r)=>{let i;return e===t?i=`${e}`:i=`${e}_${t}`,r&&(i=`${i}_${r}`),i},_BE=({exampleStore:e,key:t,example:r})=>e.has(t)?!1:(e.set(t,r),!0);function $tu({key:e,displayName:t,request:r,response:i,exampleStore:n,userOrAutoStore:a}){if(!n.has(e)){let u={displayName:t,request:r,response:i,codeSamples:void 0};return a[e]=u,_BE({exampleStore:n,key:e,example:u}),!0}return!1}function rO_({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let i={},n={},a=new Map,{userRequestExamples:u,autoRequestExamples:l,baseExample:d}=tO_({endpoint:e,ir:t,skipOptionalRequestProperties:r}),s=Object.keys(u)[0],o=Object.values(u)[0],c=Object.keys(l)[0],b=Object.values(l)[0],g=hBE({endpoint:e,userRequestExamples:u,baseRequestExample:d,firstUserRequestName:s,firstUserRequestExample:o,firstAutoRequestName:c,firstAutoRequestExample:b,userResults:i,autoResults:n,exampleStore:a});if(yBE({endpoint:e,userRequestExamples:u,requestExamplesUsed:g,userResults:i,exampleStore:a}),Object.keys(i).length===0&&Object.keys(n).length===0){let{baseExample:O}=Htu({endpoint:e}),m=cJn(c??"base","base",void 0);$tu({key:m,displayName:c??"base",request:b??d,response:O,exampleStore:a,userOrAutoStore:n})}return{userFullExamples:i,autoFullExamples:n}}function hBE({endpoint:e,userRequestExamples:t,baseRequestExample:r,firstUserRequestName:i,firstUserRequestExample:n,firstAutoRequestName:a,firstAutoRequestExample:u,userResults:l,autoResults:d,exampleStore:s}){let o=e.v2Responses?.responses??[e.response],c=new Set;for(let b of o){let g=!1,{userResponseExamples:O,autoResponseExamples:m,baseExample:w}=Htu({endpoint:e,responseObject:b}),E=Object.keys(m)[0],q=Object.values(m)[0];for(let[M,D]of Object.entries(O)){let C,R;t[M]?(R=t[M],c.add(M),C=cJn(M,M,b?.statusCode)):u&&a?(R=u,C=cJn(a,M,b?.statusCode)):(R=r,C=cJn("base",M,b?.statusCode)),$tu({key:C,displayName:M,request:R,response:D,exampleStore:s,userOrAutoStore:l})&&(g=!0)}if(!g){let M=S_(`${e.name.originalName}_example`);i&&n&&c.add(i);let D=cJn(i??a??"base",E??"base",b?.statusCode);$tu({key:D,displayName:i??a??M,request:n??u??r,response:q??w,exampleStore:s,userOrAutoStore:d})&&(g=!0)}}return c}function yBE({endpoint:e,userRequestExamples:t,requestExamplesUsed:r,userResults:i,exampleStore:n}){let{userResponseExamples:a,autoResponseExamples:u,baseExample:l}=Htu({endpoint:e}),d=Object.values(a)[0],s=Object.keys(a)[0],o=Object.keys(u)[0],c=Object.values(u)[0],b=Object.entries(t).filter(([g])=>!r.has(g));for(let[g,O]of b){let m=cJn(g,s??o??"base",d?d.statusCode:c?c.statusCode:l.statusCode);$tu({key:m,displayName:g,request:O,response:d??c??l,exampleStore:n,userOrAutoStore:i})}}function e5a({ir:e,exampleGeneration:t}){for(let[r,i]of Object.entries(e.services))for(let n of i.endpoints){if(n.userSpecifiedExamples.length>0&&t?.skipAutogenerationIfManualExamplesExist===!0)continue;let a=Z8a({ir:e,service:i,endpoint:n,typeDeclarations:e.types,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples,generationResponse:{type:"success"}});if(a.type==="failure")continue;let{example:u}=a;n.autogeneratedExamples=[{example:u}]}for(let[r,i]of Object.entries(e.websocketChannels??{})){if(i.examples.length>0&&t?.skipAutogenerationIfManualExamplesExist===!0)continue;let n=kjc({ir:e,channel:i,typeDeclarations:e.types,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples});if(n.type==="failure")continue;let{example:a}=n;i.examples=[...i.examples,a]}return e}function ewc({ir:e,exampleGeneration:t}){for(let[r,i]of Object.entries(e.services))for(let n of i.endpoints){n.v2Examples==null&&(n.v2Examples={userSpecifiedExamples:{},autogeneratedExamples:{}});let{userFullExamples:a,autoFullExamples:u}=rO_({endpoint:n,ir:e,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples});if(Object.keys(n.v2Examples.userSpecifiedExamples).length>0){if(Object.values(n.v2Examples.userSpecifiedExamples).some(d=>d.request!=null||d.response!=null))continue;let l=Object.values(n.v2Examples.userSpecifiedExamples).filter(d=>d!=null).flatMap(d=>d.codeSamples??[]);for(let[d,s]of Object.entries(u))u[d]={...s,codeSamples:l};for(let[d,s]of Object.entries(a))a[d]={...s,codeSamples:l}}n.v2Examples.autogeneratedExamples=u,n.v2Examples.userSpecifiedExamples=a}for(let[r,i]of Object.entries(e.websocketChannels??{})){if(i.examples.length>0&&t?.skipAutogenerationIfManualExamplesExist===!0)continue;let n=kjc({ir:e,channel:i,typeDeclarations:e.types,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples});if(n.type==="failure")continue;let{example:a}=n;i.examples=[...i.examples,a]}return e}function nO_({filteredIr:e,singleUnionTypeProperties:t}){return t._visit({samePropertiesAsObject:r=>{let i=e.hasTypeId(r.typeId)?{...r,object:{properties:r.object.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:tN({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)}}:void 0;return i!==void 0?J3.samePropertiesAsObject(i):void 0},singleProperty:r=>{let i=tN({filteredIr:e,exampleTypeReference:r});return i!==void 0?J3.singleProperty(i):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function tN({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:i=>({...t,shape:ay.container(Wm.list({...i,list:i.list.map(n=>tN({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),set:i=>({...t,shape:ay.container(Wm.set({...i,set:i.set.map(n=>tN({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),optional:i=>{let n=i.optional!=null?tN({filteredIr:e,exampleTypeReference:i.optional}):void 0;return n!=null?{...t,shape:ay.container(Wm.optional({optional:n,valueType:i.valueType}))}:void 0},nullable:i=>{let n=i.nullable!=null?tN({filteredIr:e,exampleTypeReference:i.nullable}):void 0;return n!=null?{...t,shape:ay.container(Wm.nullable({nullable:n,valueType:i.valueType}))}:void 0},map:i=>({...t,shape:ay.container(Wm.map({...i,map:i.map.map(n=>{let a=tN({filteredIr:e,exampleTypeReference:n.key}),u=tN({filteredIr:e,exampleTypeReference:n.value});return a!==void 0&&u!==void 0?{key:a,value:u}:void 0}).filter(n=>n!==void 0)}))}),literal:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}}),named:r=>e.hasTypeId(r.typeName.typeId)?r.shape._visit({alias:i=>{let n=tN({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...t,shape:ay.named({...r,shape:l1.alias({...i,value:n})})}:void 0},enum:i=>({...t,shape:ay.named({...r,shape:l1.enum(i)})}),object:i=>({...t,shape:ay.named({...r,shape:l1.object({...i,properties:i.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:tN({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})})}),union:i=>{let n=nO_({filteredIr:e,singleUnionTypeProperties:i.singleUnionType.shape});return n!==void 0?{...t,shape:ay.named({...r,shape:l1.union({...i,singleUnionType:{...i.singleUnionType,shape:n}})})}:void 0},undiscriminatedUnion:i=>{let n=tN({filteredIr:e,exampleTypeReference:i.singleUnionType});return n!==void 0?{...t,shape:ay.named({...r,shape:l1.undiscriminatedUnion({...i,singleUnionType:n})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function twc({filteredIr:e,pathParameters:t}){return t.map(r=>{let i=tN({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function vBE({filteredIr:e,queryParameters:t}){return t.map(r=>{let i=tN({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function iO_({filteredIr:e,headers:t}){return t.map(r=>{let i=tN({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function bBE({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=tN({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...i,value:n}:void 0}).filter(i=>i!==void 0)}),reference:r=>{let i=tN({filteredIr:e,exampleTypeReference:r});return i!==void 0?MJ.reference(i):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function gBE({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:i=>gC.ok(NB.body(i!=null?tN({filteredIr:e,exampleTypeReference:i}):void 0)),stream:i=>gC.ok(NB.stream(i.map(n=>tN({filteredIr:e,exampleTypeReference:n})).filter(iv))),sse:i=>gC.ok(NB.sse(i.map(({event:n,data:a})=>{let u=tN({filteredIr:e,exampleTypeReference:a});return u!==void 0?{event:n,data:u}:void 0}).filter(iv))),_other:({type:i})=>{throw new Error(`Received unknown type for OK example: ${i}`)}}),error:({error:r,body:i})=>gC.error({error:r,body:i!=null?tN({filteredIr:e,exampleTypeReference:i}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function rwc({filteredIr:e,example:t}){return{...t,rootPathParameters:twc({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:twc({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:twc({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:iO_({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:iO_({filteredIr:e,headers:t.endpointHeaders}),queryParameters:vBE({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?bBE({filteredIr:e,requestBody:t.request}):void 0,response:gBE({filteredIr:e,response:t.response})}}function aO_({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let i=tN({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...t,shape:l1.alias({...r,value:i})}:void 0},enum:()=>t,object:r=>({...t,shape:l1.object({...r,properties:r.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:tN({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})}),union:r=>{let i=nO_({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return i!==void 0?{...t,shape:l1.union({...r,singleUnionType:{...r.singleUnionType,shape:i}})}:void 0},undiscriminatedUnion:r=>{let i=tN({filteredIr:e,exampleTypeReference:r.singleUnionType});return i!==void 0?{...t,shape:l1.undiscriminatedUnion({...r,singleUnionType:i})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function iwc(e,t){if(t==null)return e;let r=qZi(e.types,l=>t.hasType(l)),i=Object.fromEntries(Object.entries(r).map(([l,d])=>{let s=[];if(d.userProvidedExamples=d.userProvidedExamples.map(o=>aO_({filteredIr:t,exampleType:o})).filter(o=>o!==void 0),d.shape.type==="object"){for(let o of d.shape.properties)t.hasProperty(l,o.name.wireValue)&&s.push(o);return[l,{...d,shape:Vb.object({...d.shape,properties:s})}]}return[l,d]})),n=Object.fromEntries(Object.entries(e.webhookGroups).map(([l,d])=>{let s=d.filter(o=>t.hasWebhook(o)).map(o=>{let c=o.id;return o.payload.type==="inlinedPayload"&&c!=null&&(o.payload={...o.payload,properties:o.payload.properties.filter(b=>t.hasWebhookPayloadProperty(c,b.name.wireValue))}),o});return[l,s]})),a=e.websocketChannels!=null?Object.fromEntries(Object.entries(e.websocketChannels).filter(([l])=>t.hasChannel(l)).map(([l,d])=>[l,{...d}])):{},u=e.environments;if(u){switch(u.environments.type){case"singleBaseUrl":{u.environments.environments=u.environments.environments.filter(l=>t.hasEnvironmentId(l.id));break}case"multipleBaseUrls":{u.environments.environments=u.environments.environments.filter(l=>t.hasEnvironmentId(l.id));break}}u.defaultEnvironment&&(t.hasEnvironmentId(u.defaultEnvironment)||(u.defaultEnvironment=void 0))}return{...e,environments:u,types:i,errors:qZi(e.errors,l=>t.hasError(l)),services:_d(qZi(e.services,l=>t.hasService(l)),l=>({...l,endpoints:l.endpoints.filter(d=>t.hasEndpoint(d)).map(d=>(d.autogeneratedExamples=d.autogeneratedExamples.map(s=>({...s,example:rwc({filteredIr:t,example:s.example})})),d.userSpecifiedExamples=d.userSpecifiedExamples.map(s=>({...s,example:s.example!=null?rwc({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:OBE(e.serviceTypeReferenceInfo,t)}}function OBE(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 cnn(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 GAe(e){return e.allParts.map(t=>t.originalName).join("/")}var $m={generateTypeId:e=>`type_${GAe(e.fernFilepath)}:${e.name.originalName}`,generateErrorId:e=>`error_${GAe(e.fernFilepath)}:${e.name.originalName}`,generateServiceId:e=>`service_${GAe(e.fernFilepath)}`,generateServiceIdFromFernFilepath:e=>`service_${GAe(e)}`,generateSubpackageId:e=>`subpackage_${GAe(e)}`,generateEndpointId:(e,t)=>{let r=GAe(e.fernFilepath),i=t.name.originalName;return`endpoint_${r}.${i}`},generateWebhookGroupId:e=>`webhooks_${GAe(e)}`,generateWebhookId:(e,t)=>`webhooks_${GAe(e)}.${t}`,generateWebSocketChannelId:e=>`channel_${GAe(e)}`};function lJn(e){return e.type!=null}var Gtu=class{environments=new Set;types=new Set;properties;errors=new Set;services=new Set;endpoints=new Set;requestProperties;queryParameters;webhooks=new Set;webhookPayloadProperties;channels=new Set;subpackages=new Set;constructor({types:t,properties:r,errors:i,environments:n,services:a,endpoints:u,webhooks:l,subpackages:d,queryParameters:s,requestProperties:o,webhookPayloadProperties:c,channels:b}){this.environments=n,this.types=t,this.properties=r,this.errors=i,this.services=a,this.endpoints=u,this.webhooks=l,this.webhookPayloadProperties=c,this.subpackages=d,this.requestProperties=o,this.queryParameters=s,this.channels=b}hasTypeId(t){return this.types.has(t)}hasErrorId(t){return this.errors.has(t)}hasServiceId(t){return this.services.has(t)}hasSubpackageId(t){return this.subpackages.has(t)}hasType(t){let r=$m.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=$m.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=$m.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 lnn=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=mBE(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:i,descendantTypeIdsByAudience:n,propertiesByAudience:a}){let u=$m.generateTypeId(t),l={typeId:u,allDescendants:r,descendantsByAudience:n,referencedSubpackages:i};this.types[u]=l,this.typesReferencedByService[u]==null&&(this.typesReferencedByService[u]=new Set),this.properties[u]={typeId:u,propertiesByAudience:a}}markTypeForAudiences(t,r){let i=$m.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=$m.generateErrorId(t.name),i=new Set,n=new Set;t.type!=null&&ex(t.type,i,n);let a={errorId:r,referencedTypes:i,referencedSubpackages:n};this.errors[r]=a}addEndpoint(t,r,i){let n=$m.generateServiceId(t.name),a=r.id,u=new Set,l=new Set,d=new Set;for(let s of[...t.headers,...r.headers])ex(s.valueType,u,d);for(let s of[...t.pathParameters,...r.pathParameters])ex(s.valueType,u,d);for(let s of r.queryParameters)ex(s.valueType,u,d);if(i!=null&&i.request!=null&&typeof i.request!="string"){let s=cnn(i.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:s}}r.requestBody!=null&&IA._visit(r.requestBody,{inlinedRequestBody:s=>{for(let o of s.extends)Qtu(o,u,d);for(let o of s.properties)ex(o.valueType,u,d);if(i!=null&&typeof i.request=="object"&&typeof i.request.body=="object"&&RB(i.request.body)){let o=cnn(i.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:o}}},reference:({requestBodyType:s})=>{ex(s,u,d)},fileUpload:({properties:s})=>{for(let o of s)P4._visit(o,{file:$o,bodyProperty:({valueType:c})=>{ex(c,u,d)},_other:()=>{throw new Error("Unknown FileUploadRequestProperty: "+o.type)}})},bytes:()=>{},_other:()=>{throw new Error("Unknown HttpRequestBody: "+r.requestBody?.type)}}),r.response?.body!=null&&c1._visit(r.response.body,{fileDownload:$o,json:s=>{ex(s.responseBodyType,u,d)},streaming:s=>{s._visit({sse:o=>ex(o.payload,u,d),json:o=>ex(o.payload,u,d),text:$o,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.type)}})},streamParameter:s=>{s.streamResponse._visit({sse:o=>ex(o.payload,u,d),json:o=>ex(o.payload,u,d),text:$o,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.streamResponse.type)}}),s.nonStreamResponse.type==="json"&&ex(s.nonStreamResponse.value.responseBodyType,u,d)},text:$o,bytes:$o,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(s=>{l.add($m.generateErrorId(s.error)),d.add(s.error.fernFilepath)}),this.endpoints[a]={endpointId:a,serviceId:n,referencedTypes:u,referencedErrors:l,referencedSubpackages:d}}markEndpointForAudience(t,r,i){if(this.hasAudience(i)){let n=$m.generateServiceId(t);this.servicesNeededForAudience.add(n),r.forEach(a=>{let u=a.id;this.endpointsNeededForAudience.add(u),this.endpoints[u]?.referencedSubpackages.forEach(l=>{this.addSubpackages(l)})}),this.servicesNeededForAudience.add(n),this.addSubpackages(t.fernFilepath)}}getFilteredSubpackages(){return this.subpackagesNeededForAudience}getFilteredServices(){return this.servicesNeededForAudience}getFilteredEndpoints(){return this.endpointsNeededForAudience}getFilteredChannels(){return this.channelsNeededForAudience}getFilteredWebhooks(){return this.webhooksNeededForAudience}addWebhook(t,r,i){let n=r.id;if(n==null)return;let a=new Set,u=new Set;r.payload!=null&&yH._visit(r.payload,{inlinedPayload:l=>{for(let d of l.extends)Qtu(d,a,u);for(let d of l.properties)ex(d.valueType,a,u);if(i?.payload!=null&&typeof i.payload=="object"&&!lJn(i.payload)){let d=cnn(i.payload.properties??{});this.webhookProperties[n]={webhookId:n,propertiesByAudience:d}}},reference:({payloadType:l})=>{ex(l,a,u)},_other:()=>{throw new Error("Unknown WebhookPayload: "+r.payload?.type)}}),u.add(t),this.webhooks[n]={webhookId:n,referencedTypes:a,referencedSubpackages:u}}markWebhookForAudiences(t,r,i){let n=r.id;n!=null&&this.hasAudience(i)&&(this.webhooksNeededForAudience.add(n),this.addSubpackages(t))}addChannel(t,r,i,n){if(r==null)return;let a=new Set,u=new Set;for(let l of i.messages)wL._visit(l.body,{reference:({bodyType:d})=>{ex(d,a,u)},inlinedBody:d=>{for(let s of d.extends)Qtu(s,a,u);for(let s of d.properties)ex(s.valueType,a,u)},_other:()=>{}});for(let l of i.queryParameters)ex(l.valueType,a,u);u.add(t),this.channels[r]={channelId:r,referencedTypes:a,referencedSubpackages:u}}markChannelForAudiences(t,r,i){r!=null&&this.hasAudience(i)&&(this.channelsNeededForAudience.add(r),this.addSubpackages(t))}build(){let t=new Set,r=new Set;for(let l of this.endpointsNeededForAudience.keys()){let d=this.getEndpointNode(l);for(let s of d.referencedErrors){if(r.has(s))continue;r.add(s);let o=this.getErrorNode(s);this.addReferencedTypes(t,o.referencedTypes)}this.addReferencedTypes(t,d.referencedTypes)}this.addReferencedTypes(t,this.typesNeededForAudience);for(let l of this.webhooksNeededForAudience.keys()){let d=this.getWebhookNode(l);this.addReferencedTypes(t,d.referencedTypes)}for(let l of this.channelsNeededForAudience.keys()){let d=this.getChannelNode(l);this.addReferencedTypes(t,d.referencedTypes)}let i={},n={},a={},u={};if(this.audiences.type==="filtered"){for(let[l,d]of Object.entries(this.properties)){if(!t.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=d.propertiesByAudience[o];c?.forEach(b=>{s.add(b)})}s.size>0&&(i[l]=s),i[l]=s.size>0?s:void 0}for(let[l,d]of Object.entries(this.requestProperties)){if(!this.endpointsNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=d.propertiesByAudience[o];c?.forEach(b=>{s.add(b)})}n[l]=s.size>0?s:void 0}for(let[l,d]of Object.entries(this.queryParameters)){if(!this.endpointsNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=d.parametersByAudience[o];c?.forEach(b=>{s.add(b)})}a[l]=s.size>0?s:void 0}for(let[l,d]of Object.entries(this.webhookProperties)){if(!this.webhooksNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=d.propertiesByAudience[o];c?.forEach(b=>{s.add(b)})}u[l]=s.size>0?s:void 0}}return new Gtu({types:t,properties:i,errors:r,requestProperties:n,queryParameters:a,environments:this.environmentsNeededForAudience,services:this.servicesNeededForAudience,endpoints:this.endpointsNeededForAudience,webhooks:this.webhooksNeededForAudience,webhookPayloadProperties:u,subpackages:this.subpackagesNeededForAudience,channels:this.channelsNeededForAudience})}markTypeForService(t,r){let i=this.typesReferencedByService[t]??=new Set;if(i.has(r))return;i.add(r);let n=this.getTypeNode(t);for(let a of n.allDescendants)this.markTypeForService(a,r)}addReferencedTypes(t,r){for(let i of r){if(t.has(i))continue;t.add(i);let n=this.getTypeNode(i);if(this.audiences.type==="filtered")for(let a of this.audiences.audiences){let u=n.descendantsByAudience[a];if(u!=null)u.forEach(l=>{t.add(l)});else{n.allDescendants.forEach(l=>{t.add(l)});break}}else n.allDescendants.forEach(a=>{t.add(a)})}}getTypeNode(t){let r=this.types[t];if(r==null)throw new Error(`Failed to find type node with id ${t}`);return r}getErrorNode(t){let r=this.errors[t];if(r==null)throw new Error(`Failed to find error node with id ${t}`);return r}getEndpointNode(t){let r=this.endpoints[t];if(r==null)throw new Error(`Failed to find endpoint node with id ${t}`);return r}getWebhookNode(t){let r=this.webhooks[t];if(r==null)throw new Error(`Failed to find webhook node with id ${t}`);return r}getChannelNode(t){let r=this.channels[t];if(r==null)throw new Error(`Failed to find channel node with id ${t}`);return r}hasNoAudiences(){return this.audiences.type==="none"}hasAudience(t){let r=this.audiences;switch(r.type){case"none":return!0;case"filtered":return t.some(i=>r.audiences.has(i));default:So(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let i={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add($m.generateSubpackageId(i))}}};function mBE(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:So(e)}}function ex(e,t,r){Xc._visit(e,{container:i=>{PBE(i,t,r)},named:i=>{Qtu(i,t,r)},primitive:$o,unknown:$o,_other:$o})}function Qtu(e,t,r){t.add($m.generateTypeId(e)),r.add(e.fernFilepath)}function PBE(e,t,r){Ry._visit(e,{list:i=>{ex(i,t,r)},map:i=>{ex(i.keyType,t,r),ex(i.valueType,t,r)},optional:i=>{ex(i,t,r)},nullable:i=>{ex(i,t,r)},set:i=>{ex(i,t,r)},literal:$o,_other:$o})}var nwc=class{errors;constructor(){this.errors=[]}add(t){this.errors.push({message:t})}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}},t5a=class{errors;constructor(){this.errors=new nwc}async check({from:t,to:r}){let i=this.checkBreaking({from:t,to:r});return{bump:i.isBreaking?"major":"minor",isBreaking:i.isBreaking,errors:i.errors}}checkBreaking({from:t,to:r}){this.checkTypeBreakingChanges({from:t.types,to:r.types}),this.checkErrorsBreakingChanges({from:t.errors,to:r.errors}),this.checkServicesBreakingChanges({from:t.services,to:r.services});let i=this.errors.hasErrors();return{bump:i?"major":"minor",isBreaking:i,errors:this.errors.getErrors()}}checkTypeBreakingChanges({from:t,to:r}){for(let[i,n]of Object.entries(t)){let a=r[i];if(!a){this.errors.add(`Type "${i}" was removed.`);continue}this.areTypeDeclarationsCompatible({from:n,to:a})||this.errors.add(`Type "${i}" has an incompatible change.`)}}checkErrorsBreakingChanges({from:t,to:r}){for(let[i,n]of Object.entries(t)){let a=Object.values(r).find(u=>u.name.errorId===n.name.errorId);if(!a){this.errors.add(`Error "${n.name.errorId}" with status code "${n.statusCode}" was removed.`);continue}this.checkErrorBreakingChanges({from:n,to:a})}}checkErrorBreakingChanges({from:t,to:r}){if(t.type!=null){if(r.type==null){this.errors.add(`Error "${t.name.errorId}" with status code "${t.statusCode}" had its type removed.`);return}this.areTypeReferencesCompatible({from:t.type,to:r.type})||this.errors.add(`Error "${t.name.errorId}" type reference changed.`)}this.areDeclaredErrorNamesCompatible({from:t.name,to:r.name})||this.errors.add(`Error "${t.name.errorId}" name changed.`),this.areNameAndWireValuesCompatible({from:t.discriminantValue,to:r.discriminantValue})||this.errors.add(`Error "${t.name.errorId}" discriminant value changed.`)}checkServicesBreakingChanges({from:t,to:r}){for(let[i,n]of Object.entries(t)){let a=r[i];if(!a){this.errors.add(`Service "${i}" was removed.`);continue}this.checkServiceBreakingChanges({id:i,from:n,to:a})}}checkServiceBreakingChanges({id:t,from:r,to:i}){this.checkHeadersBreakingChanges({id:t,from:r.headers,to:i.headers}),this.checkEndpointsBreakingChanges({id:t,from:r,to:i})}checkEndpointsBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.endpoints.map(u=>[u.id,u])),a=Object.fromEntries(i.endpoints.map(u=>[u.id,u]));for(let[u,l]of Object.entries(n)){let d=a[u];if(!d){this.errors.add(`Endpoint "${u}" was removed.`);continue}this.checkEndpointBreakingChanges({id:u,from:l,to:d})}}checkEndpointBreakingChanges({id:t,from:r,to:i}){this.checkHttpMethodsBreakingChanges({id:t,from:r.method,to:i.method}),this.checkHttpPathsBreakingChanges({id:t,from:r.fullPath,to:i.fullPath}),this.checkPathParametersBreakingChanges({id:t,from:r.pathParameters,to:i.pathParameters}),this.checkQueryParametersBreakingChanges({id:t,from:r.queryParameters,to:i.queryParameters}),this.checkHeadersBreakingChanges({id:t,from:r.headers,to:i.headers}),r.requestBody!=null&&(i.requestBody!=null?this.checkHttpRequestBodiesCompatible({id:t,from:r.requestBody,to:i.requestBody}):this.errors.add(`Request body was removed from endpoint "${r.id}".`)),r.response!=null&&(i.response!=null?this.checkHttpResponseBreakingChanges({id:t,from:r.response,to:i.response}):this.errors.add(`Response was removed from endpoint "${r.id}".`)),(r.pagination!=null&&i.pagination==null||r.pagination==null&&i.pagination!=null)&&this.errors.add(`Pagination was ${r.pagination!=null?"added":"removed"} from endpoint "${r.id}".`)}checkPathParametersBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.map(u=>[u.name.originalName,u])),a=Object.fromEntries(i.map(u=>[u.name.originalName,u]));for(let[u,l]of Object.entries(n)){let d=a[u];if(!d){this.errors.add(`Path parameter "${u}" was removed from endpoint "${t}".`);continue}this.areTypeReferencesCompatible({from:l.valueType,to:d.valueType})||this.errors.add(`Path parameter "${u}" type changed in endpoint "${t}".`)}}checkQueryParametersBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.map(u=>[u.name.wireValue,u])),a=Object.fromEntries(i.map(u=>[u.name.wireValue,u]));this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(n).map(([u,l])=>[u,l.valueType])),to:Object.fromEntries(Object.entries(a).map(([u,l])=>[u,l.valueType]))});for(let[u,l]of Object.entries(n)){let d=a[u];if(!d){this.errors.add(`Query parameter "${u}" was removed from endpoint "${t}".`);continue}this.areTypeReferencesCompatible({from:l.valueType,to:d.valueType})||this.errors.add(`Query parameter "${u}" type changed in endpoint "${t}".`),l.allowMultiple!==d.allowMultiple&&this.errors.add(`Query parameter "${u}" allow-multiple values changed in endpoint "${t}".`)}}checkHeadersBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.map(u=>[u.name.wireValue,u])),a=Object.fromEntries(i.map(u=>[u.name.wireValue,u]));this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(n).map(([u,l])=>[u,l.valueType])),to:Object.fromEntries(Object.entries(a).map(([u,l])=>[u,l.valueType]))});for(let[u,l]of Object.entries(n)){let d=a[u];if(!d){this.errors.add(`Header "${u}" was removed from ${t}.`);continue}this.areTypeReferencesCompatible({from:l.valueType,to:d.valueType})||this.errors.add(`Header "${u}" type changed in ${t}.`)}}checkHttpMethodsBreakingChanges({id:t,from:r,to:i}){r!==i&&this.errors.add(`HTTP method changed in ${t}.`)}checkHttpPathsBreakingChanges({id:t,from:r,to:i}){this.areHttpPathsCompatible({from:r,to:i})||this.errors.add(`HTTP path changed in ${t}.`)}areHttpPathsCompatible({from:t,to:r}){if(t.head!==r.head||t.parts.length!==r.parts.length)return!1;for(let i=0;i<t.parts.length;i++){let n=t.parts[i];if(n==null)return!1;let a=r.parts[i];if(a==null||n.pathParameter!==a.pathParameter||n.tail!==a.tail)return!1}return!0}checkHttpRequestBodiesCompatible({id:t,from:r,to:i}){switch(r.type){case"inlinedRequestBody":if(i.type==="inlinedRequestBody"&&this.areInlinedRequestBodiesCompatible({from:r,to:i}))return;break;case"reference":if(i.type==="reference"&&this.areReferenceRequestBodiesCompatible({from:r,to:i}))return;break;case"fileUpload":if(i.type==="fileUpload"&&this.areFileUploadRequestBodiesCompatible({from:r,to:i}))return;break;case"bytes":if(i.type==="bytes")return;break;default:So(r)}this.errors.add(`Request body type changed from "${r.type}" to "${i.type}" in endpoint "${t}".`)}areInlinedRequestBodiesCompatible({from:t,to:r}){let i=this.getInlinedRequestBody(t),n=this.getInlinedRequestBody(r);return this.checkForNewInlinedRequestBodyProperties({from:i,to:n}),Object.entries(i).every(([a,u])=>{let l=n[a];return l?this.areTypeReferencesCompatible({from:u,to:l}):(this.errors.add(`Request body property "${a}" was removed.`),!1)})}areReferenceRequestBodiesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.requestBodyType,to:r.requestBodyType})}areFileUploadRequestBodiesCompatible({from:t,to:r}){let i=this.getFileUploadRequest(t.properties),n=this.getFileUploadRequest(r.properties);this.checkForNewFileUploadRequestProperties({from:i,to:n});for(let[a,u]of Object.entries(i)){let l=n[a];if(!l)return this.errors.add(`File upload property "${a}" was removed.`),!1;if(u==="file"&&l!=="file")return this.errors.add(`File upload property "${a}" type changed.`),!1;if(u==="fileArray"&&l!=="fileArray")return this.errors.add(`File upload property "${a}" type changed.`),!1;if(u!=="file"&&u!=="fileArray"&&l!=="file"&&l!=="fileArray"&&!this.areTypeReferencesCompatible({from:u,to:l}))return this.errors.add(`File upload property "${a}" type changed.`),!1}return!0}checkHttpResponseBreakingChanges({id:t,from:r,to:i}){if(r.statusCode!==i.statusCode&&this.errors.add(`Response status code changed from "${r.statusCode}" to "${i.statusCode}".`),!(r.body==null&&i.body==null)){if(r.body==null||i.body==null){this.errors.add(`Response body was ${r.body==null?"added":"removed"}.`);return}switch(r.body.type){case"json":if(i.body.type==="json"){this.areJsonResponsesCompatible({from:r.body.value,to:i.body.value});return}break;case"fileDownload":if(i.body.type==="fileDownload")return;break;case"text":if(i.body.type==="text")return;break;case"bytes":if(i.body.type==="bytes")return;break;case"streaming":if(i.body.type==="streaming"){this.areStreamingResponsesCompatible({from:r.body.value,to:i.body.value});return}break;case"streamParameter":if(i.body.type==="streamParameter"){this.areStreamingResponsesCompatible({from:r.body.streamResponse,to:i.body.streamResponse});return}break;default:So(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:So(t)}return this.errors.add(`Streaming response type "${t.type}" is not compatible with type "${r.type}".`),!1}areTypeDeclarationsCompatible({from:t,to:r}){return this.areDeclaredTypeNamesCompatible({from:t.name,to:r.name})&&this.areTypeShapesCompatible({from:t.shape,to:r.shape})}areTypeShapesCompatible({from:t,to:r}){switch(t.type){case"alias":if(r.type==="alias")return this.areAliasTypesCompatible({from:t,to:r});break;case"enum":if(r.type==="enum")return this.areEnumTypesCompatible({from:t,to:r});break;case"object":if(r.type==="object")return this.areObjectTypesCompatible({from:t,to:r});break;case"union":if(r.type==="union")return this.areUnionTypesCompatible({from:t,to:r});break;case"undiscriminatedUnion":if(r.type==="undiscriminatedUnion")return this.areUndiscriminatedUnionTypesCompatible({from:t,to:r});break;default:So(t)}return this.errors.add(`Type "${t.type}" is not compatible with type "${r.type}".`),!1}areAliasTypesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.aliasOf,to:r.aliasOf})}areEnumTypesCompatible({from:t,to:r}){let i=Object.fromEntries(t.values.map(a=>[a.name.wireValue,a])),n=Object.fromEntries(r.values.map(a=>[a.name.wireValue,a]));return Object.keys(i).length!==Object.keys(n).length?!1:Object.values(i).every(a=>{let u=n[a.name.wireValue];return u?this.areNameAndWireValuesCompatible({from:a.name,to:u.name}):(this.errors.add(`Enum value "${a.name.wireValue}" was removed.`),!1)})}areObjectTypesCompatible({from:t,to:r}){let i=Object.fromEntries([...t.properties.map(a=>[a.name.wireValue,a]),...t.extendedProperties?.map(a=>[a.name.wireValue,a])??[]]),n=Object.fromEntries([...r.properties.map(a=>[a.name.wireValue,a]),...r.extendedProperties?.map(a=>[a.name.wireValue,a])??[]]);return this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(i).map(([a,u])=>[a,u.valueType])),to:Object.fromEntries(Object.entries(n).map(([a,u])=>[a,u.valueType]))}),Object.values(i).every(a=>{let u=n[a.name.wireValue];return u?this.areObjectPropertiesCompatible({from:a,to:u}):(this.errors.add(`Object property "${a.name.wireValue}" was removed.`),!1)})}areObjectPropertiesCompatible({from:t,to:r}){return this.areNameAndWireValuesCompatible({from:t.name,to:r.name})&&this.areTypeReferencesCompatible({from:t.valueType,to:r.valueType})}areUnionTypesCompatible({from:t,to:r}){if(!this.areNameAndWireValuesCompatible({from:t.discriminant,to:r.discriminant}))return this.errors.add(`Union type with discriminant value "${t.discriminant.wireValue}" changed.`),!1;let i=new Set(t.extends.map(s=>this.getKeyForDeclaration(s))),n=new Set(r.extends.map(s=>this.getKeyForDeclaration(s)));for(let s of i)if(!n.has(s))return this.errors.add(`Extended type "${s}" was removed.`),!1;let a=Object.fromEntries(t.baseProperties.map(s=>[s.name.wireValue,s])),u=Object.fromEntries(r.baseProperties.map(s=>[s.name.wireValue,s]));for(let s of Object.values(a)){let o=u[s.name.wireValue];if(!o)return this.errors.add(`Union type with discriminant value "${s.name.wireValue}" no longer has a property named "${s.name.wireValue}".`),!1;if(!this.areObjectPropertiesCompatible({from:s,to:o}))return!1}this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(a).map(([s,o])=>[s,o.valueType])),to:Object.fromEntries(Object.entries(u).map(([s,o])=>[s,o.valueType]))});let l=Object.fromEntries(t.types.map(s=>[s.discriminantValue.wireValue,s])),d=Object.fromEntries(r.types.map(s=>[s.discriminantValue.wireValue,s]));return Object.values(l).every(s=>{let o=d[s.discriminantValue.wireValue];return o?this.areSingleUnionTypesCompatible({from:s.shape,to:o.shape}):(this.errors.add(`Union type for discriminant value "${s.discriminantValue.wireValue}" was removed.`),!1)})}areSingleUnionTypesCompatible({from:t,to:r}){switch(t.propertiesType){case"samePropertiesAsObject":if(r.propertiesType==="samePropertiesAsObject")return this.areDeclaredTypeNamesCompatible({from:t,to:r});break;case"singleProperty":if(r.propertiesType==="singleProperty")return this.areNameAndWireValuesCompatible({from:t.name,to:r.name})&&this.areTypeReferencesCompatible({from:t.type,to:r.type});break;case"noProperties":if(r.propertiesType==="noProperties")return!0;break;default:So(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:So(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:So(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:So(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:So(i)}return r}getKeyForDeclaration({name:t,fernFilepath:r}){return`${r.allParts.map(n=>n.camelCase.unsafeName).join(".")}.${t.pascalCase.unsafeName}`}};function fnn(e,t,r){let{environments:i,changedBaseUrlIds1:n,changedBaseUrlIds2:a}=wBE(e.environments,t.environments,r),{services:u,websocketChannels:l}=SBE(e,t,n,a);return{apiName:e.apiName,basePath:e.basePath,selfHosted:e.selfHosted&&t.selfHosted,apiDisplayName:e.apiDisplayName??t.apiDisplayName,apiDocs:e.apiDocs??t.apiDocs,auth:{requirement:e.auth?.requirement??t.auth?.requirement,schemes:t.auth?.schemes?.length!=null&&t.auth.schemes.length>(e.auth?.schemes?.length??0)?t.auth.schemes:e.auth?.schemes??[],docs:e.auth?.docs??t.auth?.docs},headers:[...e.headers??[],...t.headers??[]],environments:i,types:{...e.types??{},...t.types??{}},constants:{...e.constants??{},...t.constants??{}},errors:{...e.errors??{},...t.errors??{}},services:u,webhookGroups:{...e.webhookGroups??{},...t.webhookGroups??{}},subpackages:jBE(e.subpackages,t.subpackages),websocketChannels:l,rootPackage:{service:e.rootPackage.service??t.rootPackage.service,types:[...e.rootPackage.types??[],...t.rootPackage.types??[]],errors:[...e.rootPackage.errors??[],...t.rootPackage.errors??[]],subpackages:[...e.rootPackage.subpackages??[],...(t.rootPackage.subpackages??[]).filter(d=>!e.rootPackage.subpackages?.includes(d))],fernFilepath:e.rootPackage.fernFilepath??t.rootPackage.fernFilepath,webhooks:e.rootPackage.webhooks??t.rootPackage.webhooks,websocket:e.rootPackage.websocket??t.rootPackage.websocket,hasEndpointsInTree:e.rootPackage.hasEndpointsInTree||t.rootPackage.hasEndpointsInTree,navigationConfig:e.rootPackage.navigationConfig??t.rootPackage.navigationConfig,docs:e.rootPackage.docs??t.rootPackage.docs},fdrApiDefinitionId:e.fdrApiDefinitionId??t.fdrApiDefinitionId,apiVersion:e.apiVersion??t.apiVersion,idempotencyHeaders:[...e.idempotencyHeaders??[],...t.idempotencyHeaders??[]],pathParameters:[...e.pathParameters??[],...t.pathParameters??[]],errorDiscriminationStrategy:e.errorDiscriminationStrategy??t.errorDiscriminationStrategy,variables:[...e.variables??[],...t.variables??[]],serviceTypeReferenceInfo:e.serviceTypeReferenceInfo??t.serviceTypeReferenceInfo,readmeConfig:e.readmeConfig??t.readmeConfig,sourceConfig:e.sourceConfig??t.sourceConfig,publishConfig:e.publishConfig??t.publishConfig,dynamic:e.dynamic??t.dynamic,sdkConfig:e.sdkConfig??t.sdkConfig,audiences:[...e.audiences??[],...t.audiences??[]]}}function jBE(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 wBE(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=oO_(e),n=oO_(t);if(i&&n&&e.environments.type==="singleBaseUrl"&&t.environments.type==="singleBaseUrl")return{environments:{defaultEnvironment:e.defaultEnvironment??t.defaultEnvironment,environments:$R.singleBaseUrl({environments:[...e.environments.environments,...t.environments.environments]})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let a=i?t.defaultEnvironment:e.defaultEnvironment,u=e.environments,l=t.environments;if(u.type==="singleBaseUrl"&&l.type==="singleBaseUrl"){let d=i?l:u,s=i?u:l,o={},{deconflictedEnvironments2:c,changedBaseUrlIds2:b}=DBE(d,s,r);if(d.environments[0]==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let g="Base",O=r.generateName("Base");return d.environments.forEach(m=>{o[m.id]=g}),{environments:{defaultEnvironment:a,environments:$R.multipleBaseUrls({baseUrls:[{id:g,name:O},...c.environments.map(m=>({id:m.id,name:m.name}))],environments:d.environments.map(m=>({id:m.id,name:m.name,urls:{[g]:m.url,...Object.fromEntries(c.environments.map(w=>[w.id,w.url]))},docs:void 0}))})},changedBaseUrlIds1:i?b:o,changedBaseUrlIds2:i?o:b}}if(u.type==="multipleBaseUrls"&&l.type==="singleBaseUrl"||u.type==="singleBaseUrl"&&l.type==="multipleBaseUrls"){let d=u.type==="singleBaseUrl"?u:l,s=u.type==="multipleBaseUrls"?u:l,{deconflictedEnvironments1:o,changedBaseUrlIds1:c}=EBE(d,s,r);return{environments:{defaultEnvironment:a,environments:$R.multipleBaseUrls({baseUrls:[...s.baseUrls,...o.environments.map(b=>({id:b.id,name:b.name}))],environments:s.environments.map(b=>({...b,urls:{...b.urls,...Object.fromEntries(o.environments.map(g=>[g.id,g.url]))}}))})},changedBaseUrlIds1:u.type==="singleBaseUrl"?c:void 0,changedBaseUrlIds2:u.type==="singleBaseUrl"?void 0:c}}if(u.type==="multipleBaseUrls"&&l.type==="multipleBaseUrls"){let{deconflictedEnvironments:d,changedBaseUrlIds:s}=MBE(u,l,r);return{environments:{defaultEnvironment:a,environments:$R.multipleBaseUrls({baseUrls:[...u.baseUrls,...d.baseUrls],environments:u.environments.flatMap(o=>d.environments.map(c=>({...o,urls:{...o.urls,...c.urls}})))})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:s}}return{environments:e??t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0}}function SBE(e,t,r,i){if(r!=null)for(let[u,l]of Object.entries(r)){for(let d of Object.values(e.services))for(let s of Object.values(d.endpoints))s.baseUrl==u&&(s.baseUrl=l),s.v2BaseUrls?.includes(u)&&(s.v2BaseUrls=s.v2BaseUrls.map(o=>o===u?l:o));for(let d of Object.values(e.websocketChannels??{}))d.baseUrl==u&&(d.baseUrl=l)}if(i!=null)for(let[u,l]of Object.entries(i)){for(let d of Object.values(t.services))for(let s of Object.values(d.endpoints))s.baseUrl==u&&(s.baseUrl=l),s.v2BaseUrls?.includes(u)&&(s.v2BaseUrls=s.v2BaseUrls.map(o=>o===u?l:o));for(let d of Object.values(t.websocketChannels??{}))d.baseUrl==u&&(d.baseUrl=l)}let n=e.services;for(let[u,l]of Object.entries(t.services))n[u]==null?n[u]=l:n[u]={availability:l.availability,name:l.name,displayName:l.displayName,basePath:l.basePath,endpoints:[...n[u].endpoints??[],...l.endpoints],pathParameters:[...n[u].pathParameters??[],...l.pathParameters??[]],headers:[...n[u].headers??[],...l.headers??[]],encoding:l.encoding,transport:l.transport,audiences:[...n[u].audiences??[],...l.audiences??[]]};let a={...e.websocketChannels??{},...t.websocketChannels??{}};return{services:n,websocketChannels:a}}function DBE(e,t,r){let i={},n=new Set(e.environments.map(s=>s.id)),a=new Set(e.environments.map(s=>s.name)),u=new Map(e.environments.map(s=>[s.url,s.id])),l=t.environments.filter(s=>{let o=u.get(s.url);return o!=null?(i[s.id]=o,!1):!0}).map(s=>{if(n.has(s.id)||a.has(s.name)){let o=awc(s.id,n);return i[s.id]=o,{...s,id:o,name:r.generateName(o)}}return s});return{deconflictedEnvironments2:$R.singleBaseUrl({environments:l}),changedBaseUrlIds2:i}}function EBE(e,t,r){let i={},n=new Set(t.baseUrls.map(d=>d.id)),a=new Set(t.baseUrls.map(d=>d.name)),u=e.environments.map(d=>{if(n.has(d.id)||a.has(d.name)){let s=awc(d.id,n);return i[d.id]=s,{...d,id:s,name:r.generateName(s)}}return d});return{deconflictedEnvironments1:$R.singleBaseUrl({environments:u}),changedBaseUrlIds1:i}}function MBE(e,t,r){let i={},n=new Set(e.baseUrls.map(s=>s.id)),a=new Set(e.baseUrls.map(s=>s.name)),u=t.baseUrls.map(s=>{if(n.has(s.id)||a.has(s.name)){let o=awc(s.id,n);return i[s.id]=o,{...s,id:o,name:r.generateName(o)}}return s}),l=t.environments.map(s=>({...s,urls:Object.fromEntries(Object.entries(s.urls).map(([o,c])=>[i[o]??o,c]))}));return{deconflictedEnvironments:$R.multipleBaseUrls({baseUrls:u,environments:l}),changedBaseUrlIds:i}}function oO_(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 awc(e,t){let r=e,i=1;for(;t.has(r);)r=`${e}-${i}`,i++;return r}var e_=class e{breadcrumbs=[];context;static STRING=Vs.TypeReference.primitive({v1:"STRING",v2:Vs.PrimitiveTypeV2.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=Vs.TypeReference.container(Vs.ContainerType.optional(e.STRING));constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r}};var sO_=require("fs/promises");var owc=class{_map;_path;_lastScalar;_fragments;_count;constructor(){this._map={},this._path=[],this._lastScalar="",this._fragments=[],this._count=0}get map(){return this._map}resolveNode(t,r){if(t.path==="."&&(r="."),!this._map[r]){let{line:i,position:n,lineStart:a}=t;this._map[r]={line:i,position:n,lineStart:a}}t.children&&t.children.length>0&&t.children.forEach(i=>{this.resolveNode(i,(r==="."?"":r)+"."+i.path)})}iterFragments(t,r){for(let i=this._fragments.length-1;i>=0;i--){if(!this._fragments[i].path.startsWith(t)||this._fragments[i].path===t)continue;let n=this._fragments.pop();r(n)}}handleState(t,r){if(t==="close"){let i=r.result,n=r.kind,a=this._path.join(".");if(n==="scalar"){this._path.pop(),this._lastScalar=`${i}`;let{line:u,position:l,lineStart:d}=r;this._path.length===0?this._map["."+i]={line:u,position:l,lineStart:d}:this._fragments.push({path:this._path.join(".")+"."+i,line:u,position:l,lineStart:d})}else if(n==="mapping"){let u={path:a,children:[],line:0,position:0,lineStart:0},l=0;this.iterFragments(a,d=>{l++,!((!d.children||d.children.length===0)&&l%2===1)&&(this._path.length===1?this.resolveNode(d,d.path):(u.children.push({...d,path:d.path.slice(a.length+1)}),u.line=d.line,u.position=d.position,u.lineStart=d.lineStart))}),u.children&&u.children.length>0&&this._fragments.push(u),this._path.pop()}else if(n==="sequence"){let u={path:a,children:[],line:0,position:0,lineStart:0},l=new Set,d=i.length;this.iterFragments(a,s=>{l.has(s.position)||(d--,l.add(s.position),this._path.length===1?this.resolveNode(s,`${a}.${d}`):(u.children.push({...s,path:d.toString()}),u.line=s.line,u.position=s.position,u.lineStart=s.lineStart))}),u.children&&u.children.length>0&&this._fragments.push(u),this._path.pop()}else this._path.pop()}if(t==="open"){if(this._count===0){let{line:i,position:n,lineStart:a}=r;this._map["."]={line:i,position:n,lineStart:a}}this._path.push(this._lastScalar),this._count++}}listen(){return this.handleState.bind(this)}lookup(t){let r=t instanceof Array?t.map(n=>`${n}`).join("."):`${t}`;r.startsWith(".")||(r="."+r),r.startsWith("..")&&(r=r.slice(1)),r=r.replace(/\[/g,".").replace(/\]/g,"");let i=this._map[r];if(i)return{line:i.line+1,column:i.position-i.lineStart+1,position:i.position}}},uO_=owc;var Umi;(function(e){e.WARNING="warning",e.ERROR="error"})(Umi||(Umi={}));var gNi=class{errors=[];logger;breadcrumbToLineNumberMapper;relativeFilepathToSpec;constructor({logger:t,relativeFilepathToSpec:r}){this.logger=t,this.relativeFilepathToSpec=r,r&&(this.breadcrumbToLineNumberMapper=new uwc({logger:t,relativePathToFile:Ia.of(r)}))}collect(t){this.errors.push(t)}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}dedupe(){let t=[],r=new Set,i=0;for(let n of this.errors){let a=n.path?n.path.join("->"):"",u=`${n.message}|${n.level||Umi.WARNING}|${a}`;r.has(u)?i++:(r.add(u),t.push(n))}return this.errors=t,i}getErrorStats(){this.dedupe();let t=0,r=0;for(let i of this.errors)i.level===Umi.ERROR?t++:r++;return{numErrors:t,numWarnings:r}}async logErrors({logWarnings:t}){this.dedupe();for(let r of this.errors)if(!(r.level===Umi.WARNING&&!t))switch(r.level){case Umi.ERROR:if(this.logger.log(pb.Error,r.message),r.path&&r.path.length>0){let i=await this.breadcrumbToLineNumberMapper?.getSourceLocation(r.path),n=i?`${this.relativeFilepathToSpec}:${i.line}:${i.column}`:r.path.join(" -> ");this.logger.log(pb.Error,` - at location (${n})`)}break}}},uwc=class{logger;relativePathToFile;map=new uO_;initialized=!1;constructor({relativePathToFile:t,logger:r}){this.relativePathToFile=t,this.logger=r}async initialize(){if(!this.initialized)try{let t=await(0,sO_.readFile)(this.relativePathToFile,"utf-8");wd.load(t,{listener:this.map.listen()}),this.initialized=!0}catch(t){this.logger.log(pb.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 d7=class e{args;spec;settings;errorCollector;logger;generationLanguage;smartCasing;casingsGenerator;namespace;exampleGenerationArgs;authOverrides;environmentOverrides;globalHeaderOverrides;enableUniqueErrorsPerEndpoint;generateV1Examples;constructor(t){this.args=t,this.spec=t.spec,this.settings=t.settings,this.errorCollector=t.errorCollector,this.logger=t.logger,this.generationLanguage=t.generationLanguage,this.smartCasing=t.smartCasing,this.namespace=t.namespace,this.casingsGenerator=iee({generationLanguage:t.generationLanguage,keywords:void 0,smartCasing:t.smartCasing}),this.exampleGenerationArgs=t.exampleGenerationArgs,this.authOverrides=t.authOverrides,this.environmentOverrides=t.environmentOverrides,this.globalHeaderOverrides=t.globalHeaderOverrides,this.enableUniqueErrorsPerEndpoint=t.enableUniqueErrorsPerEndpoint,this.generateV1Examples=t.generateV1Examples}static BREADCRUMBS_TO_IGNORE=["properties","allOf","anyOf"];convertBreadcrumbsToName(t){let r=t.filter((n,a)=>!(/^\d+$/.test(n)||e.BREADCRUMBS_TO_IGNORE.includes(n)||a===0&&n==="components"||a===1&&n==="schemas"||t[0]==="paths"&&(a===0||a===1&&["get","post","put","delete","patch"].includes(n)||a===2&&t[1]!=null&&["get","post","put","delete","patch"].includes(t[1])&&n==="parameters"))),i=S_(r.join("_"));return i.charAt(0).toUpperCase()+i.slice(1)}createFernFilepath(t={}){let r=this.namespace!=null?[this.casingsGenerator.generateName(this.namespace)]:[],i=t.name!=null?this.casingsGenerator.generateName(t.name):void 0;return{allParts:i?[...r,i]:r,packagePath:r,file:i}}resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:i}){let n=this.spec,a=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(u=>u.replace(/~1/g,"/"));for(let u of a){if(typeof n!="object"||n==null)return i||this.errorCollector.collect({level:Umi.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1};n=n[u]}return n==null?(i||this.errorCollector.collect({level:Umi.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1}):{resolved:!0,value:n}}getErrorMessageForMissingRef({reference:t}){let r=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/");return r.length>=3&&r[0]==="components"&&r[1]==="schemas"?`Schema ${r[2]} does not exist`:`${t.$ref} does not exist`}async resolveMaybeExternalReference(t){let r=this.spec,i,n=!1,a=null,u;if(this.isExternalReference(t.$ref)){n=!0;let s=t.$ref.split("#"),o=s[0];if(i=s[1],!o)return{resolved:!1};u=o;let c=await fetch(o);if(!c.ok)return{resolved:!1};try{let b=await c.text();try{a=JSON.parse(b),r=a}catch{a=wd.load(b),r=a}if(r==null)return{resolved:!1}}catch{return{resolved:!1}}if(!i)return{resolved:!0,value:r}}let l=i??t.$ref;if(l==null||typeof l!="string")return{resolved:!1};let d=l.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(s=>s.replace(/~1/g,"/"));for(let s of d){if(typeof r!="object"||r==null)return{resolved:!1};r=r[s]}if(r==null)return{resolved:!1};if(n&&typeof r=="object"&&r!==null){let s=new Set;s.add(t.$ref),r=await this.resolveNestedExternalReferences(r,a,s,u)}return{resolved:!0,value:r}}async resolveNestedExternalReferences(t,r,i,n){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){let u=[];for(let l of t)u.push(await this.resolveNestedExternalReferences(l,r,i,n));return u}if(this.isReferenceObject(t)){let u=t.$ref;if(this.isExternalReference(u)){if(i.has(u))return t;i.add(u);let l=await this.resolveMaybeExternalReference({$ref:u});if(i.delete(u),l.resolved)return l.value}else{let l=`${n}${u}`;if(i.has(l))return t;i.add(l);let d=r,s=u.substring(2).split("/").map(o=>o.replace(/~1/g,"/").replace(/~0/g,"~"));for(let o of s){if(typeof d!="object"||d===null)return t;d=d[o]}if(d!=null){let o=await this.resolveNestedExternalReferences(d,r,i,n);return i.delete(u),o}i.delete(u)}return t}let a={};for(let[u,l]of Object.entries(t))typeof l=="object"&&l!==null?a[u]=await this.resolveNestedExternalReferences(l,r,i,n):a[u]=l;return a}getExamplesFromSchema({schema:t,breadcrumbs:r}){if(t==null)return[];let i=t.example!=null?[t.example]:[];return t.examples!=null&&(Array.isArray(t.examples)?i.push(...t.examples):this.errorCollector.collect({message:"Received non-array schema examples",path:r})),i}getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:r,defaultExampleName:i}){if(t==null)return[];let n=[];if(t.example!=null){let a=this.generateUniqueName({prefix:i??`${r.join("_")}_example`,existingNames:[]});n.push([a,t.example])}return t.examples!=null&&n.push(...Object.entries(t.examples)),n}resolveMaybeReference({schemaOrReference:t,breadcrumbs:r,skipErrorCollector:i}){if(this.isReferenceObject(t)){let n=this.resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:i});return n.resolved?n.value:void 0}return t}resolveExample(t){if(!this.isReferenceObject(t))return t;let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}resolveExampleWithValue(t){if(!this.isReferenceObject(t))return this.returnExampleValue(t);let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}returnExampleValue(t){return this.isExampleWithValue(t)?t.value:t}getPropertyAccess(t){let r=t;for(;this.isReferenceObject(r);){let 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 Urr.ReadOnly;if(n)return Urr.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 l=this.resolveReference({reference:n});if(!l.resolved)continue;a=l.value}let u=this.getReadOnlyWriteOnlyFromSchema(a);r=r&&u.readOnly,i=i&&u.writeOnly}return{readOnly:r,writeOnly:i}}else return{readOnly:!!t.readOnly,writeOnly:!!t.writeOnly}}getAudiences({operation:t,breadcrumbs:r}){let n=new VH.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 VH.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(n!=null)return{status:n,message:void 0};if(t.deprecated===!0)return{status:gL.Deprecated,message:void 0}}getTypeIdFromSchemaReference(t){let r=t.$ref.match(/\/schemas\/(.+)$/);if(!(!r||!r[1]))return r[1]}createNamedTypeReference(t,r){return Xc.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(t),typeId:t,displayName:r,default:void 0,inline:!1})}typeReferenceToDeclaredTypeName(t){if(t.type!=="named")return;let r=t.typeId;return{typeId:r,fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(r),displayName:t.displayName}}removeSchemaFromInlinedTypes({id:t,inlinedTypes:r}){return Object.fromEntries(Object.entries(r).filter(([i])=>i!==t))}static maybeTrimPrefix(t,r){return t.startsWith(r)?t.slice(r.length):t}generateUniqueName({prefix:t,existingNames:r}){if(!r.includes(t))return t;let i=0;for(;r.includes(`${t}_${i}`);)i++;return`${t}_${i}`}isReferenceObject(t){return typeof t=="object"&&t!==null&&"$ref"in t}isExternalReference(t){return typeof t=="string"&&(t.startsWith("http://")||t.startsWith("https://"))}isReferenceObjectWithIdentifier(t){return this.isReferenceObject(t)&&("title"in t||"name"in t||"messageId"in t)}isExampleWithSummary(t){return typeof t=="object"&&t!=null&&"summary"in t}isExampleWithValue(t){return typeof t=="object"&&t!=null&&"value"in t}isOptional(t){return t.type==="container"&&t.container.type==="optional"}isNullable(t){return t.type==="container"&&t.container.type==="nullable"}isList(t){return t.type==="container"&&t.container.type==="list"}isFile(t){return t.type==="primitive"&&t.primitive.v2?.type==="string"&&t.primitive.v2.validation?.format==="binary"}getAsString(t){if(typeof t=="string")return t}getAsInteger(t){if(typeof t=="number"&&Number.isInteger(t))return t}getAsNumber(t){if(typeof t=="number")return t}getAsBoolean(t){if(typeof t=="boolean")return t}getAsArray(t){if(Array.isArray(t))return t}getAsObject(t){if(typeof t=="object"&&t!==null&&!Array.isArray(t))return t}getGroup({groupParts:t,namespace:r}){let i=[];return r!=null&&i.push(r),i.push(...t??[]),i}isObjectSchemaType(t){return t.type==="object"||t.properties!=null}};var Yg=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 VH={};Po(VH,{AudienceExtension:()=>Jtu,FernAvailabilityExtension:()=>Ktu,FernEnumExtension:()=>tru,FernIgnoreExtension:()=>Mnn,FernOptionalExtension:()=>rru,FernTypeExtension:()=>aru,FernTypeNameExtension:()=>oru,SdkGroupNameExtension:()=>iru,SdkMethodNameExtension:()=>nru});var Jtu=class extends Yg{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 Ktu=class extends Yg{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 gL.InDevelopment;case"PRE_RELEASE":case"BETA":return gL.PreRelease;case"GENERAL_AVAILABILITY":case"GA":return gL.GeneralAvailability;case"DEPRECATED":return gL.Deprecated;default:return}}};var $3e={};Po($3e,{BRAND:()=>eIE,DIRTY:()=>dnn,EMPTY_PATH:()=>CBE,INVALID:()=>W0,NEVER:()=>NIE,OK:()=>eK,ParseStatus:()=>WH,Schema:()=>Pw,ZodAny:()=>PNi,ZodArray:()=>$mi,ZodBigInt:()=>_nn,ZodBoolean:()=>hnn,ZodBranded:()=>i5a,ZodCatch:()=>Dnn,ZodDate:()=>ynn,ZodDefault:()=>Snn,ZodDiscriminatedUnion:()=>Ztu,ZodEffects:()=>H3e,ZodEnum:()=>jnn,ZodError:()=>oue,ZodFirstPartyTypeKind:()=>dg,ZodFunction:()=>eru,ZodIntersection:()=>Onn,ZodIssueCode:()=>td,ZodLazy:()=>mnn,ZodLiteral:()=>Pnn,ZodMap:()=>yJn,ZodNaN:()=>bJn,ZodNativeEnum:()=>wnn,ZodNever:()=>sQt,ZodNull:()=>bnn,ZodNullable:()=>hor,ZodNumber:()=>pnn,ZodObject:()=>uue,ZodOptional:()=>V3e,ZodParsedType:()=>U_,ZodPipeline:()=>n5a,ZodPromise:()=>jNi,ZodReadonly:()=>Enn,ZodRecord:()=>ktu,ZodSchema:()=>Pw,ZodSet:()=>vJn,ZodString:()=>mNi,ZodSymbol:()=>_Jn,ZodTransformer:()=>H3e,ZodTuple:()=>_or,ZodType:()=>Pw,ZodUndefined:()=>vnn,ZodUnion:()=>gnn,ZodUnknown:()=>Hmi,ZodVoid:()=>hJn,addIssueToContext:()=>Rp,any:()=>cIE,array:()=>pIE,bigint:()=>nIE,boolean:()=>gO_,coerce:()=>xIE,custom:()=>yO_,date:()=>aIE,datetimeRegex:()=>_O_,defaultErrorMap:()=>Vmi,discriminatedUnion:()=>vIE,effect:()=>AIE,enum:()=>DIE,function:()=>jIE,getErrorMap:()=>fJn,getParsedType:()=>por,instanceof:()=>rIE,intersection:()=>bIE,isAborted:()=>Ytu,isAsync:()=>dJn,isDirty:()=>Xtu,isValid:()=>ONi,late:()=>tIE,lazy:()=>wIE,literal:()=>SIE,makeIssue:()=>r5a,map:()=>mIE,nan:()=>iIE,nativeEnum:()=>EIE,never:()=>fIE,null:()=>sIE,nullable:()=>TIE,number:()=>bO_,object:()=>_IE,objectUtil:()=>swc,oboolean:()=>RIE,onumber:()=>zIE,optional:()=>qIE,ostring:()=>IIE,pipeline:()=>BIE,preprocess:()=>CIE,promise:()=>MIE,quotelessJson:()=>ABE,record:()=>OIE,set:()=>PIE,setErrorMap:()=>TBE,strictObject:()=>hIE,string:()=>vO_,symbol:()=>oIE,transformer:()=>AIE,tuple:()=>gIE,undefined:()=>uIE,union:()=>yIE,unknown:()=>lIE,util:()=>fD,void:()=>dIE});var fD;(function(e){e.assertEqual=n=>{};function t(n){}e.assertIs=t;function r(n){throw new Error}e.assertNever=r,e.arrayToEnum=n=>{let a={};for(let u of n)a[u]=u;return a},e.getValidEnumValues=n=>{let a=e.objectKeys(n).filter(l=>typeof n[n[l]]!="number"),u={};for(let l of a)u[l]=n[l];return e.objectValues(u)},e.objectValues=n=>e.objectKeys(n).map(function(a){return n[a]}),e.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{let a=[];for(let u in n)Object.prototype.hasOwnProperty.call(n,u)&&a.push(u);return a},e.find=(n,a)=>{for(let u of n)if(a(u))return u},e.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function i(n,a=" | "){return n.map(u=>typeof u=="string"?`'${u}'`:u).join(a)}e.joinValues=i,e.jsonStringifyReplacer=(n,a)=>typeof a=="bigint"?a.toString():a})(fD||(fD={}));var swc;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(swc||(swc={}));var U_=fD.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),por=e=>{switch(typeof e){case"undefined":return U_.undefined;case"string":return U_.string;case"number":return Number.isNaN(e)?U_.nan:U_.number;case"boolean":return U_.boolean;case"function":return U_.function;case"bigint":return U_.bigint;case"symbol":return U_.symbol;case"object":return Array.isArray(e)?U_.array:e===null?U_.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?U_.promise:typeof Map<"u"&&e instanceof Map?U_.map:typeof Set<"u"&&e instanceof Set?U_.set:typeof Date<"u"&&e instanceof Date?U_.date:U_.object;default:return U_.unknown}};var td=fD.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),ABE=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),oue=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(a){return a.message},i={_errors:[]},n=a=>{for(let u of a.issues)if(u.code==="invalid_union")u.unionErrors.map(n);else if(u.code==="invalid_return_type")n(u.returnTypeError);else if(u.code==="invalid_arguments")n(u.argumentsError);else if(u.path.length===0)i._errors.push(r(u));else{let l=i,d=0;for(;d<u.path.length;){let s=u.path[d];d===u.path.length-1?(l[s]=l[s]||{_errors:[]},l[s]._errors.push(r(u))):l[s]=l[s]||{_errors:[]},l=l[s],d++}}};return n(this),i}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,fD.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r={},i=[];for(let n of this.issues)if(n.path.length>0){let a=n.path[0];r[a]=r[a]||[],r[a].push(t(n))}else i.push(t(n));return{formErrors:i,fieldErrors:r}}get formErrors(){return this.flatten()}};oue.create=e=>new oue(e);var qBE=(e,t)=>{let r;switch(e.code){case td.invalid_type:e.received===U_.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case td.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,fD.jsonStringifyReplacer)}`;break;case td.unrecognized_keys:r=`Unrecognized key(s) in object: ${fD.joinValues(e.keys,", ")}`;break;case td.invalid_union:r="Invalid input";break;case td.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${fD.joinValues(e.options)}`;break;case td.invalid_enum_value:r=`Invalid enum value. Expected ${fD.joinValues(e.options)}, received '${e.received}'`;break;case td.invalid_arguments:r="Invalid function arguments";break;case td.invalid_return_type:r="Invalid function return type";break;case td.invalid_date:r="Invalid date";break;case td.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:fD.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case td.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case td.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case td.custom:r="Invalid input";break;case td.invalid_intersection_types:r="Intersection results could not be merged";break;case td.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case td.not_finite:r="Number must be finite";break;default:r=t.defaultError,fD.assertNever(e)}return{message:r}},Vmi=qBE;var cO_=Vmi;function TBE(e){cO_=e}function fJn(){return cO_}var r5a=e=>{let{data:t,path:r,errorMaps:i,issueData:n}=e,a=[...r,...n.path||[]],u={...n,path:a};if(n.message!==void 0)return{...n,path:a,message:n.message};let l="",d=i.filter(s=>!!s).slice().reverse();for(let s of d)l=s(u,{data:t,defaultError:l}).message;return{...n,path:a,message:l}},CBE=[];function Rp(e,t){let r=fJn(),i=r5a({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===Vmi?void 0:Vmi].filter(n=>!!n)});e.common.issues.push(i)}var WH=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let i=[];for(let n of r){if(n.status==="aborted")return W0;n.status==="dirty"&&t.dirty(),i.push(n.value)}return{status:t.value,value:i}}static async mergeObjectAsync(t,r){let i=[];for(let n of r){let a=await n.key,u=await n.value;i.push({key:a,value:u})}return e.mergeObjectSync(t,i)}static mergeObjectSync(t,r){let i={};for(let n of r){let{key:a,value:u}=n;if(a.status==="aborted"||u.status==="aborted")return W0;a.status==="dirty"&&t.dirty(),u.status==="dirty"&&t.dirty(),a.value!=="__proto__"&&(typeof u.value<"u"||n.alwaysSet)&&(i[a.value]=u.value)}return{status:t.value,value:i}}},W0=Object.freeze({status:"aborted"}),dnn=e=>({status:"dirty",value:e}),eK=e=>({status:"valid",value:e}),Ytu=e=>e.status==="aborted",Xtu=e=>e.status==="dirty",ONi=e=>e.status==="valid",dJn=e=>typeof Promise<"u"&&e instanceof Promise;var sv;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(sv||(sv={}));var W3e=class{constructor(t,r,i,n){this._cachedPath=[],this.parent=t,this.data=r,this._path=i,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},lO_=(e,t)=>{if(ONi(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new oue(e.common.issues);return this._error=r,this._error}}};function tj(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:i,description:n}=e;if(t&&(r||i))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:n}:{errorMap:(u,l)=>{let{message:d}=e;return u.code==="invalid_enum_value"?{message:d??l.defaultError}:typeof l.data>"u"?{message:d??i??l.defaultError}:u.code!=="invalid_type"?{message:l.defaultError}:{message:d??r??l.defaultError}},description:n}}var Pw=class{get description(){return this._def.description}_getType(t){return por(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:por(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new WH,ctx:{common:t.parent.common,data:t.data,parsedType:por(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(dJn(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let i=this.safeParse(t,r);if(i.success)return i.data;throw i.error}safeParse(t,r){let i={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:por(t)},n=this._parseSync({data:t,path:i.path,parent:i});return lO_(i,n)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:por(t)};if(!this["~standard"].async)try{let i=this._parseSync({data:t,path:[],parent:r});return ONi(i)?{value:i.value}:{issues:r.common.issues}}catch(i){i?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(i=>ONi(i)?{value:i.value}:{issues:r.common.issues})}async parseAsync(t,r){let i=await this.safeParseAsync(t,r);if(i.success)return i.data;throw i.error}async safeParseAsync(t,r){let i={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:por(t)},n=this._parse({data:t,path:i.path,parent:i}),a=await(dJn(n)?n:Promise.resolve(n));return lO_(i,a)}refine(t,r){let i=n=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(n):r;return this._refinement((n,a)=>{let u=t(n),l=()=>a.addIssue({code:td.custom,...i(n)});return typeof Promise<"u"&&u instanceof Promise?u.then(d=>d?!0:(l(),!1)):u?!0:(l(),!1)})}refinement(t,r){return this._refinement((i,n)=>t(i)?!0:(n.addIssue(typeof r=="function"?r(i,n):r),!1))}_refinement(t){return new H3e({schema:this,typeName:dg.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return V3e.create(this,this._def)}nullable(){return hor.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return $mi.create(this)}promise(){return jNi.create(this,this._def)}or(t){return gnn.create([this,t],this._def)}and(t){return Onn.create(this,t,this._def)}transform(t){return new H3e({...tj(this._def),schema:this,typeName:dg.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new Snn({...tj(this._def),innerType:this,defaultValue:r,typeName:dg.ZodDefault})}brand(){return new i5a({typeName:dg.ZodBranded,type:this,...tj(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new Dnn({...tj(this._def),innerType:this,catchValue:r,typeName:dg.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return n5a.create(this,t)}readonly(){return Enn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},BBE=/^c[^\s-]{8,}$/i,IBE=/^[0-9a-z]+$/,zBE=/^[0-9A-HJKMNP-TV-Z]{26}$/i,RBE=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,xBE=/^[a-z0-9_-]{21}$/i,NBE=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,FBE=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,LBE=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,UBE="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",cwc,VBE=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,WBE=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,HBE=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,$BE=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,GBE=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,QBE=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dO_="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",JBE=new RegExp(`^${dO_}$`);function pO_(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function KBE(e){return new RegExp(`^${pO_(e)}$`)}function _O_(e){let t=`${dO_}T${pO_(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function YBE(e,t){return!!((t==="v4"||!t)&&VBE.test(e)||(t==="v6"||!t)&&HBE.test(e))}function XBE(e,t){if(!NBE.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let i=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(i));return!(typeof n!="object"||n===null||"typ"in n&&n?.typ!=="JWT"||!n.alg||t&&n.alg!==t)}catch{return!1}}function ZBE(e,t){return!!((t==="v4"||!t)&&WBE.test(e)||(t==="v6"||!t)&&$BE.test(e))}var mNi=class e extends Pw{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==U_.string){let a=this._getOrReturnCtx(t);return Rp(a,{code:td.invalid_type,expected:U_.string,received:a.parsedType}),W0}let i=new WH,n;for(let a of this._def.checks)if(a.kind==="min")t.data.length<a.value&&(n=this._getOrReturnCtx(t,n),Rp(n,{code:td.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),i.dirty());else if(a.kind==="max")t.data.length>a.value&&(n=this._getOrReturnCtx(t,n),Rp(n,{code:td.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),i.dirty());else if(a.kind==="length"){let u=t.data.length>a.value,l=t.data.length<a.value;(u||l)&&(n=this._getOrReturnCtx(t,n),u?Rp(n,{code:td.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):l&&Rp(n,{code:td.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),i.dirty())}else if(a.kind==="email")LBE.test(t.data)||(n=this._getOrReturnCtx(t,n),Rp(n,{validation:"email",code:td.invalid_string,message:a.message}),i.dirty());else if(a.kind==="emoji")cwc||(cwc=new RegExp(UBE,"u")),cwc.test(t.data)||(n=this._getOrReturnCtx(t,n),Rp(n,{validation:"emoji",code:td.invalid_string,message:a.message}),i.dirty());else if(a.kind==="uuid")RBE.test(t.data)||(n=this._getOrReturnCtx(t,n),Rp(n,{validation:"uuid",code:td.invalid_string,message:a.message}),i.dirty());else if(a.kind==="nanoid")xBE.test(t.data)||(n=this._getOrReturnCtx(t,n),Rp(n,{validation:"nanoid",code:td.invalid_string,message:a.message}),i.dirty());else if(a.kind==="cuid")BBE.test(t.data)||(n=this._getOrReturnCtx(t,n),Rp(n,{validation:"cuid",code:td.invalid_string,message:a.message}),i.dirty());else if(a.kind==="cuid2")IBE.test(t.data)||(n=this._getOrReturnCtx(t,n),Rp(n,{validation:"cuid2",code:td.invalid_string,message:a.message}),i.dirty());else if(a.kind==="ulid")zBE.test(t.data)||(n=this._getOrReturnCtx(t,n),Rp(n,{validation:"ulid",code:td.invalid_string,message:a.message}),i.dirty());else if(a.kind==="url")try{new URL(t.data)}catch{n=this._getOrReturnCtx(t,n),Rp(n,{validation:"url",code:td.invalid_string,message:a.message}),i.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(t.data)||(n=this._getOrReturnCtx(t,n),Rp(n,{validation:"regex",code:td.invalid_string,message:a.message}),i.dirty())):a.kind==="trim"?t.data=t.data.trim():a.kind==="includes"?t.data.includes(a.value,a.position)||(n=this._getOrReturnCtx(t,n),Rp(n,{code:td.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),i.dirty()):a.kind==="toLowerCase"?t.data=t.data.toLowerCase():a.kind==="toUpperCase"?t.data=t.data.toUpperCase():a.kind==="startsWith"?t.data.startsWith(a.value)||(n=this._getOrReturnCtx(t,n),Rp(n,{code:td.invalid_string,validation:{startsWith:a.value},message:a.message}),i.dirty()):a.kind==="endsWith"?t.data.endsWith(a.value)||(n=this._getOrReturnCtx(t,n),Rp(n,{code:td.invalid_string,validation:{endsWith:a.value},message:a.message}),i.dirty()):a.kind==="datetime"?_O_(a).test(t.data)||(n=this._getOrReturnCtx(t,n),Rp(n,{code:td.invalid_string,validation:"datetime",message:a.message}),i.dirty()):a.kind==="date"?JBE.test(t.data)||(n=this._getOrReturnCtx(t,n),Rp(n,{code:td.invalid_string,validation:"date",message:a.message}),i.dirty()):a.kind==="time"?KBE(a).test(t.data)||(n=this._getOrReturnCtx(t,n),Rp(n,{code:td.invalid_string,validation:"time",message:a.message}),i.dirty()):a.kind==="duration"?FBE.test(t.data)||(n=this._getOrReturnCtx(t,n),Rp(n,{validation:"duration",code:td.invalid_string,message:a.message}),i.dirty()):a.kind==="ip"?YBE(t.data,a.version)||(n=this._getOrReturnCtx(t,n),Rp(n,{validation:"ip",code:td.invalid_string,message:a.message}),i.dirty()):a.kind==="jwt"?XBE(t.data,a.alg)||(n=this._getOrReturnCtx(t,n),Rp(n,{validation:"jwt",code:td.invalid_string,message:a.message}),i.dirty()):a.kind==="cidr"?ZBE(t.data,a.version)||(n=this._getOrReturnCtx(t,n),Rp(n,{validation:"cidr",code:td.invalid_string,message:a.message}),i.dirty()):a.kind==="base64"?GBE.test(t.data)||(n=this._getOrReturnCtx(t,n),Rp(n,{validation:"base64",code:td.invalid_string,message:a.message}),i.dirty()):a.kind==="base64url"?QBE.test(t.data)||(n=this._getOrReturnCtx(t,n),Rp(n,{validation:"base64url",code:td.invalid_string,message:a.message}),i.dirty()):fD.assertNever(a);return{status:i.value,value:t.data}}_regex(t,r,i){return this.refinement(n=>t.test(n),{validation:r,code:td.invalid_string,...sv.errToObj(i)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...sv.errToObj(t)})}url(t){return this._addCheck({kind:"url",...sv.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...sv.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...sv.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...sv.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...sv.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...sv.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...sv.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...sv.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...sv.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...sv.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...sv.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...sv.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...sv.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...sv.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...sv.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...sv.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...sv.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...sv.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...sv.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...sv.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...sv.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...sv.errToObj(r)})}nonempty(t){return this.min(1,sv.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};mNi.create=e=>new mNi({checks:[],typeName:dg.ZodString,coerce:e?.coerce??!1,...tj(e)});function kBE(e,t){let r=(e.toString().split(".")[1]||"").length,i=(t.toString().split(".")[1]||"").length,n=r>i?r:i,a=Number.parseInt(e.toFixed(n).replace(".","")),u=Number.parseInt(t.toFixed(n).replace(".",""));return a%u/10**n}var pnn=class e extends Pw{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==U_.number){let a=this._getOrReturnCtx(t);return Rp(a,{code:td.invalid_type,expected:U_.number,received:a.parsedType}),W0}let i,n=new WH;for(let a of this._def.checks)a.kind==="int"?fD.isInteger(t.data)||(i=this._getOrReturnCtx(t,i),Rp(i,{code:td.invalid_type,expected:"integer",received:"float",message:a.message}),n.dirty()):a.kind==="min"?(a.inclusive?t.data<a.value:t.data<=a.value)&&(i=this._getOrReturnCtx(t,i),Rp(i,{code:td.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?t.data>a.value:t.data>=a.value)&&(i=this._getOrReturnCtx(t,i),Rp(i,{code:td.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="multipleOf"?kBE(t.data,a.value)!==0&&(i=this._getOrReturnCtx(t,i),Rp(i,{code:td.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):a.kind==="finite"?Number.isFinite(t.data)||(i=this._getOrReturnCtx(t,i),Rp(i,{code:td.not_finite,message:a.message}),n.dirty()):fD.assertNever(a);return{status:n.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,sv.toString(r))}gt(t,r){return this.setLimit("min",t,!1,sv.toString(r))}lte(t,r){return this.setLimit("max",t,!0,sv.toString(r))}lt(t,r){return this.setLimit("max",t,!1,sv.toString(r))}setLimit(t,r,i,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:i,message:sv.toString(n)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:sv.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:sv.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:sv.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:sv.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:sv.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:sv.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:sv.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:sv.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:sv.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&fD.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let i of this._def.checks){if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;i.kind==="min"?(r===null||i.value>r)&&(r=i.value):i.kind==="max"&&(t===null||i.value<t)&&(t=i.value)}return Number.isFinite(r)&&Number.isFinite(t)}};pnn.create=e=>new pnn({checks:[],typeName:dg.ZodNumber,coerce:e?.coerce||!1,...tj(e)});var _nn=class e extends Pw{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==U_.bigint)return this._getInvalidInput(t);let i,n=new WH;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?t.data<a.value:t.data<=a.value)&&(i=this._getOrReturnCtx(t,i),Rp(i,{code:td.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?t.data>a.value:t.data>=a.value)&&(i=this._getOrReturnCtx(t,i),Rp(i,{code:td.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="multipleOf"?t.data%a.value!==BigInt(0)&&(i=this._getOrReturnCtx(t,i),Rp(i,{code:td.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):fD.assertNever(a);return{status:n.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return Rp(r,{code:td.invalid_type,expected:U_.bigint,received:r.parsedType}),W0}gte(t,r){return this.setLimit("min",t,!0,sv.toString(r))}gt(t,r){return this.setLimit("min",t,!1,sv.toString(r))}lte(t,r){return this.setLimit("max",t,!0,sv.toString(r))}lt(t,r){return this.setLimit("max",t,!1,sv.toString(r))}setLimit(t,r,i,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:i,message:sv.toString(n)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:sv.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:sv.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:sv.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:sv.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:sv.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};_nn.create=e=>new _nn({checks:[],typeName:dg.ZodBigInt,coerce:e?.coerce??!1,...tj(e)});var hnn=class extends Pw{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==U_.boolean){let i=this._getOrReturnCtx(t);return Rp(i,{code:td.invalid_type,expected:U_.boolean,received:i.parsedType}),W0}return eK(t.data)}};hnn.create=e=>new hnn({typeName:dg.ZodBoolean,coerce:e?.coerce||!1,...tj(e)});var ynn=class e extends Pw{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==U_.date){let a=this._getOrReturnCtx(t);return Rp(a,{code:td.invalid_type,expected:U_.date,received:a.parsedType}),W0}if(Number.isNaN(t.data.getTime())){let a=this._getOrReturnCtx(t);return Rp(a,{code:td.invalid_date}),W0}let i=new WH,n;for(let a of this._def.checks)a.kind==="min"?t.data.getTime()<a.value&&(n=this._getOrReturnCtx(t,n),Rp(n,{code:td.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),i.dirty()):a.kind==="max"?t.data.getTime()>a.value&&(n=this._getOrReturnCtx(t,n),Rp(n,{code:td.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),i.dirty()):fD.assertNever(a);return{status:i.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:sv.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:sv.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};ynn.create=e=>new ynn({checks:[],coerce:e?.coerce||!1,typeName:dg.ZodDate,...tj(e)});var _Jn=class extends Pw{_parse(t){if(this._getType(t)!==U_.symbol){let i=this._getOrReturnCtx(t);return Rp(i,{code:td.invalid_type,expected:U_.symbol,received:i.parsedType}),W0}return eK(t.data)}};_Jn.create=e=>new _Jn({typeName:dg.ZodSymbol,...tj(e)});var vnn=class extends Pw{_parse(t){if(this._getType(t)!==U_.undefined){let i=this._getOrReturnCtx(t);return Rp(i,{code:td.invalid_type,expected:U_.undefined,received:i.parsedType}),W0}return eK(t.data)}};vnn.create=e=>new vnn({typeName:dg.ZodUndefined,...tj(e)});var bnn=class extends Pw{_parse(t){if(this._getType(t)!==U_.null){let i=this._getOrReturnCtx(t);return Rp(i,{code:td.invalid_type,expected:U_.null,received:i.parsedType}),W0}return eK(t.data)}};bnn.create=e=>new bnn({typeName:dg.ZodNull,...tj(e)});var PNi=class extends Pw{constructor(){super(...arguments),this._any=!0}_parse(t){return eK(t.data)}};PNi.create=e=>new PNi({typeName:dg.ZodAny,...tj(e)});var Hmi=class extends Pw{constructor(){super(...arguments),this._unknown=!0}_parse(t){return eK(t.data)}};Hmi.create=e=>new Hmi({typeName:dg.ZodUnknown,...tj(e)});var sQt=class extends Pw{_parse(t){let r=this._getOrReturnCtx(t);return Rp(r,{code:td.invalid_type,expected:U_.never,received:r.parsedType}),W0}};sQt.create=e=>new sQt({typeName:dg.ZodNever,...tj(e)});var hJn=class extends Pw{_parse(t){if(this._getType(t)!==U_.undefined){let i=this._getOrReturnCtx(t);return Rp(i,{code:td.invalid_type,expected:U_.void,received:i.parsedType}),W0}return eK(t.data)}};hJn.create=e=>new hJn({typeName:dg.ZodVoid,...tj(e)});var $mi=class e extends Pw{_parse(t){let{ctx:r,status:i}=this._processInputParams(t),n=this._def;if(r.parsedType!==U_.array)return Rp(r,{code:td.invalid_type,expected:U_.array,received:r.parsedType}),W0;if(n.exactLength!==null){let u=r.data.length>n.exactLength.value,l=r.data.length<n.exactLength.value;(u||l)&&(Rp(r,{code:u?td.too_big:td.too_small,minimum:l?n.exactLength.value:void 0,maximum:u?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),i.dirty())}if(n.minLength!==null&&r.data.length<n.minLength.value&&(Rp(r,{code:td.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),i.dirty()),n.maxLength!==null&&r.data.length>n.maxLength.value&&(Rp(r,{code:td.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),i.dirty()),r.common.async)return Promise.all([...r.data].map((u,l)=>n.type._parseAsync(new W3e(r,u,r.path,l)))).then(u=>WH.mergeArray(i,u));let a=[...r.data].map((u,l)=>n.type._parseSync(new W3e(r,u,r.path,l)));return WH.mergeArray(i,a)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:sv.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:sv.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:sv.toString(r)}})}nonempty(t){return this.min(1,t)}};$mi.create=(e,t)=>new $mi({type:e,minLength:null,maxLength:null,exactLength:null,typeName:dg.ZodArray,...tj(t)});function pJn(e){if(e instanceof uue){let t={};for(let r in e.shape){let i=e.shape[r];t[r]=V3e.create(pJn(i))}return new uue({...e._def,shape:()=>t})}else return e instanceof $mi?new $mi({...e._def,type:pJn(e.element)}):e instanceof V3e?V3e.create(pJn(e.unwrap())):e instanceof hor?hor.create(pJn(e.unwrap())):e instanceof _or?_or.create(e.items.map(t=>pJn(t))):e}var uue=class e extends Pw{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=fD.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==U_.object){let s=this._getOrReturnCtx(t);return Rp(s,{code:td.invalid_type,expected:U_.object,received:s.parsedType}),W0}let{status:i,ctx:n}=this._processInputParams(t),{shape:a,keys:u}=this._getCached(),l=[];if(!(this._def.catchall instanceof sQt&&this._def.unknownKeys==="strip"))for(let s in n.data)u.includes(s)||l.push(s);let d=[];for(let s of u){let o=a[s],c=n.data[s];d.push({key:{status:"valid",value:s},value:o._parse(new W3e(n,c,n.path,s)),alwaysSet:s in n.data})}if(this._def.catchall instanceof sQt){let s=this._def.unknownKeys;if(s==="passthrough")for(let o of l)d.push({key:{status:"valid",value:o},value:{status:"valid",value:n.data[o]}});else if(s==="strict")l.length>0&&(Rp(n,{code:td.unrecognized_keys,keys:l}),i.dirty());else if(s!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let s=this._def.catchall;for(let o of l){let c=n.data[o];d.push({key:{status:"valid",value:o},value:s._parse(new W3e(n,c,n.path,o)),alwaysSet:o in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let s=[];for(let o of d){let c=await o.key,b=await o.value;s.push({key:c,value:b,alwaysSet:o.alwaysSet})}return s}).then(s=>WH.mergeObjectSync(i,s)):WH.mergeObjectSync(i,d)}get shape(){return this._def.shape()}strict(t){return sv.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,i)=>{let n=this._def.errorMap?.(r,i).message??i.defaultError;return r.code==="unrecognized_keys"?{message:sv.errToObj(t).message??n}:{message:n}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:dg.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};for(let i of fD.objectKeys(t))t[i]&&this.shape[i]&&(r[i]=this.shape[i]);return new e({...this._def,shape:()=>r})}omit(t){let r={};for(let i of fD.objectKeys(this.shape))t[i]||(r[i]=this.shape[i]);return new e({...this._def,shape:()=>r})}deepPartial(){return pJn(this)}partial(t){let r={};for(let i of fD.objectKeys(this.shape)){let n=this.shape[i];t&&!t[i]?r[i]=n:r[i]=n.optional()}return new e({...this._def,shape:()=>r})}required(t){let r={};for(let i of fD.objectKeys(this.shape))if(t&&!t[i])r[i]=this.shape[i];else{let a=this.shape[i];for(;a instanceof V3e;)a=a._def.innerType;r[i]=a}return new e({...this._def,shape:()=>r})}keyof(){return hO_(fD.objectKeys(this.shape))}};uue.create=(e,t)=>new uue({shape:()=>e,unknownKeys:"strip",catchall:sQt.create(),typeName:dg.ZodObject,...tj(t)});uue.strictCreate=(e,t)=>new uue({shape:()=>e,unknownKeys:"strict",catchall:sQt.create(),typeName:dg.ZodObject,...tj(t)});uue.lazycreate=(e,t)=>new uue({shape:e,unknownKeys:"strip",catchall:sQt.create(),typeName:dg.ZodObject,...tj(t)});var gnn=class extends Pw{_parse(t){let{ctx:r}=this._processInputParams(t),i=this._def.options;function n(a){for(let l of a)if(l.result.status==="valid")return l.result;for(let l of a)if(l.result.status==="dirty")return r.common.issues.push(...l.ctx.common.issues),l.result;let u=a.map(l=>new oue(l.ctx.common.issues));return Rp(r,{code:td.invalid_union,unionErrors:u}),W0}if(r.common.async)return Promise.all(i.map(async a=>{let u={...r,common:{...r.common,issues:[]},parent:null};return{result:await a._parseAsync({data:r.data,path:r.path,parent:u}),ctx:u}})).then(n);{let a,u=[];for(let d of i){let s={...r,common:{...r.common,issues:[]},parent:null},o=d._parseSync({data:r.data,path:r.path,parent:s});if(o.status==="valid")return o;o.status==="dirty"&&!a&&(a={result:o,ctx:s}),s.common.issues.length&&u.push(s.common.issues)}if(a)return r.common.issues.push(...a.ctx.common.issues),a.result;let l=u.map(d=>new oue(d));return Rp(r,{code:td.invalid_union,unionErrors:l}),W0}}get options(){return this._def.options}};gnn.create=(e,t)=>new gnn({options:e,typeName:dg.ZodUnion,...tj(t)});var Wmi=e=>e instanceof mnn?Wmi(e.schema):e instanceof H3e?Wmi(e.innerType()):e instanceof Pnn?[e.value]:e instanceof jnn?e.options:e instanceof wnn?fD.objectValues(e.enum):e instanceof Snn?Wmi(e._def.innerType):e instanceof vnn?[void 0]:e instanceof bnn?[null]:e instanceof V3e?[void 0,...Wmi(e.unwrap())]:e instanceof hor?[null,...Wmi(e.unwrap())]:e instanceof i5a||e instanceof Enn?Wmi(e.unwrap()):e instanceof Dnn?Wmi(e._def.innerType):[],Ztu=class e extends Pw{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==U_.object)return Rp(r,{code:td.invalid_type,expected:U_.object,received:r.parsedType}),W0;let i=this.discriminator,n=r.data[i],a=this.optionsMap.get(n);return a?r.common.async?a._parseAsync({data:r.data,path:r.path,parent:r}):a._parseSync({data:r.data,path:r.path,parent:r}):(Rp(r,{code:td.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),W0)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,i){let n=new Map;for(let a of r){let u=Wmi(a.shape[t]);if(!u.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let l of u){if(n.has(l))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(l)}`);n.set(l,a)}}return new e({typeName:dg.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:n,...tj(i)})}};function lwc(e,t){let r=por(e),i=por(t);if(e===t)return{valid:!0,data:e};if(r===U_.object&&i===U_.object){let n=fD.objectKeys(t),a=fD.objectKeys(e).filter(l=>n.indexOf(l)!==-1),u={...e,...t};for(let l of a){let d=lwc(e[l],t[l]);if(!d.valid)return{valid:!1};u[l]=d.data}return{valid:!0,data:u}}else if(r===U_.array&&i===U_.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let a=0;a<e.length;a++){let u=e[a],l=t[a],d=lwc(u,l);if(!d.valid)return{valid:!1};n.push(d.data)}return{valid:!0,data:n}}else return r===U_.date&&i===U_.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Onn=class extends Pw{_parse(t){let{status:r,ctx:i}=this._processInputParams(t),n=(a,u)=>{if(Ytu(a)||Ytu(u))return W0;let l=lwc(a.value,u.value);return l.valid?((Xtu(a)||Xtu(u))&&r.dirty(),{status:r.value,value:l.data}):(Rp(i,{code:td.invalid_intersection_types}),W0)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([a,u])=>n(a,u)):n(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}};Onn.create=(e,t,r)=>new Onn({left:e,right:t,typeName:dg.ZodIntersection,...tj(r)});var _or=class e extends Pw{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==U_.array)return Rp(i,{code:td.invalid_type,expected:U_.array,received:i.parsedType}),W0;if(i.data.length<this._def.items.length)return Rp(i,{code:td.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),W0;!this._def.rest&&i.data.length>this._def.items.length&&(Rp(i,{code:td.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let a=[...i.data].map((u,l)=>{let d=this._def.items[l]||this._def.rest;return d?d._parse(new W3e(i,u,i.path,l)):null}).filter(u=>!!u);return i.common.async?Promise.all(a).then(u=>WH.mergeArray(r,u)):WH.mergeArray(r,a)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};_or.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new _or({items:e,typeName:dg.ZodTuple,rest:null,...tj(t)})};var ktu=class e extends Pw{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==U_.object)return Rp(i,{code:td.invalid_type,expected:U_.object,received:i.parsedType}),W0;let n=[],a=this._def.keyType,u=this._def.valueType;for(let l in i.data)n.push({key:a._parse(new W3e(i,l,i.path,l)),value:u._parse(new W3e(i,i.data[l],i.path,l)),alwaysSet:l in i.data});return i.common.async?WH.mergeObjectAsync(r,n):WH.mergeObjectSync(r,n)}get element(){return this._def.valueType}static create(t,r,i){return r instanceof Pw?new e({keyType:t,valueType:r,typeName:dg.ZodRecord,...tj(i)}):new e({keyType:mNi.create(),valueType:t,typeName:dg.ZodRecord,...tj(r)})}},yJn=class extends Pw{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==U_.map)return Rp(i,{code:td.invalid_type,expected:U_.map,received:i.parsedType}),W0;let n=this._def.keyType,a=this._def.valueType,u=[...i.data.entries()].map(([l,d],s)=>({key:n._parse(new W3e(i,l,i.path,[s,"key"])),value:a._parse(new W3e(i,d,i.path,[s,"value"]))}));if(i.common.async){let l=new Map;return Promise.resolve().then(async()=>{for(let d of u){let s=await d.key,o=await d.value;if(s.status==="aborted"||o.status==="aborted")return W0;(s.status==="dirty"||o.status==="dirty")&&r.dirty(),l.set(s.value,o.value)}return{status:r.value,value:l}})}else{let l=new Map;for(let d of u){let s=d.key,o=d.value;if(s.status==="aborted"||o.status==="aborted")return W0;(s.status==="dirty"||o.status==="dirty")&&r.dirty(),l.set(s.value,o.value)}return{status:r.value,value:l}}}};yJn.create=(e,t,r)=>new yJn({valueType:t,keyType:e,typeName:dg.ZodMap,...tj(r)});var vJn=class e extends Pw{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==U_.set)return Rp(i,{code:td.invalid_type,expected:U_.set,received:i.parsedType}),W0;let n=this._def;n.minSize!==null&&i.data.size<n.minSize.value&&(Rp(i,{code:td.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),r.dirty()),n.maxSize!==null&&i.data.size>n.maxSize.value&&(Rp(i,{code:td.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),r.dirty());let a=this._def.valueType;function u(d){let s=new Set;for(let o of d){if(o.status==="aborted")return W0;o.status==="dirty"&&r.dirty(),s.add(o.value)}return{status:r.value,value:s}}let l=[...i.data.values()].map((d,s)=>a._parse(new W3e(i,d,i.path,s)));return i.common.async?Promise.all(l).then(d=>u(d)):u(l)}min(t,r){return new e({...this._def,minSize:{value:t,message:sv.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:sv.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};vJn.create=(e,t)=>new vJn({valueType:e,minSize:null,maxSize:null,typeName:dg.ZodSet,...tj(t)});var eru=class e extends Pw{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==U_.function)return Rp(r,{code:td.invalid_type,expected:U_.function,received:r.parsedType}),W0;function i(l,d){return r5a({data:l,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,fJn(),Vmi].filter(s=>!!s),issueData:{code:td.invalid_arguments,argumentsError:d}})}function n(l,d){return r5a({data:l,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,fJn(),Vmi].filter(s=>!!s),issueData:{code:td.invalid_return_type,returnTypeError:d}})}let a={errorMap:r.common.contextualErrorMap},u=r.data;if(this._def.returns instanceof jNi){let l=this;return eK(async function(...d){let s=new oue([]),o=await l._def.args.parseAsync(d,a).catch(g=>{throw s.addIssue(i(d,g)),s}),c=await Reflect.apply(u,this,o);return await l._def.returns._def.type.parseAsync(c,a).catch(g=>{throw s.addIssue(n(c,g)),s})})}else{let l=this;return eK(function(...d){let s=l._def.args.safeParse(d,a);if(!s.success)throw new oue([i(d,s.error)]);let o=Reflect.apply(u,this,s.data),c=l._def.returns.safeParse(o,a);if(!c.success)throw new oue([n(o,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:_or.create(t).rest(Hmi.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,i){return new e({args:t||_or.create([]).rest(Hmi.create()),returns:r||Hmi.create(),typeName:dg.ZodFunction,...tj(i)})}},mnn=class extends Pw{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};mnn.create=(e,t)=>new mnn({getter:e,typeName:dg.ZodLazy,...tj(t)});var Pnn=class extends Pw{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return Rp(r,{received:r.data,code:td.invalid_literal,expected:this._def.value}),W0}return{status:"valid",value:t.data}}get value(){return this._def.value}};Pnn.create=(e,t)=>new Pnn({value:e,typeName:dg.ZodLiteral,...tj(t)});function hO_(e,t){return new jnn({values:e,typeName:dg.ZodEnum,...tj(t)})}var jnn=class e extends Pw{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),i=this._def.values;return Rp(r,{expected:fD.joinValues(i),received:r.parsedType,code:td.invalid_type}),W0}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),i=this._def.values;return Rp(r,{received:r.data,code:td.invalid_enum_value,options:i}),W0}return eK(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return e.create(t,{...this._def,...r})}exclude(t,r=this._def){return e.create(this.options.filter(i=>!t.includes(i)),{...this._def,...r})}};jnn.create=hO_;var wnn=class extends Pw{_parse(t){let r=fD.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(t);if(i.parsedType!==U_.string&&i.parsedType!==U_.number){let n=fD.objectValues(r);return Rp(i,{expected:fD.joinValues(n),received:i.parsedType,code:td.invalid_type}),W0}if(this._cache||(this._cache=new Set(fD.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let n=fD.objectValues(r);return Rp(i,{received:i.data,code:td.invalid_enum_value,options:n}),W0}return eK(t.data)}get enum(){return this._def.values}};wnn.create=(e,t)=>new wnn({values:e,typeName:dg.ZodNativeEnum,...tj(t)});var jNi=class extends Pw{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==U_.promise&&r.common.async===!1)return Rp(r,{code:td.invalid_type,expected:U_.promise,received:r.parsedType}),W0;let i=r.parsedType===U_.promise?r.data:Promise.resolve(r.data);return eK(i.then(n=>this._def.type.parseAsync(n,{path:r.path,errorMap:r.common.contextualErrorMap})))}};jNi.create=(e,t)=>new jNi({type:e,typeName:dg.ZodPromise,...tj(t)});var H3e=class extends Pw{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===dg.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:i}=this._processInputParams(t),n=this._def.effect||null,a={addIssue:u=>{Rp(i,u),u.fatal?r.abort():r.dirty()},get path(){return i.path}};if(a.addIssue=a.addIssue.bind(a),n.type==="preprocess"){let u=n.transform(i.data,a);if(i.common.async)return Promise.resolve(u).then(async l=>{if(r.value==="aborted")return W0;let d=await this._def.schema._parseAsync({data:l,path:i.path,parent:i});return d.status==="aborted"?W0:d.status==="dirty"?dnn(d.value):r.value==="dirty"?dnn(d.value):d});{if(r.value==="aborted")return W0;let l=this._def.schema._parseSync({data:u,path:i.path,parent:i});return l.status==="aborted"?W0:l.status==="dirty"?dnn(l.value):r.value==="dirty"?dnn(l.value):l}}if(n.type==="refinement"){let u=l=>{let d=n.refinement(l,a);if(i.common.async)return Promise.resolve(d);if(d instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(i.common.async===!1){let l=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return l.status==="aborted"?W0:(l.status==="dirty"&&r.dirty(),u(l.value),{status:r.value,value:l.value})}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(l=>l.status==="aborted"?W0:(l.status==="dirty"&&r.dirty(),u(l.value).then(()=>({status:r.value,value:l.value}))))}if(n.type==="transform")if(i.common.async===!1){let u=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!ONi(u))return W0;let l=n.transform(u.value,a);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:l}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(u=>ONi(u)?Promise.resolve(n.transform(u.value,a)).then(l=>({status:r.value,value:l})):W0);fD.assertNever(n)}};H3e.create=(e,t,r)=>new H3e({schema:e,typeName:dg.ZodEffects,effect:t,...tj(r)});H3e.createWithPreprocess=(e,t,r)=>new H3e({schema:t,effect:{type:"preprocess",transform:e},typeName:dg.ZodEffects,...tj(r)});var V3e=class extends Pw{_parse(t){return this._getType(t)===U_.undefined?eK(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};V3e.create=(e,t)=>new V3e({innerType:e,typeName:dg.ZodOptional,...tj(t)});var hor=class extends Pw{_parse(t){return this._getType(t)===U_.null?eK(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};hor.create=(e,t)=>new hor({innerType:e,typeName:dg.ZodNullable,...tj(t)});var Snn=class extends Pw{_parse(t){let{ctx:r}=this._processInputParams(t),i=r.data;return r.parsedType===U_.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Snn.create=(e,t)=>new Snn({innerType:e,typeName:dg.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...tj(t)});var Dnn=class extends Pw{_parse(t){let{ctx:r}=this._processInputParams(t),i={...r,common:{...r.common,issues:[]}},n=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return dJn(n)?n.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new oue(i.common.issues)},input:i.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new oue(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}};Dnn.create=(e,t)=>new Dnn({innerType:e,typeName:dg.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...tj(t)});var bJn=class extends Pw{_parse(t){if(this._getType(t)!==U_.nan){let i=this._getOrReturnCtx(t);return Rp(i,{code:td.invalid_type,expected:U_.nan,received:i.parsedType}),W0}return{status:"valid",value:t.data}}};bJn.create=e=>new bJn({typeName:dg.ZodNaN,...tj(e)});var eIE=Symbol("zod_brand"),i5a=class extends Pw{_parse(t){let{ctx:r}=this._processInputParams(t),i=r.data;return this._def.type._parse({data:i,path:r.path,parent:r})}unwrap(){return this._def.type}},n5a=class e extends Pw{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return a.status==="aborted"?W0:a.status==="dirty"?(r.dirty(),dnn(a.value)):this._def.out._parseAsync({data:a.value,path:i.path,parent:i})})();{let n=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return n.status==="aborted"?W0:n.status==="dirty"?(r.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:i.path,parent:i})}}static create(t,r){return new e({in:t,out:r,typeName:dg.ZodPipeline})}},Enn=class extends Pw{_parse(t){let r=this._def.innerType._parse(t),i=n=>(ONi(n)&&(n.value=Object.freeze(n.value)),n);return dJn(r)?r.then(n=>i(n)):i(r)}unwrap(){return this._def.innerType}};Enn.create=(e,t)=>new Enn({innerType:e,typeName:dg.ZodReadonly,...tj(t)});function fO_(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function yO_(e,t={},r){return e?PNi.create().superRefine((i,n)=>{let a=e(i);if(a instanceof Promise)return a.then(u=>{if(!u){let l=fO_(t,i),d=l.fatal??r??!0;n.addIssue({code:"custom",...l,fatal:d})}});if(!a){let u=fO_(t,i),l=u.fatal??r??!0;n.addIssue({code:"custom",...u,fatal:l})}}):PNi.create()}var tIE={object:uue.lazycreate},dg;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(dg||(dg={}));var rIE=(e,t={message:`Input not instance of ${e.name}`})=>yO_(r=>r instanceof e,t),vO_=mNi.create,bO_=pnn.create,iIE=bJn.create,nIE=_nn.create,gO_=hnn.create,aIE=ynn.create,oIE=_Jn.create,uIE=vnn.create,sIE=bnn.create,cIE=PNi.create,lIE=Hmi.create,fIE=sQt.create,dIE=hJn.create,pIE=$mi.create,_IE=uue.create,hIE=uue.strictCreate,yIE=gnn.create,vIE=Ztu.create,bIE=Onn.create,gIE=_or.create,OIE=ktu.create,mIE=yJn.create,PIE=vJn.create,jIE=eru.create,wIE=mnn.create,SIE=Pnn.create,DIE=jnn.create,EIE=wnn.create,MIE=jNi.create,AIE=H3e.create,qIE=V3e.create,TIE=hor.create,CIE=H3e.createWithPreprocess,BIE=n5a.create,IIE=()=>vO_().optional(),zIE=()=>bO_().optional(),RIE=()=>gO_().optional(),xIE={string:e=>mNi.create({...e,coerce:!0}),number:e=>pnn.create({...e,coerce:!0}),boolean:e=>hnn.create({...e,coerce:!0}),bigint:e=>_nn.create({...e,coerce:!0}),date:e=>ynn.create({...e,coerce:!0})};var NIE=W0;var FIE=$3e.object({snake:$3e.string().optional(),camel:$3e.string().optional(),screamingSnake:$3e.string().optional(),pascal:$3e.string().optional()}),LIE=$3e.object({description:$3e.string().optional(),name:$3e.string().optional(),casing:FIE.optional()}),OO_=$3e.record(LIE);var tru=class extends Yg{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=OO_.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 Mnn=class extends Yg{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 rru=class extends Yg{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 iru=class extends Yg{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 nru=class extends Yg{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 aru=class extends Yg{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 oru=class extends Yg{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 cQt=class extends e_{ir;audiences;irGraph;constructor({breadcrumbs:t=[],context:r,audiences:i}){super({breadcrumbs:t,context:r}),this.audiences=i,this.irGraph=new lnn(i),this.ir={auth:{docs:void 0,requirement:Vs.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:Vs.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}}removeXFernIgnores({document:t,breadcrumbs:r=[]}){return Array.isArray(t)?t.filter((i,n)=>!new Mnn({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 Mnn({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=ewc({ir:t,exampleGeneration:r});if(this.context.generateV1Examples){let n=e5a({ir:t,exampleGeneration:r});return{...t,...n,...i}}return{...t,...i}}filterIrForAudiences(t){let r=this.irGraph.getFilteredEndpoints(),i=this.irGraph.getFilteredChannels(),n=this.irGraph.getFilteredWebhooks();for(let a of Object.values(t.services)){let u=[];for(let l of a.endpoints)r.has(l.id)&&u.push(l);a.endpoints=u}return t.websocketChannels=Object.fromEntries(Object.entries(t.websocketChannels??{}).filter(([a])=>i.has(a))),t.webhookGroups=Object.fromEntries(Object.entries(t.webhookGroups).filter(([a])=>n.has(a))),t}async resolveAllExternalRefs({spec:t}){let r=[t];for(;r.length>0;){let i=r.shift();i!=null&&(Array.isArray(i)?await this.resolveExternalRefsInArray(i,r):typeof i=="object"&&await this.resolveExternalRefsInObject(i,r))}return t}async resolveExternalRefsInArray(t,r){for(let i=0;i<t.length;i++)t[i]=await this.resolveReferenceChain(t[i],r)}async resolveExternalRefsInObject(t,r){for(let[i,n]of Object.entries(t))t[i]=await this.resolveReferenceChain(n,r)}async resolveReferenceChain(t,r){let i=t;if(!this.context.isReferenceObject(i))return r.push(i),t;for(;this.context.isReferenceObject(i);){let n=this.context.isExternalReference(i.$ref),a=await this.context.resolveMaybeExternalReference(i);if(a.resolved){if(i=a.value,n)return i}else return t}return t}shouldAddServerToCollectedServers({server:t,currentServers:r,specType:i="openapi"}){return i==="openapi"?!r.some(n=>n.url===t.url&&"x-fern-server-name"in n&&"x-fern-server-name"in t&&n["x-fern-server-name"]===t["x-fern-server-name"]):!r.some(n=>n.url===t.url&&"name"in n&&"name"in t&&n.name===t.name)}addEndpointToIr({endpoint:t,audiences:r,endpointGroup:i,endpointGroupDisplayName:n,serviceName:a}){let u=this.context.getGroup({groupParts:i,namespace:this.context.namespace}),l=this.getOrCreatePackage({group:i}),d=[...u].map(c=>this.context.casingsGenerator.generateName(c)),s=d[d.length-1];l.service==null&&(l.service=a??`service_${u.map(c=>S_(c)).join("/")}`),this.ir.services[l.service]==null&&(this.ir.services[l.service]=this.createNewService({allParts:d,finalpart:s,endpointGroupDisplayName:n})),this.ir.services[l.service]?.endpoints.push(t);let o=this.ir.services[l.service];o!=null&&(this.irGraph.addEndpoint(o,t),this.irGraph.markEndpointForAudience(o.name,[t],r))}addWebhookToIr({webhook:t,operationId:r,audiences:i,group:n}){let a=n?.join(".")??r,u=this.getOrCreatePackage({group:n});this.ir.webhookGroups[a]==null&&(this.ir.webhookGroups[a]=[]),this.ir.webhookGroups[a].push(t),u.webhooks=a;let l=this.context.createFernFilepath();this.irGraph.addWebhook(l,t),i!=null&&this.irGraph.markWebhookForAudiences(l,t,i)}addWebsocketChannelToIr({websocketChannel:t,channelPath:r,audiences:i,websocketGroup:n}){let a=S_(n?.join(".")),u=S_(r),l=this.context.namespace?`${S_(this.context.namespace)}/`:"",d=a?`channel_${l}${a}`:`channel_${l}${u}`,s=n?this.getOrCreatePackage({group:n}):this.getOrCreatePackage({group:[u]});this.ir.websocketChannels={...this.ir.websocketChannels,[d]:t},d!==""?s.websocket==null&&(s.websocket=d):this.ir.rootPackage.websocket="";let o=this.context.createFernFilepath();this.irGraph.addChannel(o,d,t),i!=null&&this.irGraph.markChannelForAudiences(o,d,i)}addAuthToIR(t){this.ir.auth=t}addErrorsToIr(t){this.ir.errors=t;for(let r of Object.values(t))this.irGraph.addError(r)}addGlobalHeadersToIr(t){this.ir.headers=t}addEnvironmentsToIr({environmentConfig:t,audiences:r}){if(this.ir.environments=t,r!=null)for(let[i,n]of Object.entries(t??{}))r[i]!=null&&this.irGraph.markEnvironmentForAudiences(n,r[i])}addTypeToRootPackage(t){this.ir.rootPackage.types.push(t)}addTypeToPackage(t){let r=this.context.getGroup({groupParts:[],namespace:this.context.namespace});this.getOrCreatePackage({group:r}).types.push(t)}addTypesToIr(t){Object.assign(this.ir.types,Object.fromEntries(Object.entries(t).map(([r,i])=>[r,i.typeDeclaration])));for(let r of Object.values(t))this.irGraph.addType({declaredTypeName:r.typeDeclaration.name,descendantTypeIds:r.typeDeclaration.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:r.propertiesByAudience,descendantFilepaths:new Set}),this.irGraph.markTypeForAudiences(r.typeDeclaration.name,r.audiences)}updateEndpointsWithDefaultUrl(t){if(t!=null)for(let r of Object.values(this.ir.services))for(let i of r.endpoints)i.baseUrl==null&&(i.baseUrl=t)}createNewService({allParts:t,finalpart:r,endpointGroupDisplayName:i}){return{name:{fernFilepath:{allParts:t,packagePath:t.slice(0,-1),file:r}},displayName:i,basePath:WF(""),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=>S_(n))),r.length==0)return this.ir.rootPackage;let i=this.ir.rootPackage;for(let n=0;n<r.length;n++){let a=r[n]??"",l=`subpackage_${r.slice(0,n+1).join("/")}`;this.ir.subpackages[l]==null&&(this.ir.subpackages[l]={name:this.context.casingsGenerator.generateName(a),displayName:void 0,...this.createPackage({name:a})});let d=this.ir.subpackages[l];i.subpackages.includes(l)||i.subpackages.push(l),i=d}return i}};var tA={};Po(tA,{AbstractConverters:()=>dwc,ExampleConverter:()=>G3e,SchemaConverters:()=>fwc,ServersConverter:()=>QAe});var dwc={};Po(dwc,{AbstractMediaTypeObjectConverter:()=>lru,AbstractParameterConverter:()=>fru});var G3e=class e extends e_{MAX_DEPTH=12;EXAMPLE_STRING=Ch.STRING;EXAMPLE_NUMBER=Ch.DOUBLE;EXAMPLE_BOOLEAN=Ch.BOOLEAN;EXAMPLE_INTEGER=Ch.INT;EXAMPLE_DATE=Ch.DATE;EXAMPLE_DATE_TIME=Ch.DATE_TIME;schema;example;depth;exampleGenerationStrategy;generateOptionalProperties;seenRefs;constructor({breadcrumbs:t,context:r,schema:i,example:n,depth:a=0,exampleGenerationStrategy:u,generateOptionalProperties:l=!1,seenRefs:d=new Set}){super({breadcrumbs:t,context:r}),this.example=n,this.schema=i,this.depth=a,this.exampleGenerationStrategy=u,this.generateOptionalProperties=l,this.seenRefs=d}convert(){if(this.depth>this.MAX_DEPTH)return{isValid:!0,coerced:!1,validExample:typeof this.example<"u"?this.example:{},errors:[]};if(this.context.isReferenceObject(this.schema)){let r=this.schema.$ref;if(this.seenRefs.has(r))return{isValid:!0,coerced:!1,validExample:this.example,errors:[]}}let t=this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});return t==null?{isValid:!1,coerced:!1,validExample:null,errors:[{message:"Schema is not resolvable",path:this.breadcrumbs}]}:typeof t!="object"?{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Schema should be an object: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]}:"nullable"in t&&t.nullable===!0&&this.example===null?{isValid:!0,coerced:!1,validExample:this.example,errors:[]}:Array.isArray(t.type)?this.convertSchemaTypeArray({resolvedSchema:t}):t.type=="null"?this.convertNull():t.type=="boolean"?this.convertBoolean():t.enum!=null?this.convertEnum(t):t.type=="number"?this.convertNumber():t.type=="string"?this.convertString():t.type=="integer"?this.convertInteger():t.type=="array"?this.convertArray({resolvedSchema:t}):"oneOf"in t&&t.oneOf!=null?this.convertOneOf({resolvedSchema:t}):"anyOf"in t&&t.anyOf!=null?this.convertAnyOf({resolvedSchema:t}):t.type=="object"||t.properties!=null||t.allOf!=null?this.convertObject({resolvedSchema:t}):typeof t=="object"&&Object.keys(t).length===0?{isValid:!0,coerced:!1,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Unsupported schema type: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]}}convertNull(){let t=this.example===null;return t?{isValid:t,coerced:!1,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Example is not null: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertBoolean(){let t=typeof this.example=="boolean";if(t)return{isValid:t,coerced:!1,validExample:this.example,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.default:this.schema.default,i=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.const:this.schema.const;return typeof r=="boolean"||typeof i=="boolean"?{isValid:!0,coerced:!1,validExample:i??r,errors:[]}:{isValid:!1,coerced:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_BOOLEAN,errors:[{message:`Example is not a boolean: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertEnum(t){let r=t.enum?.includes(this.example)??!1;if(r)return{isValid:r,coerced:!1,validExample:this.example,errors:[]};let i=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return i!==void 0&&t.enum?.includes(i)?{isValid:!0,coerced:!1,validExample:i,errors:[]}:{isValid:r,coerced:!1,validExample:t.enum?.[0],errors:[{message:`Example is not one of the allowed enum values: ${JSON.stringify(t.enum,null,2)}`,path:this.breadcrumbs}]}}convertNumber(){if(typeof this.example=="number")return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};let t=Number(this.example);if(!isNaN(t))return{isValid:!0,coerced:!0,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return typeof r=="number"?{isValid:!0,coerced:!1,validExample:r,errors:[]}:{isValid:!1,coerced:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_NUMBER,errors:[{message:`Example is not a number: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertString(){if(typeof this.example=="string")return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};if(typeof this.example!="object"&&!Array.isArray(this.example)&&this.example!=null)return{isValid:!0,coerced:!0,validExample:String(this.example),errors:[]};let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;if(typeof t=="string")return{isValid:!0,coerced:!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,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,validExample:this.example,errors:[]};if(typeof this.example=="string"){let r=Number(this.example);if(!isNaN(r)&&Number.isInteger(r))return{isValid:!0,coerced:!0,validExample:r,errors:[]}}let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return typeof t=="number"&&Number.isInteger(t)?{isValid:!0,coerced:!1,validExample:t,errors:[]}:{isValid:!1,coerced:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_INTEGER,errors:[{message:`Example is not an integer: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertArray({resolvedSchema:t}){if(t.type!="array")return{isValid:!1,coerced:!1,validExample:null,errors:[]};t.items==null&&(t.items={type:"string"});let r=this.example==null,i=this.example??t.example,a=(Array.isArray(i)?i:[i]).map(l=>new e({breadcrumbs:[...this.breadcrumbs,"items"],context:this.context,schema:t.items,example:l,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),u=a.every(l=>l?.isValid??!1)&&!r;return{isValid:u,coerced:!1,validExample:a.map(l=>l.validExample),errors:u?[]:a.flatMap(l=>l.errors)}}convertObject({resolvedSchema:t}){if(t.type=="object"&&t.properties==null&&t.allOf==null)return{isValid:!0,coerced:!1,validExample:this.example??{},errors:[]};let r=typeof this.example!="object"||this.example==null?{}:this.example,i=Object.entries(t.properties??{}).map(([d,s])=>{if(typeof s!="object")return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if(this.isDeprecatedProperty(s)&&!this.isRequiredProperty({key:d,resolvedSchema:t}))return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("readOnly"in s&&s.readOnly===!0&&"writeOnly"in s&&s.writeOnly===!0)return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("readOnly"in s&&s.readOnly===!0&&this.exampleGenerationStrategy==="request")return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("writeOnly"in s&&s.writeOnly===!0&&this.exampleGenerationStrategy==="response")return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};let o=!(d in r)||!("nullable"in s)&&r[d]==null||"nullable"in s&&s.nullable===!0&&r[d]===void 0,c=!t.required?.includes(d);if(o&&c){if(this.example===void 0&&this.generateOptionalProperties){let b=new e({breadcrumbs:[...this.breadcrumbs,d],context:this.context,schema:s,example:void 0,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()});return{key:d,result:b.convert()}}return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}}}else{let g=new e({breadcrumbs:[...this.breadcrumbs,d],context:this.context,schema:s,example:r[d],depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();return{key:d,result:g}}}),n=(t.allOf??[]).map((d,s)=>new e({breadcrumbs:[...this.breadcrumbs,`allOf[${s}]`],context:this.context,schema:{...t,...d,allOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),a=i.every(d=>d.result.isValid)&&n.every(d=>d.isValid),u=Object.fromEntries(i.map(({key:d,result:s})=>[d,s.validExample]).filter(([d,s])=>s!==void 0));for(let d of n)if(typeof d.validExample=="object"&&d.validExample!==null){let s=d.validExample;u={...u,...Object.fromEntries(Object.entries(s).filter(([o,c])=>c!==void 0))}}let l=[];if(t.additionalProperties!==!1){let d=typeof t.additionalProperties=="object"?t.additionalProperties:{oneOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"object"},{type:"array"}]},s=new Set(Object.keys(u??{}));Object.keys(r).filter(c=>!s.has(c)).forEach(c=>{let g=new e({breadcrumbs:[...this.breadcrumbs,c],context:this.context,schema:d,example:r[c],depth:this.depth+1,generateOptionalProperties:!1,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();l.push({key:c,result:g})})}for(let{key:d,result:s}of l)s.validExample!==void 0&&u[d]===void 0&&(u[d]=s.validExample);if(Object.keys(u).length===0){let d=n.find(s=>s.validExample!==void 0&&(typeof s.validExample!="object"||s.validExample===null));d&&(u=d.validExample)}return{isValid:a,coerced:!1,validExample:u,errors:[...i.flatMap(({result:d})=>d.errors),...n.flatMap(d=>d.errors)]}}convertSchemaTypeArray({resolvedSchema:t}){if(!Array.isArray(t.type))return{isValid:!1,coerced:!1,validExample:null,errors:[]};if(t.type.length===1)return new e({breadcrumbs:this.breadcrumbs,context:this.context,schema:{...t,type:t.type[0]},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();let r=t.type.map((u,l)=>new e({breadcrumbs:[...this.breadcrumbs,`type[${l}]`],context:this.context,schema:{...t,type:u},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),i=r.some(u=>u?.isValid??!1),a=r.find(u=>u.isValid)?.validExample??r[0]?.validExample??null;return{isValid:i,coerced:!1,validExample:a,errors:i?[]:r.flatMap(u=>u?.errors??[])}}convertOneOf({resolvedSchema:t}){if(!("oneOf"in t)||t.oneOf==null)return{isValid:!1,coerced:!1,validExample:null,errors:[]};let r=t.oneOf.map((u,l)=>new e({breadcrumbs:[...this.breadcrumbs,`oneOf[${l}]`],context:this.context,schema:{...t,...u,oneOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),i=r.filter(u=>u.isValid),n=i.length>0,a;return n?a=i.find(l=>!l.coerced)?.validExample??i[0]?.validExample:a=r[0]?.validExample,{isValid:n,coerced:!1,validExample:a,errors:n?[]:r.flatMap(u=>u.errors)}}convertAnyOf({resolvedSchema:t}){if(!("anyOf"in t)||t.anyOf==null)return{isValid:!1,coerced:!1,validExample:null,errors:[]};let r=t.anyOf.map((u,l)=>new e({breadcrumbs:[...this.breadcrumbs,`anyOf[${l}]`],context:this.context,schema:u,example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),i=r.filter(u=>u.isValid),n=i.length>0,a;return n?a=i.find(l=>!l.coerced)?.validExample??i[0]?.validExample:a=r[0]?.validExample,{isValid:n,coerced:!1,validExample:a,errors:n?[]:r.flatMap(u=>u.errors)}}getMaybeUpdatedSeenRefs(){let t=new Set(this.seenRefs);return this.context.isReferenceObject(this.schema)&&t.add(this.schema.$ref),t}maybeResolveSchemaExample(t){let r=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(r!=null){if("example"in r)return r.example;if("examples"in r)return Object.values(r.examples??{})[0]}}isDeprecatedProperty(t){return t!=null&&"availability"in t&&t.availability==="deprecated"}isRequiredProperty({key:t,resolvedSchema:r}){return r.required?.includes(t)??!1}};var fwc={};Po(fwc,{ArraySchemaConverter:()=>jJn,EnumSchemaConverter:()=>gJn,ObjectSchemaConverter:()=>OJn,OneOfSchemaConverter:()=>mJn,PrimitiveSchemaConverter:()=>PJn,SchemaConverter:()=>wNi,SchemaOrReferenceConverter:()=>tK});function mO_(e){return Y3({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return Xc.primitive({v1:"BASE_64",v2:Td.base64({})});case"BOOLEAN":return Xc.primitive({v1:"BOOLEAN",v2:Td.boolean({default:void 0})});case"DATE":return Xc.primitive({v1:"DATE",v2:Td.date({})});case"DATE_TIME":return Xc.primitive({v1:"DATE_TIME",v2:Td.dateTime({})});case"FLOAT":return Xc.primitive({v1:"FLOAT",v2:Td.float({})});case"DOUBLE":return Xc.primitive({v1:"DOUBLE",v2:Td.double({default:void 0,validation:void 0})});case"UINT":return Xc.primitive({v1:"UINT",v2:Td.uint({})});case"UINT_64":return Xc.primitive({v1:"UINT_64",v2:Td.uint64({})});case"INTEGER":return Xc.primitive({v1:"INTEGER",v2:Td.integer({default:void 0,validation:void 0})});case"LONG":return Xc.primitive({v1:"LONG",v2:Td.long({default:void 0})});case"STRING":return Xc.primitive({v1:"STRING",v2:Td.string({default:void 0,validation:void 0})});case"UUID":return Xc.primitive({v1:"UUID",v2:Td.uuid({})});case"BIG_INTEGER":return Xc.primitive({v1:"BIG_INTEGER",v2:Td.bigInteger({default:void 0})});default:return}},unknown:()=>Xc.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return Xc.container(Ry.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return Xc.container(Ry.list(t))},optional:t=>{if(t!=null)return Xc.container(Ry.optional(t))},nullable:t=>{if(t!=null)return Xc.container(Ry.nullable(t))},set:t=>{if(t!=null)return Xc.container(Ry.set(t))},literal:t=>Xc.container(Ry.literal(t._visit({string:r=>jL.string(r),boolean:r=>jL.boolean(r),_other:()=>{throw new Error("Unexpected literal type")}}))),named:()=>{}}})}var gJn=class extends e_{schema;maybeFernEnum;constructor({context:t,breadcrumbs:r,schema:i,maybeFernEnum:n}){super({context:t,breadcrumbs:r}),this.schema=i,this.maybeFernEnum=n}convert(){if(!this.schema.enum)return;let r=this.schema.enum.filter(n=>typeof n=="string"||typeof n=="number").map(n=>{let a=n.toString(),u=this.maybeFernEnum?.[a],l=u?.name??a;return{name:this.context.casingsGenerator.generateNameAndWireValue({name:l,wireValue:a}),docs:u?.description,availability:void 0,casing:u?.casing}});if(r.length===0){this.context.errorCollector.collect({message:`Received enum schema with no valid values: ${JSON.stringify(this.schema)}`,path:this.breadcrumbs});return}let i=this.context.getAsString(this.schema.default);return{type:Vb.enum({default:i!=null?r.find(n=>n.name.wireValue===i):void 0,values:r})}}};var uru=class extends e_{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=Xc.container(Ry.map({keyType:e_.STRING,valueType:Xc.unknown()}));return{type:Vb.alias({aliasOf:t,resolvedType:t}),referencedTypes:new Set,inlinedTypes:{}}}}tryConvertTypedMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean")return;let r=new tK({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schemaOrReferenceOrBoolean}).convert();if(r!=null){let i=Xc.container(Ry.map({keyType:e_.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:Vb.alias({aliasOf:i,resolvedType:i}),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}};function a5a({properties:e,required:t,breadcrumbs:r,context:i,errorCollector:n}){let a=[],u={},l={},d=new Set;for(let[s,o]of Object.entries(e??{})){let c=[...r,"properties",s];if(typeof o!="object"){n.collect({message:`Schema property ${s} should be an object`,path:c});continue}let b=UIE(r,o,i)??i.convertBreadcrumbsToName(c),g="nullable"in o?o.nullable:!1,m=new tK({context:i,breadcrumbs:c,schemaOrReference:o,schemaIdOverride:b,wrapAsOptional:!t.includes(s),wrapAsNullable:g}).convert();if(m!=null){a.push({name:i.casingsGenerator.generateNameAndWireValue({name:s,wireValue:s}),valueType:m.type,docs:o.description,availability:m.availability,propertyAccess:i.getPropertyAccess(o),v2Examples:m.schema?.typeDeclaration?.v2Examples??{userSpecifiedExamples:{},autogeneratedExamples:{}}}),u={...u,...m.inlinedTypes},m.schema?.typeDeclaration.referencedTypes!=null&&m.schema.typeDeclaration.referencedTypes.forEach(w=>{d.add(w)});for(let w of m.schema?.audiences??[])l[w]==null&&(l[w]=new Set),l[w].add(s)}}for(let s of Object.keys(u))d.add(s);return{convertedProperties:a,propertiesByAudience:l,inlinedTypesFromProperties:u,referencedTypes:d}}function UIE(e,t,r){return r.isReferenceObject(t)?void 0:new VH.FernTypeNameExtension({breadcrumbs:e,schema:t,context:r}).convert()}var OJn=class extends e_{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:Vb.object({properties:[],extends:[],extendedProperties:[],extraProperties:t}),propertiesByAudience:{},inlinedTypes:{},referencedTypes:new Set};let{convertedProperties:r,inlinedTypesFromProperties:i,referencedTypes:n,propertiesByAudience:a}=a5a({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector}),u=[],l=n,d=this.schema.required!=null&&this.schema.required.length>0,s=i,o=a;for(let[c,b]of(this.schema.allOf??[]).entries()){let g=[...this.breadcrumbs,"allOf",c.toString()],O;if(this.context.isReferenceObject(b)){if(!d){this.addTypeReferenceToExtends({reference:b,breadcrumbs:g,extends_:u,referencedTypes:l});continue}let M=this.context.resolveMaybeReference({schemaOrReference:b,breadcrumbs:g});if(M==null)continue;if(O=M,Object.keys(O.properties??{}).every(D=>!this.schema.required?.includes(D))){this.addTypeReferenceToExtends({reference:b,breadcrumbs:g,extends_:u,referencedTypes:l});continue}}else O=b;let{convertedProperties:m,inlinedTypesFromProperties:w,referencedTypes:E,propertiesByAudience:q}=a5a({properties:O.properties??{},required:[...this.schema.required??[],...O.required??[]],breadcrumbs:g,context:this.context,errorCollector:this.context.errorCollector});r.push(...m),s={...s,...w},o={...o,...q},E.forEach(M=>{l.add(M)})}for(let c of Object.keys(s))l.add(c);return{type:Vb.object({properties:r,extends:u.map(c=>this.context.typeReferenceToDeclaredTypeName(c)).filter(iv),extendedProperties:[],extraProperties:t}),propertiesByAudience:o,referencedTypes:l,inlinedTypes:s}}addTypeReferenceToExtends({reference:t,breadcrumbs:r,extends_:i,referencedTypes:n}){let a=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:r});a.ok&&i.push(a.reference);let u=this.context.getTypeIdFromSchemaReference(t);u!=null&&n.add(u)}};var sru=class extends Yg{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 cru;(function(e){function t(s,o){if(s.title)return s.title;if(s.typeName)return r(s.typeName);if(s.description){let c=i(s.description);if(c)return c}if(s.type==="object"&&s.properties&&Object.keys(s.properties).length>0){let c=a(s,o);if(c)return c}}e.generateDisplayNameForInlinedObject=t;function r(s){return s&&(s.includes("_")?s.split("_").map(o=>o.charAt(0).toUpperCase()+o.slice(1).toLowerCase()).join(""):s.charAt(0).toUpperCase()+s.slice(1))}e.convertToPascalCase=r;function i(s){let o=s?.split(".")[0]?.trim();if(!o)return;let c=new Set(["a","an","the","and","or","but","nor","yet","so","in","on","at","to","for","of","with","by","from","up","about","into","through","during","before","after","above","below","between","among","under","over","across","against","along","around","behind","beneath","beside","beyond","down","inside","near","off","outside","since","toward","until","upon","within","without","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","must","can","shall","this","that","these","those","it","its","they","them","their","when","where","why","how","what","which","who","whom","whose","used","using","containing","including","having","showing","providing","created","generated","processed","stored","managed","handled","returned","sent","received","given","taken","made","done","called","named","available","current","existing","present","new","old","main","primary","secondary","additional","extra","special","specific","general","common","basic","simple","complex","full","empty","complete","partial","also","then","now","here","there","only","just","even","still","already","always","never","sometimes","often","usually","mostly"]),b=o.replace(/[^a-zA-Z0-9\s]/g,"").trim().split(/\s+/).filter(m=>m.length>0).filter(m=>!c.has(m.toLowerCase())).slice(0,4);if(b.length===0)return;let O=n(b).map(m=>m.charAt(0).toUpperCase()+m.slice(1).toLowerCase()).join("");return O.length>0?O:void 0}e.cleanDescriptionForDisplayName=i;function n(s){if(s.length<=2)return s;let o=new Set(["system","service","api"]),c=new Set(["object","method","function","interface","model"]),b=[],g=[];return s.forEach(O=>{let m=O.toLowerCase();o.has(m)?g.push(O):c.has(m)&&b.length>0?b.splice(1,0,O):b.push(O)}),b.push(...g),b}e.reorderWordsForBetterSemantics=n;function a(s,o){let c=s.properties;if(!c)return;let b=Object.keys(c);if(b.length===0)return;let g=u(s,o);if(g.length>0){let w=l(g).slice(0,1).map(E=>d(E));if(w.length>0)return w.join("")}let O=l(b);if(O.length>0)return O.slice(0,1).map(w=>d(w)).join("")}e.generateNameFromObjectProperties=a;function u(s,o){let c=s.properties;if(!c)return[];let b=new Set(Object.keys(c)),g=new Set;return o.forEach(O=>{if(O!==s&&O.type==="object"&&O.properties){let m=O.properties;m&&Object.keys(m).forEach(w=>{g.add(w)})}}),Array.from(b).filter(O=>!g.has(O))}e.findUniqueProperties=u;function l(s){let o=["status","error","type","kind","mode","state","action","method","enabled","disabled","active","inactive","success","failed"],c=["config","configuration","setting","option","message","code","user","account","profile","auth","token","key","response","request","result","output","input","payload","body"],b=["name","id","value","data","info"];return s.map(O=>{let m=O.toLowerCase(),w=0;for(let E of o)m===E?w+=15:m.includes(E)&&(w+=10);for(let E of c)m===E?w+=8:m.includes(E)&&(w+=5);for(let E of b)m===E?w+=3:m.includes(E)&&(w+=2);return w+=Math.max(0,5-O.length),{prop:O,score:w}}).sort((O,m)=>O.score!==m.score?m.score-O.score:O.prop.localeCompare(m.prop)).map(O=>O.prop)}e.getMostSignificantProperties=l;function d(s){return s.includes("_")?s.split("_").map(o=>o.charAt(0).toUpperCase()+o.slice(1).toLowerCase()).join(""):s.charAt(0).toUpperCase()+s.slice(1)}e.capitalizePropertyName=d})(cru||(cru={}));var mJn=class extends e_{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 sru({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 o=new tK({context:this.context,schemaOrReference:{$ref:s},breadcrumbs:[...this.breadcrumbs,"discriminator","mapping",d]}),c=this.context.getTypeIdFromSchemaReference({$ref:s});c!=null&&r.add(c);let b=o.convert();if(b?.type!=null&&c!=null){for(let O of Object.keys(b?.inlinedTypes??{}))r.add(O);for(let O of b.schema?.typeDeclaration.referencedTypes??[])r.add(O);let g=this.context.casingsGenerator.generateNameAndWireValue({name:d,wireValue:d});t.push({docs:void 0,discriminantValue:g,availability:b.availability,displayName:d,shape:PL.samePropertiesAsObject({typeId:c,name:this.context.casingsGenerator.generateName(c),fernFilepath:{allParts:[],packagePath:[],file:void 0},displayName:d})}),i={...i,...b.inlinedTypes}}}let{convertedProperties:n,referencedTypes:a,inlinedTypesFromProperties:u}=a5a({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector});r=new Set([...r,...a]);let l=[];for(let[d,s]of(this.schema.allOf??[]).entries()){let o=[...this.breadcrumbs,"allOf",d.toString()];if(this.context.isReferenceObject(s)){let c=this.context.convertReferenceToTypeReference({reference:s,breadcrumbs:o});if(c.ok){let g=this.context.typeReferenceToDeclaredTypeName(c.reference);g!=null&&l.push(g)}let b=this.context.getTypeIdFromSchemaReference(s);b!=null&&r.add(b);continue}}for(let d of Object.keys({...i,...u}))r.add(d);return{type:Vb.union({baseProperties:n,discriminant:this.context.casingsGenerator.generateNameAndWireValue({name:this.schema.discriminator.propertyName,wireValue:this.schema.discriminator.propertyName}),extends:l,types:t}),referencedTypes:r,inlinedTypes:{...i,...u}}}convertAsUndiscriminatedUnion(){if(!this.schema.oneOf&&!this.schema.anyOf||this.schema.anyOf?.length===0&&this.schema.oneOf?.length===0)return;let t=[],r=new Set,i={},n=[...this.schema.oneOf??[],...this.schema.anyOf??[]].filter(a=>!this.context.isReferenceObject(a));for(let[a,u]of[...(this.schema.oneOf??[]).entries(),...(this.schema.anyOf??[]).entries()]){if(this.context.isReferenceObject(u)){let b;if(this.context.isReferenceObjectWithIdentifier(u))b=this.context.convertReferenceToTypeReference({reference:u,displayNameOverride:u.title??u.name??u.messageId,displayNameOverrideSource:"reference_identifier"});else if(this.getDiscriminatorKeyForRef(u)!=null){let O=this.getDiscriminatorKeyForRef(u);b=this.context.convertReferenceToTypeReference({reference:u,displayNameOverride:O,displayNameOverrideSource:"discriminator_key"})}else b=this.context.convertReferenceToTypeReference({reference:u,displayNameOverride:u.$ref.split("/").pop(),displayNameOverrideSource:"schema_identifier"});b.ok&&t.push({type:b.reference,docs:u.description});let g=this.context.getTypeIdFromSchemaReference(u);g!=null&&r.add(g);continue}let l=this.extendSubSchema(u),d=this.context.convertBreadcrumbsToName([`${this.id}_${a}`]),s=cru.generateDisplayNameForInlinedObject({...u,typeName:d},n),c=new wNi({context:this.context,id:d,nameOverride:s,breadcrumbs:[...this.breadcrumbs,`oneOf[${a}]`],schema:l??u}).convert();if(c!=null){let b=c.convertedSchema.typeDeclaration.shape;b.type==="alias"&&this.typeReferenceIsWrappedPrimitive(b.aliasOf)?t.push({type:b.aliasOf,docs:u.description}):b.type==="object"&&b.properties.length===0?t.push({type:Xc.container(Ry.map({keyType:e_.STRING,valueType:Xc.unknown()})),docs:u.description}):(t.push({type:this.context.createNamedTypeReference(d,s),docs:u.description}),i={...i,...c.inlinedTypes,[d]:c.convertedSchema}),c.convertedSchema.typeDeclaration.referencedTypes.forEach(g=>{r.add(g)})}}return{type:Vb.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 tK({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(i==null)return;let n=this.wrapInNullable(i.type);return{type:Vb.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 Xc.container(Ry.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 PJn=class extends e_{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 Xc.container(Ry.literal(jL.string(t)));if(this.context.settings.typeDatesAsStrings===!1){if(this.schema.format==="date")return Xc.primitive({v1:ny.Date,v2:Td.date({})});if(this.schema.format==="date-time")return Xc.primitive({v1:ny.DateTime,v2:Td.dateTime({})})}return Xc.primitive({v1:"STRING",v2:Td.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":switch(this.schema.format){case"double":return Xc.primitive({v1:"DOUBLE",v2:Td.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return Xc.primitive({v1:"FLOAT",v2:Td.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return Xc.primitive({v1:"INTEGER",v2:Td.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return Xc.primitive({v1:"LONG",v2:Td.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return Xc.primitive({v1:"UINT",v2:Td.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return Xc.primitive({v1:"UINT_64",v2:Td.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return Xc.primitive({v1:"DOUBLE",v2:Td.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"integer":switch(this.schema.format){case"double":return Xc.primitive({v1:"DOUBLE",v2:Td.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return Xc.primitive({v1:"FLOAT",v2:Td.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return Xc.primitive({v1:"INTEGER",v2:Td.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return Xc.primitive({v1:"LONG",v2:Td.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return Xc.primitive({v1:"UINT",v2:Td.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return Xc.primitive({v1:"UINT_64",v2:Td.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return Xc.primitive({v1:"INTEGER",v2:Td.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?Xc.container(Ry.literal(jL.boolean(t))):Xc.primitive({v1:"BOOLEAN",v2:Td.boolean({default:this.schema.default})})}default:return}}getNumberValidation(t){return{max:t.maximum,min:t.minimum,exclusiveMax:typeof t.exclusiveMaximum=="boolean"?t.exclusiveMaximum:void 0,exclusiveMin:typeof t.exclusiveMinimum=="boolean"?t.exclusiveMinimum:void 0,multipleOf:t.multipleOf}}getStringValidation(t){return{minLength:t.minLength,maxLength:t.maxLength,pattern:t.pattern,format:t.format}}};var VIE=["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],wNi=class e extends e_{schema;id;inlined;audiences;nameOverride;constructor({context:t,breadcrumbs:r,schema:i,id:n,inlined:a=!1,nameOverride:u}){super({context:t,breadcrumbs:r}),this.schema=i,this.id=n,this.inlined=a,this.nameOverride=u,this.audiences=this.context.getAudiences({operation:this.schema,breadcrumbs:this.breadcrumbs})??[]}convert(){let t=this.tryConvertFernTypeDeclaration();if(t!=null)return t;let r=this.tryConvertEnumSchema();if(r!=null)return r;let i=this.tryConvertSingularAllOfSchema();if(i!=null)return i;let n=this.tryConvertPrimitiveSchema();if(n!=null)return n;let a=this.tryConvertArraySchema();if(a!=null)return a;let u=this.tryConvertTypeArraySchema();if(u!=null)return u;let l=this.tryConvertOneOfAnyOfSchema();if(l!=null)return l;let d=this.tryConvertMapSchema();if(d!=null)return d;let s=this.tryConvertObjectAllOfSchema();if(s!=null)return s;let o=this.tryConvertUntypedSchema();if(o!=null)return o;this.context.errorCollector.collect({message:`Failed to convert schema object: ${JSON.stringify(this.schema,null,2)}`,path:this.breadcrumbs})}tryConvertEnumSchema(){if(!this.schema.enum?.length)return;let r=new VH.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),n=new gJn({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=M8n(r,n,(a,u)=>{if(u===n)return a;if(Array.isArray(a)&&Array.isArray(u))return[...a,...u]})}return new e({context:this.context,breadcrumbs:this.breadcrumbs,schema:r,id:this.id,inlined:!0}).convert()}}tryConvertPrimitiveSchema(){let r=new PJn({context:this.context,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Vb.alias({aliasOf:r,resolvedType:r}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertArraySchema(){if(this.schema.type==="array"){let r=new jJn({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Vb.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 mJn({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 uru({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReferenceOrBoolean:this.schema.additionalProperties}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertObjectAllOfSchema(){if(this.schema.type==="object"||this.schema.properties!=null||this.schema.allOf!=null){let r=new OJn({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:Vb.alias({aliasOf:Xc.unknown(),resolvedType:Xc.unknown()}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertFernTypeDeclaration(){let r=new VH.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r==null)return;let i=mO_(r);if(i!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Vb.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=[...VIE,...t];return Object.keys(this.schema).every(n=>r.includes(n))}isUntypedSchema(){return!!(this.schema&&typeof this.schema=="object"&&!("oneOf"in this.schema)&&!("anyOf"in this.schema)&&!("allOf"in this.schema)&&!("items"in this.schema)&&!("properties"in this.schema))}convertSchemaExamples(){let t={userSpecifiedExamples:{},autogeneratedExamples:{}},r=this.context.getExamplesFromSchema({schema:this.schema,breadcrumbs:this.breadcrumbs});if(r.length===0){let i=this.generateOrValidateExample({example:void 0,ignoreErrors:!0});return t.autogeneratedExamples={[`${this.id}_example_autogenerated`]:i},t}return t.userSpecifiedExamples=this.convertUserSpecifiedExamples(r),t}convertUserSpecifiedExamples(t){let r={};for(let[i,n]of t.entries()){let a=this.context.resolveExample(n),u=this.generateOrValidateExample({example:a});r[`${this.id}_example_${i}`]=u}return r}generateOrValidateExample({example:t,ignoreErrors:r}){let i=new G3e({breadcrumbs:this.breadcrumbs,context:this.context,schema:this.schema,example:t}),{validExample:n,errors:a}=i.convert();return r||a.forEach(u=>{this.context.errorCollector.collect({message:u.message,path:u.path})}),n}};var tK=class extends e_{schemaOrReference;schemaIdOverride;wrapAsOptional;wrapAsNullable;constructor({context:t,breadcrumbs:r,schemaOrReference:i,schemaIdOverride:n,wrapAsOptional:a=!1,wrapAsNullable:u=!1}){super({context:t,breadcrumbs:r}),this.schemaOrReference=i,this.schemaIdOverride=n,this.wrapAsOptional=a,this.wrapAsNullable=u}convert(){let t=this.maybeConvertReferenceObject({schemaOrReference:this.schemaOrReference});if(t!=null)return t;let r=this.maybeConvertSingularAllOfReferenceObject();return r??this.convertSchemaObject({schema:this.schemaOrReference})}maybeConvertReferenceObject({schemaOrReference:t}){if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:r.inlinedTypes??{}}}}maybeConvertSingularAllOfReferenceObject(){if(this.context.isReferenceObject(this.schemaOrReference)||this.schemaOrReference.allOf==null||this.schemaOrReference.allOf.length!==1)return;let t=this.schemaOrReference.allOf[0];if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:{}}}}convertSchemaObject({schema:t}){let r=this.schemaIdOverride??this.context.convertBreadcrumbsToName(this.breadcrumbs),i=new wNi({context:this.context,breadcrumbs:this.breadcrumbs,schema:t,id:r}),n=this.context.getAvailability({node:t,breadcrumbs:this.breadcrumbs}),a=i.convert();if(a!=null){let u=a.convertedSchema.typeDeclaration.shape;return u.type==="alias"?{type:this.wrapTypeReference(u.aliasOf),schema:a.convertedSchema,inlinedTypes:a.inlinedTypes,availability:n}:{type:this.wrapTypeReference(this.context.createNamedTypeReference(r)),schema:a.convertedSchema,inlinedTypes:{...a.inlinedTypes,[r]:a.convertedSchema},availability:n}}}wrapTypeReference(t){return this.wrapAsOptional&&this.wrapAsNullable?this.wrapInOptional(this.wrapInNullable(t)):this.wrapAsOptional?this.wrapInOptional(t):this.wrapAsNullable?this.wrapInNullable(t):t}wrapInOptional(t){return Xc.container(Ry.optional(t))}wrapInNullable(t){return Xc.container(Ry.nullable(t))}};var jJn=class e extends e_{static LIST_UNKNOWN=Xc.container(Ry.list(Xc.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 tK({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:Xc.container(Ry.list(r.type)),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var lru=class extends e_{group;method;constructor({context:t,breadcrumbs:r,group:i,method:n}){super({context:t,breadcrumbs:r}),this.group=i,this.method=n}parseMediaTypeObject({mediaTypeObject:t,resolveSchema:r,contentType:i,schemaId:n}){if(t.schema==null)return;if(r){let d=this.context.resolveMaybeReference({schemaOrReference:t.schema,breadcrumbs:[...this.breadcrumbs,"content",i]});if(d==null)return;t.schema=d}let u=new tK({context:this.context,breadcrumbs:[...this.breadcrumbs,"content",i,"schema"],schemaOrReference:t.schema,schemaIdOverride:n}).convert();if(u==null)return;let l=t.examples!=null?Object.fromEntries(Object.entries(t.examples).map(([d,s])=>{if(this.context.isReferenceObject(s)){let o=this.context.resolveReference({reference:s,breadcrumbs:[...this.breadcrumbs,"content",i,"examples"],skipErrorCollector:!0});return o.resolved?[d,o.value.value??o.value]:null}return[d,s.value??s]}).filter(d=>d!=null)):void 0;return{...u,examples:l}}parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:r}){let n=new tK({context:this.context,breadcrumbs:[...this.breadcrumbs],schemaOrReference:t,schemaIdOverride:r}).convert();if(n!=null)return{...n,examples:void 0}}convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:r,exampleGenerationStrategy:i}){let n={userSpecifiedExamples:{},autogeneratedExamples:{}},a=t?.schema,u=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_example`});for(let[l,d]of u){let s=this.context.resolveExampleWithValue(d),o=this.context.isExampleWithSummary(d)?d.summary:l;s!=null&&(a!=null?n.userSpecifiedExamples[o]=this.generateOrValidateExample({schema:a,example:s,exampleGenerationStrategy:i}):n.userSpecifiedExamples[o]=s)}if(Object.keys(n.userSpecifiedExamples).length===0&&a!=null){let l=S_(`${[...this.group,this.method].join("_")}_example`);n.autogeneratedExamples[l]=this.generateOrValidateExample({schema:a,example:void 0,ignoreErrors:!0,generateOptionalProperties:r,exampleGenerationStrategy:i})}return n}generateOrValidateExample({schema:t,example:r,ignoreErrors:i,generateOptionalProperties:n,exampleGenerationStrategy:a}){let u=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(u==null)return;let l=this.context.getExamplesFromSchema({schema:u,breadcrumbs:this.breadcrumbs}),d=new G3e({breadcrumbs:this.breadcrumbs,context:this.context,schema:u,example:r??l[0],generateOptionalProperties:n??!1,exampleGenerationStrategy:a}),{validExample:s,errors:o}=d.convert();return i||o.forEach(c=>{this.context.errorCollector.collect({message:c.message,path:c.path})}),s}};var fru=class extends e_{parameter;constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r}),this.parameter=i}convertToOutput({schema:t,typeReference:r,inlinedTypes:i}){let n=this.context.getAvailability({node:this.parameter,breadcrumbs:this.breadcrumbs}),a=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs}),u=this.getParameterSchemaWithExampleOverride({schema:a});switch(this.parameter.in){case"query":return{type:"query",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??e_.OPTIONAL_STRING,allowMultiple:this.parameter.explode??!1,v2Examples:this.convertParameterExamples({schema:u??t}),availability:n},inlinedTypes:i};case"header":return{type:"header",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??e_.OPTIONAL_STRING,env:void 0,v2Examples:this.convertParameterExamples({schema:u??t}),availability:n},inlinedTypes:i};case"path":return{type:"path",parameter:{name:this.context.casingsGenerator.generateName(this.parameter.name),docs:this.parameter.description,valueType:r??e_.STRING,location:"ENDPOINT",variable:void 0,v2Examples:this.convertParameterExamples({schema:u??t})},inlinedTypes:i};default:return}}getParameterSchemaWithExampleOverride({schema:t}){if(t!=null)return t.type==="string"&&t.example==null?{...t,example:this.parameter.name}:t}convertParameterExamples({schema:t}){let r={userSpecifiedExamples:{},autogeneratedExamples:{}},i=this.parameter.example,n=this.parameter.examples;for(let[a,u]of Object.entries(n??{})){let l=this.context.resolveExampleWithValue(u);l!=null&&(r.userSpecifiedExamples[a]=this.generateOrValidateExample({schema:t,example:l}))}if(i!=null){let a=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(r.userSpecifiedExamples)});r.userSpecifiedExamples[a]=this.generateOrValidateExample({schema:t,example:i})}if(Object.keys(r.userSpecifiedExamples).length===0){let a=`${this.parameter.name}_example`;r.autogeneratedExamples[a]=this.generateOrValidateExample({schema:t,example:void 0,ignoreErrors:!0})}return r}generateOrValidateExample({schema:t,ignoreErrors:r,example:i}){let n=new G3e({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:i}),{validExample:a,errors:u}=n.convert();return r||u.forEach(l=>{this.context.errorCollector.collect({message:l.message,path:l.path})}),a}};var dru=class extends Yg{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 PO_="Base",QAe=class e extends e_{servers;endpointLevelServers;constructor({breadcrumbs:t,context:r,servers:i,endpointLevelServers:n}){super({breadcrumbs:t,context:r}),this.servers=i,this.endpointLevelServers=n}convert(){if(this.servers==null||this.servers.length===0||this.servers[0]==null)return;if(this.endpointLevelServers!=null&&this.endpointLevelServers.length>0){let r=this.getDefaultBaseUrlName(),i={id:r,name:this.context.casingsGenerator.generateName(r)},n=this.endpointLevelServers.map(l=>{let d=e.getServerName({server:l,context:this.context});return{id:d,name:this.context.casingsGenerator.generateName(d)}}).filter((l,d,s)=>s.findIndex(o=>o.id===l.id)===d),a=[i,...n],u=this.servers.map(l=>{let d=e.getServerName({server:l,context:this.context}),s=this.endpointLevelServers?.map(o=>[e.getServerName({server:o,context:this.context}),this.getServerUrl(o)]);return{id:d,name:this.context.casingsGenerator.generateName(d),urls:{[r]:this.getServerUrl(l),...Object.fromEntries(s??[])},docs:l.description}});return{value:{defaultEnvironment:u[0]?.id,environments:$R.multipleBaseUrls({baseUrls:a,environments:u})},defaultUrl:i.id}}let t=this.withExplodedServers(this.servers).map(r=>{let i=e.getServerName({server:r,context:this.context});return{id:i,name:this.context.casingsGenerator.generateName(i),url:this.maybeRemoveTrailingSlashIfNotEmpty(this.getServerUrl(r)),docs:r.description}}).filter(iv);return{value:{defaultEnvironment:t[0]?.id,environments:$R.singleBaseUrl({environments:t})},defaultUrl:t[0]?.id}}static getServerExtensionName({server:t,context:r}){return new dru({breadcrumbs:[],server:t,context:r}).convert()}static getServerName({server:t,context:r}){return t.name!=null?t.name:e.getServerExtensionName({server:t,context:r})??t.description??t.url}getServerUrl(t){if(t.variables==null)return t.url;let r=t.url;for(let[i,n]of Object.entries(t.variables))n.default!=null&&(r=r.replace(`{${i}}`,encodeURIComponent(n.default)));return r}withExplodedServers(t){return t.flatMap(r=>{if(r.variables==null)return[r];let i=Object.entries(r.variables).filter(([l,d])=>d.enum!=null&&d.enum.length>0);if(i.length===0)return[r];let n=i[0];if(n==null)return[r];let[a,u]=n;return u.enum==null?[r]:u.enum.map(l=>{let d=r.url.replace(`{${a}}`,encodeURIComponent(l)),s={};for(let[c,b]of Object.entries(r.variables??{}))c!==a&&(s[c]=b);let o={...r,url:d,variables:Object.keys(s).length>0?s:void 0,"x-fern-server-name":r.description?`${r.description}_${l}`:`${l}`,description:r.description};return this.withExplodedServers([o])[0]})}).filter(iv)}getDefaultBaseUrlName(){return this.servers==null||this.servers.length===0||this.servers[0]==null?PO_:e.getServerExtensionName({server:this.servers[0],context:this.context})??PO_}maybeRemoveTrailingSlashIfNotEmpty(t){return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}};var o5a={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"},WIE=new Set(Object.values(o5a));var wJn=class{enabled=!0;write(t,...r){this.enabled&&process.stderr.write(`[${t}] ${r.join(" ")}
1914
+ `)),super.launch(t)}async computeLaunchArguments(t={}){let{ignoreDefaultArgs:r=!1,args:i=[],pipe:n=!1,debuggingPort:a,channel:u,executablePath:l}=t,d=[];r?Array.isArray(r)?d.push(...this.defaultArgs(t).filter(g=>!r.includes(g))):d.push(...i):d.push(...this.defaultArgs(t)),d.some(g=>g.startsWith("--remote-debugging-"))||(n?(Zc(!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,o=d.findIndex(g=>g.startsWith("--user-data-dir"));o<0&&(s=!0,d.push(`--user-data-dir=${await(0,tb_.mkdtemp)(this.getProfilePath())}`),o=d.length-1);let c=d[o].split("=",2)[1];Zc(typeof c=="string","`--user-data-dir` is malformed");let b=l;return b||(Zc(u||!this.puppeteer._isPuppeteerCore,"An `executablePath` or `channel` must be specified for `puppeteer-core`"),b=this.executablePath(u)),{executablePath:b,args:d,isTempUserDataDir:s,userDataDir:c}}async cleanUserDataDir(t,r){if(r.isTemp)try{await vQn(t)}catch(i){throw X0(i),i}}defaultArgs(t={}){let r=["--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-component-update","--disable-default-apps","--disable-dev-shm-usage","--disable-extensions","--disable-features=Translate,BackForwardCache,AcceptCHFrame,MediaRouter,OptimizationHints","--disable-hang-monitor","--disable-ipc-flooding-protection","--disable-popup-blocking","--disable-prompt-on-repost","--disable-renderer-backgrounding","--disable-sync","--enable-automation","--enable-blink-features=IdleDetection","--enable-features=NetworkServiceInProcess2","--export-tagged-pdf","--force-color-profile=srgb","--metrics-recording-only","--no-first-run","--password-store=basic","--use-mock-keychain"],{devtools:i=!1,headless:n=!i,args:a=[],userDataDir:u}=t;return u&&r.push(`--user-data-dir=${rb_.default.resolve(u)}`),i&&r.push("--auto-open-devtools-for-tabs"),n&&r.push(n==="new"?"--headless=new":"--headless","--hide-scrollbars","--mute-audio"),a.every(l=>l.startsWith("-"))&&r.push("about:blank"),r.push(...a),r}executablePath(t){return t?neu({browser:Pq.CHROME,channel:aAE(t)}):this.resolveExecutablePath()}};function aAE(e){switch(e){case"chrome":return c7.STABLE;case"chrome-dev":return c7.DEV;case"chrome-beta":return c7.BETA;case"chrome-canary":return c7.CANARY}}var FPc=ui(require("fs"),1),tnn=require("fs/promises"),ib_=ui(require("os"),1),_tu=ui(require("path"),1);eB();FA();var htu=class extends KQn{constructor(t){super(t,"firefox")}async computeLaunchArguments(t={}){let{ignoreDefaultArgs:r=!1,args:i=[],executablePath:n,pipe:a=!1,extraPrefsFirefox:u={},debuggingPort:l=null}=t,d=[];r?Array.isArray(r)?d.push(...this.defaultArgs(t).filter(g=>!r.includes(g))):d.push(...i):d.push(...this.defaultArgs(t)),d.some(g=>g.startsWith("--remote-debugging-"))||(a&&Zc(l===null,"Browser should be launched with either pipe or debugging port - not both."),d.push(`--remote-debugging-port=${l||0}`));let s,o=!0,c=d.findIndex(g=>["-profile","--profile"].includes(g));if(c!==-1){if(s=d[c+1],!s||!FPc.default.existsSync(s))throw new Error(`Firefox profile not found at '${s}'`);o=!1}else s=await(0,tnn.mkdtemp)(this.getProfilePath()),d.push("--profile"),d.push(s);await LOc(Pq.FIREFOX,{path:s,preferences:u});let b;return this.puppeteer._isPuppeteerCore||n?(Zc(n,"An `executablePath` must be specified for `puppeteer-core`"),b=n):b=this.executablePath(),{isTempUserDataDir:o,userDataDir:s,args:d,executablePath:b}}async cleanUserDataDir(t,r){if(r.isTemp)try{await vQn(t)}catch(i){throw X0(i),i}else try{await(0,tnn.unlink)(_tu.default.join(t,"user.js"));let i=_tu.default.join(t,"prefs.js.puppeteer");if(FPc.default.existsSync(i)){let n=_tu.default.join(t,"prefs.js");await(0,tnn.unlink)(n),await(0,tnn.rename)(i,n)}}catch(i){X0(i)}}executablePath(){if(this.puppeteer.browserRevision==="latest"){let r=this.puppeteer.createBrowserFetcher({product:this.product,path:this.puppeteer.defaultDownloadPath}).localRevisions();r[0]&&(this.actualBrowserRevision=r[0])}return this.resolveExecutablePath()}defaultArgs(t={}){let{devtools:r=!1,headless:i=!r,args:n=[],userDataDir:a=null}=t,u=["--no-remote"];switch(ib_.default.platform()){case"darwin":u.push("--foreground");break;case"win32":u.push("--wait-for-browser");break}return a&&(u.push("--profile"),u.push(a)),i&&u.push("--headless"),r&&u.push("--devtools"),n.every(l=>l.startsWith("-"))&&u.push("about:blank"),u.push(...n),u}};var nb_=require("path");var C8a=Object.freeze({chromium:"1108766",firefox:"latest"});var LPc=function(e,t,r,i,n){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?n.call(e,r):n?n.value=r:t.set(e,r),r},uQt=function(e,t,r,i){if(r==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?i:r==="a"?i.call(e):i?i.value:t.get(e)},YQn,Fmi,I8a,B8a,XQn=class extends S2a{constructor(t){let{configuration:r,...i}=t;switch(super(i),YQn.add(this),Fmi.set(this,void 0),I8a.set(this,void 0),this.configuration={},r&&(this.configuration=r),this.configuration.defaultProduct){case"firefox":this.defaultBrowserRevision=C8a.firefox;break;default:this.configuration.defaultProduct="chrome",this.defaultBrowserRevision=C8a.chromium;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.createBrowserFetcher=this.createBrowserFetcher.bind(this)}connect(t){return super.connect(t)}launch(t={}){let{product:r=this.defaultProduct}=t;return LPc(this,I8a,r,"f"),uQt(this,YQn,"a",B8a).launch(t)}executablePath(t){return uQt(this,YQn,"a",B8a).executablePath(t)}get browserRevision(){var t,r,i;return(i=(r=(t=uQt(this,Fmi,"f"))===null||t===void 0?void 0:t.getActualBrowserRevision())!==null&&r!==void 0?r:this.configuration.browserRevision)!==null&&i!==void 0?i:this.defaultBrowserRevision}get defaultDownloadPath(){var t;return(t=this.configuration.downloadPath)!==null&&t!==void 0?t:(0,nb_.join)(this.configuration.cacheDirectory,this.product)}get lastLaunchedProduct(){var t;return(t=uQt(this,I8a,"f"))!==null&&t!==void 0?t:this.defaultProduct}get defaultProduct(){var t;return(t=this.configuration.defaultProduct)!==null&&t!==void 0?t:"chrome"}get product(){return uQt(this,YQn,"a",B8a).product}defaultArgs(t={}){return uQt(this,YQn,"a",B8a).defaultArgs(t)}createBrowserFetcher(t={}){var r;let i=this.defaultDownloadPath;if(!t.path&&i&&(t.path=i),!t.path)throw new Error("A `path` must be specified for `puppeteer-core`.");return!("useMacOSARMBinary"in t)&&(!((r=this.configuration.experiments)===null||r===void 0)&&r.macArmChromiumEnabled)&&(t.useMacOSARMBinary=!0),!("host"in t)&&this.configuration.downloadHost&&(t.host=this.configuration.downloadHost),!("product"in t)&&this.configuration.defaultProduct&&(t.product=this.configuration.defaultProduct),new Qko(t)}};Fmi=new WeakMap,I8a=new WeakMap,YQn=new WeakSet,B8a=function(){if(uQt(this,Fmi,"f")&&uQt(this,Fmi,"f").product===this.lastLaunchedProduct)return uQt(this,Fmi,"f");switch(this.lastLaunchedProduct){case"chrome":this.defaultBrowserRevision=C8a.chromium,LPc(this,Fmi,new ptu(this),"f");break;case"firefox":this.defaultBrowserRevision=C8a.firefox,LPc(this,Fmi,new htu(this),"f");break;default:throw new Error(`Unknown product: ${uQt(this,I8a,"f")}`)}return uQt(this,Fmi,"f")};h0c();V6a();var oAE=new XQn({isPuppeteerCore:!0}),{connect:k45,createBrowserFetcher:e25,defaultArgs:t25,executablePath:r25,launch:i25}=oAE;var Bg_=require("os"),Ig_=require("path"),zg_=ui(Cg_(),1);function CCE(e){switch(e){case"chrome":case"firefox":return!0;default:return!1}}var Rg_=()=>{var e,t,r,i,n,a,u,l,d,s,o,c,b,g,O,m,w,E,q,M,D,C,R,G,I,L,V,Y,K,X,oe,pe,de,Oe,Ue,bt,De;let Te=(0,zg_.cosmiconfigSync)("puppeteer").search(),Rt=Te?Te.config:{};if(Rt.defaultProduct=(i=(r=(t=(e=process.env.PUPPETEER_PRODUCT)!==null&&e!==void 0?e:process.env.npm_config_puppeteer_product)!==null&&t!==void 0?t:process.env.npm_package_config_puppeteer_product)!==null&&r!==void 0?r:Rt.defaultProduct)!==null&&i!==void 0?i:"chrome",Rt.executablePath=(u=(a=(n=process.env.PUPPETEER_EXECUTABLE_PATH)!==null&&n!==void 0?n:process.env.npm_config_puppeteer_executable_path)!==null&&a!==void 0?a:process.env.npm_package_config_puppeteer_executable_path)!==null&&u!==void 0?u:Rt.executablePath,Rt.executablePath&&(Rt.skipDownload=!0),Rt.skipDownload=!!((b=(c=(o=(s=(d=(l=process.env.PUPPETEER_SKIP_DOWNLOAD)!==null&&l!==void 0?l:process.env.npm_config_puppeteer_skip_download)!==null&&d!==void 0?d:process.env.npm_package_config_puppeteer_skip_download)!==null&&s!==void 0?s:process.env.PUPPETEER_SKIP_CHROMIUM_DOWNLOAD)!==null&&o!==void 0?o:process.env.npm_config_puppeteer_skip_chromium_download)!==null&&c!==void 0?c:process.env.npm_package_config_puppeteer_skip_chromium_download)!==null&&b!==void 0?b:Rt.skipDownload),Rt.skipDownload||(Rt.browserRevision=(w=(m=(O=(g=process.env.PUPPETEER_CHROMIUM_REVISION)!==null&&g!==void 0?g:process.env.PUPPETEER_BROWSER_REVISION)!==null&&O!==void 0?O:process.env.npm_config_puppeteer_browser_revision)!==null&&m!==void 0?m:process.env.npm_package_config_puppeteer_browser_revision)!==null&&w!==void 0?w:Rt.browserRevision,Rt.downloadHost=(M=(q=(E=process.env.PUPPETEER_DOWNLOAD_HOST)!==null&&E!==void 0?E:process.env.npm_config_puppeteer_download_host)!==null&&q!==void 0?q:process.env.npm_package_config_puppeteer_download_host)!==null&&M!==void 0?M:Rt.downloadHost,Rt.downloadPath=(R=(C=(D=process.env.PUPPETEER_DOWNLOAD_PATH)!==null&&D!==void 0?D:process.env.npm_config_puppeteer_download_path)!==null&&C!==void 0?C:process.env.npm_package_config_puppeteer_download_path)!==null&&R!==void 0?R:Rt.downloadPath),Rt.cacheDirectory=(V=(L=(I=(G=process.env.PUPPETEER_CACHE_DIR)!==null&&G!==void 0?G:process.env.npm_config_puppeteer_cache_dir)!==null&&I!==void 0?I:process.env.npm_package_config_puppeteer_cache_dir)!==null&&L!==void 0?L:Rt.cacheDirectory)!==null&&V!==void 0?V:(0,Ig_.join)((0,Bg_.homedir)(),".cache","puppeteer"),Rt.temporaryDirectory=(X=(K=(Y=process.env.PUPPETEER_TMP_DIR)!==null&&Y!==void 0?Y:process.env.npm_config_puppeteer_tmp_dir)!==null&&K!==void 0?K:process.env.npm_package_config_puppeteer_tmp_dir)!==null&&X!==void 0?X:Rt.temporaryDirectory,(oe=Rt.experiments)!==null&&oe!==void 0||(Rt.experiments={}),Rt.experiments.macArmChromiumEnabled=!!((Oe=(de=(pe=process.env.PUPPETEER_EXPERIMENTAL_CHROMIUM_MAC_ARM)!==null&&pe!==void 0?pe:process.env.npm_config_puppeteer_experimental_chromium_mac_arm)!==null&&de!==void 0?de:process.env.npm_package_config_puppeteer_experimental_chromium_mac_arm)!==null&&Oe!==void 0?Oe:Rt.experiments.macArmChromiumEnabled),Rt.logLevel=(De=(bt=(Ue=process.env.PUPPETEER_LOGLEVEL)!==null&&Ue!==void 0?Ue:process.env.npm_config_LOGLEVEL)!==null&&bt!==void 0?bt:process.env.npm_package_config_LOGLEVEL)!==null&&De!==void 0?De:Rt.logLevel,!CCE(Rt.defaultProduct))throw new Error(`Unsupported product ${Rt.defaultProduct}`);return Rt};var BCE=Rg_(),ICE=new XQn({isPuppeteerCore:!1,configuration:BCE}),{connect:d85,createBrowserFetcher:p85,defaultArgs:_85,executablePath:h85,launch:xg_}=ICE;var zCE="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",RCE={"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 K8a(e,t=3,r=1e3,i=2){try{return await e()}catch(n){if(t>0)return await new Promise(a=>setTimeout(a,r)),K8a(e,t-1,r*i,i);throw n}}async function Ng_(){try{return await xg_({headless:"new",ignoreHTTPSErrors:!0})}catch{throw new Error("Could not create a Puppeteer instance")}}async function xCE(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(RCE),await r.setUserAgent(zCE),await r.setJavaScriptEnabled(!0),await K8a(()=>r.goto(t.toString(),{waitUntil:"networkidle2",timeout:3e4}));let i=await K8a(()=>r.content());return await r.close(),i}catch{throw new Error("Failed to download page from Puppeteer")}}async function NCE(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 Qjc({url:e,browser:t}){try{let r;if(t?r=await xCE(t,e):r=await K8a(()=>NCE(e)),r)return r;throw new Error("An unknown error occurred.")}catch{throw new Error(`Error retrieving HTML for ${e.toString()}`)}}async function Fg_(e){try{let t=await K8a(()=>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 FCE=["png","jpeg","jpg","webp","avif","svg","ico","jfif","pjpeg","pjp","svgz","bmp"];async function Lg_(e){if(!e)return{success:!1,data:void 0};if(e.startsWith("data:image/"))return{success:!0,data:[e,e]};let t=(0,aJn.join)(process.cwd(),"fern");try{let r=await LCE(e,(0,aJn.join)(t,"images"));return r=r.replace(t,""),{success:!0,data:[e,r]}}catch{return{success:!1,data:void 0}}}async function LCE(e,t){let r=VCE(e),i=(0,aJn.join)(t,r);if(!UCE(r))throw new Error(`${r} - file extension not supported`);if((0,Ntu.existsSync)(i))return i;try{(0,Ntu.mkdirSync)((0,aJn.dirname)(i),{recursive:!0})}catch{throw new Error(`${i} - failed to create directory`)}try{let n=await Fg_(e);return nc_(i,n),i}catch{throw new Error(`${i}: failed to download file from source`)}}function UCE(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&&!FCE.includes(i))}function VCE(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 WCE(e){let t=[];return Vf(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 Ug_(e,t){let r=w$n(e),i=WCE(r);if(i!=null){let n=await Promise.all(i.map(async a=>{let u=await Lg_(a.properties.src);return u.success&&u.data?u.data[1]:""}));t.push(...n)}for(let n=t.length-1;n>=0;n--)t[n]||t.splice(n,1)}var Vg_=28;async function Wg_(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 Ug_(a,r)))}let i=[...new Set(r).values()];if(i.length!==0){if(i.length===1&&i[0]!=null){let n=Ia.of(nJ(i[0]));return{light:n,dark:n,height:Vg_}}if(i[0]!=null&&i[1]!=null){let n=Ia.of(nJ(i[0])),a=Ia.of(nJ(i[1]));return{light:n,dark:a,height:Vg_}}}}var Ftu=class extends jrn{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:z7a});let i=await this.getHastForUrl(this.url),n=_l_(i)??[];if(n.length===0)this.logger.debug("No tabs found on the page");else{this.logger.debug(`Found ${n.length} tabs:`);for(let o of n)this.logger.debug(` - Tab: ${o.name} (${o.url})`)}for(let o of n){let c=await this.scrapeTab({name:o.name,url:o.url});if(!c)continue;let b=r.getNavigationBuilder({tabId:this.kebabCaseWithoutEmojis(o.name),tabConfig:{slug:o.url,displayName:o.name}}),g=Eu(this.absolutePathToFernDirectory,Ia.of(this.kebabCaseWithoutEmojis(o.name)));await this.downloadMarkdownPages({absolutePathToOutputDirectory:g,sections:c});let O=await this.getNavigationItems({absolutePathToOutputDirectory:g,sections:c});for(let m of O)b.addItem({item:m})}let a=await Ng_(),u=await Wg_(this.url,a);u!=null&&r.setLogo({logo:u});let l=await Nn_(i);r.setTitle({title:l});let d=await In_(i);if(d!=null){let o=await this.getAndCreateAssetsDirectory(),c=await fetch(d);if(c.ok){let b=Buffer.from(await c.arrayBuffer()),g=Eu(o,Ia.of("favicon"));await(0,vNi.writeFile)(g,new Uint8Array(b)),r.setFavicon({favicon:hae(this.absolutePathToFernDirectory,g)})}}let s=await yl_(i);r.setColors({colors:s}),a&&await a.close(),r.build({outputDirectory:this.absolutePathToFernDirectory})}async getAndCreateAssetsDirectory(){let t=Eu(this.absolutePathToFernDirectory,Ia.of("assets"));return await(0,vNi.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=fl_(n);if(!a){this.logger.debug(`No sidebar element found for tab: ${t} (${r})`);return}let u=dl_(a);return this.logger.debug(`Successfully scraped tab: ${t}`),u}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 Qjc({url:t});return w$n(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,vNi.mkdir)(n,{recursive:!0}),await Promise.all(i.pages.filter(a=>a.type==="page").map(async a=>{let u=new URL(a.slug.toString(),this.url);this.logger.debug(`Fetching page: ${u.toString()}`);let l=await Qjc({url:u}),d=await ll_({logger:this.logger,html:l,url:u});if(d.success&&d.data){let s=this.getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:n,page:a.slug});await(0,vNi.writeFile)(s,d.data.mdx),d.data.images.imageURLs.length>0&&(this.logger.debug(`Found ${d.data.images.imageURLs.length} images to download for ${u.toString()}`),await Promise.all(Object.entries(d.data.images.imageURLToFilename).map(async([o,c])=>{try{let b=await fetch(o);if(!b.ok){this.logger.warn(`Failed to download image ${o}, status: ${b.status}`);return}let g=Buffer.from(await b.arrayBuffer()),O=Eu(n,Ia.of(c)),m=Rd(O);await(0,vNi.mkdir)(m,{recursive:!0}),await(0,vNi.writeFile)(O,new Uint8Array(g)),this.logger.debug(`Saved image to ${O}`)}catch(b){this.logger.warn(`Error downloading image ${o}: ${b}`)}})))}else this.logger.warn(`Failed to parse page ${u.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}),u={section:n.group,contents:[],slug:this.kebabCaseWithoutEmojis(n.group)};for(let l of n.pages)if(l.type==="page")u.contents.push({page:l.page,path:hae(this.absolutePathToFernDirectory,this.getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:a,page:l.slug}))});else{let d=await this.getNavigationItems({absolutePathToOutputDirectory:a,sections:[l]});u.contents.push(...d)}i.push(u)}return i}getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:t,page:r}){return Eu(t,Ia.of(`${this.kebabCaseWithoutEmojis(r.split("/").pop()||r)}.mdx`))}getAbsolutePathToOutputDirectoryForSection({absolutePathToOutputDirectory:t,section:r}){return Eu(t,Ia.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 Hg_=require("fs/promises");async function Jjc({readmeUrl:e,outputPath:t,taskContext:r,versionOfCli:i,organization:n}){let a=new wrn;a.setInstance({companyName:n}),await new Ftu({url:e,context:r,builder:a,absolutePathToFernDirectory:Eu(Fc.of(process.cwd()),Ia.of("fern"))}).import({args:{},builder:a}),await a.build({outputDirectory:t}),await(0,Hg_.writeFile)(Eu(Fc.of(t),Ia.of(KW),Ia.of(lae)),JSON.stringify({version:i,organization:n},void 0,4))}var Kjc=async({readmeUrl:e,organization:t,taskContext:r,versionOfCli:i})=>{if(!e||!fki(e)){r.failAndThrow("Provide a URL to a readme-generated site");return}let n=Fc.of(_I());await Jjc({readmeUrl:e,outputPath:n,taskContext:r,versionOfCli:i,organization:t})};var $g_="0.0.0";var Gg_={[Bh.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,qB(e)])),[Bh.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"]),[Bh.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"]),[Bh.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"]),[Bh.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"]),[Bh.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"]),[Bh.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"]),[Bh.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"]),[Bh.GenerationLanguage.SWIFT]:new Set([])};var $CE=["go","ruby"];function iee({generationLanguage:e,keywords:t,smartCasing:r}){let i={generateName:(n,a)=>{let u=c=>({unsafeName:c,safeName:GCE({name:c,keywords:QCE({generationLanguage:e,keywords:t})})}),l=S_(n),d=qB(l),s=TZi(n),o=EZi(l);return r&&(!YCE(o)&&(e==null||$CE.includes(e))&&(l=o.map((c,b)=>{if(b>0){let g=Ltu(c);if(g!=null)return g;if(Utu(c))return c.toUpperCase()}return c}).join(""),d=qB(o.map((c,b)=>{let g=Ltu(c);return g??(Utu(c)?c.toUpperCase():b===0?qB(c):c)}).join(""))),s=n.split(" ").map(c=>c.split(/(\d+)/).map(TZi).join("")).join("_")),{originalName:n,camelCase:u(a?.casingOverrides?.camel??l),snakeCase:u(a?.casingOverrides?.snake??s),screamingSnakeCase:u(a?.casingOverrides?.["screaming-snake"]??s.toUpperCase()),pascalCase:u(a?.casingOverrides?.pascal??d)}},generateNameAndWireValue:({name:n,wireValue:a,opts:u})=>({name:i.generateName(n,u),wireValue:a})};return i}function GCE({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":KCE(e)?"_"+e:e}function QCE({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return Gg_[e]}var JCE=/^[0-9]/;function KCE(e){return JCE.test(e)}function YCE(e){return e.some((t,r)=>{if(r===0)return!1;let i=e[r-1];if(i==null)return!1;let n=Ltu(i)!=null||Utu(i),a=Ltu(t)!=null||Utu(t);return n&&a})}function Ltu(e){return ZCE.get(e.toUpperCase())}function Utu(e){return XCE.has(e.toUpperCase())}var XCE=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"]),ZCE=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]);function Yjc({rawApiFileSchema:e,casingsGenerator:t}){if(e.auth==null)return{docs:void 0,requirement:toe.All,schemes:[]};let r=typeof e.auth!="string"?e.auth.docs:void 0;return Ren(e.auth,{single:i=>{let n=Qg_({reference:i,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t});return{docs:r,requirement:toe.All,schemes:[n]}},any:({any:i})=>({docs:r,requirement:toe.Any,schemes:i.map(n=>Qg_({reference:n,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t}))})})}function Qg_({reference:e,authSchemeDeclarations:t,casingsGenerator:r}){let i=(a,u)=>{let l=t?.[a];if(l==null)throw new Error("Unknown auth scheme: "+a);return mNa(l,{header:d=>BA.header({docs:u,name:r.generateNameAndWireValue({name:d.name??a,wireValue:d.header}),valueType:Xc.primitive({v1:ny.String,v2:Td.string({default:void 0,validation:void 0})}),prefix:d.prefix,headerEnvVar:d.env}),basic:d=>Jg_({casingsGenerator:r,docs:u,rawScheme:d}),tokenBearer:d=>Vtu({casingsGenerator:r,docs:u,rawScheme:d}),inferredBearer(d){return Vtu({casingsGenerator:r,docs:u,rawScheme:void 0})},oauth:d=>Vtu({casingsGenerator:r,docs:u,rawScheme:void 0})})},n=typeof e=="string"?e:e.scheme;switch(n){case"bearer":case"oauth":return Vtu({casingsGenerator:r,docs:void 0,rawScheme:void 0});case"basic":return Jg_({casingsGenerator:r,docs:void 0,rawScheme:void 0});default:return i(n,typeof e!="string"?e.docs:void 0)}}function Vtu({casingsGenerator:e,docs:t,rawScheme:r}){return BA.bearer({docs:t,token:e.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function Jg_({casingsGenerator:e,docs:t,rawScheme:r}){return BA.basic({docs:t,username:e.generateName(r?.username?.name??"username"),usernameEnvVar:r?.username?.env,password:e.generateName(r?.password?.name??"password"),passwordEnvVar:r?.password?.env})}function WF(e){let t=eBE(e),{value:r,done:i}=Xjc(t,"{");return i?{head:r,parts:[]}:{head:r,parts:[...kCE(t)]}}function*kCE(e){let t;do{let{value:r}=Xjc(e,"}"),i=Xjc(e,"{");t=i.done,yield{pathParameter:r,tail:i.value}}while(!t)}function*eBE(e){for(let t of e)yield t}function Xjc(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 Y8a({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:Krr(i,{singleBaseUrl:()=>$R.singleBaseUrl(tBE({environments:t,casingsGenerator:r})),multipleBaseUrls:n=>$R.multipleBaseUrls(rBE({baseUrls:Object.keys(n.urls),environments:t,casingsGenerator:r}))})},audiences:{...Object.fromEntries(Object.entries(t).map(([n,a])=>[n,Krr(a,{singleBaseUrl:u=>[...typeof u=="string"?[]:u.audiences??[]],multipleBaseUrls:u=>[...u.audiences??[]]})]))}}}function tBE({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,i])=>Krr(i,{singleBaseUrl:n=>({docs:typeof n=="string"?void 0:n.docs,id:r,name:t.generateName(r),url:Kg_(typeof n=="string"?n:n.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function rBE({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(i=>({id:i,name:r.generateName(i)})),environments:Object.entries(t).map(([i,n])=>Krr(n,{multipleBaseUrls:a=>({docs:a.docs,id:i,name:r.generateName(i),urls:_d(a.urls,u=>Kg_(u))}),singleBaseUrl:()=>{throw new Error(`Environment ${i} does not have multiple base URLs`)}}))}}function Kg_(e){return e.endsWith("/")?e.slice(0,-1):e}function X8a(e){let t=2166136261;function r(n,a){if(typeof n=="object"&&n!=null){if(a>64){i("[MaxDepthExceeded]");return}if(Array.isArray(n)){i("[");for(let u=0;u<n.length;u++)u>0&&i(","),r(n[u],a+1);i("]")}else i("{"),Object.keys(n).sort().forEach((l,d)=>{d>0&&i(","),i(l),i(":"),r(n[l],a+1)}),i("}")}else i(String(n))}function i(n){for(let a=0;a<n.length;a++){let u=n.charCodeAt(a);t^=u,t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24),t>>>=0}}return r(e,0),t.toString(16)}function lor({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 Yg_({fieldName:e,containerType:t,maxDepth:r,currentDepth:i,typeDeclarations:n,skipOptionalProperties:a}){if(i>=r)return dor({containerType:t});switch(t.type){case"list":{let u=OT({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?dor({containerType:t}):{type:"success",example:Wm.list({list:[u.example,u.example],itemType:t.list}),jsonExample:[u.jsonExample,u.jsonExample]}}case"literal":return{type:"success",example:Wm.literal({literal:t.literal._visit({boolean:u=>Vd.boolean(u),string:u=>Vd.string({original:u}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:t.literal._visit({boolean:u=>u,string:u=>u,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":{if(a)return dor({containerType:t});let u=OT({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?dor({containerType:t}):{type:"success",example:Wm.optional({optional:u.example,valueType:t.optional}),jsonExample:u.jsonExample}}case"nullable":{if(a)return dor({containerType:t});let u=OT({fieldName:e,typeReference:t.nullable,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?dor({containerType:t}):{type:"success",example:Wm.nullable({nullable:u.example,valueType:t.nullable}),jsonExample:u.jsonExample}}case"set":{let u=OT({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?dor({containerType:t}):{type:"success",example:Wm.set({set:[u.example],itemType:t.set}),jsonExample:[u.jsonExample]}}case"map":{let u=OT({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a}),l=OT({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"||l.type==="failure"?dor({containerType:t}):{type:"success",example:Wm.map({map:[{key:u.example,value:l.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[u.jsonExample]:l.jsonExample}}}default:So(t)}}function dor({containerType:e}){switch(e.type){case"list":return{type:"success",example:Wm.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:Wm.literal({literal:e.literal._visit({boolean:t=>Vd.boolean(t),string:t=>Vd.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:Wm.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"nullable":return{type:"success",example:Wm.nullable({nullable:void 0,valueType:e.nullable}),jsonExample:void 0};case"set":return{type:"success",example:Wm.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:Wm.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:So(e)}}function Zg_({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":return uBE({fieldName:e,default_:iBE(t.v2),validation:nBE(t.v2)});case"BASE_64":return{type:"success",example:Vd.base64(Ch.BASE64),jsonExample:Ch.BASE64};case"BOOLEAN":return{type:"success",example:Vd.boolean(Ch.BOOLEAN),jsonExample:Ch.BOOLEAN};case"DATE":return{type:"success",example:Vd.date(Ch.DATE),jsonExample:Ch.DATE};case"DATE_TIME":return{type:"success",example:Vd.datetime({datetime:new Date(Ch.DATE_TIME),raw:Ch.DATE_TIME}),jsonExample:Ch.DATE_TIME};case"DOUBLE":return sBE({fieldName:e,validation:aBE(t.v2)});case"FLOAT":return{type:"success",example:Vd.float(Ch.FLOAT),jsonExample:Ch.FLOAT};case"INTEGER":return cBE({fieldName:e,validation:oBE(t.v2)});case"UINT_64":return{type:"success",example:Vd.uint64(Ch.INT64),jsonExample:Ch.INT64};case"UINT":return{type:"success",example:Vd.uint(Ch.UINT),jsonExample:Ch.UINT};case"BIG_INTEGER":return{type:"success",example:Vd.bigInteger(Ch.INT64.toString()),jsonExample:`${Ch.INT64}`};case"LONG":return{type:"success",example:Vd.long(Ch.INT64),jsonExample:Ch.INT64};case"UUID":return{type:"success",example:Vd.uuid(Ch.UUID),jsonExample:Ch.UUID};default:So(t.v1)}}function iBE(e){if(e?.type==="string")return e.default}function nBE(e){if(e?.type==="string")return e.validation}function aBE(e){if(e?.type==="double")return e.validation}function oBE(e){if(e?.type==="integer")return e.validation}function Xg_(e){if(e<=Ch.SAMPLE_STRINGS.length){let t=Ch.SAMPLE_STRINGS[e-1];if(t)return t;throw new Error(`Unexpected undefined value in SAMPLE_STRINGS at index ${e-1}`)}return Ch.SAMPLE_STRINGS[Ch.SAMPLE_STRINGS.length-1]+".".repeat(e-Ch.SAMPLE_STRINGS.length)}function uBE({fieldName:e,default_:t,validation:r}){if(t!=null)return{type:"success",example:Vd.string({original:t}),jsonExample:t};if(r){let n=r.minLength,a=r.maxLength;if(n){let u=Xg_(n);return{type:"success",example:Vd.string({original:u}),jsonExample:u}}else if(a!=null&&a<10){let u=Xg_(a);return{type:"success",example:Vd.string({original:u}),jsonExample:u}}}let i=e??Ch.STRING;return{type:"success",example:Vd.string({original:i}),jsonExample:i}}function sBE({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:Vd.double(r),jsonExample:r};if(i)return{type:"success",example:Vd.double(i),jsonExample:i}}return{type:"success",example:Vd.double(Ch.DOUBLE),jsonExample:Ch.DOUBLE}}function cBE({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:Vd.integer(r),jsonExample:r};if(i)return{type:"success",example:Vd.integer(i),jsonExample:i}}return{type:"success",example:Vd.integer(Ch.INT),jsonExample:Ch.INT}}function oJn({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let u=OT({fieldName:e,typeDeclarations:t,typeReference:r.shape.aliasOf,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure")return u;let{example:l,jsonExample:d}=u;return{type:"success",example:l1.alias({value:l}),jsonExample:d}}case"enum":{let u=r.shape.values[0];return u==null?{type:"failure",message:"No enum values present"}:{type:"success",example:l1.enum({value:u.name}),jsonExample:u.name.wireValue}}case"object":{let u={},l=[];if((r.shape.extendedProperties==null||r.shape.extendedProperties.length===0)&&r.shape.extends!=null)for(let c of r.shape.extends){let b=t[c.typeId];if(b==null)continue;let g=oJn({fieldName:e,typeDeclaration:b,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});g!=null&&g.type==="success"&&g.example.type==="object"&&(Object.assign(u,g.jsonExample),l.push(...g.example.properties))}let d=lBE({fieldName:e,typeDeclaration:r,objectTypeDeclaration:r.shape,typeDeclarations:t,currentDepth:n,maxDepth:i,skipOptionalProperties:a});if(d.type==="failure")return d;let{example:s,jsonExample:o}=d;return{type:"success",example:l1.object({properties:[...l,...s.properties]}),jsonExample:Object.assign({},u,o)}}case"undiscriminatedUnion":{let u=0;for(let l of r.shape.members){let d=OT({fieldName:e,typeReference:l.type,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});if(d.type==="failure"){++u;continue}let{example:s,jsonExample:o}=d;return{type:"success",example:l1.undiscriminatedUnion({index:u,singleUnionType:s}),jsonExample:o}}break}case"union":{let u=r.shape.discriminant,l={};if(r.shape.baseProperties!=null)for(let d of r.shape.baseProperties){let s=OT({fieldName:d.name.wireValue,typeReference:d.valueType,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});s.type==="success"&&(l[d.name.wireValue]=s.jsonExample)}for(let d of r.shape.types){let s=d.shape._visit({noProperties:()=>({type:"success",example:l1.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:J3.noProperties()}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,...l}}),samePropertiesAsObject:o=>{let c=t[o.typeId];if(c==null)return{type:"failure",message:`Failed to find type declaration with id ${o.typeId}`};let b=oJn({currentDepth:n,maxDepth:i,fieldName:e,typeDeclaration:c,typeDeclarations:t,skipOptionalProperties:a});if(b==null)return{type:"failure",message:"Failed to generate example for type reference"};if(b.type==="failure")return b;let{example:g,jsonExample:O}=b;return{type:"success",example:l1.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:J3.samePropertiesAsObject({typeId:c.name.typeId,object:g.type==="object"?g:{properties:[]}})}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,...typeof O=="object"?O:{},...l}}},singleProperty:o=>{let c=OT({currentDepth:n+1,maxDepth:i,fieldName:e,typeReference:o.type,typeDeclarations:t,skipOptionalProperties:a});if(c.type==="failure")return c;let{example:b,jsonExample:g}=c;return{type:"success",example:l1.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:J3.singleProperty(b)}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,[o.name.wireValue]:g,...l}}},_other:()=>{throw new Error("Encountered unknown union type")}});if(s.type!=="failure")return s}}}return{type:"failure",message:"Failed to generate example for type reference"}}function lBE({fieldName:e,typeDeclaration:t,objectTypeDeclaration:r,typeDeclarations:i,maxDepth:n,currentDepth:a,skipOptionalProperties:u}){let l={},d=[];for(let s of[...r.properties??[],...r.extendedProperties??[]]){let o=OT({fieldName:s.name.wireValue,typeReference:s.valueType,typeDeclarations:i,currentDepth:a+1,maxDepth:n,skipOptionalProperties:u});if(o.type==="failure"&&!lor({typeDeclarations:i,typeReference:s.valueType}))return{type:"failure",message:`Failed to generate required property ${s.name.wireValue} b/c ${o.message}`};if(o.type==="failure")continue;let{example:c,jsonExample:b}=o;d.push({name:s.name,originalTypeDeclaration:t.name,value:c}),l[s.name.wireValue]=b}return{type:"success",example:l1.object({properties:d}),jsonExample:l}}function OT({fieldName:e,typeReference:t,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){if(n>i)return{type:"failure",message:"Exceeded max depth"};switch(t.type){case"named":{let u=r[t.typeId];if(u==null)return{type:"failure",message:`Failed to find type declaration with id ${t.typeId}`};let l=oJn({fieldName:e,typeDeclaration:u,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(l==null)return{type:"failure",message:"Failed to generate example for type declaration"};if(l.type==="failure")return l;let{example:d,jsonExample:s}=l;return{type:"success",example:{jsonExample:s,shape:ay.named({shape:d,typeName:u.name})},jsonExample:s}}case"container":{let u=Yg_({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure"){let{example:s,jsonExample:o}=dor({containerType:t.container});return{type:"success",example:{jsonExample:o,shape:ay.container(s)},jsonExample:o}}let{example:l,jsonExample:d}=u;return{type:"success",example:{jsonExample:d,shape:ay.container(l)},jsonExample:d}}case"primitive":{let{jsonExample:u,example:l}=Zg_({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:u,shape:ay.primitive(l)},jsonExample:u}}case"unknown":{let u={key:"value"};return{type:"success",example:{jsonExample:u,shape:ay.unknown(u)},jsonExample:u}}}}function snn(e,t){let r=[];for(let i of e){let n=OT({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 uJn(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&lor({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=OT({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 Wtu(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&lor({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=OT({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?q8.exploded():q8.single(),value:n.example})}return{type:"success",example:r,jsonExample:void 0}}var Zjc=Xc.primitive({v1:ny.String,v2:Td.string({default:void 0,validation:void 0})});function Z8a({ir:e,endpoint:t,service:r,typeDeclarations:i,skipOptionalRequestProperties:n,generationResponse:a}){let u={name:void 0,endpointHeaders:[],endpointPathParameters:[],queryParameters:[],servicePathParameters:[],serviceHeaders:[],rootPathParameters:[],request:void 0,response:gC.ok(NB.body(void 0)),docs:void 0},l=snn(t.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(l.type==="failure")return l;u.endpointPathParameters=l.example;let d=snn(r.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(d.type==="failure")return d;u.servicePathParameters=d.example;let s=snn(e.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(s.type==="failure")return s;u.rootPathParameters=s.example;let o=Wtu(t.queryParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:10});if(o.type==="failure")return o;u.queryParameters=o.example;let c=uJn(t.headers,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(c.type==="failure")return c;u.endpointHeaders=c.example;let b=uJn(r.headers,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(b.type==="failure")return b;if(u.serviceHeaders=b.example,t.requestBody!=null)switch(t.requestBody.type){case"bytes":return{type:"failure",message:"Bytes request unsupported"};case"fileUpload":return{type:"failure",message:"File upload unsupported"};case"inlinedRequestBody":{let g={},O=[];if(t.requestBody.extends!=null)for(let m of t.requestBody.extends){let w=i[m.typeId];if(w==null)throw new Error(`Failed to find extended type declaration with id ${m.typeId}`);let E=oJn({typeDeclaration:w,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});E!=null&&E.type==="success"&&Object.assign(g,E.jsonExample)}for(let m of[...t.requestBody.properties??[],...t.requestBody.extendedProperties??[]]){let w=OT({fieldName:m.name.wireValue,typeReference:m.valueType,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});if(w.type==="failure"&&!lor({typeDeclarations:i,typeReference:m.valueType}))return{type:"failure",message:`Failed to generate required property ${m.name.wireValue} b/c ${w.message}`};if(w.type==="failure")continue;let{example:E,jsonExample:q}=w;O.push({name:m.name,originalTypeDeclaration:void 0,value:E}),g[m.name.wireValue]=q}u.request=MJ.inlinedRequestBody({jsonExample:g,properties:O});break}case"reference":{let g=OT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:n});if(g.type==="failure")return g;let{example:O}=g;u.request=MJ.reference(O);break}default:So(t.requestBody)}if(a.type==="success"&&t.response?.body!=null)switch(t.response.body.type){case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":{let g=OT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.responseBodyType,skipOptionalProperties:!1});if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=gC.ok(NB.body({...O,jsonExample:m}));break}case"streamParameter":{let g;switch(t.response.body.nonStreamResponse.type){case"bytes":return{type:"failure",message:"Bytes unsupported"};case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":g=OT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.nonStreamResponse.value.responseBodyType,skipOptionalProperties:!1});break;case"text":g=OT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:Zjc,skipOptionalProperties:!1});break;default:So(t.response.body.nonStreamResponse)}if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=gC.ok(NB.body({...O,jsonExample:m}));break}case"streaming":{let g;switch(t.response.body.value.type){case"sse":{if(g=OT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=gC.ok(NB.sse([{data:{...O,jsonExample:m},event:""}]));break}case"json":{if(g=OT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=gC.ok(NB.stream([{...O,jsonExample:m}]));break}case"text":{if(g=OT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:Zjc,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=gC.ok(NB.stream([{...O,jsonExample:m}]));break}default:So(t.response.body.value)}break}case"text":{let g=OT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:Zjc,skipOptionalProperties:!1});if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=gC.ok(NB.body({...O,jsonExample:m}));break}case"bytes":return{type:"failure",message:"Bytes unsupported"};default:So(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)u.response=gC.error({body:void 0,error:a.declaration.name});else{let g=OT({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:a.declaration.type,skipOptionalProperties:n});if(g.type==="failure")return g;let{example:O}=g;u.response=gC.error({body:O,error:a.declaration.name})}try{return{type:"success",example:{id:X8a(u),url:fBE(t,u),...u},jsonExample:void 0}}catch(g){return{type:"failure",message:`Parse failure with exceptions ${g}`}}}function fBE(e,t){let r={};[...t.rootPathParameters,...t.servicePathParameters,...t.endpointPathParameters].forEach(n=>{let a=n.value.jsonExample,u=typeof a=="string"?a:JSON.stringify(a);r[n.name.originalName]=u});let i=e.fullPath.head+e.fullPath.parts.map(n=>encodeURIComponent(`${r[n.pathParameter]}`)+n.tail).join("");return i.startsWith("/")||i===""?i:`/${i}`}function kjc({ir:e,channel:t,typeDeclarations:r,skipOptionalRequestProperties:i}){let n={name:void 0,pathParameters:[],headers:[],queryParameters:[],messages:[],docs:void 0},a=snn(t.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(a.type==="failure")return a;n.pathParameters.push(...a.example);let u=snn(e.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(u.type==="failure")return u;n.pathParameters.push(...u.example);let l=Wtu(t.queryParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:10});if(l.type==="failure")return l;n.queryParameters=l.example;let d=uJn(t.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(d.type==="failure")return d;n.headers.push(...d.example);let s=uJn(e.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(s.type==="failure")return s;n.headers.push(...s.example);let c=t.messages.filter(O=>O.origin==="client")[0];if(c!=null){let O=kg_({message:c,typeDeclarations:r,skipOptionalRequestProperties:i});O!=null&&n.messages.push({type:c.type,body:O})}let g=t.messages.filter(O=>O.origin==="server")[0];if(g!=null){let O=kg_({message:g,typeDeclarations:r,skipOptionalRequestProperties:i});O!=null&&n.messages.push({type:g.type,body:O})}return{type:"success",example:{...n,url:dBE(t,n)},jsonExample:void 0}}function kg_({message:e,typeDeclarations:t,skipOptionalRequestProperties:r}){if(e.body.type==="inlinedBody")return;let i=OT({currentDepth:0,maxDepth:10,typeDeclarations:t,typeReference:e.body.bodyType,skipOptionalProperties:r});if(i.type==="success")return hAe.reference(i.example)}function dBE(e,t){let r={};[...t.pathParameters].forEach(n=>{let a=n.value.jsonExample,u=typeof a=="string"?a:JSON.stringify(a);r[n.name.originalName]=u});let i=e.path.head+e.path.parts.map(n=>encodeURIComponent(`${r[n.pathParameter]}`)+n.tail).join("");return i.startsWith("/")||i===""?i:`/${i}`}function sJn(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{},i=Object.values(t)[0],n=Object.values(r)[0];return{userExample:i,autoExample:n}}function bNi(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{};return{userExamples:t,autoExamples:r}}function eO_({ir:e,endpoint:t,skipOptionalRequestProperties:r}){let i=e.types,n={pathParameters:{},queryParameters:{},headers:{}};for(let u of t.pathParameters){let{userExample:l,autoExample:d}=sJn(u.v2Examples);l!==void 0?n.pathParameters[u.name.originalName]=l:d!==void 0&&(n.pathParameters[u.name.originalName]=d)}for(let u of t.queryParameters){let{userExample:l,autoExample:d}=sJn(u.v2Examples);if(l!==void 0)n.queryParameters[u.name.name.originalName]=l;else if(d!==void 0){if(r&&lor({typeReference:u.valueType,typeDeclarations:i}))continue;n.queryParameters[u.name.name.originalName]=d}}let a=[...t.headers,...e.headers,...e.idempotencyHeaders];for(let u of a){let{userExample:l,autoExample:d}=sJn(u.v2Examples);if(l!==void 0)n.headers[u.name.wireValue]=l;else if(d!==void 0){if(r&&lor({typeReference:u.valueType,typeDeclarations:i}))continue;n.headers[u.name.wireValue]=d}}return n}function tO_({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let{pathParameters:i,queryParameters:n,headers:a}=eO_({endpoint:e,ir:t,skipOptionalRequestProperties:r}),u={},l={},d={endpoint:{method:e.method,path:pBE(e)},baseUrl:void 0,environment:e.baseUrl,auth:void 0,pathParameters:i,queryParameters:n,headers:a,requestBody:void 0,docs:void 0};if(e.requestBody!=null)switch(e.requestBody.type){case"bytes":break;case"fileUpload":{let{userExamples:s,autoExamples:o}=bNi(e.requestBody.v2Examples);for(let[c,b]of Object.entries(s))u[c]={...d,requestBody:b};for(let[c,b]of Object.entries(o))l[c]={...d,requestBody:b};break}case"inlinedRequestBody":{let{userExamples:s,autoExamples:o}=bNi(e.requestBody.v2Examples);for(let[c,b]of Object.entries(s))u[c]={...d,requestBody:b};for(let[c,b]of Object.entries(o))l[c]={...d,requestBody:b};break}case"reference":{let{userExamples:s,autoExamples:o}=bNi(e.requestBody.v2Examples);for(let[c,b]of Object.entries(s))u[c]={...d,requestBody:b};for(let[c,b]of Object.entries(o))l[c]={...d,requestBody:b};break}default:So(e.requestBody)}return{userRequestExamples:u,autoRequestExamples:l,baseExample:d}}function pBE(e){let t={};[...e.pathParameters,...e.allPathParameters].forEach(i=>{let{userExample:n,autoExample:a}=sJn(i.v2Examples),u=n??a,l;u==null?l=i.name.originalName:l=typeof u=="string"?u:JSON.stringify(u),t[i.name.originalName]=l});let r=e.fullPath.head+e.fullPath.parts.map(i=>encodeURIComponent(`${t[i.pathParameter]}`)+i.tail).join("");return r.startsWith("/")||r===""?r:`/${r}`}function Htu({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:m4.json(k8a(null))}}:{userResponseExamples:{},autoResponseExamples:{},baseExample:a};switch(r.body.type){case"bytes":break;case"fileDownload":break;case"text":{let u=r.body,{userExamples:l,autoExamples:d}=bNi(u.v2Examples);for(let[s,o]of Object.entries(l)){let c=e.source?.type==="openrpc"?k8a(o):o;i[s]={...a,body:m4.json(c)}}for(let[s,o]of Object.entries(d)){let c=e.source?.type==="openrpc"?k8a(o):o;n[s]={...a,body:m4.json(c)}}break}case"json":{let u=r.body.value;if(u.type==="response"){let{userExamples:l,autoExamples:d}=bNi(u.v2Examples);for(let[s,o]of Object.entries(l)){let c=e.source?.type==="openrpc"?k8a(o):o;i[s]={...a,body:m4.json(c)}}for(let[s,o]of Object.entries(d)){let c=e.source?.type==="openrpc"?k8a(o):o;n[s]={...a,body:m4.json(c)}}}break}case"streaming":{let u=r.body.value;if(u.type==="json"){let{userExamples:l,autoExamples:d}=bNi(u.v2Examples);for(let[s,o]of Object.entries(l))i[s]={...a,body:m4.stream([o])};for(let[s,o]of Object.entries(d))n[s]={...a,body:m4.stream([o])}}break}case"streamParameter":break;default:So(r.body)}return{userResponseExamples:i,autoResponseExamples:n,baseExample:a}}function k8a(e,t=1){return{id:t,jsonrpc:"2.0",result:e}}var cJn=(e,t,r)=>{let i;return e===t?i=`${e}`:i=`${e}_${t}`,r&&(i=`${i}_${r}`),i},_BE=({exampleStore:e,key:t,example:r})=>e.has(t)?!1:(e.set(t,r),!0);function $tu({key:e,displayName:t,request:r,response:i,exampleStore:n,userOrAutoStore:a}){if(!n.has(e)){let u={displayName:t,request:r,response:i,codeSamples:void 0};return a[e]=u,_BE({exampleStore:n,key:e,example:u}),!0}return!1}function rO_({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let i={},n={},a=new Map,{userRequestExamples:u,autoRequestExamples:l,baseExample:d}=tO_({endpoint:e,ir:t,skipOptionalRequestProperties:r}),s=Object.keys(u)[0],o=Object.values(u)[0],c=Object.keys(l)[0],b=Object.values(l)[0],g=hBE({endpoint:e,userRequestExamples:u,baseRequestExample:d,firstUserRequestName:s,firstUserRequestExample:o,firstAutoRequestName:c,firstAutoRequestExample:b,userResults:i,autoResults:n,exampleStore:a});if(yBE({endpoint:e,userRequestExamples:u,requestExamplesUsed:g,userResults:i,exampleStore:a}),Object.keys(i).length===0&&Object.keys(n).length===0){let{baseExample:O}=Htu({endpoint:e}),m=cJn(c??"base","base",void 0);$tu({key:m,displayName:c??"base",request:b??d,response:O,exampleStore:a,userOrAutoStore:n})}return{userFullExamples:i,autoFullExamples:n}}function hBE({endpoint:e,userRequestExamples:t,baseRequestExample:r,firstUserRequestName:i,firstUserRequestExample:n,firstAutoRequestName:a,firstAutoRequestExample:u,userResults:l,autoResults:d,exampleStore:s}){let o=e.v2Responses?.responses??[e.response],c=new Set;for(let b of o){let g=!1,{userResponseExamples:O,autoResponseExamples:m,baseExample:w}=Htu({endpoint:e,responseObject:b}),E=Object.keys(m)[0],q=Object.values(m)[0];for(let[M,D]of Object.entries(O)){let C,R;t[M]?(R=t[M],c.add(M),C=cJn(M,M,b?.statusCode)):u&&a?(R=u,C=cJn(a,M,b?.statusCode)):(R=r,C=cJn("base",M,b?.statusCode)),$tu({key:C,displayName:M,request:R,response:D,exampleStore:s,userOrAutoStore:l})&&(g=!0)}if(!g){let M=S_(`${e.name.originalName}_example`);i&&n&&c.add(i);let D=cJn(i??a??"base",E??"base",b?.statusCode);$tu({key:D,displayName:i??a??M,request:n??u??r,response:q??w,exampleStore:s,userOrAutoStore:d})&&(g=!0)}}return c}function yBE({endpoint:e,userRequestExamples:t,requestExamplesUsed:r,userResults:i,exampleStore:n}){let{userResponseExamples:a,autoResponseExamples:u,baseExample:l}=Htu({endpoint:e}),d=Object.values(a)[0],s=Object.keys(a)[0],o=Object.keys(u)[0],c=Object.values(u)[0],b=Object.entries(t).filter(([g])=>!r.has(g));for(let[g,O]of b){let m=cJn(g,s??o??"base",d?d.statusCode:c?c.statusCode:l.statusCode);$tu({key:m,displayName:g,request:O,response:d??c??l,exampleStore:n,userOrAutoStore:i})}}function e5a({ir:e,exampleGeneration:t}){for(let[r,i]of Object.entries(e.services))for(let n of i.endpoints){if(n.userSpecifiedExamples.length>0&&t?.skipAutogenerationIfManualExamplesExist===!0)continue;let a=Z8a({ir:e,service:i,endpoint:n,typeDeclarations:e.types,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples,generationResponse:{type:"success"}});if(a.type==="failure")continue;let{example:u}=a;n.autogeneratedExamples=[{example:u}]}for(let[r,i]of Object.entries(e.websocketChannels??{})){if(i.examples.length>0&&t?.skipAutogenerationIfManualExamplesExist===!0)continue;let n=kjc({ir:e,channel:i,typeDeclarations:e.types,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples});if(n.type==="failure")continue;let{example:a}=n;i.examples=[...i.examples,a]}return e}function ewc({ir:e,exampleGeneration:t}){for(let[r,i]of Object.entries(e.services))for(let n of i.endpoints){n.v2Examples==null&&(n.v2Examples={userSpecifiedExamples:{},autogeneratedExamples:{}});let{userFullExamples:a,autoFullExamples:u}=rO_({endpoint:n,ir:e,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples});if(Object.keys(n.v2Examples.userSpecifiedExamples).length>0){if(Object.values(n.v2Examples.userSpecifiedExamples).some(d=>d.request!=null||d.response!=null))continue;let l=Object.values(n.v2Examples.userSpecifiedExamples).filter(d=>d!=null).flatMap(d=>d.codeSamples??[]);for(let[d,s]of Object.entries(u))u[d]={...s,codeSamples:l};for(let[d,s]of Object.entries(a))a[d]={...s,codeSamples:l}}n.v2Examples.autogeneratedExamples=u,n.v2Examples.userSpecifiedExamples=a}for(let[r,i]of Object.entries(e.websocketChannels??{})){if(i.examples.length>0&&t?.skipAutogenerationIfManualExamplesExist===!0)continue;let n=kjc({ir:e,channel:i,typeDeclarations:e.types,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples});if(n.type==="failure")continue;let{example:a}=n;i.examples=[...i.examples,a]}return e}function nO_({filteredIr:e,singleUnionTypeProperties:t}){return t._visit({samePropertiesAsObject:r=>{let i=e.hasTypeId(r.typeId)?{...r,object:{properties:r.object.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:tN({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)}}:void 0;return i!==void 0?J3.samePropertiesAsObject(i):void 0},singleProperty:r=>{let i=tN({filteredIr:e,exampleTypeReference:r});return i!==void 0?J3.singleProperty(i):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function tN({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:i=>({...t,shape:ay.container(Wm.list({...i,list:i.list.map(n=>tN({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),set:i=>({...t,shape:ay.container(Wm.set({...i,set:i.set.map(n=>tN({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),optional:i=>{let n=i.optional!=null?tN({filteredIr:e,exampleTypeReference:i.optional}):void 0;return n!=null?{...t,shape:ay.container(Wm.optional({optional:n,valueType:i.valueType}))}:void 0},nullable:i=>{let n=i.nullable!=null?tN({filteredIr:e,exampleTypeReference:i.nullable}):void 0;return n!=null?{...t,shape:ay.container(Wm.nullable({nullable:n,valueType:i.valueType}))}:void 0},map:i=>({...t,shape:ay.container(Wm.map({...i,map:i.map.map(n=>{let a=tN({filteredIr:e,exampleTypeReference:n.key}),u=tN({filteredIr:e,exampleTypeReference:n.value});return a!==void 0&&u!==void 0?{key:a,value:u}:void 0}).filter(n=>n!==void 0)}))}),literal:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}}),named:r=>e.hasTypeId(r.typeName.typeId)?r.shape._visit({alias:i=>{let n=tN({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...t,shape:ay.named({...r,shape:l1.alias({...i,value:n})})}:void 0},enum:i=>({...t,shape:ay.named({...r,shape:l1.enum(i)})}),object:i=>({...t,shape:ay.named({...r,shape:l1.object({...i,properties:i.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:tN({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})})}),union:i=>{let n=nO_({filteredIr:e,singleUnionTypeProperties:i.singleUnionType.shape});return n!==void 0?{...t,shape:ay.named({...r,shape:l1.union({...i,singleUnionType:{...i.singleUnionType,shape:n}})})}:void 0},undiscriminatedUnion:i=>{let n=tN({filteredIr:e,exampleTypeReference:i.singleUnionType});return n!==void 0?{...t,shape:ay.named({...r,shape:l1.undiscriminatedUnion({...i,singleUnionType:n})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function twc({filteredIr:e,pathParameters:t}){return t.map(r=>{let i=tN({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function vBE({filteredIr:e,queryParameters:t}){return t.map(r=>{let i=tN({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function iO_({filteredIr:e,headers:t}){return t.map(r=>{let i=tN({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function bBE({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=tN({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...i,value:n}:void 0}).filter(i=>i!==void 0)}),reference:r=>{let i=tN({filteredIr:e,exampleTypeReference:r});return i!==void 0?MJ.reference(i):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function gBE({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:i=>gC.ok(NB.body(i!=null?tN({filteredIr:e,exampleTypeReference:i}):void 0)),stream:i=>gC.ok(NB.stream(i.map(n=>tN({filteredIr:e,exampleTypeReference:n})).filter(iv))),sse:i=>gC.ok(NB.sse(i.map(({event:n,data:a})=>{let u=tN({filteredIr:e,exampleTypeReference:a});return u!==void 0?{event:n,data:u}:void 0}).filter(iv))),_other:({type:i})=>{throw new Error(`Received unknown type for OK example: ${i}`)}}),error:({error:r,body:i})=>gC.error({error:r,body:i!=null?tN({filteredIr:e,exampleTypeReference:i}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function rwc({filteredIr:e,example:t}){return{...t,rootPathParameters:twc({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:twc({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:twc({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:iO_({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:iO_({filteredIr:e,headers:t.endpointHeaders}),queryParameters:vBE({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?bBE({filteredIr:e,requestBody:t.request}):void 0,response:gBE({filteredIr:e,response:t.response})}}function aO_({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let i=tN({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...t,shape:l1.alias({...r,value:i})}:void 0},enum:()=>t,object:r=>({...t,shape:l1.object({...r,properties:r.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:tN({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})}),union:r=>{let i=nO_({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return i!==void 0?{...t,shape:l1.union({...r,singleUnionType:{...r.singleUnionType,shape:i}})}:void 0},undiscriminatedUnion:r=>{let i=tN({filteredIr:e,exampleTypeReference:r.singleUnionType});return i!==void 0?{...t,shape:l1.undiscriminatedUnion({...r,singleUnionType:i})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function iwc(e,t){if(t==null)return e;let r=qZi(e.types,l=>t.hasType(l)),i=Object.fromEntries(Object.entries(r).map(([l,d])=>{let s=[];if(d.userProvidedExamples=d.userProvidedExamples.map(o=>aO_({filteredIr:t,exampleType:o})).filter(o=>o!==void 0),d.shape.type==="object"){for(let o of d.shape.properties)t.hasProperty(l,o.name.wireValue)&&s.push(o);return[l,{...d,shape:Vb.object({...d.shape,properties:s})}]}return[l,d]})),n=Object.fromEntries(Object.entries(e.webhookGroups).map(([l,d])=>{let s=d.filter(o=>t.hasWebhook(o)).map(o=>{let c=o.id;return o.payload.type==="inlinedPayload"&&c!=null&&(o.payload={...o.payload,properties:o.payload.properties.filter(b=>t.hasWebhookPayloadProperty(c,b.name.wireValue))}),o});return[l,s]})),a=e.websocketChannels!=null?Object.fromEntries(Object.entries(e.websocketChannels).filter(([l])=>t.hasChannel(l)).map(([l,d])=>[l,{...d}])):{},u=e.environments;if(u){switch(u.environments.type){case"singleBaseUrl":{u.environments.environments=u.environments.environments.filter(l=>t.hasEnvironmentId(l.id));break}case"multipleBaseUrls":{u.environments.environments=u.environments.environments.filter(l=>t.hasEnvironmentId(l.id));break}}u.defaultEnvironment&&(t.hasEnvironmentId(u.defaultEnvironment)||(u.defaultEnvironment=void 0))}return{...e,environments:u,types:i,errors:qZi(e.errors,l=>t.hasError(l)),services:_d(qZi(e.services,l=>t.hasService(l)),l=>({...l,endpoints:l.endpoints.filter(d=>t.hasEndpoint(d)).map(d=>(d.autogeneratedExamples=d.autogeneratedExamples.map(s=>({...s,example:rwc({filteredIr:t,example:s.example})})),d.userSpecifiedExamples=d.userSpecifiedExamples.map(s=>({...s,example:s.example!=null?rwc({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:OBE(e.serviceTypeReferenceInfo,t)}}function OBE(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 cnn(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 GAe(e){return e.allParts.map(t=>t.originalName).join("/")}var $m={generateTypeId:e=>`type_${GAe(e.fernFilepath)}:${e.name.originalName}`,generateErrorId:e=>`error_${GAe(e.fernFilepath)}:${e.name.originalName}`,generateServiceId:e=>`service_${GAe(e.fernFilepath)}`,generateServiceIdFromFernFilepath:e=>`service_${GAe(e)}`,generateSubpackageId:e=>`subpackage_${GAe(e)}`,generateEndpointId:(e,t)=>{let r=GAe(e.fernFilepath),i=t.name.originalName;return`endpoint_${r}.${i}`},generateWebhookGroupId:e=>`webhooks_${GAe(e)}`,generateWebhookId:(e,t)=>`webhooks_${GAe(e)}.${t}`,generateWebSocketChannelId:e=>`channel_${GAe(e)}`};function lJn(e){return e.type!=null}var Gtu=class{environments=new Set;types=new Set;properties;errors=new Set;services=new Set;endpoints=new Set;requestProperties;queryParameters;webhooks=new Set;webhookPayloadProperties;channels=new Set;subpackages=new Set;constructor({types:t,properties:r,errors:i,environments:n,services:a,endpoints:u,webhooks:l,subpackages:d,queryParameters:s,requestProperties:o,webhookPayloadProperties:c,channels:b}){this.environments=n,this.types=t,this.properties=r,this.errors=i,this.services=a,this.endpoints=u,this.webhooks=l,this.webhookPayloadProperties=c,this.subpackages=d,this.requestProperties=o,this.queryParameters=s,this.channels=b}hasTypeId(t){return this.types.has(t)}hasErrorId(t){return this.errors.has(t)}hasServiceId(t){return this.services.has(t)}hasSubpackageId(t){return this.subpackages.has(t)}hasType(t){let r=$m.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=$m.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=$m.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 lnn=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=mBE(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:i,descendantTypeIdsByAudience:n,propertiesByAudience:a}){let u=$m.generateTypeId(t),l={typeId:u,allDescendants:r,descendantsByAudience:n,referencedSubpackages:i};this.types[u]=l,this.typesReferencedByService[u]==null&&(this.typesReferencedByService[u]=new Set),this.properties[u]={typeId:u,propertiesByAudience:a}}markTypeForAudiences(t,r){let i=$m.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=$m.generateErrorId(t.name),i=new Set,n=new Set;t.type!=null&&ex(t.type,i,n);let a={errorId:r,referencedTypes:i,referencedSubpackages:n};this.errors[r]=a}addEndpoint(t,r,i){let n=$m.generateServiceId(t.name),a=r.id,u=new Set,l=new Set,d=new Set;for(let s of[...t.headers,...r.headers])ex(s.valueType,u,d);for(let s of[...t.pathParameters,...r.pathParameters])ex(s.valueType,u,d);for(let s of r.queryParameters)ex(s.valueType,u,d);if(i!=null&&i.request!=null&&typeof i.request!="string"){let s=cnn(i.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:s}}r.requestBody!=null&&IA._visit(r.requestBody,{inlinedRequestBody:s=>{for(let o of s.extends)Qtu(o,u,d);for(let o of s.properties)ex(o.valueType,u,d);if(i!=null&&typeof i.request=="object"&&typeof i.request.body=="object"&&RB(i.request.body)){let o=cnn(i.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:o}}},reference:({requestBodyType:s})=>{ex(s,u,d)},fileUpload:({properties:s})=>{for(let o of s)P4._visit(o,{file:$o,bodyProperty:({valueType:c})=>{ex(c,u,d)},_other:()=>{throw new Error("Unknown FileUploadRequestProperty: "+o.type)}})},bytes:()=>{},_other:()=>{throw new Error("Unknown HttpRequestBody: "+r.requestBody?.type)}}),r.response?.body!=null&&c1._visit(r.response.body,{fileDownload:$o,json:s=>{ex(s.responseBodyType,u,d)},streaming:s=>{s._visit({sse:o=>ex(o.payload,u,d),json:o=>ex(o.payload,u,d),text:$o,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.type)}})},streamParameter:s=>{s.streamResponse._visit({sse:o=>ex(o.payload,u,d),json:o=>ex(o.payload,u,d),text:$o,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.streamResponse.type)}}),s.nonStreamResponse.type==="json"&&ex(s.nonStreamResponse.value.responseBodyType,u,d)},text:$o,bytes:$o,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(s=>{l.add($m.generateErrorId(s.error)),d.add(s.error.fernFilepath)}),this.endpoints[a]={endpointId:a,serviceId:n,referencedTypes:u,referencedErrors:l,referencedSubpackages:d}}markEndpointForAudience(t,r,i){if(this.hasAudience(i)){let n=$m.generateServiceId(t);this.servicesNeededForAudience.add(n),r.forEach(a=>{let u=a.id;this.endpointsNeededForAudience.add(u),this.endpoints[u]?.referencedSubpackages.forEach(l=>{this.addSubpackages(l)})}),this.servicesNeededForAudience.add(n),this.addSubpackages(t.fernFilepath)}}getFilteredSubpackages(){return this.subpackagesNeededForAudience}getFilteredServices(){return this.servicesNeededForAudience}getFilteredEndpoints(){return this.endpointsNeededForAudience}getFilteredChannels(){return this.channelsNeededForAudience}getFilteredWebhooks(){return this.webhooksNeededForAudience}addWebhook(t,r,i){let n=r.id;if(n==null)return;let a=new Set,u=new Set;r.payload!=null&&yH._visit(r.payload,{inlinedPayload:l=>{for(let d of l.extends)Qtu(d,a,u);for(let d of l.properties)ex(d.valueType,a,u);if(i?.payload!=null&&typeof i.payload=="object"&&!lJn(i.payload)){let d=cnn(i.payload.properties??{});this.webhookProperties[n]={webhookId:n,propertiesByAudience:d}}},reference:({payloadType:l})=>{ex(l,a,u)},_other:()=>{throw new Error("Unknown WebhookPayload: "+r.payload?.type)}}),u.add(t),this.webhooks[n]={webhookId:n,referencedTypes:a,referencedSubpackages:u}}markWebhookForAudiences(t,r,i){let n=r.id;n!=null&&this.hasAudience(i)&&(this.webhooksNeededForAudience.add(n),this.addSubpackages(t))}addChannel(t,r,i,n){if(r==null)return;let a=new Set,u=new Set;for(let l of i.messages)wL._visit(l.body,{reference:({bodyType:d})=>{ex(d,a,u)},inlinedBody:d=>{for(let s of d.extends)Qtu(s,a,u);for(let s of d.properties)ex(s.valueType,a,u)},_other:()=>{}});for(let l of i.queryParameters)ex(l.valueType,a,u);u.add(t),this.channels[r]={channelId:r,referencedTypes:a,referencedSubpackages:u}}markChannelForAudiences(t,r,i){r!=null&&this.hasAudience(i)&&(this.channelsNeededForAudience.add(r),this.addSubpackages(t))}build(){let t=new Set,r=new Set;for(let l of this.endpointsNeededForAudience.keys()){let d=this.getEndpointNode(l);for(let s of d.referencedErrors){if(r.has(s))continue;r.add(s);let o=this.getErrorNode(s);this.addReferencedTypes(t,o.referencedTypes)}this.addReferencedTypes(t,d.referencedTypes)}this.addReferencedTypes(t,this.typesNeededForAudience);for(let l of this.webhooksNeededForAudience.keys()){let d=this.getWebhookNode(l);this.addReferencedTypes(t,d.referencedTypes)}for(let l of this.channelsNeededForAudience.keys()){let d=this.getChannelNode(l);this.addReferencedTypes(t,d.referencedTypes)}let i={},n={},a={},u={};if(this.audiences.type==="filtered"){for(let[l,d]of Object.entries(this.properties)){if(!t.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=d.propertiesByAudience[o];c?.forEach(b=>{s.add(b)})}s.size>0&&(i[l]=s),i[l]=s.size>0?s:void 0}for(let[l,d]of Object.entries(this.requestProperties)){if(!this.endpointsNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=d.propertiesByAudience[o];c?.forEach(b=>{s.add(b)})}n[l]=s.size>0?s:void 0}for(let[l,d]of Object.entries(this.queryParameters)){if(!this.endpointsNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=d.parametersByAudience[o];c?.forEach(b=>{s.add(b)})}a[l]=s.size>0?s:void 0}for(let[l,d]of Object.entries(this.webhookProperties)){if(!this.webhooksNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=d.propertiesByAudience[o];c?.forEach(b=>{s.add(b)})}u[l]=s.size>0?s:void 0}}return new Gtu({types:t,properties:i,errors:r,requestProperties:n,queryParameters:a,environments:this.environmentsNeededForAudience,services:this.servicesNeededForAudience,endpoints:this.endpointsNeededForAudience,webhooks:this.webhooksNeededForAudience,webhookPayloadProperties:u,subpackages:this.subpackagesNeededForAudience,channels:this.channelsNeededForAudience})}markTypeForService(t,r){let i=this.typesReferencedByService[t]??=new Set;if(i.has(r))return;i.add(r);let n=this.getTypeNode(t);for(let a of n.allDescendants)this.markTypeForService(a,r)}addReferencedTypes(t,r){for(let i of r){if(t.has(i))continue;t.add(i);let n=this.getTypeNode(i);if(this.audiences.type==="filtered")for(let a of this.audiences.audiences){let u=n.descendantsByAudience[a];if(u!=null)u.forEach(l=>{t.add(l)});else{n.allDescendants.forEach(l=>{t.add(l)});break}}else n.allDescendants.forEach(a=>{t.add(a)})}}getTypeNode(t){let r=this.types[t];if(r==null)throw new Error(`Failed to find type node with id ${t}`);return r}getErrorNode(t){let r=this.errors[t];if(r==null)throw new Error(`Failed to find error node with id ${t}`);return r}getEndpointNode(t){let r=this.endpoints[t];if(r==null)throw new Error(`Failed to find endpoint node with id ${t}`);return r}getWebhookNode(t){let r=this.webhooks[t];if(r==null)throw new Error(`Failed to find webhook node with id ${t}`);return r}getChannelNode(t){let r=this.channels[t];if(r==null)throw new Error(`Failed to find channel node with id ${t}`);return r}hasNoAudiences(){return this.audiences.type==="none"}hasAudience(t){let r=this.audiences;switch(r.type){case"none":return!0;case"filtered":return t.some(i=>r.audiences.has(i));default:So(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let i={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add($m.generateSubpackageId(i))}}};function mBE(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:So(e)}}function ex(e,t,r){Xc._visit(e,{container:i=>{PBE(i,t,r)},named:i=>{Qtu(i,t,r)},primitive:$o,unknown:$o,_other:$o})}function Qtu(e,t,r){t.add($m.generateTypeId(e)),r.add(e.fernFilepath)}function PBE(e,t,r){Ry._visit(e,{list:i=>{ex(i,t,r)},map:i=>{ex(i.keyType,t,r),ex(i.valueType,t,r)},optional:i=>{ex(i,t,r)},nullable:i=>{ex(i,t,r)},set:i=>{ex(i,t,r)},literal:$o,_other:$o})}var nwc=class{errors;constructor(){this.errors=[]}add(t){this.errors.push({message:t})}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}},t5a=class{errors;constructor(){this.errors=new nwc}async check({from:t,to:r}){let i=this.checkBreaking({from:t,to:r});return{bump:i.isBreaking?"major":"minor",isBreaking:i.isBreaking,errors:i.errors}}checkBreaking({from:t,to:r}){this.checkTypeBreakingChanges({from:t.types,to:r.types}),this.checkErrorsBreakingChanges({from:t.errors,to:r.errors}),this.checkServicesBreakingChanges({from:t.services,to:r.services});let i=this.errors.hasErrors();return{bump:i?"major":"minor",isBreaking:i,errors:this.errors.getErrors()}}checkTypeBreakingChanges({from:t,to:r}){for(let[i,n]of Object.entries(t)){let a=r[i];if(!a){this.errors.add(`Type "${i}" was removed.`);continue}this.areTypeDeclarationsCompatible({from:n,to:a})||this.errors.add(`Type "${i}" has an incompatible change.`)}}checkErrorsBreakingChanges({from:t,to:r}){for(let[i,n]of Object.entries(t)){let a=Object.values(r).find(u=>u.name.errorId===n.name.errorId);if(!a){this.errors.add(`Error "${n.name.errorId}" with status code "${n.statusCode}" was removed.`);continue}this.checkErrorBreakingChanges({from:n,to:a})}}checkErrorBreakingChanges({from:t,to:r}){if(t.type!=null){if(r.type==null){this.errors.add(`Error "${t.name.errorId}" with status code "${t.statusCode}" had its type removed.`);return}this.areTypeReferencesCompatible({from:t.type,to:r.type})||this.errors.add(`Error "${t.name.errorId}" type reference changed.`)}this.areDeclaredErrorNamesCompatible({from:t.name,to:r.name})||this.errors.add(`Error "${t.name.errorId}" name changed.`),this.areNameAndWireValuesCompatible({from:t.discriminantValue,to:r.discriminantValue})||this.errors.add(`Error "${t.name.errorId}" discriminant value changed.`)}checkServicesBreakingChanges({from:t,to:r}){for(let[i,n]of Object.entries(t)){let a=r[i];if(!a){this.errors.add(`Service "${i}" was removed.`);continue}this.checkServiceBreakingChanges({id:i,from:n,to:a})}}checkServiceBreakingChanges({id:t,from:r,to:i}){this.checkHeadersBreakingChanges({id:t,from:r.headers,to:i.headers}),this.checkEndpointsBreakingChanges({id:t,from:r,to:i})}checkEndpointsBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.endpoints.map(u=>[u.id,u])),a=Object.fromEntries(i.endpoints.map(u=>[u.id,u]));for(let[u,l]of Object.entries(n)){let d=a[u];if(!d){this.errors.add(`Endpoint "${u}" was removed.`);continue}this.checkEndpointBreakingChanges({id:u,from:l,to:d})}}checkEndpointBreakingChanges({id:t,from:r,to:i}){this.checkHttpMethodsBreakingChanges({id:t,from:r.method,to:i.method}),this.checkHttpPathsBreakingChanges({id:t,from:r.fullPath,to:i.fullPath}),this.checkPathParametersBreakingChanges({id:t,from:r.pathParameters,to:i.pathParameters}),this.checkQueryParametersBreakingChanges({id:t,from:r.queryParameters,to:i.queryParameters}),this.checkHeadersBreakingChanges({id:t,from:r.headers,to:i.headers}),r.requestBody!=null&&(i.requestBody!=null?this.checkHttpRequestBodiesCompatible({id:t,from:r.requestBody,to:i.requestBody}):this.errors.add(`Request body was removed from endpoint "${r.id}".`)),r.response!=null&&(i.response!=null?this.checkHttpResponseBreakingChanges({id:t,from:r.response,to:i.response}):this.errors.add(`Response was removed from endpoint "${r.id}".`)),(r.pagination!=null&&i.pagination==null||r.pagination==null&&i.pagination!=null)&&this.errors.add(`Pagination was ${r.pagination!=null?"added":"removed"} from endpoint "${r.id}".`)}checkPathParametersBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.map(u=>[u.name.originalName,u])),a=Object.fromEntries(i.map(u=>[u.name.originalName,u]));for(let[u,l]of Object.entries(n)){let d=a[u];if(!d){this.errors.add(`Path parameter "${u}" was removed from endpoint "${t}".`);continue}this.areTypeReferencesCompatible({from:l.valueType,to:d.valueType})||this.errors.add(`Path parameter "${u}" type changed in endpoint "${t}".`)}}checkQueryParametersBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.map(u=>[u.name.wireValue,u])),a=Object.fromEntries(i.map(u=>[u.name.wireValue,u]));this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(n).map(([u,l])=>[u,l.valueType])),to:Object.fromEntries(Object.entries(a).map(([u,l])=>[u,l.valueType]))});for(let[u,l]of Object.entries(n)){let d=a[u];if(!d){this.errors.add(`Query parameter "${u}" was removed from endpoint "${t}".`);continue}this.areTypeReferencesCompatible({from:l.valueType,to:d.valueType})||this.errors.add(`Query parameter "${u}" type changed in endpoint "${t}".`),l.allowMultiple!==d.allowMultiple&&this.errors.add(`Query parameter "${u}" allow-multiple values changed in endpoint "${t}".`)}}checkHeadersBreakingChanges({id:t,from:r,to:i}){let n=Object.fromEntries(r.map(u=>[u.name.wireValue,u])),a=Object.fromEntries(i.map(u=>[u.name.wireValue,u]));this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(n).map(([u,l])=>[u,l.valueType])),to:Object.fromEntries(Object.entries(a).map(([u,l])=>[u,l.valueType]))});for(let[u,l]of Object.entries(n)){let d=a[u];if(!d){this.errors.add(`Header "${u}" was removed from ${t}.`);continue}this.areTypeReferencesCompatible({from:l.valueType,to:d.valueType})||this.errors.add(`Header "${u}" type changed in ${t}.`)}}checkHttpMethodsBreakingChanges({id:t,from:r,to:i}){r!==i&&this.errors.add(`HTTP method changed in ${t}.`)}checkHttpPathsBreakingChanges({id:t,from:r,to:i}){this.areHttpPathsCompatible({from:r,to:i})||this.errors.add(`HTTP path changed in ${t}.`)}areHttpPathsCompatible({from:t,to:r}){if(t.head!==r.head||t.parts.length!==r.parts.length)return!1;for(let i=0;i<t.parts.length;i++){let n=t.parts[i];if(n==null)return!1;let a=r.parts[i];if(a==null||n.pathParameter!==a.pathParameter||n.tail!==a.tail)return!1}return!0}checkHttpRequestBodiesCompatible({id:t,from:r,to:i}){switch(r.type){case"inlinedRequestBody":if(i.type==="inlinedRequestBody"&&this.areInlinedRequestBodiesCompatible({from:r,to:i}))return;break;case"reference":if(i.type==="reference"&&this.areReferenceRequestBodiesCompatible({from:r,to:i}))return;break;case"fileUpload":if(i.type==="fileUpload"&&this.areFileUploadRequestBodiesCompatible({from:r,to:i}))return;break;case"bytes":if(i.type==="bytes")return;break;default:So(r)}this.errors.add(`Request body type changed from "${r.type}" to "${i.type}" in endpoint "${t}".`)}areInlinedRequestBodiesCompatible({from:t,to:r}){let i=this.getInlinedRequestBody(t),n=this.getInlinedRequestBody(r);return this.checkForNewInlinedRequestBodyProperties({from:i,to:n}),Object.entries(i).every(([a,u])=>{let l=n[a];return l?this.areTypeReferencesCompatible({from:u,to:l}):(this.errors.add(`Request body property "${a}" was removed.`),!1)})}areReferenceRequestBodiesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.requestBodyType,to:r.requestBodyType})}areFileUploadRequestBodiesCompatible({from:t,to:r}){let i=this.getFileUploadRequest(t.properties),n=this.getFileUploadRequest(r.properties);this.checkForNewFileUploadRequestProperties({from:i,to:n});for(let[a,u]of Object.entries(i)){let l=n[a];if(!l)return this.errors.add(`File upload property "${a}" was removed.`),!1;if(u==="file"&&l!=="file")return this.errors.add(`File upload property "${a}" type changed.`),!1;if(u==="fileArray"&&l!=="fileArray")return this.errors.add(`File upload property "${a}" type changed.`),!1;if(u!=="file"&&u!=="fileArray"&&l!=="file"&&l!=="fileArray"&&!this.areTypeReferencesCompatible({from:u,to:l}))return this.errors.add(`File upload property "${a}" type changed.`),!1}return!0}checkHttpResponseBreakingChanges({id:t,from:r,to:i}){if(r.statusCode!==i.statusCode&&this.errors.add(`Response status code changed from "${r.statusCode}" to "${i.statusCode}".`),!(r.body==null&&i.body==null)){if(r.body==null||i.body==null){this.errors.add(`Response body was ${r.body==null?"added":"removed"}.`);return}switch(r.body.type){case"json":if(i.body.type==="json"){this.areJsonResponsesCompatible({from:r.body.value,to:i.body.value});return}break;case"fileDownload":if(i.body.type==="fileDownload")return;break;case"text":if(i.body.type==="text")return;break;case"bytes":if(i.body.type==="bytes")return;break;case"streaming":if(i.body.type==="streaming"){this.areStreamingResponsesCompatible({from:r.body.value,to:i.body.value});return}break;case"streamParameter":if(i.body.type==="streamParameter"){this.areStreamingResponsesCompatible({from:r.body.streamResponse,to:i.body.streamResponse});return}break;default:So(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:So(t)}return this.errors.add(`Streaming response type "${t.type}" is not compatible with type "${r.type}".`),!1}areTypeDeclarationsCompatible({from:t,to:r}){return this.areDeclaredTypeNamesCompatible({from:t.name,to:r.name})&&this.areTypeShapesCompatible({from:t.shape,to:r.shape})}areTypeShapesCompatible({from:t,to:r}){switch(t.type){case"alias":if(r.type==="alias")return this.areAliasTypesCompatible({from:t,to:r});break;case"enum":if(r.type==="enum")return this.areEnumTypesCompatible({from:t,to:r});break;case"object":if(r.type==="object")return this.areObjectTypesCompatible({from:t,to:r});break;case"union":if(r.type==="union")return this.areUnionTypesCompatible({from:t,to:r});break;case"undiscriminatedUnion":if(r.type==="undiscriminatedUnion")return this.areUndiscriminatedUnionTypesCompatible({from:t,to:r});break;default:So(t)}return this.errors.add(`Type "${t.type}" is not compatible with type "${r.type}".`),!1}areAliasTypesCompatible({from:t,to:r}){return this.areTypeReferencesCompatible({from:t.aliasOf,to:r.aliasOf})}areEnumTypesCompatible({from:t,to:r}){let i=Object.fromEntries(t.values.map(a=>[a.name.wireValue,a])),n=Object.fromEntries(r.values.map(a=>[a.name.wireValue,a]));return Object.keys(i).length!==Object.keys(n).length?!1:Object.values(i).every(a=>{let u=n[a.name.wireValue];return u?this.areNameAndWireValuesCompatible({from:a.name,to:u.name}):(this.errors.add(`Enum value "${a.name.wireValue}" was removed.`),!1)})}areObjectTypesCompatible({from:t,to:r}){let i=Object.fromEntries([...t.properties.map(a=>[a.name.wireValue,a]),...t.extendedProperties?.map(a=>[a.name.wireValue,a])??[]]),n=Object.fromEntries([...r.properties.map(a=>[a.name.wireValue,a]),...r.extendedProperties?.map(a=>[a.name.wireValue,a])??[]]);return this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(i).map(([a,u])=>[a,u.valueType])),to:Object.fromEntries(Object.entries(n).map(([a,u])=>[a,u.valueType]))}),Object.values(i).every(a=>{let u=n[a.name.wireValue];return u?this.areObjectPropertiesCompatible({from:a,to:u}):(this.errors.add(`Object property "${a.name.wireValue}" was removed.`),!1)})}areObjectPropertiesCompatible({from:t,to:r}){return this.areNameAndWireValuesCompatible({from:t.name,to:r.name})&&this.areTypeReferencesCompatible({from:t.valueType,to:r.valueType})}areUnionTypesCompatible({from:t,to:r}){if(!this.areNameAndWireValuesCompatible({from:t.discriminant,to:r.discriminant}))return this.errors.add(`Union type with discriminant value "${t.discriminant.wireValue}" changed.`),!1;let i=new Set(t.extends.map(s=>this.getKeyForDeclaration(s))),n=new Set(r.extends.map(s=>this.getKeyForDeclaration(s)));for(let s of i)if(!n.has(s))return this.errors.add(`Extended type "${s}" was removed.`),!1;let a=Object.fromEntries(t.baseProperties.map(s=>[s.name.wireValue,s])),u=Object.fromEntries(r.baseProperties.map(s=>[s.name.wireValue,s]));for(let s of Object.values(a)){let o=u[s.name.wireValue];if(!o)return this.errors.add(`Union type with discriminant value "${s.name.wireValue}" no longer has a property named "${s.name.wireValue}".`),!1;if(!this.areObjectPropertiesCompatible({from:s,to:o}))return!1}this.checkForNewRequiredTypeReferences({from:Object.fromEntries(Object.entries(a).map(([s,o])=>[s,o.valueType])),to:Object.fromEntries(Object.entries(u).map(([s,o])=>[s,o.valueType]))});let l=Object.fromEntries(t.types.map(s=>[s.discriminantValue.wireValue,s])),d=Object.fromEntries(r.types.map(s=>[s.discriminantValue.wireValue,s]));return Object.values(l).every(s=>{let o=d[s.discriminantValue.wireValue];return o?this.areSingleUnionTypesCompatible({from:s.shape,to:o.shape}):(this.errors.add(`Union type for discriminant value "${s.discriminantValue.wireValue}" was removed.`),!1)})}areSingleUnionTypesCompatible({from:t,to:r}){switch(t.propertiesType){case"samePropertiesAsObject":if(r.propertiesType==="samePropertiesAsObject")return this.areDeclaredTypeNamesCompatible({from:t,to:r});break;case"singleProperty":if(r.propertiesType==="singleProperty")return this.areNameAndWireValuesCompatible({from:t.name,to:r.name})&&this.areTypeReferencesCompatible({from:t.type,to:r.type});break;case"noProperties":if(r.propertiesType==="noProperties")return!0;break;default:So(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:So(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:So(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:So(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:So(i)}return r}getKeyForDeclaration({name:t,fernFilepath:r}){return`${r.allParts.map(n=>n.camelCase.unsafeName).join(".")}.${t.pascalCase.unsafeName}`}};function fnn(e,t,r){let{environments:i,changedBaseUrlIds1:n,changedBaseUrlIds2:a}=wBE(e.environments,t.environments,r),{services:u,websocketChannels:l}=SBE(e,t,n,a);return{apiName:e.apiName,basePath:e.basePath,selfHosted:e.selfHosted&&t.selfHosted,apiDisplayName:e.apiDisplayName??t.apiDisplayName,apiDocs:e.apiDocs??t.apiDocs,auth:{requirement:e.auth?.requirement??t.auth?.requirement,schemes:t.auth?.schemes?.length!=null&&t.auth.schemes.length>(e.auth?.schemes?.length??0)?t.auth.schemes:e.auth?.schemes??[],docs:e.auth?.docs??t.auth?.docs},headers:[...e.headers??[],...t.headers??[]],environments:i,types:{...e.types??{},...t.types??{}},constants:{...e.constants??{},...t.constants??{}},errors:{...e.errors??{},...t.errors??{}},services:u,webhookGroups:{...e.webhookGroups??{},...t.webhookGroups??{}},subpackages:jBE(e.subpackages,t.subpackages),websocketChannels:l,rootPackage:{service:e.rootPackage.service??t.rootPackage.service,types:[...e.rootPackage.types??[],...t.rootPackage.types??[]],errors:[...e.rootPackage.errors??[],...t.rootPackage.errors??[]],subpackages:[...e.rootPackage.subpackages??[],...(t.rootPackage.subpackages??[]).filter(d=>!e.rootPackage.subpackages?.includes(d))],fernFilepath:e.rootPackage.fernFilepath??t.rootPackage.fernFilepath,webhooks:e.rootPackage.webhooks??t.rootPackage.webhooks,websocket:e.rootPackage.websocket??t.rootPackage.websocket,hasEndpointsInTree:e.rootPackage.hasEndpointsInTree||t.rootPackage.hasEndpointsInTree,navigationConfig:e.rootPackage.navigationConfig??t.rootPackage.navigationConfig,docs:e.rootPackage.docs??t.rootPackage.docs},fdrApiDefinitionId:e.fdrApiDefinitionId??t.fdrApiDefinitionId,apiVersion:e.apiVersion??t.apiVersion,idempotencyHeaders:[...e.idempotencyHeaders??[],...t.idempotencyHeaders??[]],pathParameters:[...e.pathParameters??[],...t.pathParameters??[]],errorDiscriminationStrategy:e.errorDiscriminationStrategy??t.errorDiscriminationStrategy,variables:[...e.variables??[],...t.variables??[]],serviceTypeReferenceInfo:e.serviceTypeReferenceInfo??t.serviceTypeReferenceInfo,readmeConfig:e.readmeConfig??t.readmeConfig,sourceConfig:e.sourceConfig??t.sourceConfig,publishConfig:e.publishConfig??t.publishConfig,dynamic:e.dynamic??t.dynamic,sdkConfig:e.sdkConfig??t.sdkConfig,audiences:[...e.audiences??[],...t.audiences??[]]}}function jBE(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 wBE(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=oO_(e),n=oO_(t);if(i&&n&&e.environments.type==="singleBaseUrl"&&t.environments.type==="singleBaseUrl")return{environments:{defaultEnvironment:e.defaultEnvironment??t.defaultEnvironment,environments:$R.singleBaseUrl({environments:[...e.environments.environments,...t.environments.environments]})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let a=i?t.defaultEnvironment:e.defaultEnvironment,u=e.environments,l=t.environments;if(u.type==="singleBaseUrl"&&l.type==="singleBaseUrl"){let d=i?l:u,s=i?u:l,o={},{deconflictedEnvironments2:c,changedBaseUrlIds2:b}=DBE(d,s,r);if(d.environments[0]==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let g="Base",O=r.generateName("Base");return d.environments.forEach(m=>{o[m.id]=g}),{environments:{defaultEnvironment:a,environments:$R.multipleBaseUrls({baseUrls:[{id:g,name:O},...c.environments.map(m=>({id:m.id,name:m.name}))],environments:d.environments.map(m=>({id:m.id,name:m.name,urls:{[g]:m.url,...Object.fromEntries(c.environments.map(w=>[w.id,w.url]))},docs:void 0}))})},changedBaseUrlIds1:i?b:o,changedBaseUrlIds2:i?o:b}}if(u.type==="multipleBaseUrls"&&l.type==="singleBaseUrl"||u.type==="singleBaseUrl"&&l.type==="multipleBaseUrls"){let d=u.type==="singleBaseUrl"?u:l,s=u.type==="multipleBaseUrls"?u:l,{deconflictedEnvironments1:o,changedBaseUrlIds1:c}=EBE(d,s,r);return{environments:{defaultEnvironment:a,environments:$R.multipleBaseUrls({baseUrls:[...s.baseUrls,...o.environments.map(b=>({id:b.id,name:b.name}))],environments:s.environments.map(b=>({...b,urls:{...b.urls,...Object.fromEntries(o.environments.map(g=>[g.id,g.url]))}}))})},changedBaseUrlIds1:u.type==="singleBaseUrl"?c:void 0,changedBaseUrlIds2:u.type==="singleBaseUrl"?void 0:c}}if(u.type==="multipleBaseUrls"&&l.type==="multipleBaseUrls"){let{deconflictedEnvironments:d,changedBaseUrlIds:s}=MBE(u,l,r);return{environments:{defaultEnvironment:a,environments:$R.multipleBaseUrls({baseUrls:[...u.baseUrls,...d.baseUrls],environments:u.environments.flatMap(o=>d.environments.map(c=>({...o,urls:{...o.urls,...c.urls}})))})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:s}}return{environments:e??t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0}}function SBE(e,t,r,i){if(r!=null)for(let[u,l]of Object.entries(r)){for(let d of Object.values(e.services))for(let s of Object.values(d.endpoints))s.baseUrl==u&&(s.baseUrl=l),s.v2BaseUrls?.includes(u)&&(s.v2BaseUrls=s.v2BaseUrls.map(o=>o===u?l:o));for(let d of Object.values(e.websocketChannels??{}))d.baseUrl==u&&(d.baseUrl=l)}if(i!=null)for(let[u,l]of Object.entries(i)){for(let d of Object.values(t.services))for(let s of Object.values(d.endpoints))s.baseUrl==u&&(s.baseUrl=l),s.v2BaseUrls?.includes(u)&&(s.v2BaseUrls=s.v2BaseUrls.map(o=>o===u?l:o));for(let d of Object.values(t.websocketChannels??{}))d.baseUrl==u&&(d.baseUrl=l)}let n=e.services;for(let[u,l]of Object.entries(t.services))n[u]==null?n[u]=l:n[u]={availability:l.availability,name:l.name,displayName:l.displayName,basePath:l.basePath,endpoints:[...n[u].endpoints??[],...l.endpoints],pathParameters:[...n[u].pathParameters??[],...l.pathParameters??[]],headers:[...n[u].headers??[],...l.headers??[]],encoding:l.encoding,transport:l.transport,audiences:[...n[u].audiences??[],...l.audiences??[]]};let a={...e.websocketChannels??{},...t.websocketChannels??{}};return{services:n,websocketChannels:a}}function DBE(e,t,r){let i={},n=new Set(e.environments.map(s=>s.id)),a=new Set(e.environments.map(s=>s.name)),u=new Map(e.environments.map(s=>[s.url,s.id])),l=t.environments.filter(s=>{let o=u.get(s.url);return o!=null?(i[s.id]=o,!1):!0}).map(s=>{if(n.has(s.id)||a.has(s.name)){let o=awc(s.id,n);return i[s.id]=o,{...s,id:o,name:r.generateName(o)}}return s});return{deconflictedEnvironments2:$R.singleBaseUrl({environments:l}),changedBaseUrlIds2:i}}function EBE(e,t,r){let i={},n=new Set(t.baseUrls.map(d=>d.id)),a=new Set(t.baseUrls.map(d=>d.name)),u=e.environments.map(d=>{if(n.has(d.id)||a.has(d.name)){let s=awc(d.id,n);return i[d.id]=s,{...d,id:s,name:r.generateName(s)}}return d});return{deconflictedEnvironments1:$R.singleBaseUrl({environments:u}),changedBaseUrlIds1:i}}function MBE(e,t,r){let i={},n=new Set(e.baseUrls.map(s=>s.id)),a=new Set(e.baseUrls.map(s=>s.name)),u=t.baseUrls.map(s=>{if(n.has(s.id)||a.has(s.name)){let o=awc(s.id,n);return i[s.id]=o,{...s,id:o,name:r.generateName(o)}}return s}),l=t.environments.map(s=>({...s,urls:Object.fromEntries(Object.entries(s.urls).map(([o,c])=>[i[o]??o,c]))}));return{deconflictedEnvironments:$R.multipleBaseUrls({baseUrls:u,environments:l}),changedBaseUrlIds:i}}function oO_(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 awc(e,t){let r=e,i=1;for(;t.has(r);)r=`${e}-${i}`,i++;return r}var e_=class e{breadcrumbs=[];context;static STRING=Vs.TypeReference.primitive({v1:"STRING",v2:Vs.PrimitiveTypeV2.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=Vs.TypeReference.container(Vs.ContainerType.optional(e.STRING));constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r}};var sO_=require("fs/promises");var owc=class{_map;_path;_lastScalar;_fragments;_count;constructor(){this._map={},this._path=[],this._lastScalar="",this._fragments=[],this._count=0}get map(){return this._map}resolveNode(t,r){if(t.path==="."&&(r="."),!this._map[r]){let{line:i,position:n,lineStart:a}=t;this._map[r]={line:i,position:n,lineStart:a}}t.children&&t.children.length>0&&t.children.forEach(i=>{this.resolveNode(i,(r==="."?"":r)+"."+i.path)})}iterFragments(t,r){for(let i=this._fragments.length-1;i>=0;i--){if(!this._fragments[i].path.startsWith(t)||this._fragments[i].path===t)continue;let n=this._fragments.pop();r(n)}}handleState(t,r){if(t==="close"){let i=r.result,n=r.kind,a=this._path.join(".");if(n==="scalar"){this._path.pop(),this._lastScalar=`${i}`;let{line:u,position:l,lineStart:d}=r;this._path.length===0?this._map["."+i]={line:u,position:l,lineStart:d}:this._fragments.push({path:this._path.join(".")+"."+i,line:u,position:l,lineStart:d})}else if(n==="mapping"){let u={path:a,children:[],line:0,position:0,lineStart:0},l=0;this.iterFragments(a,d=>{l++,!((!d.children||d.children.length===0)&&l%2===1)&&(this._path.length===1?this.resolveNode(d,d.path):(u.children.push({...d,path:d.path.slice(a.length+1)}),u.line=d.line,u.position=d.position,u.lineStart=d.lineStart))}),u.children&&u.children.length>0&&this._fragments.push(u),this._path.pop()}else if(n==="sequence"){let u={path:a,children:[],line:0,position:0,lineStart:0},l=new Set,d=i.length;this.iterFragments(a,s=>{l.has(s.position)||(d--,l.add(s.position),this._path.length===1?this.resolveNode(s,`${a}.${d}`):(u.children.push({...s,path:d.toString()}),u.line=s.line,u.position=s.position,u.lineStart=s.lineStart))}),u.children&&u.children.length>0&&this._fragments.push(u),this._path.pop()}else this._path.pop()}if(t==="open"){if(this._count===0){let{line:i,position:n,lineStart:a}=r;this._map["."]={line:i,position:n,lineStart:a}}this._path.push(this._lastScalar),this._count++}}listen(){return this.handleState.bind(this)}lookup(t){let r=t instanceof Array?t.map(n=>`${n}`).join("."):`${t}`;r.startsWith(".")||(r="."+r),r.startsWith("..")&&(r=r.slice(1)),r=r.replace(/\[/g,".").replace(/\]/g,"");let i=this._map[r];if(i)return{line:i.line+1,column:i.position-i.lineStart+1,position:i.position}}},uO_=owc;var Umi;(function(e){e.WARNING="warning",e.ERROR="error"})(Umi||(Umi={}));var gNi=class{errors=[];logger;breadcrumbToLineNumberMapper;relativeFilepathToSpec;constructor({logger:t,relativeFilepathToSpec:r}){this.logger=t,this.relativeFilepathToSpec=r,r&&(this.breadcrumbToLineNumberMapper=new uwc({logger:t,relativePathToFile:Ia.of(r)}))}collect(t){this.errors.push(t)}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}dedupe(){let t=[],r=new Set,i=0;for(let n of this.errors){let a=n.path?n.path.join("->"):"",u=`${n.message}|${n.level||Umi.WARNING}|${a}`;r.has(u)?i++:(r.add(u),t.push(n))}return this.errors=t,i}getErrorStats(){this.dedupe();let t=0,r=0;for(let i of this.errors)i.level===Umi.ERROR?t++:r++;return{numErrors:t,numWarnings:r}}async logErrors({logWarnings:t}){this.dedupe();for(let r of this.errors)if(!(r.level===Umi.WARNING&&!t))switch(r.level){case Umi.ERROR:if(this.logger.log(pb.Error,r.message),r.path&&r.path.length>0){let i=await this.breadcrumbToLineNumberMapper?.getSourceLocation(r.path),n=i?`${this.relativeFilepathToSpec}:${i.line}:${i.column}`:r.path.join(" -> ");this.logger.log(pb.Error,` - at location (${n})`)}break}}},uwc=class{logger;relativePathToFile;map=new uO_;initialized=!1;constructor({relativePathToFile:t,logger:r}){this.relativePathToFile=t,this.logger=r}async initialize(){if(!this.initialized)try{let t=await(0,sO_.readFile)(this.relativePathToFile,"utf-8");wd.load(t,{listener:this.map.listen()}),this.initialized=!0}catch(t){this.logger.log(pb.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 d7=class e{args;spec;settings;errorCollector;logger;generationLanguage;smartCasing;casingsGenerator;namespace;exampleGenerationArgs;authOverrides;environmentOverrides;globalHeaderOverrides;enableUniqueErrorsPerEndpoint;generateV1Examples;constructor(t){this.args=t,this.spec=t.spec,this.settings=t.settings,this.errorCollector=t.errorCollector,this.logger=t.logger,this.generationLanguage=t.generationLanguage,this.smartCasing=t.smartCasing,this.namespace=t.namespace,this.casingsGenerator=iee({generationLanguage:t.generationLanguage,keywords:void 0,smartCasing:t.smartCasing}),this.exampleGenerationArgs=t.exampleGenerationArgs,this.authOverrides=t.authOverrides,this.environmentOverrides=t.environmentOverrides,this.globalHeaderOverrides=t.globalHeaderOverrides,this.enableUniqueErrorsPerEndpoint=t.enableUniqueErrorsPerEndpoint,this.generateV1Examples=t.generateV1Examples}static BREADCRUMBS_TO_IGNORE=["properties","allOf","anyOf"];convertBreadcrumbsToName(t){let r=t.filter((n,a)=>!(/^\d+$/.test(n)||e.BREADCRUMBS_TO_IGNORE.includes(n)||a===0&&n==="components"||a===1&&n==="schemas"||t[0]==="paths"&&(a===0||a===1&&["get","post","put","delete","patch"].includes(n)||a===2&&t[1]!=null&&["get","post","put","delete","patch"].includes(t[1])&&n==="parameters"))),i=S_(r.join("_"));return i.charAt(0).toUpperCase()+i.slice(1)}createFernFilepath(t={}){let r=this.namespace!=null?[this.casingsGenerator.generateName(this.namespace)]:[],i=t.name!=null?this.casingsGenerator.generateName(t.name):void 0;return{allParts:i?[...r,i]:r,packagePath:r,file:i}}resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:i}){let n=this.spec,a=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(u=>u.replace(/~1/g,"/"));for(let u of a){if(typeof n!="object"||n==null)return i||this.errorCollector.collect({level:Umi.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1};n=n[u]}return n==null?(i||this.errorCollector.collect({level:Umi.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1}):{resolved:!0,value:n}}getErrorMessageForMissingRef({reference:t}){let r=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/");return r.length>=3&&r[0]==="components"&&r[1]==="schemas"?`Schema ${r[2]} does not exist`:`${t.$ref} does not exist`}async resolveMaybeExternalReference(t){let r=this.spec,i,n=!1,a=null,u;if(this.isExternalReference(t.$ref)){n=!0;let s=t.$ref.split("#"),o=s[0];if(i=s[1],!o)return{resolved:!1};u=o;let c=await fetch(o);if(!c.ok)return{resolved:!1};try{let b=await c.text();try{a=JSON.parse(b),r=a}catch{a=wd.load(b),r=a}if(r==null)return{resolved:!1}}catch{return{resolved:!1}}if(!i)return{resolved:!0,value:r}}let l=i??t.$ref;if(l==null||typeof l!="string")return{resolved:!1};let d=l.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(s=>s.replace(/~1/g,"/"));for(let s of d){if(typeof r!="object"||r==null)return{resolved:!1};r=r[s]}if(r==null)return{resolved:!1};if(n&&typeof r=="object"&&r!==null){let s=new Set;s.add(t.$ref),r=await this.resolveNestedExternalReferences(r,a,s,u)}return{resolved:!0,value:r}}async resolveNestedExternalReferences(t,r,i,n){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){let u=[];for(let l of t)u.push(await this.resolveNestedExternalReferences(l,r,i,n));return u}if(this.isReferenceObject(t)){let u=t.$ref;if(this.isExternalReference(u)){if(i.has(u))return t;i.add(u);let l=await this.resolveMaybeExternalReference({$ref:u});if(i.delete(u),l.resolved)return l.value}else{let l=`${n}${u}`;if(i.has(l))return t;i.add(l);let d=r,s=u.substring(2).split("/").map(o=>o.replace(/~1/g,"/").replace(/~0/g,"~"));for(let o of s){if(typeof d!="object"||d===null)return t;d=d[o]}if(d!=null){let o=await this.resolveNestedExternalReferences(d,r,i,n);return i.delete(u),o}i.delete(u)}return t}let a={};for(let[u,l]of Object.entries(t))typeof l=="object"&&l!==null?a[u]=await this.resolveNestedExternalReferences(l,r,i,n):a[u]=l;return a}getExamplesFromSchema({schema:t,breadcrumbs:r}){if(t==null)return[];let i=t.example!=null?[t.example]:[];return t.examples!=null&&(Array.isArray(t.examples)?i.push(...t.examples):this.errorCollector.collect({message:"Received non-array schema examples",path:r})),i}getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:r,defaultExampleName:i}){if(t==null)return[];let n=[];if(t.example!=null){let a=this.generateUniqueName({prefix:i??`${r.join("_")}_example`,existingNames:[]});n.push([a,t.example])}return t.examples!=null&&n.push(...Object.entries(t.examples)),n}resolveMaybeReference({schemaOrReference:t,breadcrumbs:r,skipErrorCollector:i}){if(this.isReferenceObject(t)){let n=this.resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:i});return n.resolved?n.value:void 0}return t}resolveExample(t){if(!this.isReferenceObject(t))return t;let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}resolveExampleWithValue(t){if(!this.isReferenceObject(t))return this.returnExampleValue(t);let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}returnExampleValue(t){return this.isExampleWithValue(t)?t.value:t}getPropertyAccess(t){let r=t;for(;this.isReferenceObject(r);){let 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 Urr.ReadOnly;if(n)return Urr.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 l=this.resolveReference({reference:n});if(!l.resolved)continue;a=l.value}let u=this.getReadOnlyWriteOnlyFromSchema(a);r=r&&u.readOnly,i=i&&u.writeOnly}return{readOnly:r,writeOnly:i}}else return{readOnly:!!t.readOnly,writeOnly:!!t.writeOnly}}getAudiences({operation:t,breadcrumbs:r}){let n=new VH.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 VH.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(n!=null)return{status:n,message:void 0};if(t.deprecated===!0)return{status:gL.Deprecated,message:void 0}}getTypeIdFromSchemaReference(t){let r=t.$ref.match(/\/schemas\/(.+)$/);if(!(!r||!r[1]))return r[1]}createNamedTypeReference(t,r){return Xc.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(t),typeId:t,displayName:r,default:void 0,inline:!1})}typeReferenceToDeclaredTypeName(t){if(t.type!=="named")return;let r=t.typeId;return{typeId:r,fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(r),displayName:t.displayName}}removeSchemaFromInlinedTypes({id:t,inlinedTypes:r}){return Object.fromEntries(Object.entries(r).filter(([i])=>i!==t))}static maybeTrimPrefix(t,r){return t.startsWith(r)?t.slice(r.length):t}generateUniqueName({prefix:t,existingNames:r}){if(!r.includes(t))return t;let i=0;for(;r.includes(`${t}_${i}`);)i++;return`${t}_${i}`}isReferenceObject(t){return typeof t=="object"&&t!==null&&"$ref"in t}isExternalReference(t){return typeof t=="string"&&(t.startsWith("http://")||t.startsWith("https://"))}isReferenceObjectWithIdentifier(t){return this.isReferenceObject(t)&&("title"in t||"name"in t||"messageId"in t)}isExampleWithSummary(t){return typeof t=="object"&&t!=null&&"summary"in t}isExampleWithValue(t){return typeof t=="object"&&t!=null&&"value"in t}isOptional(t){return t.type==="container"&&t.container.type==="optional"}isNullable(t){return t.type==="container"&&t.container.type==="nullable"}isList(t){return t.type==="container"&&t.container.type==="list"}isFile(t){return t.type==="primitive"&&t.primitive.v2?.type==="string"&&t.primitive.v2.validation?.format==="binary"}getAsString(t){if(typeof t=="string")return t}getAsInteger(t){if(typeof t=="number"&&Number.isInteger(t))return t}getAsNumber(t){if(typeof t=="number")return t}getAsBoolean(t){if(typeof t=="boolean")return t}getAsArray(t){if(Array.isArray(t))return t}getAsObject(t){if(typeof t=="object"&&t!==null&&!Array.isArray(t))return t}getGroup({groupParts:t,namespace:r}){let i=[];return r!=null&&i.push(r),i.push(...t??[]),i}isObjectSchemaType(t){return t.type==="object"||t.properties!=null}};var Yg=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 VH={};Po(VH,{AudienceExtension:()=>Jtu,FernAvailabilityExtension:()=>Ktu,FernEnumExtension:()=>tru,FernIgnoreExtension:()=>Mnn,FernOptionalExtension:()=>rru,FernTypeExtension:()=>aru,FernTypeNameExtension:()=>oru,SdkGroupNameExtension:()=>iru,SdkMethodNameExtension:()=>nru});var Jtu=class extends Yg{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 Ktu=class extends Yg{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 gL.InDevelopment;case"PRE_RELEASE":case"BETA":return gL.PreRelease;case"GENERAL_AVAILABILITY":case"GA":return gL.GeneralAvailability;case"DEPRECATED":return gL.Deprecated;default:return}}};var $3e={};Po($3e,{BRAND:()=>eIE,DIRTY:()=>dnn,EMPTY_PATH:()=>CBE,INVALID:()=>W0,NEVER:()=>NIE,OK:()=>eK,ParseStatus:()=>WH,Schema:()=>Pw,ZodAny:()=>PNi,ZodArray:()=>$mi,ZodBigInt:()=>_nn,ZodBoolean:()=>hnn,ZodBranded:()=>i5a,ZodCatch:()=>Dnn,ZodDate:()=>ynn,ZodDefault:()=>Snn,ZodDiscriminatedUnion:()=>Ztu,ZodEffects:()=>H3e,ZodEnum:()=>jnn,ZodError:()=>oue,ZodFirstPartyTypeKind:()=>dg,ZodFunction:()=>eru,ZodIntersection:()=>Onn,ZodIssueCode:()=>td,ZodLazy:()=>mnn,ZodLiteral:()=>Pnn,ZodMap:()=>yJn,ZodNaN:()=>bJn,ZodNativeEnum:()=>wnn,ZodNever:()=>sQt,ZodNull:()=>bnn,ZodNullable:()=>hor,ZodNumber:()=>pnn,ZodObject:()=>uue,ZodOptional:()=>V3e,ZodParsedType:()=>U_,ZodPipeline:()=>n5a,ZodPromise:()=>jNi,ZodReadonly:()=>Enn,ZodRecord:()=>ktu,ZodSchema:()=>Pw,ZodSet:()=>vJn,ZodString:()=>mNi,ZodSymbol:()=>_Jn,ZodTransformer:()=>H3e,ZodTuple:()=>_or,ZodType:()=>Pw,ZodUndefined:()=>vnn,ZodUnion:()=>gnn,ZodUnknown:()=>Hmi,ZodVoid:()=>hJn,addIssueToContext:()=>Rp,any:()=>cIE,array:()=>pIE,bigint:()=>nIE,boolean:()=>gO_,coerce:()=>xIE,custom:()=>yO_,date:()=>aIE,datetimeRegex:()=>_O_,defaultErrorMap:()=>Vmi,discriminatedUnion:()=>vIE,effect:()=>AIE,enum:()=>DIE,function:()=>jIE,getErrorMap:()=>fJn,getParsedType:()=>por,instanceof:()=>rIE,intersection:()=>bIE,isAborted:()=>Ytu,isAsync:()=>dJn,isDirty:()=>Xtu,isValid:()=>ONi,late:()=>tIE,lazy:()=>wIE,literal:()=>SIE,makeIssue:()=>r5a,map:()=>mIE,nan:()=>iIE,nativeEnum:()=>EIE,never:()=>fIE,null:()=>sIE,nullable:()=>TIE,number:()=>bO_,object:()=>_IE,objectUtil:()=>swc,oboolean:()=>RIE,onumber:()=>zIE,optional:()=>qIE,ostring:()=>IIE,pipeline:()=>BIE,preprocess:()=>CIE,promise:()=>MIE,quotelessJson:()=>ABE,record:()=>OIE,set:()=>PIE,setErrorMap:()=>TBE,strictObject:()=>hIE,string:()=>vO_,symbol:()=>oIE,transformer:()=>AIE,tuple:()=>gIE,undefined:()=>uIE,union:()=>yIE,unknown:()=>lIE,util:()=>fD,void:()=>dIE});var fD;(function(e){e.assertEqual=n=>{};function t(n){}e.assertIs=t;function r(n){throw new Error}e.assertNever=r,e.arrayToEnum=n=>{let a={};for(let u of n)a[u]=u;return a},e.getValidEnumValues=n=>{let a=e.objectKeys(n).filter(l=>typeof n[n[l]]!="number"),u={};for(let l of a)u[l]=n[l];return e.objectValues(u)},e.objectValues=n=>e.objectKeys(n).map(function(a){return n[a]}),e.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{let a=[];for(let u in n)Object.prototype.hasOwnProperty.call(n,u)&&a.push(u);return a},e.find=(n,a)=>{for(let u of n)if(a(u))return u},e.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function i(n,a=" | "){return n.map(u=>typeof u=="string"?`'${u}'`:u).join(a)}e.joinValues=i,e.jsonStringifyReplacer=(n,a)=>typeof a=="bigint"?a.toString():a})(fD||(fD={}));var swc;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(swc||(swc={}));var U_=fD.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),por=e=>{switch(typeof e){case"undefined":return U_.undefined;case"string":return U_.string;case"number":return Number.isNaN(e)?U_.nan:U_.number;case"boolean":return U_.boolean;case"function":return U_.function;case"bigint":return U_.bigint;case"symbol":return U_.symbol;case"object":return Array.isArray(e)?U_.array:e===null?U_.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?U_.promise:typeof Map<"u"&&e instanceof Map?U_.map:typeof Set<"u"&&e instanceof Set?U_.set:typeof Date<"u"&&e instanceof Date?U_.date:U_.object;default:return U_.unknown}};var td=fD.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),ABE=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),oue=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(a){return a.message},i={_errors:[]},n=a=>{for(let u of a.issues)if(u.code==="invalid_union")u.unionErrors.map(n);else if(u.code==="invalid_return_type")n(u.returnTypeError);else if(u.code==="invalid_arguments")n(u.argumentsError);else if(u.path.length===0)i._errors.push(r(u));else{let l=i,d=0;for(;d<u.path.length;){let s=u.path[d];d===u.path.length-1?(l[s]=l[s]||{_errors:[]},l[s]._errors.push(r(u))):l[s]=l[s]||{_errors:[]},l=l[s],d++}}};return n(this),i}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,fD.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r={},i=[];for(let n of this.issues)if(n.path.length>0){let a=n.path[0];r[a]=r[a]||[],r[a].push(t(n))}else i.push(t(n));return{formErrors:i,fieldErrors:r}}get formErrors(){return this.flatten()}};oue.create=e=>new oue(e);var qBE=(e,t)=>{let r;switch(e.code){case td.invalid_type:e.received===U_.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case td.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,fD.jsonStringifyReplacer)}`;break;case td.unrecognized_keys:r=`Unrecognized key(s) in object: ${fD.joinValues(e.keys,", ")}`;break;case td.invalid_union:r="Invalid input";break;case td.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${fD.joinValues(e.options)}`;break;case td.invalid_enum_value:r=`Invalid enum value. Expected ${fD.joinValues(e.options)}, received '${e.received}'`;break;case td.invalid_arguments:r="Invalid function arguments";break;case td.invalid_return_type:r="Invalid function return type";break;case td.invalid_date:r="Invalid date";break;case td.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:fD.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case td.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case td.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case td.custom:r="Invalid input";break;case td.invalid_intersection_types:r="Intersection results could not be merged";break;case td.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case td.not_finite:r="Number must be finite";break;default:r=t.defaultError,fD.assertNever(e)}return{message:r}},Vmi=qBE;var cO_=Vmi;function TBE(e){cO_=e}function fJn(){return cO_}var r5a=e=>{let{data:t,path:r,errorMaps:i,issueData:n}=e,a=[...r,...n.path||[]],u={...n,path:a};if(n.message!==void 0)return{...n,path:a,message:n.message};let l="",d=i.filter(s=>!!s).slice().reverse();for(let s of d)l=s(u,{data:t,defaultError:l}).message;return{...n,path:a,message:l}},CBE=[];function Rp(e,t){let r=fJn(),i=r5a({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===Vmi?void 0:Vmi].filter(n=>!!n)});e.common.issues.push(i)}var WH=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let i=[];for(let n of r){if(n.status==="aborted")return W0;n.status==="dirty"&&t.dirty(),i.push(n.value)}return{status:t.value,value:i}}static async mergeObjectAsync(t,r){let i=[];for(let n of r){let a=await n.key,u=await n.value;i.push({key:a,value:u})}return e.mergeObjectSync(t,i)}static mergeObjectSync(t,r){let i={};for(let n of r){let{key:a,value:u}=n;if(a.status==="aborted"||u.status==="aborted")return W0;a.status==="dirty"&&t.dirty(),u.status==="dirty"&&t.dirty(),a.value!=="__proto__"&&(typeof u.value<"u"||n.alwaysSet)&&(i[a.value]=u.value)}return{status:t.value,value:i}}},W0=Object.freeze({status:"aborted"}),dnn=e=>({status:"dirty",value:e}),eK=e=>({status:"valid",value:e}),Ytu=e=>e.status==="aborted",Xtu=e=>e.status==="dirty",ONi=e=>e.status==="valid",dJn=e=>typeof Promise<"u"&&e instanceof Promise;var sv;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(sv||(sv={}));var W3e=class{constructor(t,r,i,n){this._cachedPath=[],this.parent=t,this.data=r,this._path=i,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},lO_=(e,t)=>{if(ONi(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new oue(e.common.issues);return this._error=r,this._error}}};function tj(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:i,description:n}=e;if(t&&(r||i))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:n}:{errorMap:(u,l)=>{let{message:d}=e;return u.code==="invalid_enum_value"?{message:d??l.defaultError}:typeof l.data>"u"?{message:d??i??l.defaultError}:u.code!=="invalid_type"?{message:l.defaultError}:{message:d??r??l.defaultError}},description:n}}var Pw=class{get description(){return this._def.description}_getType(t){return por(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:por(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new WH,ctx:{common:t.parent.common,data:t.data,parsedType:por(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(dJn(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let i=this.safeParse(t,r);if(i.success)return i.data;throw i.error}safeParse(t,r){let i={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:por(t)},n=this._parseSync({data:t,path:i.path,parent:i});return lO_(i,n)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:por(t)};if(!this["~standard"].async)try{let i=this._parseSync({data:t,path:[],parent:r});return ONi(i)?{value:i.value}:{issues:r.common.issues}}catch(i){i?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(i=>ONi(i)?{value:i.value}:{issues:r.common.issues})}async parseAsync(t,r){let i=await this.safeParseAsync(t,r);if(i.success)return i.data;throw i.error}async safeParseAsync(t,r){let i={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:por(t)},n=this._parse({data:t,path:i.path,parent:i}),a=await(dJn(n)?n:Promise.resolve(n));return lO_(i,a)}refine(t,r){let i=n=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(n):r;return this._refinement((n,a)=>{let u=t(n),l=()=>a.addIssue({code:td.custom,...i(n)});return typeof Promise<"u"&&u instanceof Promise?u.then(d=>d?!0:(l(),!1)):u?!0:(l(),!1)})}refinement(t,r){return this._refinement((i,n)=>t(i)?!0:(n.addIssue(typeof r=="function"?r(i,n):r),!1))}_refinement(t){return new H3e({schema:this,typeName:dg.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return V3e.create(this,this._def)}nullable(){return hor.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return $mi.create(this)}promise(){return jNi.create(this,this._def)}or(t){return gnn.create([this,t],this._def)}and(t){return Onn.create(this,t,this._def)}transform(t){return new H3e({...tj(this._def),schema:this,typeName:dg.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new Snn({...tj(this._def),innerType:this,defaultValue:r,typeName:dg.ZodDefault})}brand(){return new i5a({typeName:dg.ZodBranded,type:this,...tj(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new Dnn({...tj(this._def),innerType:this,catchValue:r,typeName:dg.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return n5a.create(this,t)}readonly(){return Enn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},BBE=/^c[^\s-]{8,}$/i,IBE=/^[0-9a-z]+$/,zBE=/^[0-9A-HJKMNP-TV-Z]{26}$/i,RBE=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,xBE=/^[a-z0-9_-]{21}$/i,NBE=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,FBE=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,LBE=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,UBE="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",cwc,VBE=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,WBE=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,HBE=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,$BE=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,GBE=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,QBE=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dO_="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",JBE=new RegExp(`^${dO_}$`);function pO_(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function KBE(e){return new RegExp(`^${pO_(e)}$`)}function _O_(e){let t=`${dO_}T${pO_(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function YBE(e,t){return!!((t==="v4"||!t)&&VBE.test(e)||(t==="v6"||!t)&&HBE.test(e))}function XBE(e,t){if(!NBE.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let i=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(i));return!(typeof n!="object"||n===null||"typ"in n&&n?.typ!=="JWT"||!n.alg||t&&n.alg!==t)}catch{return!1}}function ZBE(e,t){return!!((t==="v4"||!t)&&WBE.test(e)||(t==="v6"||!t)&&$BE.test(e))}var mNi=class e extends Pw{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==U_.string){let a=this._getOrReturnCtx(t);return Rp(a,{code:td.invalid_type,expected:U_.string,received:a.parsedType}),W0}let i=new WH,n;for(let a of this._def.checks)if(a.kind==="min")t.data.length<a.value&&(n=this._getOrReturnCtx(t,n),Rp(n,{code:td.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),i.dirty());else if(a.kind==="max")t.data.length>a.value&&(n=this._getOrReturnCtx(t,n),Rp(n,{code:td.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),i.dirty());else if(a.kind==="length"){let u=t.data.length>a.value,l=t.data.length<a.value;(u||l)&&(n=this._getOrReturnCtx(t,n),u?Rp(n,{code:td.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):l&&Rp(n,{code:td.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),i.dirty())}else if(a.kind==="email")LBE.test(t.data)||(n=this._getOrReturnCtx(t,n),Rp(n,{validation:"email",code:td.invalid_string,message:a.message}),i.dirty());else if(a.kind==="emoji")cwc||(cwc=new RegExp(UBE,"u")),cwc.test(t.data)||(n=this._getOrReturnCtx(t,n),Rp(n,{validation:"emoji",code:td.invalid_string,message:a.message}),i.dirty());else if(a.kind==="uuid")RBE.test(t.data)||(n=this._getOrReturnCtx(t,n),Rp(n,{validation:"uuid",code:td.invalid_string,message:a.message}),i.dirty());else if(a.kind==="nanoid")xBE.test(t.data)||(n=this._getOrReturnCtx(t,n),Rp(n,{validation:"nanoid",code:td.invalid_string,message:a.message}),i.dirty());else if(a.kind==="cuid")BBE.test(t.data)||(n=this._getOrReturnCtx(t,n),Rp(n,{validation:"cuid",code:td.invalid_string,message:a.message}),i.dirty());else if(a.kind==="cuid2")IBE.test(t.data)||(n=this._getOrReturnCtx(t,n),Rp(n,{validation:"cuid2",code:td.invalid_string,message:a.message}),i.dirty());else if(a.kind==="ulid")zBE.test(t.data)||(n=this._getOrReturnCtx(t,n),Rp(n,{validation:"ulid",code:td.invalid_string,message:a.message}),i.dirty());else if(a.kind==="url")try{new URL(t.data)}catch{n=this._getOrReturnCtx(t,n),Rp(n,{validation:"url",code:td.invalid_string,message:a.message}),i.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(t.data)||(n=this._getOrReturnCtx(t,n),Rp(n,{validation:"regex",code:td.invalid_string,message:a.message}),i.dirty())):a.kind==="trim"?t.data=t.data.trim():a.kind==="includes"?t.data.includes(a.value,a.position)||(n=this._getOrReturnCtx(t,n),Rp(n,{code:td.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),i.dirty()):a.kind==="toLowerCase"?t.data=t.data.toLowerCase():a.kind==="toUpperCase"?t.data=t.data.toUpperCase():a.kind==="startsWith"?t.data.startsWith(a.value)||(n=this._getOrReturnCtx(t,n),Rp(n,{code:td.invalid_string,validation:{startsWith:a.value},message:a.message}),i.dirty()):a.kind==="endsWith"?t.data.endsWith(a.value)||(n=this._getOrReturnCtx(t,n),Rp(n,{code:td.invalid_string,validation:{endsWith:a.value},message:a.message}),i.dirty()):a.kind==="datetime"?_O_(a).test(t.data)||(n=this._getOrReturnCtx(t,n),Rp(n,{code:td.invalid_string,validation:"datetime",message:a.message}),i.dirty()):a.kind==="date"?JBE.test(t.data)||(n=this._getOrReturnCtx(t,n),Rp(n,{code:td.invalid_string,validation:"date",message:a.message}),i.dirty()):a.kind==="time"?KBE(a).test(t.data)||(n=this._getOrReturnCtx(t,n),Rp(n,{code:td.invalid_string,validation:"time",message:a.message}),i.dirty()):a.kind==="duration"?FBE.test(t.data)||(n=this._getOrReturnCtx(t,n),Rp(n,{validation:"duration",code:td.invalid_string,message:a.message}),i.dirty()):a.kind==="ip"?YBE(t.data,a.version)||(n=this._getOrReturnCtx(t,n),Rp(n,{validation:"ip",code:td.invalid_string,message:a.message}),i.dirty()):a.kind==="jwt"?XBE(t.data,a.alg)||(n=this._getOrReturnCtx(t,n),Rp(n,{validation:"jwt",code:td.invalid_string,message:a.message}),i.dirty()):a.kind==="cidr"?ZBE(t.data,a.version)||(n=this._getOrReturnCtx(t,n),Rp(n,{validation:"cidr",code:td.invalid_string,message:a.message}),i.dirty()):a.kind==="base64"?GBE.test(t.data)||(n=this._getOrReturnCtx(t,n),Rp(n,{validation:"base64",code:td.invalid_string,message:a.message}),i.dirty()):a.kind==="base64url"?QBE.test(t.data)||(n=this._getOrReturnCtx(t,n),Rp(n,{validation:"base64url",code:td.invalid_string,message:a.message}),i.dirty()):fD.assertNever(a);return{status:i.value,value:t.data}}_regex(t,r,i){return this.refinement(n=>t.test(n),{validation:r,code:td.invalid_string,...sv.errToObj(i)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...sv.errToObj(t)})}url(t){return this._addCheck({kind:"url",...sv.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...sv.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...sv.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...sv.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...sv.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...sv.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...sv.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...sv.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...sv.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...sv.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...sv.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...sv.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...sv.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...sv.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...sv.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...sv.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...sv.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...sv.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...sv.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...sv.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...sv.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...sv.errToObj(r)})}nonempty(t){return this.min(1,sv.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};mNi.create=e=>new mNi({checks:[],typeName:dg.ZodString,coerce:e?.coerce??!1,...tj(e)});function kBE(e,t){let r=(e.toString().split(".")[1]||"").length,i=(t.toString().split(".")[1]||"").length,n=r>i?r:i,a=Number.parseInt(e.toFixed(n).replace(".","")),u=Number.parseInt(t.toFixed(n).replace(".",""));return a%u/10**n}var pnn=class e extends Pw{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==U_.number){let a=this._getOrReturnCtx(t);return Rp(a,{code:td.invalid_type,expected:U_.number,received:a.parsedType}),W0}let i,n=new WH;for(let a of this._def.checks)a.kind==="int"?fD.isInteger(t.data)||(i=this._getOrReturnCtx(t,i),Rp(i,{code:td.invalid_type,expected:"integer",received:"float",message:a.message}),n.dirty()):a.kind==="min"?(a.inclusive?t.data<a.value:t.data<=a.value)&&(i=this._getOrReturnCtx(t,i),Rp(i,{code:td.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?t.data>a.value:t.data>=a.value)&&(i=this._getOrReturnCtx(t,i),Rp(i,{code:td.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="multipleOf"?kBE(t.data,a.value)!==0&&(i=this._getOrReturnCtx(t,i),Rp(i,{code:td.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):a.kind==="finite"?Number.isFinite(t.data)||(i=this._getOrReturnCtx(t,i),Rp(i,{code:td.not_finite,message:a.message}),n.dirty()):fD.assertNever(a);return{status:n.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,sv.toString(r))}gt(t,r){return this.setLimit("min",t,!1,sv.toString(r))}lte(t,r){return this.setLimit("max",t,!0,sv.toString(r))}lt(t,r){return this.setLimit("max",t,!1,sv.toString(r))}setLimit(t,r,i,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:i,message:sv.toString(n)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:sv.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:sv.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:sv.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:sv.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:sv.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:sv.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:sv.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:sv.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:sv.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&fD.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let i of this._def.checks){if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;i.kind==="min"?(r===null||i.value>r)&&(r=i.value):i.kind==="max"&&(t===null||i.value<t)&&(t=i.value)}return Number.isFinite(r)&&Number.isFinite(t)}};pnn.create=e=>new pnn({checks:[],typeName:dg.ZodNumber,coerce:e?.coerce||!1,...tj(e)});var _nn=class e extends Pw{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==U_.bigint)return this._getInvalidInput(t);let i,n=new WH;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?t.data<a.value:t.data<=a.value)&&(i=this._getOrReturnCtx(t,i),Rp(i,{code:td.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?t.data>a.value:t.data>=a.value)&&(i=this._getOrReturnCtx(t,i),Rp(i,{code:td.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="multipleOf"?t.data%a.value!==BigInt(0)&&(i=this._getOrReturnCtx(t,i),Rp(i,{code:td.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):fD.assertNever(a);return{status:n.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return Rp(r,{code:td.invalid_type,expected:U_.bigint,received:r.parsedType}),W0}gte(t,r){return this.setLimit("min",t,!0,sv.toString(r))}gt(t,r){return this.setLimit("min",t,!1,sv.toString(r))}lte(t,r){return this.setLimit("max",t,!0,sv.toString(r))}lt(t,r){return this.setLimit("max",t,!1,sv.toString(r))}setLimit(t,r,i,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:i,message:sv.toString(n)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:sv.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:sv.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:sv.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:sv.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:sv.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};_nn.create=e=>new _nn({checks:[],typeName:dg.ZodBigInt,coerce:e?.coerce??!1,...tj(e)});var hnn=class extends Pw{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==U_.boolean){let i=this._getOrReturnCtx(t);return Rp(i,{code:td.invalid_type,expected:U_.boolean,received:i.parsedType}),W0}return eK(t.data)}};hnn.create=e=>new hnn({typeName:dg.ZodBoolean,coerce:e?.coerce||!1,...tj(e)});var ynn=class e extends Pw{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==U_.date){let a=this._getOrReturnCtx(t);return Rp(a,{code:td.invalid_type,expected:U_.date,received:a.parsedType}),W0}if(Number.isNaN(t.data.getTime())){let a=this._getOrReturnCtx(t);return Rp(a,{code:td.invalid_date}),W0}let i=new WH,n;for(let a of this._def.checks)a.kind==="min"?t.data.getTime()<a.value&&(n=this._getOrReturnCtx(t,n),Rp(n,{code:td.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),i.dirty()):a.kind==="max"?t.data.getTime()>a.value&&(n=this._getOrReturnCtx(t,n),Rp(n,{code:td.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),i.dirty()):fD.assertNever(a);return{status:i.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:sv.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:sv.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};ynn.create=e=>new ynn({checks:[],coerce:e?.coerce||!1,typeName:dg.ZodDate,...tj(e)});var _Jn=class extends Pw{_parse(t){if(this._getType(t)!==U_.symbol){let i=this._getOrReturnCtx(t);return Rp(i,{code:td.invalid_type,expected:U_.symbol,received:i.parsedType}),W0}return eK(t.data)}};_Jn.create=e=>new _Jn({typeName:dg.ZodSymbol,...tj(e)});var vnn=class extends Pw{_parse(t){if(this._getType(t)!==U_.undefined){let i=this._getOrReturnCtx(t);return Rp(i,{code:td.invalid_type,expected:U_.undefined,received:i.parsedType}),W0}return eK(t.data)}};vnn.create=e=>new vnn({typeName:dg.ZodUndefined,...tj(e)});var bnn=class extends Pw{_parse(t){if(this._getType(t)!==U_.null){let i=this._getOrReturnCtx(t);return Rp(i,{code:td.invalid_type,expected:U_.null,received:i.parsedType}),W0}return eK(t.data)}};bnn.create=e=>new bnn({typeName:dg.ZodNull,...tj(e)});var PNi=class extends Pw{constructor(){super(...arguments),this._any=!0}_parse(t){return eK(t.data)}};PNi.create=e=>new PNi({typeName:dg.ZodAny,...tj(e)});var Hmi=class extends Pw{constructor(){super(...arguments),this._unknown=!0}_parse(t){return eK(t.data)}};Hmi.create=e=>new Hmi({typeName:dg.ZodUnknown,...tj(e)});var sQt=class extends Pw{_parse(t){let r=this._getOrReturnCtx(t);return Rp(r,{code:td.invalid_type,expected:U_.never,received:r.parsedType}),W0}};sQt.create=e=>new sQt({typeName:dg.ZodNever,...tj(e)});var hJn=class extends Pw{_parse(t){if(this._getType(t)!==U_.undefined){let i=this._getOrReturnCtx(t);return Rp(i,{code:td.invalid_type,expected:U_.void,received:i.parsedType}),W0}return eK(t.data)}};hJn.create=e=>new hJn({typeName:dg.ZodVoid,...tj(e)});var $mi=class e extends Pw{_parse(t){let{ctx:r,status:i}=this._processInputParams(t),n=this._def;if(r.parsedType!==U_.array)return Rp(r,{code:td.invalid_type,expected:U_.array,received:r.parsedType}),W0;if(n.exactLength!==null){let u=r.data.length>n.exactLength.value,l=r.data.length<n.exactLength.value;(u||l)&&(Rp(r,{code:u?td.too_big:td.too_small,minimum:l?n.exactLength.value:void 0,maximum:u?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),i.dirty())}if(n.minLength!==null&&r.data.length<n.minLength.value&&(Rp(r,{code:td.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),i.dirty()),n.maxLength!==null&&r.data.length>n.maxLength.value&&(Rp(r,{code:td.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),i.dirty()),r.common.async)return Promise.all([...r.data].map((u,l)=>n.type._parseAsync(new W3e(r,u,r.path,l)))).then(u=>WH.mergeArray(i,u));let a=[...r.data].map((u,l)=>n.type._parseSync(new W3e(r,u,r.path,l)));return WH.mergeArray(i,a)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:sv.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:sv.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:sv.toString(r)}})}nonempty(t){return this.min(1,t)}};$mi.create=(e,t)=>new $mi({type:e,minLength:null,maxLength:null,exactLength:null,typeName:dg.ZodArray,...tj(t)});function pJn(e){if(e instanceof uue){let t={};for(let r in e.shape){let i=e.shape[r];t[r]=V3e.create(pJn(i))}return new uue({...e._def,shape:()=>t})}else return e instanceof $mi?new $mi({...e._def,type:pJn(e.element)}):e instanceof V3e?V3e.create(pJn(e.unwrap())):e instanceof hor?hor.create(pJn(e.unwrap())):e instanceof _or?_or.create(e.items.map(t=>pJn(t))):e}var uue=class e extends Pw{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=fD.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==U_.object){let s=this._getOrReturnCtx(t);return Rp(s,{code:td.invalid_type,expected:U_.object,received:s.parsedType}),W0}let{status:i,ctx:n}=this._processInputParams(t),{shape:a,keys:u}=this._getCached(),l=[];if(!(this._def.catchall instanceof sQt&&this._def.unknownKeys==="strip"))for(let s in n.data)u.includes(s)||l.push(s);let d=[];for(let s of u){let o=a[s],c=n.data[s];d.push({key:{status:"valid",value:s},value:o._parse(new W3e(n,c,n.path,s)),alwaysSet:s in n.data})}if(this._def.catchall instanceof sQt){let s=this._def.unknownKeys;if(s==="passthrough")for(let o of l)d.push({key:{status:"valid",value:o},value:{status:"valid",value:n.data[o]}});else if(s==="strict")l.length>0&&(Rp(n,{code:td.unrecognized_keys,keys:l}),i.dirty());else if(s!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let s=this._def.catchall;for(let o of l){let c=n.data[o];d.push({key:{status:"valid",value:o},value:s._parse(new W3e(n,c,n.path,o)),alwaysSet:o in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let s=[];for(let o of d){let c=await o.key,b=await o.value;s.push({key:c,value:b,alwaysSet:o.alwaysSet})}return s}).then(s=>WH.mergeObjectSync(i,s)):WH.mergeObjectSync(i,d)}get shape(){return this._def.shape()}strict(t){return sv.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,i)=>{let n=this._def.errorMap?.(r,i).message??i.defaultError;return r.code==="unrecognized_keys"?{message:sv.errToObj(t).message??n}:{message:n}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:dg.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};for(let i of fD.objectKeys(t))t[i]&&this.shape[i]&&(r[i]=this.shape[i]);return new e({...this._def,shape:()=>r})}omit(t){let r={};for(let i of fD.objectKeys(this.shape))t[i]||(r[i]=this.shape[i]);return new e({...this._def,shape:()=>r})}deepPartial(){return pJn(this)}partial(t){let r={};for(let i of fD.objectKeys(this.shape)){let n=this.shape[i];t&&!t[i]?r[i]=n:r[i]=n.optional()}return new e({...this._def,shape:()=>r})}required(t){let r={};for(let i of fD.objectKeys(this.shape))if(t&&!t[i])r[i]=this.shape[i];else{let a=this.shape[i];for(;a instanceof V3e;)a=a._def.innerType;r[i]=a}return new e({...this._def,shape:()=>r})}keyof(){return hO_(fD.objectKeys(this.shape))}};uue.create=(e,t)=>new uue({shape:()=>e,unknownKeys:"strip",catchall:sQt.create(),typeName:dg.ZodObject,...tj(t)});uue.strictCreate=(e,t)=>new uue({shape:()=>e,unknownKeys:"strict",catchall:sQt.create(),typeName:dg.ZodObject,...tj(t)});uue.lazycreate=(e,t)=>new uue({shape:e,unknownKeys:"strip",catchall:sQt.create(),typeName:dg.ZodObject,...tj(t)});var gnn=class extends Pw{_parse(t){let{ctx:r}=this._processInputParams(t),i=this._def.options;function n(a){for(let l of a)if(l.result.status==="valid")return l.result;for(let l of a)if(l.result.status==="dirty")return r.common.issues.push(...l.ctx.common.issues),l.result;let u=a.map(l=>new oue(l.ctx.common.issues));return Rp(r,{code:td.invalid_union,unionErrors:u}),W0}if(r.common.async)return Promise.all(i.map(async a=>{let u={...r,common:{...r.common,issues:[]},parent:null};return{result:await a._parseAsync({data:r.data,path:r.path,parent:u}),ctx:u}})).then(n);{let a,u=[];for(let d of i){let s={...r,common:{...r.common,issues:[]},parent:null},o=d._parseSync({data:r.data,path:r.path,parent:s});if(o.status==="valid")return o;o.status==="dirty"&&!a&&(a={result:o,ctx:s}),s.common.issues.length&&u.push(s.common.issues)}if(a)return r.common.issues.push(...a.ctx.common.issues),a.result;let l=u.map(d=>new oue(d));return Rp(r,{code:td.invalid_union,unionErrors:l}),W0}}get options(){return this._def.options}};gnn.create=(e,t)=>new gnn({options:e,typeName:dg.ZodUnion,...tj(t)});var Wmi=e=>e instanceof mnn?Wmi(e.schema):e instanceof H3e?Wmi(e.innerType()):e instanceof Pnn?[e.value]:e instanceof jnn?e.options:e instanceof wnn?fD.objectValues(e.enum):e instanceof Snn?Wmi(e._def.innerType):e instanceof vnn?[void 0]:e instanceof bnn?[null]:e instanceof V3e?[void 0,...Wmi(e.unwrap())]:e instanceof hor?[null,...Wmi(e.unwrap())]:e instanceof i5a||e instanceof Enn?Wmi(e.unwrap()):e instanceof Dnn?Wmi(e._def.innerType):[],Ztu=class e extends Pw{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==U_.object)return Rp(r,{code:td.invalid_type,expected:U_.object,received:r.parsedType}),W0;let i=this.discriminator,n=r.data[i],a=this.optionsMap.get(n);return a?r.common.async?a._parseAsync({data:r.data,path:r.path,parent:r}):a._parseSync({data:r.data,path:r.path,parent:r}):(Rp(r,{code:td.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),W0)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,i){let n=new Map;for(let a of r){let u=Wmi(a.shape[t]);if(!u.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let l of u){if(n.has(l))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(l)}`);n.set(l,a)}}return new e({typeName:dg.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:n,...tj(i)})}};function lwc(e,t){let r=por(e),i=por(t);if(e===t)return{valid:!0,data:e};if(r===U_.object&&i===U_.object){let n=fD.objectKeys(t),a=fD.objectKeys(e).filter(l=>n.indexOf(l)!==-1),u={...e,...t};for(let l of a){let d=lwc(e[l],t[l]);if(!d.valid)return{valid:!1};u[l]=d.data}return{valid:!0,data:u}}else if(r===U_.array&&i===U_.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let a=0;a<e.length;a++){let u=e[a],l=t[a],d=lwc(u,l);if(!d.valid)return{valid:!1};n.push(d.data)}return{valid:!0,data:n}}else return r===U_.date&&i===U_.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Onn=class extends Pw{_parse(t){let{status:r,ctx:i}=this._processInputParams(t),n=(a,u)=>{if(Ytu(a)||Ytu(u))return W0;let l=lwc(a.value,u.value);return l.valid?((Xtu(a)||Xtu(u))&&r.dirty(),{status:r.value,value:l.data}):(Rp(i,{code:td.invalid_intersection_types}),W0)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([a,u])=>n(a,u)):n(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}};Onn.create=(e,t,r)=>new Onn({left:e,right:t,typeName:dg.ZodIntersection,...tj(r)});var _or=class e extends Pw{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==U_.array)return Rp(i,{code:td.invalid_type,expected:U_.array,received:i.parsedType}),W0;if(i.data.length<this._def.items.length)return Rp(i,{code:td.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),W0;!this._def.rest&&i.data.length>this._def.items.length&&(Rp(i,{code:td.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let a=[...i.data].map((u,l)=>{let d=this._def.items[l]||this._def.rest;return d?d._parse(new W3e(i,u,i.path,l)):null}).filter(u=>!!u);return i.common.async?Promise.all(a).then(u=>WH.mergeArray(r,u)):WH.mergeArray(r,a)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};_or.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new _or({items:e,typeName:dg.ZodTuple,rest:null,...tj(t)})};var ktu=class e extends Pw{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==U_.object)return Rp(i,{code:td.invalid_type,expected:U_.object,received:i.parsedType}),W0;let n=[],a=this._def.keyType,u=this._def.valueType;for(let l in i.data)n.push({key:a._parse(new W3e(i,l,i.path,l)),value:u._parse(new W3e(i,i.data[l],i.path,l)),alwaysSet:l in i.data});return i.common.async?WH.mergeObjectAsync(r,n):WH.mergeObjectSync(r,n)}get element(){return this._def.valueType}static create(t,r,i){return r instanceof Pw?new e({keyType:t,valueType:r,typeName:dg.ZodRecord,...tj(i)}):new e({keyType:mNi.create(),valueType:t,typeName:dg.ZodRecord,...tj(r)})}},yJn=class extends Pw{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==U_.map)return Rp(i,{code:td.invalid_type,expected:U_.map,received:i.parsedType}),W0;let n=this._def.keyType,a=this._def.valueType,u=[...i.data.entries()].map(([l,d],s)=>({key:n._parse(new W3e(i,l,i.path,[s,"key"])),value:a._parse(new W3e(i,d,i.path,[s,"value"]))}));if(i.common.async){let l=new Map;return Promise.resolve().then(async()=>{for(let d of u){let s=await d.key,o=await d.value;if(s.status==="aborted"||o.status==="aborted")return W0;(s.status==="dirty"||o.status==="dirty")&&r.dirty(),l.set(s.value,o.value)}return{status:r.value,value:l}})}else{let l=new Map;for(let d of u){let s=d.key,o=d.value;if(s.status==="aborted"||o.status==="aborted")return W0;(s.status==="dirty"||o.status==="dirty")&&r.dirty(),l.set(s.value,o.value)}return{status:r.value,value:l}}}};yJn.create=(e,t,r)=>new yJn({valueType:t,keyType:e,typeName:dg.ZodMap,...tj(r)});var vJn=class e extends Pw{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==U_.set)return Rp(i,{code:td.invalid_type,expected:U_.set,received:i.parsedType}),W0;let n=this._def;n.minSize!==null&&i.data.size<n.minSize.value&&(Rp(i,{code:td.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),r.dirty()),n.maxSize!==null&&i.data.size>n.maxSize.value&&(Rp(i,{code:td.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),r.dirty());let a=this._def.valueType;function u(d){let s=new Set;for(let o of d){if(o.status==="aborted")return W0;o.status==="dirty"&&r.dirty(),s.add(o.value)}return{status:r.value,value:s}}let l=[...i.data.values()].map((d,s)=>a._parse(new W3e(i,d,i.path,s)));return i.common.async?Promise.all(l).then(d=>u(d)):u(l)}min(t,r){return new e({...this._def,minSize:{value:t,message:sv.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:sv.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};vJn.create=(e,t)=>new vJn({valueType:e,minSize:null,maxSize:null,typeName:dg.ZodSet,...tj(t)});var eru=class e extends Pw{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==U_.function)return Rp(r,{code:td.invalid_type,expected:U_.function,received:r.parsedType}),W0;function i(l,d){return r5a({data:l,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,fJn(),Vmi].filter(s=>!!s),issueData:{code:td.invalid_arguments,argumentsError:d}})}function n(l,d){return r5a({data:l,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,fJn(),Vmi].filter(s=>!!s),issueData:{code:td.invalid_return_type,returnTypeError:d}})}let a={errorMap:r.common.contextualErrorMap},u=r.data;if(this._def.returns instanceof jNi){let l=this;return eK(async function(...d){let s=new oue([]),o=await l._def.args.parseAsync(d,a).catch(g=>{throw s.addIssue(i(d,g)),s}),c=await Reflect.apply(u,this,o);return await l._def.returns._def.type.parseAsync(c,a).catch(g=>{throw s.addIssue(n(c,g)),s})})}else{let l=this;return eK(function(...d){let s=l._def.args.safeParse(d,a);if(!s.success)throw new oue([i(d,s.error)]);let o=Reflect.apply(u,this,s.data),c=l._def.returns.safeParse(o,a);if(!c.success)throw new oue([n(o,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:_or.create(t).rest(Hmi.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,i){return new e({args:t||_or.create([]).rest(Hmi.create()),returns:r||Hmi.create(),typeName:dg.ZodFunction,...tj(i)})}},mnn=class extends Pw{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};mnn.create=(e,t)=>new mnn({getter:e,typeName:dg.ZodLazy,...tj(t)});var Pnn=class extends Pw{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return Rp(r,{received:r.data,code:td.invalid_literal,expected:this._def.value}),W0}return{status:"valid",value:t.data}}get value(){return this._def.value}};Pnn.create=(e,t)=>new Pnn({value:e,typeName:dg.ZodLiteral,...tj(t)});function hO_(e,t){return new jnn({values:e,typeName:dg.ZodEnum,...tj(t)})}var jnn=class e extends Pw{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),i=this._def.values;return Rp(r,{expected:fD.joinValues(i),received:r.parsedType,code:td.invalid_type}),W0}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),i=this._def.values;return Rp(r,{received:r.data,code:td.invalid_enum_value,options:i}),W0}return eK(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return e.create(t,{...this._def,...r})}exclude(t,r=this._def){return e.create(this.options.filter(i=>!t.includes(i)),{...this._def,...r})}};jnn.create=hO_;var wnn=class extends Pw{_parse(t){let r=fD.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(t);if(i.parsedType!==U_.string&&i.parsedType!==U_.number){let n=fD.objectValues(r);return Rp(i,{expected:fD.joinValues(n),received:i.parsedType,code:td.invalid_type}),W0}if(this._cache||(this._cache=new Set(fD.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let n=fD.objectValues(r);return Rp(i,{received:i.data,code:td.invalid_enum_value,options:n}),W0}return eK(t.data)}get enum(){return this._def.values}};wnn.create=(e,t)=>new wnn({values:e,typeName:dg.ZodNativeEnum,...tj(t)});var jNi=class extends Pw{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==U_.promise&&r.common.async===!1)return Rp(r,{code:td.invalid_type,expected:U_.promise,received:r.parsedType}),W0;let i=r.parsedType===U_.promise?r.data:Promise.resolve(r.data);return eK(i.then(n=>this._def.type.parseAsync(n,{path:r.path,errorMap:r.common.contextualErrorMap})))}};jNi.create=(e,t)=>new jNi({type:e,typeName:dg.ZodPromise,...tj(t)});var H3e=class extends Pw{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===dg.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:i}=this._processInputParams(t),n=this._def.effect||null,a={addIssue:u=>{Rp(i,u),u.fatal?r.abort():r.dirty()},get path(){return i.path}};if(a.addIssue=a.addIssue.bind(a),n.type==="preprocess"){let u=n.transform(i.data,a);if(i.common.async)return Promise.resolve(u).then(async l=>{if(r.value==="aborted")return W0;let d=await this._def.schema._parseAsync({data:l,path:i.path,parent:i});return d.status==="aborted"?W0:d.status==="dirty"?dnn(d.value):r.value==="dirty"?dnn(d.value):d});{if(r.value==="aborted")return W0;let l=this._def.schema._parseSync({data:u,path:i.path,parent:i});return l.status==="aborted"?W0:l.status==="dirty"?dnn(l.value):r.value==="dirty"?dnn(l.value):l}}if(n.type==="refinement"){let u=l=>{let d=n.refinement(l,a);if(i.common.async)return Promise.resolve(d);if(d instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(i.common.async===!1){let l=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return l.status==="aborted"?W0:(l.status==="dirty"&&r.dirty(),u(l.value),{status:r.value,value:l.value})}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(l=>l.status==="aborted"?W0:(l.status==="dirty"&&r.dirty(),u(l.value).then(()=>({status:r.value,value:l.value}))))}if(n.type==="transform")if(i.common.async===!1){let u=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!ONi(u))return W0;let l=n.transform(u.value,a);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:l}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(u=>ONi(u)?Promise.resolve(n.transform(u.value,a)).then(l=>({status:r.value,value:l})):W0);fD.assertNever(n)}};H3e.create=(e,t,r)=>new H3e({schema:e,typeName:dg.ZodEffects,effect:t,...tj(r)});H3e.createWithPreprocess=(e,t,r)=>new H3e({schema:t,effect:{type:"preprocess",transform:e},typeName:dg.ZodEffects,...tj(r)});var V3e=class extends Pw{_parse(t){return this._getType(t)===U_.undefined?eK(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};V3e.create=(e,t)=>new V3e({innerType:e,typeName:dg.ZodOptional,...tj(t)});var hor=class extends Pw{_parse(t){return this._getType(t)===U_.null?eK(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};hor.create=(e,t)=>new hor({innerType:e,typeName:dg.ZodNullable,...tj(t)});var Snn=class extends Pw{_parse(t){let{ctx:r}=this._processInputParams(t),i=r.data;return r.parsedType===U_.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Snn.create=(e,t)=>new Snn({innerType:e,typeName:dg.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...tj(t)});var Dnn=class extends Pw{_parse(t){let{ctx:r}=this._processInputParams(t),i={...r,common:{...r.common,issues:[]}},n=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return dJn(n)?n.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new oue(i.common.issues)},input:i.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new oue(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}};Dnn.create=(e,t)=>new Dnn({innerType:e,typeName:dg.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...tj(t)});var bJn=class extends Pw{_parse(t){if(this._getType(t)!==U_.nan){let i=this._getOrReturnCtx(t);return Rp(i,{code:td.invalid_type,expected:U_.nan,received:i.parsedType}),W0}return{status:"valid",value:t.data}}};bJn.create=e=>new bJn({typeName:dg.ZodNaN,...tj(e)});var eIE=Symbol("zod_brand"),i5a=class extends Pw{_parse(t){let{ctx:r}=this._processInputParams(t),i=r.data;return this._def.type._parse({data:i,path:r.path,parent:r})}unwrap(){return this._def.type}},n5a=class e extends Pw{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return a.status==="aborted"?W0:a.status==="dirty"?(r.dirty(),dnn(a.value)):this._def.out._parseAsync({data:a.value,path:i.path,parent:i})})();{let n=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return n.status==="aborted"?W0:n.status==="dirty"?(r.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:i.path,parent:i})}}static create(t,r){return new e({in:t,out:r,typeName:dg.ZodPipeline})}},Enn=class extends Pw{_parse(t){let r=this._def.innerType._parse(t),i=n=>(ONi(n)&&(n.value=Object.freeze(n.value)),n);return dJn(r)?r.then(n=>i(n)):i(r)}unwrap(){return this._def.innerType}};Enn.create=(e,t)=>new Enn({innerType:e,typeName:dg.ZodReadonly,...tj(t)});function fO_(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function yO_(e,t={},r){return e?PNi.create().superRefine((i,n)=>{let a=e(i);if(a instanceof Promise)return a.then(u=>{if(!u){let l=fO_(t,i),d=l.fatal??r??!0;n.addIssue({code:"custom",...l,fatal:d})}});if(!a){let u=fO_(t,i),l=u.fatal??r??!0;n.addIssue({code:"custom",...u,fatal:l})}}):PNi.create()}var tIE={object:uue.lazycreate},dg;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(dg||(dg={}));var rIE=(e,t={message:`Input not instance of ${e.name}`})=>yO_(r=>r instanceof e,t),vO_=mNi.create,bO_=pnn.create,iIE=bJn.create,nIE=_nn.create,gO_=hnn.create,aIE=ynn.create,oIE=_Jn.create,uIE=vnn.create,sIE=bnn.create,cIE=PNi.create,lIE=Hmi.create,fIE=sQt.create,dIE=hJn.create,pIE=$mi.create,_IE=uue.create,hIE=uue.strictCreate,yIE=gnn.create,vIE=Ztu.create,bIE=Onn.create,gIE=_or.create,OIE=ktu.create,mIE=yJn.create,PIE=vJn.create,jIE=eru.create,wIE=mnn.create,SIE=Pnn.create,DIE=jnn.create,EIE=wnn.create,MIE=jNi.create,AIE=H3e.create,qIE=V3e.create,TIE=hor.create,CIE=H3e.createWithPreprocess,BIE=n5a.create,IIE=()=>vO_().optional(),zIE=()=>bO_().optional(),RIE=()=>gO_().optional(),xIE={string:e=>mNi.create({...e,coerce:!0}),number:e=>pnn.create({...e,coerce:!0}),boolean:e=>hnn.create({...e,coerce:!0}),bigint:e=>_nn.create({...e,coerce:!0}),date:e=>ynn.create({...e,coerce:!0})};var NIE=W0;var FIE=$3e.object({snake:$3e.string().optional(),camel:$3e.string().optional(),screamingSnake:$3e.string().optional(),pascal:$3e.string().optional()}),LIE=$3e.object({description:$3e.string().optional(),name:$3e.string().optional(),casing:FIE.optional()}),OO_=$3e.record(LIE);var tru=class extends Yg{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=OO_.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 Mnn=class extends Yg{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 rru=class extends Yg{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 iru=class extends Yg{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 nru=class extends Yg{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 aru=class extends Yg{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 oru=class extends Yg{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 cQt=class extends e_{ir;audiences;irGraph;constructor({breadcrumbs:t=[],context:r,audiences:i}){super({breadcrumbs:t,context:r}),this.audiences=i,this.irGraph=new lnn(i),this.ir={auth:{docs:void 0,requirement:Vs.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:Vs.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}}removeXFernIgnores({document:t,breadcrumbs:r=[]}){return Array.isArray(t)?t.filter((i,n)=>!new Mnn({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 Mnn({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=ewc({ir:t,exampleGeneration:r});if(this.context.generateV1Examples){let n=e5a({ir:t,exampleGeneration:r});return{...t,...n,...i}}return{...t,...i}}filterIrForAudiences(t){let r=this.irGraph.getFilteredEndpoints(),i=this.irGraph.getFilteredChannels(),n=this.irGraph.getFilteredWebhooks();for(let a of Object.values(t.services)){let u=[];for(let l of a.endpoints)r.has(l.id)&&u.push(l);a.endpoints=u}return t.websocketChannels=Object.fromEntries(Object.entries(t.websocketChannels??{}).filter(([a])=>i.has(a))),t.webhookGroups=Object.fromEntries(Object.entries(t.webhookGroups).filter(([a])=>n.has(a))),t}async resolveAllExternalRefs({spec:t}){let r=[t];for(;r.length>0;){let i=r.shift();i!=null&&(Array.isArray(i)?await this.resolveExternalRefsInArray(i,r):typeof i=="object"&&await this.resolveExternalRefsInObject(i,r))}return t}async resolveExternalRefsInArray(t,r){for(let i=0;i<t.length;i++)t[i]=await this.resolveReferenceChain(t[i],r)}async resolveExternalRefsInObject(t,r){for(let[i,n]of Object.entries(t))t[i]=await this.resolveReferenceChain(n,r)}async resolveReferenceChain(t,r){let i=t;if(!this.context.isReferenceObject(i))return r.push(i),t;for(;this.context.isReferenceObject(i);){let n=this.context.isExternalReference(i.$ref),a=await this.context.resolveMaybeExternalReference(i);if(a.resolved){if(i=a.value,n)return i}else return t}return t}shouldAddServerToCollectedServers({server:t,currentServers:r,specType:i="openapi"}){return i==="openapi"?!r.some(n=>n.url===t.url&&"x-fern-server-name"in n&&"x-fern-server-name"in t&&n["x-fern-server-name"]===t["x-fern-server-name"]):!r.some(n=>n.url===t.url&&"name"in n&&"name"in t&&n.name===t.name)}addEndpointToIr({endpoint:t,audiences:r,endpointGroup:i,endpointGroupDisplayName:n,serviceName:a}){let u=this.context.getGroup({groupParts:i,namespace:this.context.namespace}),l=this.getOrCreatePackage({group:i}),d=[...u].map(c=>this.context.casingsGenerator.generateName(c)),s=d[d.length-1];l.service==null&&(l.service=a??`service_${u.map(c=>S_(c)).join("/")}`),this.ir.services[l.service]==null&&(this.ir.services[l.service]=this.createNewService({allParts:d,finalpart:s,endpointGroupDisplayName:n})),this.ir.services[l.service]?.endpoints.push(t);let o=this.ir.services[l.service];o!=null&&(this.irGraph.addEndpoint(o,t),this.irGraph.markEndpointForAudience(o.name,[t],r))}addWebhookToIr({webhook:t,operationId:r,audiences:i,group:n}){let a=n?.join(".")??r,u=this.getOrCreatePackage({group:n});this.ir.webhookGroups[a]==null&&(this.ir.webhookGroups[a]=[]),this.ir.webhookGroups[a].push(t),u.webhooks=a;let l=this.context.createFernFilepath();this.irGraph.addWebhook(l,t),i!=null&&this.irGraph.markWebhookForAudiences(l,t,i)}addWebsocketChannelToIr({websocketChannel:t,channelPath:r,audiences:i,websocketGroup:n}){let a=S_(n?.join(".")),u=S_(r),l=this.context.namespace?`${S_(this.context.namespace)}/`:"",d=a?`channel_${l}${a}`:`channel_${l}${u}`,s=n?this.getOrCreatePackage({group:n}):this.getOrCreatePackage({group:[u]});this.ir.websocketChannels={...this.ir.websocketChannels,[d]:t},d!==""?s.websocket==null&&(s.websocket=d):this.ir.rootPackage.websocket="";let o=this.context.createFernFilepath();this.irGraph.addChannel(o,d,t),i!=null&&this.irGraph.markChannelForAudiences(o,d,i)}addAuthToIR(t){this.ir.auth=t}addErrorsToIr(t){this.ir.errors=t;for(let r of Object.values(t))this.irGraph.addError(r)}addGlobalHeadersToIr(t){this.ir.headers=t}addEnvironmentsToIr({environmentConfig:t,audiences:r}){if(this.ir.environments=t,r!=null)for(let[i,n]of Object.entries(t??{}))r[i]!=null&&this.irGraph.markEnvironmentForAudiences(n,r[i])}addTypeToRootPackage(t){this.ir.rootPackage.types.push(t)}addTypeToPackage(t){let r=this.context.getGroup({groupParts:[],namespace:this.context.namespace});this.getOrCreatePackage({group:r}).types.push(t)}addTypesToIr(t){Object.assign(this.ir.types,Object.fromEntries(Object.entries(t).map(([r,i])=>[r,i.typeDeclaration])));for(let r of Object.values(t))this.irGraph.addType({declaredTypeName:r.typeDeclaration.name,descendantTypeIds:r.typeDeclaration.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:r.propertiesByAudience,descendantFilepaths:new Set}),this.irGraph.markTypeForAudiences(r.typeDeclaration.name,r.audiences)}updateEndpointsWithDefaultUrl(t){if(t!=null)for(let r of Object.values(this.ir.services))for(let i of r.endpoints)i.baseUrl==null&&(i.baseUrl=t)}createNewService({allParts:t,finalpart:r,endpointGroupDisplayName:i}){return{name:{fernFilepath:{allParts:t,packagePath:t.slice(0,-1),file:r}},displayName:i,basePath:WF(""),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=>S_(n))),r.length==0)return this.ir.rootPackage;let i=this.ir.rootPackage;for(let n=0;n<r.length;n++){let a=r[n]??"",l=`subpackage_${r.slice(0,n+1).join("/")}`;this.ir.subpackages[l]==null&&(this.ir.subpackages[l]={name:this.context.casingsGenerator.generateName(a),displayName:void 0,...this.createPackage({name:a})});let d=this.ir.subpackages[l];i.subpackages.includes(l)||i.subpackages.push(l),i=d}return i}};var tA={};Po(tA,{AbstractConverters:()=>dwc,ExampleConverter:()=>G3e,SchemaConverters:()=>fwc,ServersConverter:()=>QAe});var dwc={};Po(dwc,{AbstractMediaTypeObjectConverter:()=>lru,AbstractParameterConverter:()=>fru});var G3e=class e extends e_{MAX_DEPTH=12;EXAMPLE_STRING=Ch.STRING;EXAMPLE_NUMBER=Ch.DOUBLE;EXAMPLE_BOOLEAN=Ch.BOOLEAN;EXAMPLE_INTEGER=Ch.INT;EXAMPLE_DATE=Ch.DATE;EXAMPLE_DATE_TIME=Ch.DATE_TIME;schema;example;depth;exampleGenerationStrategy;generateOptionalProperties;seenRefs;constructor({breadcrumbs:t,context:r,schema:i,example:n,depth:a=0,exampleGenerationStrategy:u,generateOptionalProperties:l=!1,seenRefs:d=new Set}){super({breadcrumbs:t,context:r}),this.example=n,this.schema=i,this.depth=a,this.exampleGenerationStrategy=u,this.generateOptionalProperties=l,this.seenRefs=d}convert(){if(this.depth>this.MAX_DEPTH)return{isValid:!0,coerced:!1,validExample:typeof this.example<"u"?this.example:{},errors:[]};if(this.context.isReferenceObject(this.schema)){let r=this.schema.$ref;if(this.seenRefs.has(r))return{isValid:!0,coerced:!1,validExample:this.example,errors:[]}}let t=this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});return t==null?{isValid:!1,coerced:!1,validExample:null,errors:[{message:"Schema is not resolvable",path:this.breadcrumbs}]}:typeof t!="object"?{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Schema should be an object: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]}:"nullable"in t&&t.nullable===!0&&this.example===null?{isValid:!0,coerced:!1,validExample:this.example,errors:[]}:Array.isArray(t.type)?this.convertSchemaTypeArray({resolvedSchema:t}):t.type=="null"?this.convertNull():t.type=="boolean"?this.convertBoolean():t.enum!=null?this.convertEnum(t):t.type=="number"?this.convertNumber():t.type=="string"?this.convertString():t.type=="integer"?this.convertInteger():t.type=="array"?this.convertArray({resolvedSchema:t}):"oneOf"in t&&t.oneOf!=null?this.convertOneOf({resolvedSchema:t}):"anyOf"in t&&t.anyOf!=null?this.convertAnyOf({resolvedSchema:t}):t.type=="object"||t.properties!=null||t.allOf!=null?this.convertObject({resolvedSchema:t}):typeof t=="object"&&Object.keys(t).length===0?{isValid:!0,coerced:!1,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Unsupported schema type: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]}}convertNull(){let t=this.example===null;return t?{isValid:t,coerced:!1,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Example is not null: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertBoolean(){let t=typeof this.example=="boolean";if(t)return{isValid:t,coerced:!1,validExample:this.example,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.default:this.schema.default,i=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.const:this.schema.const;return typeof r=="boolean"||typeof i=="boolean"?{isValid:!0,coerced:!1,validExample:i??r,errors:[]}:{isValid:!1,coerced:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_BOOLEAN,errors:[{message:`Example is not a boolean: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertEnum(t){let r=t.enum?.includes(this.example)??!1;if(r)return{isValid:r,coerced:!1,validExample:this.example,errors:[]};let i=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return i!==void 0&&t.enum?.includes(i)?{isValid:!0,coerced:!1,validExample:i,errors:[]}:{isValid:r,coerced:!1,validExample:t.enum?.[0],errors:[{message:`Example is not one of the allowed enum values: ${JSON.stringify(t.enum,null,2)}`,path:this.breadcrumbs}]}}convertNumber(){if(typeof this.example=="number")return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};let t=Number(this.example);if(!isNaN(t))return{isValid:!0,coerced:!0,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return typeof r=="number"?{isValid:!0,coerced:!1,validExample:r,errors:[]}:{isValid:!1,coerced:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_NUMBER,errors:[{message:`Example is not a number: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertString(){if(typeof this.example=="string")return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};if(typeof this.example!="object"&&!Array.isArray(this.example)&&this.example!=null)return{isValid:!0,coerced:!0,validExample:String(this.example),errors:[]};let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;if(typeof t=="string")return{isValid:!0,coerced:!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,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,validExample:this.example,errors:[]};if(typeof this.example=="string"){let r=Number(this.example);if(!isNaN(r)&&Number.isInteger(r))return{isValid:!0,coerced:!0,validExample:r,errors:[]}}let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return typeof t=="number"&&Number.isInteger(t)?{isValid:!0,coerced:!1,validExample:t,errors:[]}:{isValid:!1,coerced:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_INTEGER,errors:[{message:`Example is not an integer: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertArray({resolvedSchema:t}){if(t.type!="array")return{isValid:!1,coerced:!1,validExample:null,errors:[]};t.items==null&&(t.items={type:"string"});let r=this.example==null,i=this.example??t.example,a=(Array.isArray(i)?i:[i]).map(l=>new e({breadcrumbs:[...this.breadcrumbs,"items"],context:this.context,schema:t.items,example:l,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),u=a.every(l=>l?.isValid??!1)&&!r;return{isValid:u,coerced:!1,validExample:a.map(l=>l.validExample),errors:u?[]:a.flatMap(l=>l.errors)}}convertObject({resolvedSchema:t}){if(t.type=="object"&&t.properties==null&&t.allOf==null)return{isValid:!0,coerced:!1,validExample:this.example??{},errors:[]};let r=typeof this.example!="object"||this.example==null?{}:this.example,i=Object.entries(t.properties??{}).map(([d,s])=>{if(typeof s!="object")return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if(this.isDeprecatedProperty(s)&&!this.isRequiredProperty({key:d,resolvedSchema:t}))return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("readOnly"in s&&s.readOnly===!0&&"writeOnly"in s&&s.writeOnly===!0)return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("readOnly"in s&&s.readOnly===!0&&this.exampleGenerationStrategy==="request")return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};if("writeOnly"in s&&s.writeOnly===!0&&this.exampleGenerationStrategy==="response")return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}};let o=!(d in r)||!("nullable"in s)&&r[d]==null||"nullable"in s&&s.nullable===!0&&r[d]===void 0,c=!t.required?.includes(d);if(o&&c){if(this.example===void 0&&this.generateOptionalProperties){let b=new e({breadcrumbs:[...this.breadcrumbs,d],context:this.context,schema:s,example:void 0,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()});return{key:d,result:b.convert()}}return{key:d,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}}}else{let g=new e({breadcrumbs:[...this.breadcrumbs,d],context:this.context,schema:s,example:r[d],depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();return{key:d,result:g}}}),n=(t.allOf??[]).map((d,s)=>new e({breadcrumbs:[...this.breadcrumbs,`allOf[${s}]`],context:this.context,schema:{...t,...d,allOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),a=i.every(d=>d.result.isValid)&&n.every(d=>d.isValid),u=Object.fromEntries(i.map(({key:d,result:s})=>[d,s.validExample]).filter(([d,s])=>s!==void 0));for(let d of n)if(typeof d.validExample=="object"&&d.validExample!==null){let s=d.validExample;u={...u,...Object.fromEntries(Object.entries(s).filter(([o,c])=>c!==void 0))}}let l=[];if(t.additionalProperties!==!1){let d=typeof t.additionalProperties=="object"?t.additionalProperties:{oneOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"object"},{type:"array"}]},s=new Set(Object.keys(u??{}));Object.keys(r).filter(c=>!s.has(c)).forEach(c=>{let g=new e({breadcrumbs:[...this.breadcrumbs,c],context:this.context,schema:d,example:r[c],depth:this.depth+1,generateOptionalProperties:!1,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();l.push({key:c,result:g})})}for(let{key:d,result:s}of l)s.validExample!==void 0&&u[d]===void 0&&(u[d]=s.validExample);if(Object.keys(u).length===0){let d=n.find(s=>s.validExample!==void 0&&(typeof s.validExample!="object"||s.validExample===null));d&&(u=d.validExample)}return{isValid:a,coerced:!1,validExample:u,errors:[...i.flatMap(({result:d})=>d.errors),...n.flatMap(d=>d.errors)]}}convertSchemaTypeArray({resolvedSchema:t}){if(!Array.isArray(t.type))return{isValid:!1,coerced:!1,validExample:null,errors:[]};if(t.type.length===1)return new e({breadcrumbs:this.breadcrumbs,context:this.context,schema:{...t,type:t.type[0]},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();let r=t.type.map((u,l)=>new e({breadcrumbs:[...this.breadcrumbs,`type[${l}]`],context:this.context,schema:{...t,type:u},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),i=r.some(u=>u?.isValid??!1),a=r.find(u=>u.isValid)?.validExample??r[0]?.validExample??null;return{isValid:i,coerced:!1,validExample:a,errors:i?[]:r.flatMap(u=>u?.errors??[])}}convertOneOf({resolvedSchema:t}){if(!("oneOf"in t)||t.oneOf==null)return{isValid:!1,coerced:!1,validExample:null,errors:[]};let r=t.oneOf.map((u,l)=>new e({breadcrumbs:[...this.breadcrumbs,`oneOf[${l}]`],context:this.context,schema:{...t,...u,oneOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),i=r.filter(u=>u.isValid),n=i.length>0,a;return n?a=i.find(l=>!l.coerced)?.validExample??i[0]?.validExample:a=r[0]?.validExample,{isValid:n,coerced:!1,validExample:a,errors:n?[]:r.flatMap(u=>u.errors)}}convertAnyOf({resolvedSchema:t}){if(!("anyOf"in t)||t.anyOf==null)return{isValid:!1,coerced:!1,validExample:null,errors:[]};let r=t.anyOf.map((u,l)=>new e({breadcrumbs:[...this.breadcrumbs,`anyOf[${l}]`],context:this.context,schema:u,example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),i=r.filter(u=>u.isValid),n=i.length>0,a;return n?a=i.find(l=>!l.coerced)?.validExample??i[0]?.validExample:a=r[0]?.validExample,{isValid:n,coerced:!1,validExample:a,errors:n?[]:r.flatMap(u=>u.errors)}}getMaybeUpdatedSeenRefs(){let t=new Set(this.seenRefs);return this.context.isReferenceObject(this.schema)&&t.add(this.schema.$ref),t}maybeResolveSchemaExample(t){let r=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(r!=null){if("example"in r)return r.example;if("examples"in r)return Object.values(r.examples??{})[0]}}isDeprecatedProperty(t){return t!=null&&"availability"in t&&t.availability==="deprecated"}isRequiredProperty({key:t,resolvedSchema:r}){return r.required?.includes(t)??!1}};var fwc={};Po(fwc,{ArraySchemaConverter:()=>jJn,EnumSchemaConverter:()=>gJn,ObjectSchemaConverter:()=>OJn,OneOfSchemaConverter:()=>mJn,PrimitiveSchemaConverter:()=>PJn,SchemaConverter:()=>wNi,SchemaOrReferenceConverter:()=>tK});function mO_(e){return Y3({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return Xc.primitive({v1:"BASE_64",v2:Td.base64({})});case"BOOLEAN":return Xc.primitive({v1:"BOOLEAN",v2:Td.boolean({default:void 0})});case"DATE":return Xc.primitive({v1:"DATE",v2:Td.date({})});case"DATE_TIME":return Xc.primitive({v1:"DATE_TIME",v2:Td.dateTime({})});case"FLOAT":return Xc.primitive({v1:"FLOAT",v2:Td.float({})});case"DOUBLE":return Xc.primitive({v1:"DOUBLE",v2:Td.double({default:void 0,validation:void 0})});case"UINT":return Xc.primitive({v1:"UINT",v2:Td.uint({})});case"UINT_64":return Xc.primitive({v1:"UINT_64",v2:Td.uint64({})});case"INTEGER":return Xc.primitive({v1:"INTEGER",v2:Td.integer({default:void 0,validation:void 0})});case"LONG":return Xc.primitive({v1:"LONG",v2:Td.long({default:void 0})});case"STRING":return Xc.primitive({v1:"STRING",v2:Td.string({default:void 0,validation:void 0})});case"UUID":return Xc.primitive({v1:"UUID",v2:Td.uuid({})});case"BIG_INTEGER":return Xc.primitive({v1:"BIG_INTEGER",v2:Td.bigInteger({default:void 0})});default:return}},unknown:()=>Xc.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return Xc.container(Ry.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return Xc.container(Ry.list(t))},optional:t=>{if(t!=null)return Xc.container(Ry.optional(t))},nullable:t=>{if(t!=null)return Xc.container(Ry.nullable(t))},set:t=>{if(t!=null)return Xc.container(Ry.set(t))},literal:t=>Xc.container(Ry.literal(t._visit({string:r=>jL.string(r),boolean:r=>jL.boolean(r),_other:()=>{throw new Error("Unexpected literal type")}}))),named:()=>{}}})}var gJn=class extends e_{schema;maybeFernEnum;constructor({context:t,breadcrumbs:r,schema:i,maybeFernEnum:n}){super({context:t,breadcrumbs:r}),this.schema=i,this.maybeFernEnum=n}convert(){if(!this.schema.enum)return;let r=this.schema.enum.filter(n=>typeof n=="string"||typeof n=="number").map(n=>{let a=n.toString(),u=this.maybeFernEnum?.[a],l=u?.name??a;return{name:this.context.casingsGenerator.generateNameAndWireValue({name:l,wireValue:a}),docs:u?.description,availability:void 0,casing:u?.casing}});if(r.length===0){this.context.errorCollector.collect({message:`Received enum schema with no valid values: ${JSON.stringify(this.schema)}`,path:this.breadcrumbs});return}let i=this.context.getAsString(this.schema.default);return{type:Vb.enum({default:i!=null?r.find(n=>n.name.wireValue===i):void 0,values:r})}}};var uru=class extends e_{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=Xc.container(Ry.map({keyType:e_.STRING,valueType:Xc.unknown()}));return{type:Vb.alias({aliasOf:t,resolvedType:t}),referencedTypes:new Set,inlinedTypes:{}}}}tryConvertTypedMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean")return;let r=new tK({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schemaOrReferenceOrBoolean}).convert();if(r!=null){let i=Xc.container(Ry.map({keyType:e_.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:Vb.alias({aliasOf:i,resolvedType:i}),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}};function a5a({properties:e,required:t,breadcrumbs:r,context:i,errorCollector:n}){let a=[],u={},l={},d=new Set;for(let[s,o]of Object.entries(e??{})){let c=[...r,"properties",s];if(typeof o!="object"){n.collect({message:`Schema property ${s} should be an object`,path:c});continue}let b=UIE(r,o,i)??i.convertBreadcrumbsToName(c),g="nullable"in o?o.nullable:!1,m=new tK({context:i,breadcrumbs:c,schemaOrReference:o,schemaIdOverride:b,wrapAsOptional:!t.includes(s),wrapAsNullable:g}).convert();if(m!=null){a.push({name:i.casingsGenerator.generateNameAndWireValue({name:s,wireValue:s}),valueType:m.type,docs:o.description,availability:m.availability,propertyAccess:i.getPropertyAccess(o),v2Examples:m.schema?.typeDeclaration?.v2Examples??{userSpecifiedExamples:{},autogeneratedExamples:{}}}),u={...u,...m.inlinedTypes},m.schema?.typeDeclaration.referencedTypes!=null&&m.schema.typeDeclaration.referencedTypes.forEach(w=>{d.add(w)});for(let w of m.schema?.audiences??[])l[w]==null&&(l[w]=new Set),l[w].add(s)}}for(let s of Object.keys(u))d.add(s);return{convertedProperties:a,propertiesByAudience:l,inlinedTypesFromProperties:u,referencedTypes:d}}function UIE(e,t,r){return r.isReferenceObject(t)?void 0:new VH.FernTypeNameExtension({breadcrumbs:e,schema:t,context:r}).convert()}var OJn=class extends e_{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:Vb.object({properties:[],extends:[],extendedProperties:[],extraProperties:t}),propertiesByAudience:{},inlinedTypes:{},referencedTypes:new Set};let{convertedProperties:r,inlinedTypesFromProperties:i,referencedTypes:n,propertiesByAudience:a}=a5a({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector}),u=[],l=n,d=this.schema.required!=null&&this.schema.required.length>0,s=i,o=a;for(let[c,b]of(this.schema.allOf??[]).entries()){let g=[...this.breadcrumbs,"allOf",c.toString()],O;if(this.context.isReferenceObject(b)){let M=this.context.resolveMaybeReference({schemaOrReference:b,breadcrumbs:g});if(M==null){this.context.logger.debug?.(`[ObjectSchemaConverter] allOf[${c}] reference could not be resolved. Skipping: ${JSON.stringify(b)}`);continue}if(O=M,typeof O.additionalProperties=="boolean"&&O.additionalProperties&&(t=!0),!d||Object.keys(O.properties??{}).every(D=>!this.schema.required?.includes(D))){this.addTypeReferenceToExtends({reference:b,breadcrumbs:g,extends_:u,referencedTypes:l});continue}}else O=b;typeof O.additionalProperties=="boolean"&&O.additionalProperties&&(t=!0);let{convertedProperties:m,inlinedTypesFromProperties:w,referencedTypes:E,propertiesByAudience:q}=a5a({properties:O.properties??{},required:[...this.schema.required??[],...O.required??[]],breadcrumbs:g,context:this.context,errorCollector:this.context.errorCollector});r.push(...m),s={...s,...w},o={...o,...q},E.forEach(M=>{l.add(M)})}for(let c of Object.keys(s))l.add(c);return{type:Vb.object({properties:r,extends:u.map(c=>this.context.typeReferenceToDeclaredTypeName(c)).filter(iv),extendedProperties:[],extraProperties:t}),propertiesByAudience:o,referencedTypes:l,inlinedTypes:s}}addTypeReferenceToExtends({reference:t,breadcrumbs:r,extends_:i,referencedTypes:n}){let a=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:r});a.ok&&i.push(a.reference);let u=this.context.getTypeIdFromSchemaReference(t);u!=null&&n.add(u)}};var sru=class extends Yg{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 cru;(function(e){function t(s,o){if(s.title)return s.title;if(s.typeName)return r(s.typeName);if(s.description){let c=i(s.description);if(c)return c}if(s.type==="object"&&s.properties&&Object.keys(s.properties).length>0){let c=a(s,o);if(c)return c}}e.generateDisplayNameForInlinedObject=t;function r(s){return s&&(s.includes("_")?s.split("_").map(o=>o.charAt(0).toUpperCase()+o.slice(1).toLowerCase()).join(""):s.charAt(0).toUpperCase()+s.slice(1))}e.convertToPascalCase=r;function i(s){let o=s?.split(".")[0]?.trim();if(!o)return;let c=new Set(["a","an","the","and","or","but","nor","yet","so","in","on","at","to","for","of","with","by","from","up","about","into","through","during","before","after","above","below","between","among","under","over","across","against","along","around","behind","beneath","beside","beyond","down","inside","near","off","outside","since","toward","until","upon","within","without","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","must","can","shall","this","that","these","those","it","its","they","them","their","when","where","why","how","what","which","who","whom","whose","used","using","containing","including","having","showing","providing","created","generated","processed","stored","managed","handled","returned","sent","received","given","taken","made","done","called","named","available","current","existing","present","new","old","main","primary","secondary","additional","extra","special","specific","general","common","basic","simple","complex","full","empty","complete","partial","also","then","now","here","there","only","just","even","still","already","always","never","sometimes","often","usually","mostly"]),b=o.replace(/[^a-zA-Z0-9\s]/g,"").trim().split(/\s+/).filter(m=>m.length>0).filter(m=>!c.has(m.toLowerCase())).slice(0,4);if(b.length===0)return;let O=n(b).map(m=>m.charAt(0).toUpperCase()+m.slice(1).toLowerCase()).join("");return O.length>0?O:void 0}e.cleanDescriptionForDisplayName=i;function n(s){if(s.length<=2)return s;let o=new Set(["system","service","api"]),c=new Set(["object","method","function","interface","model"]),b=[],g=[];return s.forEach(O=>{let m=O.toLowerCase();o.has(m)?g.push(O):c.has(m)&&b.length>0?b.splice(1,0,O):b.push(O)}),b.push(...g),b}e.reorderWordsForBetterSemantics=n;function a(s,o){let c=s.properties;if(!c)return;let b=Object.keys(c);if(b.length===0)return;let g=u(s,o);if(g.length>0){let w=l(g).slice(0,1).map(E=>d(E));if(w.length>0)return w.join("")}let O=l(b);if(O.length>0)return O.slice(0,1).map(w=>d(w)).join("")}e.generateNameFromObjectProperties=a;function u(s,o){let c=s.properties;if(!c)return[];let b=new Set(Object.keys(c)),g=new Set;return o.forEach(O=>{if(O!==s&&O.type==="object"&&O.properties){let m=O.properties;m&&Object.keys(m).forEach(w=>{g.add(w)})}}),Array.from(b).filter(O=>!g.has(O))}e.findUniqueProperties=u;function l(s){let o=["status","error","type","kind","mode","state","action","method","enabled","disabled","active","inactive","success","failed"],c=["config","configuration","setting","option","message","code","user","account","profile","auth","token","key","response","request","result","output","input","payload","body"],b=["name","id","value","data","info"];return s.map(O=>{let m=O.toLowerCase(),w=0;for(let E of o)m===E?w+=15:m.includes(E)&&(w+=10);for(let E of c)m===E?w+=8:m.includes(E)&&(w+=5);for(let E of b)m===E?w+=3:m.includes(E)&&(w+=2);return w+=Math.max(0,5-O.length),{prop:O,score:w}}).sort((O,m)=>O.score!==m.score?m.score-O.score:O.prop.localeCompare(m.prop)).map(O=>O.prop)}e.getMostSignificantProperties=l;function d(s){return s.includes("_")?s.split("_").map(o=>o.charAt(0).toUpperCase()+o.slice(1).toLowerCase()).join(""):s.charAt(0).toUpperCase()+s.slice(1)}e.capitalizePropertyName=d})(cru||(cru={}));var mJn=class extends e_{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 sru({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 o=new tK({context:this.context,schemaOrReference:{$ref:s},breadcrumbs:[...this.breadcrumbs,"discriminator","mapping",d]}),c=this.context.getTypeIdFromSchemaReference({$ref:s});c!=null&&r.add(c);let b=o.convert();if(b?.type!=null&&c!=null){for(let O of Object.keys(b?.inlinedTypes??{}))r.add(O);for(let O of b.schema?.typeDeclaration.referencedTypes??[])r.add(O);let g=this.context.casingsGenerator.generateNameAndWireValue({name:d,wireValue:d});t.push({docs:void 0,discriminantValue:g,availability:b.availability,displayName:d,shape:PL.samePropertiesAsObject({typeId:c,name:this.context.casingsGenerator.generateName(c),fernFilepath:{allParts:[],packagePath:[],file:void 0},displayName:d})}),i={...i,...b.inlinedTypes}}}let{convertedProperties:n,referencedTypes:a,inlinedTypesFromProperties:u}=a5a({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector});r=new Set([...r,...a]);let l=[];for(let[d,s]of(this.schema.allOf??[]).entries()){let o=[...this.breadcrumbs,"allOf",d.toString()];if(this.context.isReferenceObject(s)){let c=this.context.convertReferenceToTypeReference({reference:s,breadcrumbs:o});if(c.ok){let g=this.context.typeReferenceToDeclaredTypeName(c.reference);g!=null&&l.push(g)}let b=this.context.getTypeIdFromSchemaReference(s);b!=null&&r.add(b);continue}}for(let d of Object.keys({...i,...u}))r.add(d);return{type:Vb.union({baseProperties:n,discriminant:this.context.casingsGenerator.generateNameAndWireValue({name:this.schema.discriminator.propertyName,wireValue:this.schema.discriminator.propertyName}),extends:l,types:t}),referencedTypes:r,inlinedTypes:{...i,...u}}}convertAsUndiscriminatedUnion(){if(!this.schema.oneOf&&!this.schema.anyOf||this.schema.anyOf?.length===0&&this.schema.oneOf?.length===0)return;let t=[],r=new Set,i={},n=[...this.schema.oneOf??[],...this.schema.anyOf??[]].filter(a=>!this.context.isReferenceObject(a));for(let[a,u]of[...(this.schema.oneOf??[]).entries(),...(this.schema.anyOf??[]).entries()]){if(this.context.isReferenceObject(u)){let b;if(this.context.isReferenceObjectWithIdentifier(u))b=this.context.convertReferenceToTypeReference({reference:u,displayNameOverride:u.title??u.name??u.messageId,displayNameOverrideSource:"reference_identifier"});else if(this.getDiscriminatorKeyForRef(u)!=null){let O=this.getDiscriminatorKeyForRef(u);b=this.context.convertReferenceToTypeReference({reference:u,displayNameOverride:O,displayNameOverrideSource:"discriminator_key"})}else b=this.context.convertReferenceToTypeReference({reference:u,displayNameOverride:u.$ref.split("/").pop(),displayNameOverrideSource:"schema_identifier"});b.ok&&t.push({type:b.reference,docs:u.description});let g=this.context.getTypeIdFromSchemaReference(u);g!=null&&r.add(g);continue}let l=this.extendSubSchema(u),d=this.context.convertBreadcrumbsToName([`${this.id}_${a}`]),s=cru.generateDisplayNameForInlinedObject({...u,typeName:d},n),c=new wNi({context:this.context,id:d,nameOverride:s,breadcrumbs:[...this.breadcrumbs,`oneOf[${a}]`],schema:l??u}).convert();if(c!=null){let b=c.convertedSchema.typeDeclaration.shape;b.type==="alias"&&this.typeReferenceIsWrappedPrimitive(b.aliasOf)?t.push({type:b.aliasOf,docs:u.description}):b.type==="object"&&b.properties.length===0?t.push({type:Xc.container(Ry.map({keyType:e_.STRING,valueType:Xc.unknown()})),docs:u.description}):(t.push({type:this.context.createNamedTypeReference(d,s),docs:u.description}),i={...i,...c.inlinedTypes,[d]:c.convertedSchema}),c.convertedSchema.typeDeclaration.referencedTypes.forEach(g=>{r.add(g)})}}return{type:Vb.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 tK({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(i==null)return;let n=this.wrapInNullable(i.type);return{type:Vb.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 Xc.container(Ry.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 PJn=class extends e_{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 Xc.container(Ry.literal(jL.string(t)));if(this.context.settings.typeDatesAsStrings===!1){if(this.schema.format==="date")return Xc.primitive({v1:ny.Date,v2:Td.date({})});if(this.schema.format==="date-time")return Xc.primitive({v1:ny.DateTime,v2:Td.dateTime({})})}return Xc.primitive({v1:"STRING",v2:Td.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":switch(this.schema.format){case"double":return Xc.primitive({v1:"DOUBLE",v2:Td.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return Xc.primitive({v1:"FLOAT",v2:Td.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return Xc.primitive({v1:"INTEGER",v2:Td.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return Xc.primitive({v1:"LONG",v2:Td.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return Xc.primitive({v1:"UINT",v2:Td.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return Xc.primitive({v1:"UINT_64",v2:Td.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return Xc.primitive({v1:"DOUBLE",v2:Td.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"integer":switch(this.schema.format){case"double":return Xc.primitive({v1:"DOUBLE",v2:Td.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return Xc.primitive({v1:"FLOAT",v2:Td.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return Xc.primitive({v1:"INTEGER",v2:Td.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return Xc.primitive({v1:"LONG",v2:Td.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return Xc.primitive({v1:"UINT",v2:Td.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return Xc.primitive({v1:"UINT_64",v2:Td.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return Xc.primitive({v1:"INTEGER",v2:Td.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?Xc.container(Ry.literal(jL.boolean(t))):Xc.primitive({v1:"BOOLEAN",v2:Td.boolean({default:this.schema.default})})}default:return}}getNumberValidation(t){return{max:t.maximum,min:t.minimum,exclusiveMax:typeof t.exclusiveMaximum=="boolean"?t.exclusiveMaximum:void 0,exclusiveMin:typeof t.exclusiveMinimum=="boolean"?t.exclusiveMinimum:void 0,multipleOf:t.multipleOf}}getStringValidation(t){return{minLength:t.minLength,maxLength:t.maxLength,pattern:t.pattern,format:t.format}}};var VIE=["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],wNi=class e extends e_{schema;id;inlined;audiences;nameOverride;constructor({context:t,breadcrumbs:r,schema:i,id:n,inlined:a=!1,nameOverride:u}){super({context:t,breadcrumbs:r}),this.schema=i,this.id=n,this.inlined=a,this.nameOverride=u,this.audiences=this.context.getAudiences({operation:this.schema,breadcrumbs:this.breadcrumbs})??[]}convert(){let t=this.tryConvertFernTypeDeclaration();if(t!=null)return t;let r=this.tryConvertEnumSchema();if(r!=null)return r;let i=this.tryConvertSingularAllOfSchema();if(i!=null)return i;let n=this.tryConvertPrimitiveSchema();if(n!=null)return n;let a=this.tryConvertArraySchema();if(a!=null)return a;let u=this.tryConvertTypeArraySchema();if(u!=null)return u;let l=this.tryConvertOneOfAnyOfSchema();if(l!=null)return l;let d=this.tryConvertMapSchema();if(d!=null)return d;let s=this.tryConvertObjectAllOfSchema();if(s!=null)return s;let o=this.tryConvertUntypedSchema();if(o!=null)return o;this.context.errorCollector.collect({message:`Failed to convert schema object: ${JSON.stringify(this.schema,null,2)}`,path:this.breadcrumbs})}tryConvertEnumSchema(){if(!this.schema.enum?.length)return;let r=new VH.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),n=new gJn({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=M8n(r,n,(a,u)=>{if(u===n)return a;if(Array.isArray(a)&&Array.isArray(u))return[...a,...u]})}return new e({context:this.context,breadcrumbs:this.breadcrumbs,schema:r,id:this.id,inlined:!0}).convert()}}tryConvertPrimitiveSchema(){let r=new PJn({context:this.context,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Vb.alias({aliasOf:r,resolvedType:r}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertArraySchema(){if(this.schema.type==="array"){let r=new jJn({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Vb.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 mJn({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 uru({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReferenceOrBoolean:this.schema.additionalProperties}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertObjectAllOfSchema(){if(this.schema.type==="object"||this.schema.properties!=null||this.schema.allOf!=null){let r=new OJn({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:Vb.alias({aliasOf:Xc.unknown(),resolvedType:Xc.unknown()}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertFernTypeDeclaration(){let r=new VH.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r==null)return;let i=mO_(r);if(i!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Vb.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=[...VIE,...t];return Object.keys(this.schema).every(n=>r.includes(n))}isUntypedSchema(){return!!(this.schema&&typeof this.schema=="object"&&!("oneOf"in this.schema)&&!("anyOf"in this.schema)&&!("allOf"in this.schema)&&!("items"in this.schema)&&!("properties"in this.schema))}convertSchemaExamples(){let t={userSpecifiedExamples:{},autogeneratedExamples:{}},r=this.context.getExamplesFromSchema({schema:this.schema,breadcrumbs:this.breadcrumbs});if(r.length===0){let i=this.generateOrValidateExample({example:void 0,ignoreErrors:!0});return t.autogeneratedExamples={[`${this.id}_example_autogenerated`]:i},t}return t.userSpecifiedExamples=this.convertUserSpecifiedExamples(r),t}convertUserSpecifiedExamples(t){let r={};for(let[i,n]of t.entries()){let a=this.context.resolveExample(n),u=this.generateOrValidateExample({example:a});r[`${this.id}_example_${i}`]=u}return r}generateOrValidateExample({example:t,ignoreErrors:r}){let i=new G3e({breadcrumbs:this.breadcrumbs,context:this.context,schema:this.schema,example:t}),{validExample:n,errors:a}=i.convert();return r||a.forEach(u=>{this.context.errorCollector.collect({message:u.message,path:u.path})}),n}};var tK=class extends e_{schemaOrReference;schemaIdOverride;wrapAsOptional;wrapAsNullable;constructor({context:t,breadcrumbs:r,schemaOrReference:i,schemaIdOverride:n,wrapAsOptional:a=!1,wrapAsNullable:u=!1}){super({context:t,breadcrumbs:r}),this.schemaOrReference=i,this.schemaIdOverride=n,this.wrapAsOptional=a,this.wrapAsNullable=u}convert(){let t=this.maybeConvertReferenceObject({schemaOrReference:this.schemaOrReference});if(t!=null)return t;let r=this.maybeConvertSingularAllOfReferenceObject();return r??this.convertSchemaObject({schema:this.schemaOrReference})}maybeConvertReferenceObject({schemaOrReference:t}){if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:r.inlinedTypes??{}}}}maybeConvertSingularAllOfReferenceObject(){if(this.context.isReferenceObject(this.schemaOrReference)||this.schemaOrReference.allOf==null||this.schemaOrReference.allOf.length!==1)return;let t=this.schemaOrReference.allOf[0];if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:{}}}}convertSchemaObject({schema:t}){let r=this.schemaIdOverride??this.context.convertBreadcrumbsToName(this.breadcrumbs),i=new wNi({context:this.context,breadcrumbs:this.breadcrumbs,schema:t,id:r}),n=this.context.getAvailability({node:t,breadcrumbs:this.breadcrumbs}),a=i.convert();if(a!=null){let u=a.convertedSchema.typeDeclaration.shape;return u.type==="alias"?{type:this.wrapTypeReference(u.aliasOf),schema:a.convertedSchema,inlinedTypes:a.inlinedTypes,availability:n}:{type:this.wrapTypeReference(this.context.createNamedTypeReference(r)),schema:a.convertedSchema,inlinedTypes:{...a.inlinedTypes,[r]:a.convertedSchema},availability:n}}}wrapTypeReference(t){return this.wrapAsOptional&&this.wrapAsNullable?this.wrapInOptional(this.wrapInNullable(t)):this.wrapAsOptional?this.wrapInOptional(t):this.wrapAsNullable?this.wrapInNullable(t):t}wrapInOptional(t){return Xc.container(Ry.optional(t))}wrapInNullable(t){return Xc.container(Ry.nullable(t))}};var jJn=class e extends e_{static LIST_UNKNOWN=Xc.container(Ry.list(Xc.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 tK({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:Xc.container(Ry.list(r.type)),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var lru=class extends e_{group;method;constructor({context:t,breadcrumbs:r,group:i,method:n}){super({context:t,breadcrumbs:r}),this.group=i,this.method=n}parseMediaTypeObject({mediaTypeObject:t,resolveSchema:r,contentType:i,schemaId:n}){if(t.schema==null)return;if(r){let d=this.context.resolveMaybeReference({schemaOrReference:t.schema,breadcrumbs:[...this.breadcrumbs,"content",i]});if(d==null)return;t.schema=d}let u=new tK({context:this.context,breadcrumbs:[...this.breadcrumbs,"content",i,"schema"],schemaOrReference:t.schema,schemaIdOverride:n}).convert();if(u==null)return;let l=t.examples!=null?Object.fromEntries(Object.entries(t.examples).map(([d,s])=>{if(this.context.isReferenceObject(s)){let o=this.context.resolveReference({reference:s,breadcrumbs:[...this.breadcrumbs,"content",i,"examples"],skipErrorCollector:!0});return o.resolved?[d,o.value.value??o.value]:null}return[d,s.value??s]}).filter(d=>d!=null)):void 0;return{...u,examples:l}}parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:r}){let n=new tK({context:this.context,breadcrumbs:[...this.breadcrumbs],schemaOrReference:t,schemaIdOverride:r}).convert();if(n!=null)return{...n,examples:void 0}}convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:r,exampleGenerationStrategy:i}){let n={userSpecifiedExamples:{},autogeneratedExamples:{}},a=t?.schema,u=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_example`});for(let[l,d]of u){let s=this.context.resolveExampleWithValue(d),o=this.context.isExampleWithSummary(d)?d.summary:l;s!=null&&(a!=null?n.userSpecifiedExamples[o]=this.generateOrValidateExample({schema:a,example:s,exampleGenerationStrategy:i}):n.userSpecifiedExamples[o]=s)}if(Object.keys(n.userSpecifiedExamples).length===0&&a!=null){let l=S_(`${[...this.group,this.method].join("_")}_example`);n.autogeneratedExamples[l]=this.generateOrValidateExample({schema:a,example:void 0,ignoreErrors:!0,generateOptionalProperties:r,exampleGenerationStrategy:i})}return n}generateOrValidateExample({schema:t,example:r,ignoreErrors:i,generateOptionalProperties:n,exampleGenerationStrategy:a}){let u=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(u==null)return;let l=this.context.getExamplesFromSchema({schema:u,breadcrumbs:this.breadcrumbs}),d=new G3e({breadcrumbs:this.breadcrumbs,context:this.context,schema:u,example:r??l[0],generateOptionalProperties:n??!1,exampleGenerationStrategy:a}),{validExample:s,errors:o}=d.convert();return i||o.forEach(c=>{this.context.errorCollector.collect({message:c.message,path:c.path})}),s}};var fru=class extends e_{parameter;constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r}),this.parameter=i}convertToOutput({schema:t,typeReference:r,inlinedTypes:i}){let n=this.context.getAvailability({node:this.parameter,breadcrumbs:this.breadcrumbs}),a=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs}),u=this.getParameterSchemaWithExampleOverride({schema:a});switch(this.parameter.in){case"query":return{type:"query",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??e_.OPTIONAL_STRING,allowMultiple:this.parameter.explode??!1,v2Examples:this.convertParameterExamples({schema:u??t}),availability:n},inlinedTypes:i};case"header":return{type:"header",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??e_.OPTIONAL_STRING,env:void 0,v2Examples:this.convertParameterExamples({schema:u??t}),availability:n},inlinedTypes:i};case"path":return{type:"path",parameter:{name:this.context.casingsGenerator.generateName(this.parameter.name),docs:this.parameter.description,valueType:r??e_.STRING,location:"ENDPOINT",variable:void 0,v2Examples:this.convertParameterExamples({schema:u??t})},inlinedTypes:i};default:return}}getParameterSchemaWithExampleOverride({schema:t}){if(t!=null)return t.type==="string"&&t.example==null?{...t,example:this.parameter.name}:t}convertParameterExamples({schema:t}){let r={userSpecifiedExamples:{},autogeneratedExamples:{}},i=this.parameter.example,n=this.parameter.examples;for(let[a,u]of Object.entries(n??{})){let l=this.context.resolveExampleWithValue(u);l!=null&&(r.userSpecifiedExamples[a]=this.generateOrValidateExample({schema:t,example:l}))}if(i!=null){let a=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(r.userSpecifiedExamples)});r.userSpecifiedExamples[a]=this.generateOrValidateExample({schema:t,example:i})}if(Object.keys(r.userSpecifiedExamples).length===0){let a=`${this.parameter.name}_example`;r.autogeneratedExamples[a]=this.generateOrValidateExample({schema:t,example:void 0,ignoreErrors:!0})}return r}generateOrValidateExample({schema:t,ignoreErrors:r,example:i}){let n=new G3e({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:i}),{validExample:a,errors:u}=n.convert();return r||u.forEach(l=>{this.context.errorCollector.collect({message:l.message,path:l.path})}),a}};var dru=class extends Yg{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 PO_="Base",QAe=class e extends e_{servers;endpointLevelServers;constructor({breadcrumbs:t,context:r,servers:i,endpointLevelServers:n}){super({breadcrumbs:t,context:r}),this.servers=i,this.endpointLevelServers=n}convert(){if(this.servers==null||this.servers.length===0||this.servers[0]==null)return;if(this.endpointLevelServers!=null&&this.endpointLevelServers.length>0){let r=this.getDefaultBaseUrlName(),i={id:r,name:this.context.casingsGenerator.generateName(r)},n=this.endpointLevelServers.map(l=>{let d=e.getServerName({server:l,context:this.context});return{id:d,name:this.context.casingsGenerator.generateName(d)}}).filter((l,d,s)=>s.findIndex(o=>o.id===l.id)===d),a=[i,...n],u=this.servers.map(l=>{let d=e.getServerName({server:l,context:this.context}),s=this.endpointLevelServers?.map(o=>[e.getServerName({server:o,context:this.context}),this.getServerUrl(o)]);return{id:d,name:this.context.casingsGenerator.generateName(d),urls:{[r]:this.getServerUrl(l),...Object.fromEntries(s??[])},docs:l.description}});return{value:{defaultEnvironment:u[0]?.id,environments:$R.multipleBaseUrls({baseUrls:a,environments:u})},defaultUrl:i.id}}let t=this.withExplodedServers(this.servers).map(r=>{let i=e.getServerName({server:r,context:this.context});return{id:i,name:this.context.casingsGenerator.generateName(i),url:this.maybeRemoveTrailingSlashIfNotEmpty(this.getServerUrl(r)),docs:r.description}}).filter(iv);return{value:{defaultEnvironment:t[0]?.id,environments:$R.singleBaseUrl({environments:t})},defaultUrl:t[0]?.id}}static getServerExtensionName({server:t,context:r}){return new dru({breadcrumbs:[],server:t,context:r}).convert()}static getServerName({server:t,context:r}){return t.name!=null?t.name:e.getServerExtensionName({server:t,context:r})??t.description??t.url}getServerUrl(t){if(t.variables==null)return t.url;let r=t.url;for(let[i,n]of Object.entries(t.variables))n.default!=null&&(r=r.replace(`{${i}}`,encodeURIComponent(n.default)));return r}withExplodedServers(t){return t.flatMap(r=>{if(r.variables==null)return[r];let i=Object.entries(r.variables).filter(([l,d])=>d.enum!=null&&d.enum.length>0);if(i.length===0)return[r];let n=i[0];if(n==null)return[r];let[a,u]=n;return u.enum==null?[r]:u.enum.map(l=>{let d=r.url.replace(`{${a}}`,encodeURIComponent(l)),s={};for(let[c,b]of Object.entries(r.variables??{}))c!==a&&(s[c]=b);let o={...r,url:d,variables:Object.keys(s).length>0?s:void 0,"x-fern-server-name":r.description?`${r.description}_${l}`:`${l}`,description:r.description};return this.withExplodedServers([o])[0]})}).filter(iv)}getDefaultBaseUrlName(){return this.servers==null||this.servers.length===0||this.servers[0]==null?PO_:e.getServerExtensionName({server:this.servers[0],context:this.context})??PO_}maybeRemoveTrailingSlashIfNotEmpty(t){return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}};var o5a={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"},WIE=new Set(Object.values(o5a));var wJn=class{enabled=!0;write(t,...r){this.enabled&&process.stderr.write(`[${t}] ${r.join(" ")}
1915
1915
  `)}disable(){this.enabled=!1}enable(){this.enabled=!0}trace(...t){this.write(pb.Trace,...t)}debug(...t){this.write(pb.Debug,...t)}info(...t){this.write(pb.Info,...t)}warn(...t){this.write(pb.Warn,...t)}error(...t){this.write(pb.Error,...t)}log(t,...r){this.write(t,...r)}};var lQt={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}},pru={MESSAGE:4,ENUM:5,SERVICE:6};var _ru=class extends e_{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,lQt.ENUM.VALUE,i]),availability:void 0}});return{type:Vb.enum({default:void 0,values:t})}}};function jO_(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1)}var wO_=new Set([Bg.DOUBLE,Bg.FLOAT,Bg.INT64,Bg.UINT64,Bg.INT32,Bg.FIXED64,Bg.FIXED32,Bg.BOOL,Bg.STRING,Bg.BYTES,Bg.UINT32,Bg.SFIXED32,Bg.SFIXED64,Bg.SINT32,Bg.SINT64]);var hru=class e extends e_{static LIST_UNKNOWN=Xc.container(Ry.list(Xc.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 SNi({context:this.context,breadcrumbs:this.breadcrumbs,field:{...this.field,label:o8n.OPTIONAL},sourceCodeInfoPath:this.sourceCodeInfoPath}).convert();if(r!=null){let i=new Set;return{typeReference:Xc.container(Ry.list(r.type)),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var yru=class extends e_{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 Bg.STRING:return Xc.primitive({v1:ny.String,v2:Td.string({default:void 0,validation:void 0})});case Bg.DOUBLE:return Xc.primitive({v1:ny.Double,v2:Td.double({default:void 0,validation:void 0})});case Bg.FLOAT:return Xc.primitive({v1:ny.Float,v2:Td.float({})});case Bg.INT32:return Xc.primitive({v1:ny.Integer,v2:Td.integer({default:void 0,validation:void 0})});case Bg.INT64:return Xc.primitive({v1:ny.Long,v2:Td.long({default:void 0})});case Bg.UINT32:return Xc.primitive({v1:ny.Uint,v2:Td.uint({default:void 0})});case Bg.UINT64:return Xc.primitive({v1:ny.Uint64,v2:Td.uint64({default:void 0})});case Bg.BOOL:return Xc.primitive({v1:ny.Boolean,v2:Td.boolean({default:void 0})});default:return Xc.unknown()}}};var SNi=class extends e_{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 hru({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}}if(wO_.has(this.field.type)){let i=new yru({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:{}}}if((this.field.type===Bg.MESSAGE||this.field.type===Bg.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:{}}}}wrapInOptional(t){return Xc.container(Ry.optional(t))}};function SO_({fields:e,breadcrumbs:t,context:r,sourceCodeInfoPath:i}){let n=[],a={},u=new Set,l={};for(let[d,s]of e.entries()){let c=new SNi({context:r,breadcrumbs:[...t,"fields",s.name],field:s,sourceCodeInfoPath:[...i,lQt.MESSAGE.FIELD,d]}).convert();if(c!=null){let b={name:r.casingsGenerator.generateNameAndWireValue({name:s.name,wireValue:s.name}),valueType:c.type,docs:r.getCommentForPath([...i,lQt.MESSAGE.FIELD,d]),availability:void 0,propertyAccess:void 0,v2Examples:void 0};if(Object.hasOwn(s,"oneofIndex")&&s.oneofIndex!=null){l[s.oneofIndex]==null&&(l[s.oneofIndex]=[]),l[s.oneofIndex].push(s);continue}n.push(b)}}return{convertedFields:n,referencedTypes:u,propertiesByAudience:a,oneOfFields:l}}var vru=class extends e_{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 SNi({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:Vb.undiscriminatedUnion({members:t}),referencedTypes:new Set,inlinedTypes:{}}}};var bru=class extends e_{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:u}=SO_({fields:this.message.field,breadcrumbs:this.breadcrumbs,context:this.context,sourceCodeInfoPath:this.sourceCodeInfoPath});for(let l of n)r.add(l);for(let[l,d]of this.message.nestedType.entries()){let o=new DNi({context:this.context,breadcrumbs:this.breadcrumbs,schema:d,sourceCodeInfoPath:[...this.sourceCodeInfoPath,lQt.MESSAGE.NESTED_TYPE,l],schemaIndex:l}).convert();if(o!=null){for(let c of o.convertedSchema.typeDeclaration.referencedTypes)r.add(c);t={...t,...Object.fromEntries(Object.entries(o.inlinedTypes).map(([c,b])=>[this.prependDelimitedParentMessageName(c),this.context.updateTypeId(b,this.prependDelimitedParentMessageName(c))])),[this.prependDelimitedParentMessageName(d.name)]:this.context.updateTypeId(o.convertedSchema,this.prependDelimitedParentMessageName(d.name))}}}for(let[l,d]of this.message.enumType.entries()){let o=new DNi({context:this.context,breadcrumbs:this.breadcrumbs,schema:d,sourceCodeInfoPath:[...this.sourceCodeInfoPath,lQt.MESSAGE.ENUM_TYPE,l],schemaIndex:l}).convert();if(o!=null){for(let c of o.convertedSchema.typeDeclaration.referencedTypes)r.add(c);t={...t,...Object.fromEntries(Object.entries(o.inlinedTypes).map(([c,b])=>[this.prependDelimitedParentMessageName(c),this.context.updateTypeId(b,this.prependDelimitedParentMessageName(c))])),[this.prependDelimitedParentMessageName(d.name)]:this.context.updateTypeId(o.convertedSchema,this.prependDelimitedParentMessageName(d.name))}}}for(let[l,d]of this.message.oneofDecl.entries()){let o=new vru({context:this.context,breadcrumbs:this.breadcrumbs,oneOfFields:u[l]??[],sourceCodeInfoPath:[...this.sourceCodeInfoPath,lQt.MESSAGE.ONEOF_DECL,l]}).convert();if(o!=null){for(let g of o.referencedTypes)r.add(g);let c={typeDeclaration:this.createTypeDeclaration({shape:o.type,referencedTypes:o.referencedTypes,typeName:this.prependParentMessageName(jO_(d.name))}),audiences:[],propertiesByAudience:{}},b=this.context.convertGrpcReferenceToTypeReference({typeName:this.context.maybePrependPackageName(c.typeDeclaration.name.typeId)});b.ok===!0&&(i.push({name:this.context.casingsGenerator.generateNameAndWireValue({name:d.name,wireValue:d.name}),valueType:b.reference,docs:void 0,availability:void 0,propertyAccess:void 0,v2Examples:void 0}),t={...t,[c.typeDeclaration.name.typeId]:c})}}return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Vb.object({properties:i,extends:[],extendedProperties:[],extraProperties:!1}),referencedTypes:r,typeName:this.message.name,docs:this.context.getCommentForPath(this.sourceCodeInfoPath)}),audiences:[],propertiesByAudience:a},inlinedTypes:t}}createTypeDeclaration({shape:t,referencedTypes:r,typeName:i,docs:n}){return{name:this.convertDeclaredTypeName(i),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:void 0,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 DNi=class extends e_{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 _ru({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)}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}}tryConvertGrpcMessage(){if(this.schema.$typeName==="google.protobuf.DescriptorProto"){let r=new bru({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}){return{name:this.convertDeclaredTypeName(),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:void 0,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 SJn=class extends d7{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:Xc.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 pwc(){return{4:{},5:{},6:{}}}function DO_(e){let t=pwc();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 u=t[n];for(let l=1;l<i.length;l++){let d=i[l];d!=null&&(d in u||(u[d]={}),u=u[d])}u._comment=a.trim()}),t}var u5a=class e extends e_{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:u=new Set}){super({context:r,breadcrumbs:t}),this.message=i,this.type=n,this.depth=a,this.seenMessages=u}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((o,c)=>{o.name&&n.set(c,o.name)});for(let o of this.message.field)Object.hasOwn(o,"oneofIndex")&&o.oneofIndex!=null&&(i.has(o.oneofIndex)||i.set(o.oneofIndex,o));for(let o of this.message.field){let c=o.name??"";if(!(!c||Object.hasOwn(o,"oneofIndex")&&o.oneofIndex!=null&&i.get(o.oneofIndex)!==o))try{let g=this.convertField({field:o,seenMessages:t,fieldName:c});r.set(c,{field:o,result:g})}catch(g){r.set(c,{field:o,result:{isValid:!1,coerced:!1,validExample:null,errors:[`Error converting field ${c}: ${g}`]}})}}let a=Array.from(r.values()),u=a.every(({result:o})=>o.isValid),l=a.flatMap(({result:o})=>o.errors),d={},s=new Map;for(let[o,{field:c,result:b}]of r.entries()){if(!b.isValid||b.validExample===null||b.validExample===void 0)continue;if(Object.hasOwn(c,"oneofIndex")&&c.oneofIndex!=null&&n.has(c.oneofIndex)){let O=n.get(c.oneofIndex)??void 0;O!=null&&s.set(O,{fieldName:o,value:b.validExample})}else d[o]=b.validExample}for(let[o,{fieldName:c,value:b}]of s.entries())d[o]={[c]:b};return{isValid:u,coerced:!1,validExample:d,errors:l}}convertField({field:t,seenMessages:r,fieldName:i}){return t.label===o8n.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 Bg.DOUBLE:case Bg.FLOAT:case Bg.INT64:case Bg.UINT64:case Bg.INT32:case Bg.FIXED64:case Bg.FIXED32:case Bg.UINT32:case Bg.SFIXED32:case Bg.SFIXED64:case Bg.SINT32:case Bg.SINT64:return this.convertNumber();case Bg.BOOL:return this.convertBoolean();case Bg.STRING:return this.convertString(this.EXAMPLE_STRING);case Bg.BYTES:return this.convertBytes();case Bg.ENUM:return this.convertEnum(t);case Bg.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),u,l;if(this.context.getCodeGeneratorRequest())for(let s of this.context.getCodeGeneratorRequest().protoFile){let o=this.context.resolveTypeIdToProtoFile(a);if(o.ok){u=o.message,o.protoFileName!==this.context.spec.name?l=new SJn({...this.context,comments:pwc(),codeGeneratorRequest:this.context.getCodeGeneratorRequest(),spec:s,logger:new wJn}):l=this.context;break}}return!u||!l?{isValid:!0,coerced:!1,validExample:null,errors:[`Could not find message type ${a}`]}:new e({context:l,breadcrumbs:[...this.breadcrumbs,i],message:u,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 u=this.findEnumInMessage(t,a,n);if(u!=null)return u}}};var gru=class extends e_{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:xB.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,availability:void 0,userSpecifiedExamples:[],autogeneratedExamples:[],idempotent:!1,basePath:void 0,fullPath:{head:this.operation.name,parts:[]},allPathParameters:[],pagination:void 0,transport:void 0,source:DJ.proto({methodType:this.getGrpcMethodType()}),audiences:[]}}}getGrpcMethodType(){return this.operation.clientStreaming&&this.operation.serverStreaming?$$t.BidirectionalStream:this.operation.clientStreaming?$$t.ClientStream:this.operation.serverStreaming?$$t.ServerStream:$$t.Unary}convertRequestBody(){let t=this.context.convertGrpcReferenceToTypeReference({typeName:this.operation.inputType,displayNameOverride:this.context.maybeRemoveGrpcPackagePrefix(this.operation.inputType)});return t.ok?{requestBody:IA.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:c1.json(OL.response({responseBodyType:t.reference,docs:void 0,v2Examples:void 0})),statusCode:void 0},responseExample:void 0}:{responseBody:void 0,responseExample:void 0}}};var Oru=class extends e_{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 gru({context:this.context,breadcrumbs:this.breadcrumbs,operation:i,serviceName:this.service.name,sourceCodeInfoPath:[...this.sourceCodeInfoPath,lQt.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 EO_(){return{displayName:void 0,request:{endpoint:{method:Nrr.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:Vs.V2HttpEndpointResponseBody.json({}),docs:void 0},codeSamples:[]}}var mru=class extends cQt{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 DNi({context:this.context,breadcrumbs:[...this.breadcrumbs,this.context.spec.package],schema:r,sourceCodeInfoPath:[pru.ENUM,t],schemaIndex:t}).convert();n!=null&&this.addTypesToIr({...n.inlinedTypes,[this.context.maybePrependPackageName(r.name)]:n.convertedSchema})}for(let[t,r]of this.context.spec.messageType.entries()){let n=new DNi({context:this.context,breadcrumbs:[...this.breadcrumbs,this.context.spec.package],schema:r,sourceCodeInfoPath:[pru.MESSAGE,t],schemaIndex:t}).convert();n!=null&&this.addTypesToIr({...n.inlinedTypes,[this.context.maybePrependPackageName(r.name)]:n.convertedSchema})}}convertServices(){for(let[t,r]of this.context.spec.service.entries()){let n=new Oru({context:this.context,breadcrumbs:this.breadcrumbs,service:r,sourceCodeInfoPath:[pru.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=EO_(),u=this.constructRequestBodyExample(n),l=this.constructResponseBodyExample(n);u!=null&&a.request!=null&&(a.request.requestBody=u),l!=null&&a.response!=null&&(a.response.body=m4.json(l)),n.v2Examples={userSpecifiedExamples:{},autogeneratedExamples:{[i]:a}}}}constructRequestBodyExample(t){let r=t.requestBody.requestBodyType.typeId,i=this.context.resolveTypeIdToProtoFile(r);if(i.ok)return new u5a({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 u5a({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 u=this.context.getGroup({groupParts:i,namespace:this.context.namespace}),l=this.getOrCreatePackage({group:i}),d=[...u].map(c=>this.context.casingsGenerator.generateName(c)),s=d[d.length-1];l.service==null&&(l.service=a??`service_${u.map(c=>S_(c)).join("/")}`),this.ir.services[l.service]==null&&(this.ir.services[l.service]=this.createNewService({allParts:d,finalpart:s,endpointGroupDisplayName:n})),this.ir.services[l.service]?.endpoints.push(t);let o=this.ir.services[l.service];o!=null&&(this.irGraph.addEndpoint(o,t),this.irGraph.markEndpointForAudience(o.name,[t],r))}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]??"",l=`subpackage_${r.slice(0,n+1).join("/")}`;this.ir.subpackages[l]==null&&(this.ir.subpackages[l]={name:this.context.casingsGenerator.generateName(a),displayName:a,...this.createPackage({name:a})});let d=this.ir.subpackages[l];i.subpackages.includes(l)||i.subpackages.push(l),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 MO_({req:e,options:t}){let r,i=iee({generationLanguage:void 0,keywords:void 0,smartCasing:!1});for(let a of e.protoFile){let l=new mru({context:new SJn({codeGeneratorRequest:e,spec:a,settings:{},errorCollector:new gNi({logger:{log:(d,...s)=>{}},relativeFilepathToSpec:void 0}),logger:new wJn,generationLanguage:void 0,smartCasing:!1,exampleGenerationArgs:{disabled:!0},enableUniqueErrorsPerEndpoint:!1,generateV1Examples:!1,comments:DO_(a)}),breadcrumbs:[],audiences:{type:"all"}}).convert();l!=null&&(r=r===void 0?l:fnn(r,l,i))}let n=Ap.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 AO_(e){return{}}var _wc=HIE({name:"protoc-gen-fern",version:`v${String($g_)}`,run:MO_});function HIE({name:e,version:t,run:r}){return{name:e,version:t,run(i){let n=AO_(i.parameter),a=r({req:i,options:n});return $IE([a],nzd,azd)}}}function $IE(e,t,r){return cza(oAo,{supportedFeatures:hC.parse(yza.PROTO3_OPTIONAL|yza.SUPPORTS_EDITIONS),minimumEdition:t,maximumEdition:r,file:e})}var CO_=ui(require("net"),1),BO_=ui(require("os"),1),Pru=class extends Error{constructor(t){super(`${t} is locked`)}},DJn={old:new Set,young:new Set},GIE=1e3*15;var s5a,QIE=()=>{let e=BO_.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},qO_=e=>new Promise((t,r)=>{let i=CO_.default.createServer();i.unref(),i.on("error",r),i.listen(e,()=>{let{port:n}=i.address();i.close(()=>{t(n)})})}),TO_=async(e,t)=>{if(e.host||e.port===0)return qO_(e);for(let r of t)try{await qO_({port:e.port,host:r})}catch(i){if(!["EADDRNOTAVAIL","EINVAL"].includes(i.code))throw i}return e.port},JIE=function*(e){e&&(yield*e),yield 0};async function EJn(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)}s5a===void 0&&(s5a=setTimeout(()=>{s5a=void 0,DJn.old=DJn.young,DJn.young=new Set},GIE),s5a.unref&&s5a.unref());let i=QIE();for(let n of JIE(t))try{if(r.has(n))continue;let a=await TO_({...e,port:n},i);for(;DJn.old.has(a)||DJn.young.has(a);){if(n!==0)throw new Pru(n);a=await TO_({...e,port:n},i)}return DJn.young.add(a),a}catch(a){if(!["EADDRINUSE","EACCES"].includes(a.code)&&!(a instanceof Pru))throw a}throw new Error("No available ports found")}var Ann=class e extends Error{constructor(t){super(t||"yargs error"),this.name="YError",Error.captureStackTrace&&Error.captureStackTrace(this,e)}};function IO_(){return KIE()?0:1}function KIE(){return YIE()&&!process.defaultApp}function YIE(){return!!process.versions.electron}function hwc(e){return e.slice(IO_()+1)}function zO_(){return process.argv[IO_()]}var jru=require("assert");var xO_=require("util"),NO_=require("fs"),FO_=require("url");var fQt=require("path");var ezE={},XIE="require is not supported by ESM",RO_="loading a directory of commands is not supported yet for ESM",c5a;try{c5a=(0,FO_.fileURLToPath)(ezE.url)}catch{c5a=process.cwd()}var ZIE=c5a.substring(0,c5a.lastIndexOf("node_modules")),kIE={assert:{notStrictEqual:jru.notStrictEqual,strictEqual:jru.strictEqual},cliui:Y2a,findUp:peu,getEnv:e=>process.env[e],inspect:xO_.inspect,getCallerFile:()=>{throw new Ann(RO_)},getProcessArgvBin:zO_,mainFilename:ZIE||process.cwd(),Parser:PQn,path:{basename:fQt.basename,dirname:fQt.dirname,extname:fQt.extname,relative:fQt.relative,resolve:fQt.resolve},process:{argv:()=>process.argv,cwd:process.cwd,emitWarning:(e,t)=>process.emitWarning(e,t),execPath:()=>process.execPath,exit:process.exit,nextTick:process.nextTick,stdColumns:typeof process.stdout.columns<"u"?process.stdout.columns:null},readFileSync:NO_.readFileSync,require:()=>{throw new Ann(XIE)},requireDirectory:()=>{throw new Ann(RO_)},stringWidth:e=>[...e].length,y18n:_eu({directory:(0,fQt.resolve)(c5a,"../../../locales"),updateFiles:!1})};var gm_=ui(bm_(),1),{applyExtends:pzE,cjsPlatformShim:_zE,Parser:hzE,processArgv:yzE,Yargs:Rru}=gm_.default;Rru.applyExtends=(e,t,r)=>pzE(e,t,r,_zE);Rru.hideBin=yzE.hideBin;Rru.Parser=hzE;var Om_=Rru;var mm_=require("fs/promises");var Pm_=require("path"),jm_=ui(hk(),1);async function wm_({url:e,logger:t}){try{let r=await vzE({url:e,logger:t}),i=await jm_.default.dir(),n=(0,Pm_.join)(i.path,e.endsWith(".json")?"openapi.json":"openapi.yaml");return t.debug("tmpDir",i.path),t.debug("filePath",n),await(0,mm_.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 vzE({url:e,logger:t}){let r=await xF.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:XBo(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)`),XBo(r.data))}var y5a=ui(XIi(),1);function xwc(e,t){if(e=y5a.default.parse(e),t=y5a.default.parse(t),!(y5a.default.compareBuild(e,t)>=0))return y5a.default.diff(e,t)||"build"}var bzE=/^([0-9]+)\.([0-9]+)\.([0-9]+)-([0-9]+)-([a-z0-9])+$/,gzE=/^([0-9]+)\.([0-9]+)\.([0-9]+)-rc[.-]?([0-9]+)-([0-9]+)-([a-z0-9])+$/,OzE=/^([0-9]+)\.([0-9]+)\.([0-9]+)-rc[.-]?([0-9]+)$/,mzE=/^([0-9]+)\.([0-9]+)\.([0-9]+)$/,PzE=/^([0-9]+)\.([0-9]+)\.([0-9]+)-alpha[.-]?([0-9]+)$/,jzE=/^([0-9]+)\.([0-9]+)\.([0-9]+)-beta[.-]?([0-9]+)$/;function Lnn(e){let t=e.match(PzE);if(t!=null){let[l,d,s,o,c]=t,b=tx(d),g=tx(s),O=tx(o),m=tx(c);if(b==null||g==null||O==null||m==null)throw new Error("Cannot parse alpha version: "+e);return{type:"alpha",major:b,minor:g,patch:O,index:m}}let r=e.match(jzE);if(r!=null){let[l,d,s,o,c]=r,b=tx(d),g=tx(s),O=tx(o),m=tx(c);if(b==null||g==null||O==null||m==null)throw new Error("Cannot parse beta version: "+e);return{type:"beta",major:b,minor:g,patch:O,index:m}}let i=e.match(bzE);if(i!=null){let[l,d,s,o,c]=i,b=tx(d),g=tx(s),O=tx(o),m=tx(c);if(b==null||g==null||O==null||m==null)throw new Error("Cannot parse post-release commit version: "+e);return{type:"post-release-commit",major:b,minor:g,patch:O,commitIndex:m}}let n=e.match(OzE);if(n!=null){let[l,d,s,o,c]=n,b=tx(d),g=tx(s),O=tx(o),m=tx(c);if(b==null||g==null||O==null||m==null)throw new Error("Cannot parse RC version: "+e);return{type:"rc",major:b,minor:g,patch:O,releaseCandidateIndex:m}}let a=e.match(gzE);if(a!=null){let[l,d,s,o,c,b]=a,g=tx(d),O=tx(s),m=tx(o),w=tx(c),E=tx(b);if(g==null||O==null||m==null||w==null||E==null)throw new Error("Cannot parse post-RC version: "+e);return{type:"post-rc-commit",major:g,minor:O,patch:m,releaseCandidateIndex:w,commitIndex:E}}let u=e.match(mzE);if(u!=null){let[l,d,s,o]=u,c=tx(d),b=tx(s),g=tx(o);if(c==null||b==null||g==null)throw new Error("Cannot parse release version: "+e);return{type:"release",major:c,minor:b,patch:g}}throw new Error("Failed to parse version: "+e)}function tx(e){if(e==null||e.length===0)return;let t=Number(e);if(!isNaN(t))return t}function sue(e,t){if(e===t)return!1;let r=Lnn(e),i=Lnn(t);if(r.major!==i.major||r.minor!==i.minor||r.patch!==i.patch)return xwc(Sm_(r),Sm_(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!sue(t,e)}function Sm_(e){return`${e.major}.${e.minor}.${e.patch}`}var qNi=e=>e.name==="up"||e.name==="k"||e.ctrl&&e.name==="p",IJn=e=>e.name==="down"||e.name==="j"||e.ctrl&&e.name==="n",Dm_=e=>e.name==="space",zJn=e=>e.name==="backspace",xru=e=>"1234567890".includes(e.name),L4=e=>e.name==="enter"||e.name==="return";var Nru=class extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(t){super(),this.cause=t?.cause}},Fru=class extends Error{name="CancelPromptError";message="Prompt was canceled"},v5a=class extends Error{name="ExitPromptError"},Lru=class extends Error{name="HookError"},bor=class extends Error{name="ValidationError"};var qm_=require("async_hooks");var Uru=require("async_hooks");var Em_=new Uru.AsyncLocalStorage;function wzE(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function Mm_(e,t){let r=wzE(e);return Em_.run(r,()=>{function i(n){r.handleChange=()=>{r.index=0,n()},r.handleChange()}return t(i)})}function Unn(){let e=Em_.getStore();if(!e)throw new Lru("[Inquirer] Hook functions can only be called from within a prompt");return e}function Nwc(){return Unn().rl}function Fwc(e){let t=(...r)=>{let i=Unn(),n=!1,a=i.handleChange;i.handleChange=()=>{n=!0};let u=e(...r);return n&&a(),i.handleChange=a,u};return Uru.AsyncResource.bind(t)}function RJn(e){let t=Unn(),{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 Am_(){Unn().handleChange()}var Vnn={queue(e){let t=Unn(),{index:r}=t;t.hooksEffect.push(()=>{t.hooksCleanup[r]?.();let i=e(Nwc());if(i!=null&&typeof i!="function")throw new bor("useEffect return value must be a cleanup function or nothing.");t.hooksCleanup[r]=i})},run(){let e=Unn();Fwc(()=>{e.hooksEffect.forEach(t=>{t()}),e.hooksEffect.length=0})()},clearAll(){let e=Unn();e.hooksCleanup.forEach(t=>{t?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function H0(e){return RJn(t=>{let r=qm_.AsyncResource.bind(function(a){t.get()!==a&&(t.set(a),Am_())});if(t.initialized)return[t.get(),r];let i=typeof e=="function"?e():e;return t.set(i),[i,r]})}function pQt(e,t){RJn(r=>{let i=r.get();(!Array.isArray(i)||t.some((a,u)=>!Object.is(a,i[u])))&&Vnn.queue(e),r.set(t)})}var X3e=ui(z8(),1);var Tm_={prefix:{idle:X3e.default.blue("?"),done:X3e.default.green(E4.tick)},spinner:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map(e=>X3e.default.yellow(e))},style:{answer:X3e.default.cyan,message:X3e.default.bold,error:e=>X3e.default.red(`> ${e}`),defaultAnswer:e=>X3e.default.dim(`(${e})`),help:X3e.default.dim,highlight:X3e.default.cyan,key:e=>X3e.default.cyan(X3e.default.bold(`<${e}>`))}};function Cm_(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 Bm_(...e){let t={};for(let r of e)for(let[i,n]of Object.entries(r)){let a=t[i];t[i]=Cm_(a)&&Cm_(n)?Bm_(a,n):n}return t}function rN(...e){let t=[Tm_,...e.filter(r=>r!=null)];return Bm_(...t)}function h7({status:e="idle",theme:t}){let[r,i]=H0(!1),[n,a]=H0(0),{prefix:u,spinner:l}=rN(t);return pQt(()=>{if(e==="loading"){let s,o=-1,c=setTimeout(()=>{i(!0),s=setInterval(()=>{o=o+1,a(o%l.frames.length)},l.interval)},300);return()=>{clearTimeout(c),clearInterval(s)}}else i(!1)},[e]),r?l.frames[n]:typeof u=="string"?u:u[e==="loading"?"idle":e]??u.idle}function cue(e,t){return RJn(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 Z3e(e){return H0({current:e})[0]}function y7(e){let t=Z3e(e);t.current=e,pQt(r=>{let i=!1,n=Fwc((a,u)=>{i||t.current(u,r)});return r.input.on("keypress",n),()=>{i=!0,r.input.removeListener("keypress",n)}},[])}var Im_=ui(Mlc(),1),zm_=ui(Rlc(),1);function b5a(e,t){return e.split(`
1916
1916
  `).flatMap(r=>(0,zm_.default)(r,t,{trim:!1,hard:!0}).split(`
1917
1917
  `).map(i=>i.trimEnd())).join(`
@@ -1953,10 +1953,10 @@ ${M}${q}${D}${eP_.default.cursorHide}`});function Jru({message:e,error:t,logger:
1953
1953
  Run ${Ds.cyan("fern generator upgrade")} to upgrade your generators.`),n.length>2&&(r+=`
1954
1954
  Run ${Ds.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),THn(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function l1c({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!jP_(e))return;let n=t??"",a=e.filter(l=>l.isUpgradeAvailable);r!=null&&(a=a.slice(0,r+1));let u=a.sort((l,d)=>l.generatorName.localeCompare(d.generatorName)||l.currentVersion.localeCompare(d.currentVersion));for(let l of u)n+=`
1955
1955
  ${await hRE(l.generatorName)} (${l.apiName!=null?"API: "+l.apiName+", ":""}Group: ${l.generatorGroup}) `+Ds.dim(l.currentVersion)+Ds.reset(" \u2192 ")+Ds.green(l.latestVersion);return n+=`
1956
- `,i?THn(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function hRE(e){let r=await new PP_.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new Error(`Generator ${e} not found`);return r.body.displayName}async function yRE({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let l={type:"singleApi",versions:{}};return await SP_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,o,c)=>{l.versions[s]==null&&(l.versions[s]={});let b=TIi(o.name,c),g=await Brr({generatorName:b,cliVersion:e.environment.packageVersion,currentGeneratorVersion:o.version,channel:n,includeMajor:a,context:c});g!=null&&(l.versions[s][o.name]={previousVersion:o.version,latestVersion:g})},generatorFilter:r,groupFilter:i}),l}let u={type:"multiApi",versions:{}};return await SP_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(l,d,s,o)=>{if(l==null)return;u.versions[l]==null&&(u.versions[l]={}),u.versions[l][d]==null&&(u.versions[l][d]={});let c=TIi(s.name,o),b=await Brr({generatorName:c,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:o});b!=null&&(u.versions[l][d][s.name]={previousVersion:s.version,latestVersion:b})},generatorFilter:r,groupFilter:i}),u}async function SP_({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async u=>{let l=await k$t({absolutePathToWorkspace:a.absoluteFilePath,context:u});if(!(l==null||l.groups==null)){for(let d of l.groups)if(!(n!=null&&d.groupName!==n))for(let s of d.generators)i!=null&&s.name!==i||await r(a.workspaceName,d.groupName,s,u)}})}))}function DP_(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[u,l]of Object.entries(a)){r.debug(`Checking if ${u} in group ${n} has an upgrade available...`);let d=sue(l.latestVersion,l.previousVersion);r.debug(`Latest version: ${l.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:u,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:l.previousVersion,latestVersion:l.latestVersion})}return i}async function kru({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let l=await yRE({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(l.type==="multiApi")for(let[d,s]of Object.entries(l.versions))u.push(...DP_(s,d,t.logger));else u.push(...DP_(l.versions,void 0,t.logger))}return u}var E5a=class extends Error{response;request;options;constructor(t,r,i){let n=t.status||t.status===0?t.status:"",a=t.statusText||"",u=`${n} ${a}`.trim(),l=u?`status code ${u}`:"an unknown error";super(`Request failed with ${l}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var UJn=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var f1c=(()=>{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})(),EP_=typeof globalThis.AbortController=="function",MP_=typeof globalThis.ReadableStream=="function",AP_=typeof globalThis.FormData=="function",eiu=["get","post","put","patch","head","delete"],vRE=()=>{};vRE();var qP_={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},tiu=2147483647,TP_=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,riu=Symbol("stop"),CP_={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},BP_={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 bRE=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=TP_,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},IP_=(e,t)=>{let r=Number(e.headers.get("content-length"))||0,i=0;return e.status===204?(t&&t({percent:1,totalBytes:r,transferredBytes:i},new Uint8Array),new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new Response(new ReadableStream({async start(n){let a=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array);async function u(){let{done:l,value:d}=await a.read();if(l){n.close();return}if(t){i+=d.byteLength;let s=r===0?0:i/r;t({percent:s,transferredBytes:i,totalBytes:r},d)}n.enqueue(d),await u()}await u()}}),{status:e.status,statusText:e.statusText,headers:e.headers})},zP_=(e,t)=>{let r=bRE(e.body),i=0;return new Request(e,{duplex:"half",body:new ReadableStream({async start(n){let a=e.body instanceof ReadableStream?e.body.getReader():new Response("").body.getReader();async function u(){let{done:l,value:d}=await a.read();if(l){t&&t({percent:1,transferredBytes:i,totalBytes:Math.max(r,i)},new Uint8Array),n.close();return}i+=d.byteLength;let s=r===0?0:i/r;(r<i||s===1)&&(s=.99),t&&t({percent:Number(s.toFixed(2)),transferredBytes:i,totalBytes:r},d),n.enqueue(d),await u()}await u()}})})};var VJn=e=>e!==null&&typeof e=="object";var M5a=(...e)=>{for(let t of e)if((!VJn(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return _1c({},...e)},d1c=(e={},t={})=>{let r=new globalThis.Headers(e),i=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(let[a,u]of n.entries())i&&u==="undefined"||u===void 0?r.delete(a):r.set(a,u);return r};function iiu(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:_1c(e[r]??[],t[r]??[])}var p1c=(e={},t={})=>({beforeRequest:iiu(e,t,"beforeRequest"),beforeRetry:iiu(e,t,"beforeRetry"),afterResponse:iiu(e,t,"afterResponse"),beforeError:iiu(e,t,"beforeError")}),_1c=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(VJn(n)){for(let[a,u]of Object.entries(n))VJn(u)&&a in t&&(u=_1c(t[a],u)),t={...t,[a]:u};VJn(n.hooks)&&(i=p1c(i,n.hooks),t.hooks=i),VJn(n.headers)&&(r=d1c(r,n.headers),t.headers=r)}return t};var xP_=e=>eiu.includes(e)?e.toUpperCase():e,gRE=["get","put","head","delete","options","trace"],ORE=[408,413,429,500,502,503,504],mRE=[413,429,503],RP_={limit:2,methods:gRE,statusCodes:ORE,afterStatusCodes:mRE,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},NP_=(e={})=>{if(typeof e=="number")return{...RP_,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{...RP_,...e}};async function h1c(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new UJn(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function y1c(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 FP_=(e,t)=>{let r={};for(let i in t)!(i in BP_)&&!(i in CP_)&&!(i in e)&&(r[i]=t[i]);return r};var A5a=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>tiu)throw new RangeError(`The \`timeout\` option cannot be greater than ${tiu}`);await Promise.resolve();let l=await i._fetch();for(let d of i._options.hooks.afterResponse){let s=await d(i.request,i._options,i._decorateResponse(l.clone()));s instanceof globalThis.Response&&(l=s)}if(i._decorateResponse(l),!l.ok&&i._options.throwHttpErrors){let d=new E5a(l,i.request,i._options);for(let s of i._options.hooks.beforeError)d=await s(d);throw d}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!MP_)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return IP_(l.clone(),i._options.onDownloadProgress)}return l},u=(i._options.retry.methods.includes(i.request.method.toLowerCase())?i._retry(n):n()).finally(async()=>{i.request.bodyUsed||await i.request.body?.cancel()});for(let[l,d]of Object.entries(qP_))u[l]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||d);let s=await u;if(l==="json"){if(s.status===204||(await s.clone().arrayBuffer()).byteLength===0)return"";if(r.parseJson)return r.parseJson(await s.text())}return s[l]()};return u}request;abortController;_retryCount=0;_input;_options;constructor(t,r={}){if(this._input=t,this._options={...r,headers:d1c(this._input.headers,r.headers),hooks:p1c({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:xP_(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:NP_(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(EP_){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(f1c&&(this._options.duplex="half"),this._options.json!==void 0&&(this._options.body=this._options.stringifyJson?.(this._options.json)??JSON.stringify(this._options.json),this._options.headers.set("content-type",this._options.headers.get("content-type")??"application/json")),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){let n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(AP_&&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(!f1c)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=zP_(this.request,this._options.onUploadProgress))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof UJn)throw t;if(t instanceof E5a){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),tiu);if(this._retryCount<1)throw r;await y1c(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})===riu)return;return this._retry(t)}}async _fetch(){for(let i of this._options.hooks.beforeRequest){let n=await i(this.request,this._options);if(n instanceof Request){this.request=n;break}if(n instanceof Response)return n}let t=FP_(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):h1c(r,t,this.abortController,this._options)}};var v1c=e=>{let t=(r,i)=>A5a.create(r,M5a(e,i));for(let r of eiu)t[r]=(i,n)=>A5a.create(i,M5a(e,n,{method:r}));return t.create=r=>v1c(M5a(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),v1c(M5a(e,r))),t.stop=riu,t},PRE=v1c(),LP_=PRE;var cj_=ui(sj_(),1);function P1c(e){let t=(0,cj_.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var iw_=ui(rw_(),1),nw_=ui(XIi(),1),z1c=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},R1c=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function x1c(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??P1c(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),l=(0,iw_.default)(a.toString(),{recursive:!0}),d={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete d.accept,l&&(d.authorization=`${l.type} ${l.token}`);let s;try{s=await LP_(u,{headers:d,keepalive:!0}).json()}catch(c){throw c?.response?.status===404?new z1c(e):c}if(t.allVersions)return s;let o=new R1c(e,r);if(s["dist-tags"][r]){let{time:c}=s;s=s.versions[s["dist-tags"][r]],s.time=c}else if(r){let c=!!s.versions[r];if(i&&!c)for(let[g,O]of Object.entries(s.versions))O.deprecated&&delete s.versions[g];if(!c){let g=Object.keys(s.versions);if(r=nw_.default.maxSatisfying(g,r),!r)throw o}let{time:b}=s;if(s=s.versions[r],s.time=b,!s)throw o}return s}async function z5a(e,t){let{version:r}=await x1c(e.toLowerCase(),t);return r}async function INi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:z5a(e.packageName,{version:t?"prerelease":"latest"})}var aw_=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],hiu=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=pb.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new Zru(t,r),this.isLocal=i??!1;let n=this.getPackageName(),a=this.getPackageVersion(),u=this.getCliName();(n==null||a==null||u==null)&&this.exitProgram(),this.environment={packageName:n,packageVersion:a,cliName:u}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.66.17"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Ds.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new sL}failWithoutThrowing(t,r){this.didSucceed=!1,Jru({message:t,error:r,logger:this.logger})}async exit({code:t}={}){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await PHn()).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 wP_({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1956
+ `,i?THn(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function hRE(e){let r=await new PP_.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new Error(`Generator ${e} not found`);return r.body.displayName}async function yRE({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let l={type:"singleApi",versions:{}};return await SP_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,o,c)=>{l.versions[s]==null&&(l.versions[s]={});let b=TIi(o.name,c),g=await Brr({generatorName:b,cliVersion:e.environment.packageVersion,currentGeneratorVersion:o.version,channel:n,includeMajor:a,context:c});g!=null&&(l.versions[s][o.name]={previousVersion:o.version,latestVersion:g})},generatorFilter:r,groupFilter:i}),l}let u={type:"multiApi",versions:{}};return await SP_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(l,d,s,o)=>{if(l==null)return;u.versions[l]==null&&(u.versions[l]={}),u.versions[l][d]==null&&(u.versions[l][d]={});let c=TIi(s.name,o),b=await Brr({generatorName:c,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:o});b!=null&&(u.versions[l][d][s.name]={previousVersion:s.version,latestVersion:b})},generatorFilter:r,groupFilter:i}),u}async function SP_({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async u=>{let l=await k$t({absolutePathToWorkspace:a.absoluteFilePath,context:u});if(!(l==null||l.groups==null)){for(let d of l.groups)if(!(n!=null&&d.groupName!==n))for(let s of d.generators)i!=null&&s.name!==i||await r(a.workspaceName,d.groupName,s,u)}})}))}function DP_(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[u,l]of Object.entries(a)){r.debug(`Checking if ${u} in group ${n} has an upgrade available...`);let d=sue(l.latestVersion,l.previousVersion);r.debug(`Latest version: ${l.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:u,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:l.previousVersion,latestVersion:l.latestVersion})}return i}async function kru({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let l=await yRE({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(l.type==="multiApi")for(let[d,s]of Object.entries(l.versions))u.push(...DP_(s,d,t.logger));else u.push(...DP_(l.versions,void 0,t.logger))}return u}var E5a=class extends Error{response;request;options;constructor(t,r,i){let n=t.status||t.status===0?t.status:"",a=t.statusText||"",u=`${n} ${a}`.trim(),l=u?`status code ${u}`:"an unknown error";super(`Request failed with ${l}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var UJn=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var f1c=(()=>{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})(),EP_=typeof globalThis.AbortController=="function",MP_=typeof globalThis.ReadableStream=="function",AP_=typeof globalThis.FormData=="function",eiu=["get","post","put","patch","head","delete"],vRE=()=>{};vRE();var qP_={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},tiu=2147483647,TP_=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,riu=Symbol("stop"),CP_={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},BP_={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 bRE=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=TP_,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},IP_=(e,t)=>{let r=Number(e.headers.get("content-length"))||0,i=0;return e.status===204?(t&&t({percent:1,totalBytes:r,transferredBytes:i},new Uint8Array),new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new Response(new ReadableStream({async start(n){let a=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array);async function u(){let{done:l,value:d}=await a.read();if(l){n.close();return}if(t){i+=d.byteLength;let s=r===0?0:i/r;t({percent:s,transferredBytes:i,totalBytes:r},d)}n.enqueue(d),await u()}await u()}}),{status:e.status,statusText:e.statusText,headers:e.headers})},zP_=(e,t)=>{let r=bRE(e.body),i=0;return new Request(e,{duplex:"half",body:new ReadableStream({async start(n){let a=e.body instanceof ReadableStream?e.body.getReader():new Response("").body.getReader();async function u(){let{done:l,value:d}=await a.read();if(l){t&&t({percent:1,transferredBytes:i,totalBytes:Math.max(r,i)},new Uint8Array),n.close();return}i+=d.byteLength;let s=r===0?0:i/r;(r<i||s===1)&&(s=.99),t&&t({percent:Number(s.toFixed(2)),transferredBytes:i,totalBytes:r},d),n.enqueue(d),await u()}await u()}})})};var VJn=e=>e!==null&&typeof e=="object";var M5a=(...e)=>{for(let t of e)if((!VJn(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return _1c({},...e)},d1c=(e={},t={})=>{let r=new globalThis.Headers(e),i=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(let[a,u]of n.entries())i&&u==="undefined"||u===void 0?r.delete(a):r.set(a,u);return r};function iiu(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:_1c(e[r]??[],t[r]??[])}var p1c=(e={},t={})=>({beforeRequest:iiu(e,t,"beforeRequest"),beforeRetry:iiu(e,t,"beforeRetry"),afterResponse:iiu(e,t,"afterResponse"),beforeError:iiu(e,t,"beforeError")}),_1c=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(VJn(n)){for(let[a,u]of Object.entries(n))VJn(u)&&a in t&&(u=_1c(t[a],u)),t={...t,[a]:u};VJn(n.hooks)&&(i=p1c(i,n.hooks),t.hooks=i),VJn(n.headers)&&(r=d1c(r,n.headers),t.headers=r)}return t};var xP_=e=>eiu.includes(e)?e.toUpperCase():e,gRE=["get","put","head","delete","options","trace"],ORE=[408,413,429,500,502,503,504],mRE=[413,429,503],RP_={limit:2,methods:gRE,statusCodes:ORE,afterStatusCodes:mRE,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},NP_=(e={})=>{if(typeof e=="number")return{...RP_,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{...RP_,...e}};async function h1c(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new UJn(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function y1c(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 FP_=(e,t)=>{let r={};for(let i in t)!(i in BP_)&&!(i in CP_)&&!(i in e)&&(r[i]=t[i]);return r};var A5a=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>tiu)throw new RangeError(`The \`timeout\` option cannot be greater than ${tiu}`);await Promise.resolve();let l=await i._fetch();for(let d of i._options.hooks.afterResponse){let s=await d(i.request,i._options,i._decorateResponse(l.clone()));s instanceof globalThis.Response&&(l=s)}if(i._decorateResponse(l),!l.ok&&i._options.throwHttpErrors){let d=new E5a(l,i.request,i._options);for(let s of i._options.hooks.beforeError)d=await s(d);throw d}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!MP_)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return IP_(l.clone(),i._options.onDownloadProgress)}return l},u=(i._options.retry.methods.includes(i.request.method.toLowerCase())?i._retry(n):n()).finally(async()=>{i.request.bodyUsed||await i.request.body?.cancel()});for(let[l,d]of Object.entries(qP_))u[l]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||d);let s=await u;if(l==="json"){if(s.status===204||(await s.clone().arrayBuffer()).byteLength===0)return"";if(r.parseJson)return r.parseJson(await s.text())}return s[l]()};return u}request;abortController;_retryCount=0;_input;_options;constructor(t,r={}){if(this._input=t,this._options={...r,headers:d1c(this._input.headers,r.headers),hooks:p1c({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:xP_(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:NP_(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(EP_){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(f1c&&(this._options.duplex="half"),this._options.json!==void 0&&(this._options.body=this._options.stringifyJson?.(this._options.json)??JSON.stringify(this._options.json),this._options.headers.set("content-type",this._options.headers.get("content-type")??"application/json")),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){let n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(AP_&&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(!f1c)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=zP_(this.request,this._options.onUploadProgress))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof UJn)throw t;if(t instanceof E5a){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),tiu);if(this._retryCount<1)throw r;await y1c(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})===riu)return;return this._retry(t)}}async _fetch(){for(let i of this._options.hooks.beforeRequest){let n=await i(this.request,this._options);if(n instanceof Request){this.request=n;break}if(n instanceof Response)return n}let t=FP_(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):h1c(r,t,this.abortController,this._options)}};var v1c=e=>{let t=(r,i)=>A5a.create(r,M5a(e,i));for(let r of eiu)t[r]=(i,n)=>A5a.create(i,M5a(e,n,{method:r}));return t.create=r=>v1c(M5a(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),v1c(M5a(e,r))),t.stop=riu,t},PRE=v1c(),LP_=PRE;var cj_=ui(sj_(),1);function P1c(e){let t=(0,cj_.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var iw_=ui(rw_(),1),nw_=ui(XIi(),1),z1c=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},R1c=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function x1c(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??P1c(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),l=(0,iw_.default)(a.toString(),{recursive:!0}),d={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete d.accept,l&&(d.authorization=`${l.type} ${l.token}`);let s;try{s=await LP_(u,{headers:d,keepalive:!0}).json()}catch(c){throw c?.response?.status===404?new z1c(e):c}if(t.allVersions)return s;let o=new R1c(e,r);if(s["dist-tags"][r]){let{time:c}=s;s=s.versions[s["dist-tags"][r]],s.time=c}else if(r){let c=!!s.versions[r];if(i&&!c)for(let[g,O]of Object.entries(s.versions))O.deprecated&&delete s.versions[g];if(!c){let g=Object.keys(s.versions);if(r=nw_.default.maxSatisfying(g,r),!r)throw o}let{time:b}=s;if(s=s.versions[r],s.time=b,!s)throw o}return s}async function z5a(e,t){let{version:r}=await x1c(e.toLowerCase(),t);return r}async function INi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:z5a(e.packageName,{version:t?"prerelease":"latest"})}var aw_=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],hiu=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=pb.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new Zru(t,r),this.isLocal=i??!1;let n=this.getPackageName(),a=this.getPackageVersion(),u=this.getCliName();(n==null||a==null||u==null)&&this.exitProgram(),this.environment={packageName:n,packageVersion:a,cliName:u}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.66.19"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Ds.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new sL}failWithoutThrowing(t,r){this.didSucceed=!1,Jru({message:t,error:r,logger:this.logger})}async exit({code:t}={}){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await PHn()).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 wP_({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1957
1957
  `)||(r+=`
1958
1958
  `),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=QWs(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 O5a(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 sL}finally{i.finish()}return n}async instrumentPostHogEvent(t){this.isLocal||(await PHn()).sendEvent(t)}logger=Ger((t,...r)=>this.log(t,...r));stderr=Ger((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=ow_(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?ow_(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=aw_[this.numTasks++%aw_.length],u=Ds.hex(a)(n);return{...this.constructTaskInit(),logPrefix:u}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===hI.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=>WBi.indexOf(n.level)>=WBi.indexOf(this.logLevel));this.ttyAwareLogger.log(i,{includeDebugInfo:this.logLevel===pb.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 INi({cliEnvironment:this.environment,includePreReleases:t}),i=sue(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await kru({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){return await Kwc({message:t,default:r})}async getInput(t){return await Ywc({message:t.message,default:t.default})}};function ow_(e){return`[${e}]:`}var hQt=class{generatorsConfiguration;workspaceName;cliVersion;absoluteFilePath;changelog;constructor({generatorsConfiguration:t,workspaceName:r,cliVersion:i,absoluteFilePath:n,changelog:a}){this.generatorsConfiguration=t,this.workspaceName=r,this.cliVersion=i,this.absoluteFilePath=n,this.changelog=a}};var ZAe=class extends hQt{definition;sources;type="fern";constructor({definition:t,sources:r,...i}){super(i),this.definition=t,this.sources=r??[]}async getDefinition(){return this.definition}async toFernWorkspace(){return this}getSources(){return this.sources}getAbsoluteFilePaths(){return[this.absoluteFilePath]}};var Jmi={enableUniqueErrorsPerEndpoint:!1,detectGlobalHeaders:!0,objectQueryParameters:!1,respectReadonlySchemas:!1,respectNullableSchemas:!1,onlyIncludeReferencedSchemas:!1,inlinePathParameters:!1,useBytesForBinaryResponse:!1,respectForwardCompatibleEnums:!1};function R5a({options:e,overrides:t}){return{enableUniqueErrorsPerEndpoint:t?.enableUniqueErrorsPerEndpoint??e?.enableUniqueErrorsPerEndpoint??Jmi.enableUniqueErrorsPerEndpoint,detectGlobalHeaders:t?.detectGlobalHeaders??e?.detectGlobalHeaders??Jmi.detectGlobalHeaders,objectQueryParameters:t?.objectQueryParameters??e?.objectQueryParameters??Jmi.objectQueryParameters,respectReadonlySchemas:t?.respectReadonlySchemas??e?.respectReadonlySchemas??Jmi.respectReadonlySchemas,respectNullableSchemas:t?.respectNullableSchemas??e?.respectNullableSchemas??Jmi.respectNullableSchemas,onlyIncludeReferencedSchemas:t?.onlyIncludeReferencedSchemas??e?.onlyIncludeReferencedSchemas??Jmi.onlyIncludeReferencedSchemas,inlinePathParameters:t?.inlinePathParameters??e?.inlinePathParameters??Jmi.inlinePathParameters,useBytesForBinaryResponse:t?.useBytesForBinaryResponse??e?.useBytesForBinaryResponse??Jmi.useBytesForBinaryResponse,respectForwardCompatibleEnums:t?.respectForwardCompatibleEnums??e?.respectForwardCompatibleEnums??Jmi.respectForwardCompatibleEnums}}var nK={openapi:e=>({...e,type:"openapi",_visit:function(t){return nK._visit(this,t)}}),protobuf:e=>({...e,type:"protobuf",_visit:function(t){return nK._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"openapi":return t.openapi(e);case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var KJn={protobuf:e=>({...e,type:"protobuf",_visit:function(t){return KJn._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var JL={basic:e=>({...e,type:"basic",_visit:function(t){return JL._visit(this,t)}}),bearer:e=>({...e,type:"bearer",_visit:function(t){return JL._visit(this,t)}}),header:e=>({...e,type:"header",_visit:function(t){return JL._visit(this,t)}}),query:e=>({...e,type:"query",_visit:function(t){return JL._visit(this,t)}}),oauth:e=>({...e,type:"oauth",_visit:function(t){return JL._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"basic":return t.basic(e);case"bearer":return t.bearer(e);case"header":return t.header(e);case"query":return t.query(e);case"oauth":return t.oauth(e);default:return t._other(e)}}};var xg={primitive:e=>({value:e,type:"primitive",_visit:function(t){return xg._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return xg._visit(this,t)}}),array:e=>({value:e,type:"array",_visit:function(t){return xg._visit(this,t)}}),map:e=>({value:e,type:"map",_visit:function(t){return xg._visit(this,t)}}),enum:e=>({value:e,type:"enum",_visit:function(t){return xg._visit(this,t)}}),literal:e=>({value:e,type:"literal",_visit:function(t){return xg._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return xg._visit(this,t)}}),unknown:e=>({value:e,type:"unknown",_visit:function(t){return xg._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e.value);case"object":return t.object(e);case"array":return t.array(e.value);case"map":return t.map(e.value);case"enum":return t.enum(e.value);case"literal":return t.literal(e.value);case"oneOf":return t.oneOf(e.value);case"unknown":return t.unknown(e.value);default:return t._other(e)}}};var h_={int:e=>({value:e,type:"int",_visit:function(t){return h_._visit(this,t)}}),int64:e=>({value:e,type:"int64",_visit:function(t){return h_._visit(this,t)}}),uint:e=>({value:e,type:"uint",_visit:function(t){return h_._visit(this,t)}}),uint64:e=>({value:e,type:"uint64",_visit:function(t){return h_._visit(this,t)}}),float:e=>({value:e,type:"float",_visit:function(t){return h_._visit(this,t)}}),double:e=>({value:e,type:"double",_visit:function(t){return h_._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return h_._visit(this,t)}}),datetime:e=>({value:e,type:"datetime",_visit:function(t){return h_._visit(this,t)}}),date:e=>({value:e,type:"date",_visit:function(t){return h_._visit(this,t)}}),base64:e=>({value:e,type:"base64",_visit:function(t){return h_._visit(this,t)}}),boolean:e=>({value:e,type:"boolean",_visit:function(t){return h_._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e.value);case"int64":return t.int64(e.value);case"uint":return t.uint(e.value);case"uint64":return t.uint64(e.value);case"float":return t.float(e.value);case"double":return t.double(e.value);case"string":return t.string(e.value);case"datetime":return t.datetime(e.value);case"date":return t.date(e.value);case"base64":return t.base64(e.value);case"boolean":return t.boolean(e.value);default:return t._other(e)}}};var zNi={boolean:e=>({value:e,type:"boolean",_visit:function(t){return zNi._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return zNi._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 RNi={discriminated:e=>({value:e,type:"discriminated",_visit:function(t){return RNi._visit(this,t)}}),undiscriminated:e=>({value:e,type:"undiscriminated",_visit:function(t){return RNi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e.value);case"undiscriminated":return t.undiscriminated(e.value);default:return t._other(e)}}};var $H={GenerallyAvailable:"GenerallyAvailable",Beta:"Beta",Deprecated:"Deprecated",_visit:(e,t)=>{switch(e){case $H.GenerallyAvailable:return t.generallyAvailable();case $H.Beta:return t.beta();case $H.Deprecated:return t.deprecated();default:return t._other()}}};var t7e={cursor:e=>({...e,type:"cursor",_visit:function(t){return t7e._visit(this,t)}}),offset:e=>({...e,type:"offset",_visit:function(t){return t7e._visit(this,t)}}),custom:e=>({...e,type:"custom",_visit:function(t){return t7e._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 Kmi={language:e=>({...e,type:"language",_visit:function(t){return Kmi._visit(this,t)}}),sdk:e=>({...e,type:"sdk",_visit:function(t){return Kmi._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 GH={Curl:"curl",Python:"python",Javascript:"javascript",Typescript:"typescript",Go:"go",Ruby:"ruby",Csharp:"csharp",Java:"java",Js:"js",Node:"node",Ts:"ts",Nodets:"nodets",Golang:"golang",Dotnet:"dotnet",Jvm:"jvm",_visit:(e,t)=>{switch(e){case GH.Curl:return t.curl();case GH.Python:return t.python();case GH.Javascript:return t.javascript();case GH.Typescript:return t.typescript();case GH.Go:return t.go();case GH.Ruby:return t.ruby();case GH.Csharp:return t.csharp();case GH.Java:return t.java();case GH.Js:return t.js();case GH.Node:return t.node();case GH.Ts:return t.ts();case GH.Nodets:return t.nodets();case GH.Golang:return t.golang();case GH.Dotnet:return t.dotnet();case GH.Jvm:return t.jvm();default:return t._other()}}};var yQt={unknown:e=>({value:e,type:"unknown",_visit:function(t){return yQt._visit(this,t)}}),full:e=>({...e,type:"full",_visit:function(t){return yQt._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"unknown":return t.unknown(e.value);case"full":return t.full(e);default:return t._other(e)}}};var vQt={withStreaming:e=>({...e,type:"withStreaming",_visit:function(t){return vQt._visit(this,t)}}),withoutStreaming:e=>({value:e,type:"withoutStreaming",_visit:function(t){return vQt._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"withStreaming":return t.withStreaming(e);case"withoutStreaming":return t.withoutStreaming(e.value);default:return t._other(e)}}};var QH={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD",Options:"OPTIONS",Trace:"TRACE",_visit:(e,t)=>{switch(e){case QH.Get:return t.get();case QH.Post:return t.post();case QH.Put:return t.put();case QH.Patch:return t.patch();case QH.Delete:return t.delete();case QH.Head:return t.head();case QH.Options:return t.options();case QH.Trace:return t.trace();default:return t._other()}}};var gor={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return gor._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return gor._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return gor._visit(this,t)}}),formUrlEncoded:e=>({...e,type:"formUrlEncoded",_visit:function(t){return gor._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"octetStream":return t.octetStream(e);case"multipart":return t.multipart(e);case"json":return t.json(e);case"formUrlEncoded":return t.formUrlEncoded(e);default:return t._other(e)}}};var Ymi={file:e=>({...e,type:"file",_visit:function(t){return Ymi._visit(this,t)}}),json:e=>({value:e,type:"json",_visit:function(t){return Ymi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e.value);default:return t._other(e)}}};var aK={file:e=>({...e,type:"file",_visit:function(t){return aK._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return aK._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return aK._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return aK._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return aK._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return aK._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return aK._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e);case"text":return t.text(e);case"bytes":return t.bytes(e);case"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var cv={primitive:e=>({...e,type:"primitive",_visit:function(t){return cv._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return cv._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return cv._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return cv._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return cv._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return cv._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return cv._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return cv._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return cv._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return cv._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return cv._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e);case"object":return t.object(e);case"array":return t.array(e);case"map":return t.map(e);case"optional":return t.optional(e);case"enum":return t.enum(e);case"reference":return t.reference(e);case"literal":return t.literal(e);case"oneOf":return t.oneOf(e.value);case"nullable":return t.nullable(e);case"unknown":return t.unknown(e);default:return t._other(e)}}};var jw={int:e=>({...e,type:"int",_visit:function(t){return jw._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return jw._visit(this,t)}}),uint:()=>({type:"uint",_visit:function(e){return jw._visit(this,e)}}),uint64:()=>({type:"uint64",_visit:function(e){return jw._visit(this,e)}}),float:()=>({type:"float",_visit:function(e){return jw._visit(this,e)}}),double:e=>({...e,type:"double",_visit:function(t){return jw._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return jw._visit(this,t)}}),datetime:()=>({type:"datetime",_visit:function(e){return jw._visit(this,e)}}),date:()=>({type:"date",_visit:function(e){return jw._visit(this,e)}}),base64:()=>({type:"base64",_visit:function(e){return jw._visit(this,e)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return jw._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e);case"int64":return t.int64(e);case"uint":return t.uint();case"uint64":return t.uint64();case"float":return t.float();case"double":return t.double(e);case"string":return t.string(e);case"datetime":return t.datetime();case"date":return t.date();case"base64":return t.base64();case"boolean":return t.boolean(e);default:return t._other(e)}}};var Kz={boolean:e=>({value:e,type:"boolean",_visit:function(t){return Kz._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return Kz._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 Xmi={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return Xmi._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return Xmi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e);case"undiscriminated":return t.undiscriminated(e);default:return t._other(e)}}};var nee={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return nee._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return nee._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return nee._visit(this,t)}}),formUrlEncoded:e=>({...e,type:"formUrlEncoded",_visit:function(t){return nee._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"octetStream":return t.octetStream(e);case"multipart":return t.multipart(e);case"json":return t.json(e);case"formUrlEncoded":return t.formUrlEncoded(e);default:return t._other(e)}}};var iB={file:e=>({...e,type:"file",_visit:function(t){return iB._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return iB._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return iB._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return iB._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return iB._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return iB._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return iB._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e);case"text":return t.text(e);case"bytes":return t.bytes(e);case"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var Al={primitive:e=>({...e,type:"primitive",_visit:function(t){return Al._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Al._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return Al._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return Al._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return Al._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return Al._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return Al._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return Al._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Al._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return Al._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return Al._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e);case"object":return t.object(e);case"array":return t.array(e);case"map":return t.map(e);case"optional":return t.optional(e);case"enum":return t.enum(e);case"reference":return t.reference(e);case"literal":return t.literal(e);case"oneOf":return t.oneOf(e.value);case"nullable":return t.nullable(e);case"unknown":return t.unknown(e);default:return t._other(e)}}};var aee={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return aee._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return aee._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e);case"undiscriminated":return t.undiscriminated(e);default:return t._other(e)}}};var ap={int:e=>({...e,type:"int",_visit:function(t){return ap._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return ap._visit(this,t)}}),uint:e=>({...e,type:"uint",_visit:function(t){return ap._visit(this,t)}}),uint64:e=>({...e,type:"uint64",_visit:function(t){return ap._visit(this,t)}}),float:e=>({...e,type:"float",_visit:function(t){return ap._visit(this,t)}}),double:e=>({...e,type:"double",_visit:function(t){return ap._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return ap._visit(this,t)}}),datetime:e=>({...e,type:"datetime",_visit:function(t){return ap._visit(this,t)}}),date:e=>({...e,type:"date",_visit:function(t){return ap._visit(this,t)}}),base64:e=>({...e,type:"base64",_visit:function(t){return ap._visit(this,t)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return ap._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e);case"int64":return t.int64(e);case"uint":return t.uint(e);case"uint64":return t.uint64(e);case"float":return t.float(e);case"double":return t.double(e);case"string":return t.string(e);case"datetime":return t.datetime(e);case"date":return t.date(e);case"base64":return t.base64(e);case"boolean":return t.boolean(e);default:return t._other(e)}}};var vv={};Po(vv,{AllOfPropertyConflict:()=>bKn,ArraySchema:()=>Cnu,ArraySchemaWithExample:()=>cau,Availability:()=>Siu,Base64WithExample:()=>nau,BasicSecurityScheme:()=>Miu,BearerSecurityScheme:()=>Aiu,BooleanSchema:()=>Dnu,BooleanWithExample:()=>aau,BytesResponse:()=>cKn,CasingOverrides:()=>Ciu,CommonProperty:()=>Lnu,CommonPropertyWithExample:()=>bau,CursorPagination:()=>cnu,CustomCodeSample:()=>unu,CustomCodeSampleLanguage:()=>nnu,CustomCodeSampleSdk:()=>onu,CustomPagination:()=>fnu,DateWithExample:()=>iau,DatetimeWithExample:()=>rau,DiscriminatedOneOfSchema:()=>Nnu,DiscriminatedOneOfSchemaWithExample:()=>yau,DoubleSchema:()=>wnu,DoubleWithExample:()=>eau,Encoding:()=>wiu,Endpoint:()=>dnu,EndpointExample:()=>pKn,EndpointResponseExample:()=>inu,EndpointSdkName:()=>Por,EndpointWithExample:()=>Rw_,EnumSchema:()=>kJn,EnumSchemaWithExample:()=>uau,EnumValue:()=>FNi,ErrorExample:()=>Ziu,FernExample:()=>enu,FileResponse:()=>uKn,FileSchema:()=>Hiu,FloatWithExample:()=>knu,FormUrlEncodedRequest:()=>Kiu,FullEndpointExample:()=>snu,FullExample:()=>PT,FullObjectExample:()=>Fiu,FullOneOfExample:()=>Uiu,GlobalHeader:()=>Mnu,Header:()=>UNi,HeaderExample:()=>dKn,HeaderSecurityScheme:()=>qiu,HeaderWithExample:()=>HNi,HttpEndpointServer:()=>lKn,HttpError:()=>kiu,HttpErrorWithExample:()=>Jnu,HttpMethod:()=>rKn,IdempotencyHeader:()=>Anu,Int64WithExample:()=>Ynu,IntSchema:()=>Pnu,IntWithExample:()=>Knu,JsonRequest:()=>Jiu,JsonRequestWithExample:()=>Hnu,JsonResponse:()=>sKn,JsonResponseWithExample:()=>mKn,KeyValuePair:()=>Liu,LiteralExample:()=>Niu,LiteralSchema:()=>vKn,LiteralSchemaValue:()=>qnu,LongSchema:()=>jnu,MapSchema:()=>Bnu,MapSchemaWithExample:()=>lau,MultipartRequest:()=>oKn,MultipartRequestProperty:()=>Qiu,MultipartRequestPropertyEncoding:()=>Giu,MultipartSchema:()=>$iu,NamedFullExample:()=>i7e,Namespace:()=>Biu,NamespaceId:()=>xiu,NullableSchema:()=>znu,NullableSchemaWithExample:()=>dau,OauthSecurityScheme:()=>ziu,ObjectProperty:()=>xnu,ObjectPropertyConflictInfo:()=>gKn,ObjectPropertyWithExample:()=>hau,ObjectSchema:()=>Tnu,ObjectSchemaWithExample:()=>pau,OctetStreamRequest:()=>aKn,OffsetPagination:()=>lnu,OneOfSchema:()=>Rnu,OneOfSchemaWithExample:()=>_au,OpenApiIntermediateRepresentation:()=>Iw_,OpenApiSource:()=>Oiu,OptionalSchema:()=>Inu,OptionalSchemaWithExample:()=>fau,Pagination:()=>_Kn,ParseFormUrlEncodedRequest:()=>$nu,ParseMultipartRequest:()=>Wnu,ParseOctetStreamRequest:()=>Vnu,PathParameter:()=>iKn,PathParameterExample:()=>tnu,PathParameterWithExample:()=>Unu,PrimitiveExample:()=>tKn,PrimitiveSchema:()=>WNi,PrimitiveSchemaValue:()=>Enu,PrimitiveSchemaValueWithExample:()=>oau,PrimitiveSchemaWithExample:()=>PKn,PropertyKey:()=>eKn,ProtobufEncoding:()=>jiu,ProtobufSource:()=>miu,QueryParameter:()=>nKn,QueryParameterExample:()=>fKn,QueryParameterWithExample:()=>OKn,QuerySecurityScheme:()=>Tiu,ReferencedSchema:()=>jor,Request:()=>Yiu,RequestWithExample:()=>Gnu,Response:()=>Xiu,ResponseWithExample:()=>Qnu,Schema:()=>VO,SchemaId:()=>oee,SchemaWithExample:()=>gM,Schemas:()=>mnu,SdkGroup:()=>Iiu,SdkGroupInfo:()=>Viu,SdkGroupName:()=>LNi,SecurityScheme:()=>Riu,SecuritySchemeId:()=>Eiu,Server:()=>L5a,Source:()=>Piu,StatusCode:()=>Oor,StreamingResponseExample:()=>rnu,StringSchema:()=>Snu,StringSchemaWithExample:()=>tau,SupportedSdkLanguage:()=>anu,Tag:()=>Diu,TagId:()=>uee,Tags:()=>Wiu,TextResponse:()=>VNi,Uint64WithExample:()=>Znu,UintWithExample:()=>Xnu,UnDiscriminatedOneOfSchema:()=>Fnu,UnDiscriminatedOneOfSchemaWithExample:()=>vau,UnknownSchemaWithExample:()=>sau,Webhook:()=>pnu,WebhookExampleCall:()=>yKn,WebhookHttpMethod:()=>hKn,WebhookWithExample:()=>xw_,WebsocketChannel:()=>Onu,WebsocketHandshake:()=>_nu,WebsocketHandshakeWithExample:()=>zw_,WebsocketMessageExample:()=>bnu,WebsocketMessageOrigin:()=>hnu,WebsocketMessageSchema:()=>ynu,WebsocketServer:()=>vnu,WebsocketSessionExample:()=>gnu,WithAvailability:()=>Jh,WithDescription:()=>ff,WithEncoding:()=>lue,WithInline:()=>bM,WithName:()=>k0,WithNamespace:()=>P0,WithSdkGroupName:()=>Mm,WithSdkMethodName:()=>mor,WithSource:()=>Oh,WithStatusCode:()=>r7e,WithTitle:()=>Em,commons:()=>V1c,example:()=>W1c,finalIr:()=>H1c,parseIr:()=>$1c});var V1c={};Po(V1c,{BasicSecurityScheme:()=>Miu,BearerSecurityScheme:()=>Aiu,Encoding:()=>wiu,HeaderSecurityScheme:()=>qiu,Namespace:()=>Biu,NamespaceId:()=>xiu,OauthSecurityScheme:()=>ziu,OpenApiSource:()=>Oiu,ProtobufEncoding:()=>jiu,ProtobufSource:()=>miu,QuerySecurityScheme:()=>Tiu,SchemaId:()=>oee,SdkGroup:()=>Iiu,SdkGroupName:()=>LNi,SecurityScheme:()=>Riu,SecuritySchemeId:()=>Eiu,Server:()=>L5a,Source:()=>Piu,StatusCode:()=>Oor,Tag:()=>Diu,TagId:()=>uee,WithAvailability:()=>Jh,WithDescription:()=>ff,WithEncoding:()=>lue,WithInline:()=>bM,WithName:()=>k0,WithNamespace:()=>P0,WithSdkGroupName:()=>Mm,WithSdkMethodName:()=>mor,WithSource:()=>Oh,WithStatusCode:()=>r7e,WithTitle:()=>Em});var gt={};Po(gt,{JsonError:()=>YJn,ParseError:()=>XJn,any:()=>mw_,bigint:()=>sw_,boolean:()=>Pw_,booleanLiteral:()=>Ow_,date:()=>cw_,discriminant:()=>Tw_,enum_:()=>viu,getObjectLikeUtils:()=>bQt,getObjectUtils:()=>ean,getSchemaUtils:()=>mT,isProperty:()=>NNi,lazy:()=>lw_,lazyObject:()=>vw_,list:()=>giu,number:()=>jw_,object:()=>biu,objectWithoutOptionalProperties:()=>yw_,optional:()=>N1c,property:()=>dw_,record:()=>Ew_,set:()=>Mw_,string:()=>ww_,stringLiteral:()=>gw_,transform:()=>F1c,undiscriminatedUnion:()=>qw_,union:()=>Bw_,unknown:()=>Sw_,withParsedProperties:()=>U1c});var Zj={BIGINT:"bigint",DATE:"date",ENUM:"enum",LIST:"list",STRING_LITERAL:"stringLiteral",BOOLEAN_LITERAL:"booleanLiteral",OBJECT:"object",ANY:"any",BOOLEAN:"boolean",NUMBER:"number",STRING:"string",UNKNOWN:"unknown",RECORD:"record",SET:"set",UNION:"union",UNDISCRIMINATED_UNION:"undiscriminatedUnion",OPTIONAL:"optional"};function VA(e,t){return`Expected ${t}. Received ${MxE(e)}.`}function MxE(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 KL(e){return{...e,json:uw_(e.json),parse:uw_(e.parse)}}function uw_(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(`
1959
- `)),{ok:!0,value:t}):i}}function yiu(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var YJn=class e extends Error{errors;constructor(t){super(t.map(yiu).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var XJn=class e extends Error{errors;constructor(t){super(t.map(yiu).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function mT(e){return{optional:()=>N1c(e),transform:t=>F1c(e,t),parseOrThrow:(t,r)=>{let i=e.parse(t,r);if(i.ok)return i.value;throw new XJn(i.errors)},jsonOrThrow:(t,r)=>{let i=e.json(t,r);if(i.ok)return i.value;throw new YJn(i.errors)}}}function N1c(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:()=>Zj.OPTIONAL};return{...t,...mT(t)}}function F1c(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,...mT(r)}}function sw_(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:VA(t,"string")}]}:{ok:!0,value:BigInt(t)},json:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t=="bigint"?{ok:!0,value:t.toString()}:{ok:!1,errors:[{path:r,message:VA(t,"bigint")}]},getType:()=>Zj.BIGINT};return{...KL(e),...mT(e)}}var AxE=/^([+-]?\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 cw_(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:VA(t,"string")}]}:AxE.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:VA(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:VA(t,"Date object")}]},getType:()=>Zj.DATE};return{...KL(e),...mT(e)}}function oK(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{...KL(r),...mT(r)}}}function viu(e){let t=new Set(e);return oK(Zj.ENUM,(i,{allowUnrecognizedEnumValues:n,breadcrumbsPrefix:a=[]}={})=>typeof i!="string"?{ok:!1,errors:[{path:a,message:VA(i,"string")}]}:!t.has(i)&&!n?{ok:!1,errors:[{path:a,message:VA(i,"enum")}]}:{ok:!0,value:i})()}function lw_(e){let t=L1c(e);return{...t,...mT(t)}}function L1c(e){return{parse:(t,r)=>ZJn(e).parse(t,r),json:(t,r)=>ZJn(e).json(t,r),getType:()=>ZJn(e).getType()}}function ZJn(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function x5a(e){return Object.entries(e)}function N5a(e,t){let r=new Set(t);return Object.entries(e).reduce((i,[n,a])=>(r.has(n)&&(i[n]=a),i),{})}function xNi(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 F5a(e){return Object.keys(e)}function fw_(e,t){let r=[],i=[];for(let n of e)t(n)?r.push(n):i.push(n);return[r,i]}function bQt(e){return{withParsedProperties:t=>U1c(e,t)}}function U1c(e,t){let r={parse:(i,n)=>{let a=e.parse(i,n);if(!a.ok)return a;let u=Object.entries(t).reduce((l,[d,s])=>({...l,[d]:typeof s=="function"?s(a.value):s}),{});return{ok:!0,value:{...a.value,...u}}},json:(i,n)=>{if(!xNi(i))return{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:VA(i,"object")}]};let a=new Set(Object.keys(t)),u=N5a(i,Object.keys(i).filter(l=>!a.has(l)));return e.json(u,n)},getType:()=>e.getType()};return{...r,...mT(r),...bQt(r)}}function dw_(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function NNi(e){return e.isProperty}function biu(e){let t={_getRawProperties:()=>Object.entries(e).map(([r,i])=>NNi(i)?i.rawKey:r),_getParsedProperties:()=>F5a(e),parse:(r,i)=>{let n={},a=[];for(let[u,l]of x5a(e)){let d=NNi(l)?l.rawKey:u,s=NNi(l)?l.valueSchema:l,o={rawKey:d,parsedKey:u,valueSchema:s};n[d]=o,hw_(s)&&a.push(d)}return pw_({value:r,requiredKeys:a,getProperty:u=>{let l=n[u];if(l!=null)return{transformedKey:l.parsedKey,transform:d=>l.valueSchema.parse(d,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],u]})}},unrecognizedObjectKeys:i?.unrecognizedObjectKeys,skipValidation:i?.skipValidation,breadcrumbsPrefix:i?.breadcrumbsPrefix,omitUndefined:i?.omitUndefined})},json:(r,i)=>{let n=[];for(let[a,u]of x5a(e)){let l=NNi(u)?u.valueSchema:u;hw_(l)&&n.push(a)}return pw_({value:r,requiredKeys:n,getProperty:a=>{let u=e[a];if(u!=null)return NNi(u)?{transformedKey:u.rawKey,transform:l=>u.valueSchema.json(l,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],a]})}:{transformedKey:a,transform:l=>u.json(l,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],a]})}},unrecognizedObjectKeys:i?.unrecognizedObjectKeys,skipValidation:i?.skipValidation,breadcrumbsPrefix:i?.breadcrumbsPrefix,omitUndefined:i?.omitUndefined})},getType:()=>Zj.OBJECT};return{...KL(t),...mT(t),...bQt(t),...ean(t)}}function pw_({value:e,requiredKeys:t,getProperty:r,unrecognizedObjectKeys:i="fail",skipValidation:n=!1,breadcrumbsPrefix:a=[]}){if(!xNi(e))return{ok:!1,errors:[{path:a,message:VA(e,"object")}]};let u=new Set(t),l=[],d={};for(let[s,o]of Object.entries(e)){let c=r(s);if(c!=null){u.delete(s);let b=c.transform(o);b.ok?d[c.transformedKey]=b.value:(d[s]=o,l.push(...b.errors))}else switch(i){case"fail":l.push({path:[...a,s],message:`Unexpected key "${s}"`});break;case"strip":break;case"passthrough":d[s]=o;break}}return l.push(...t.filter(s=>u.has(s)).map(s=>({path:a,message:`Missing required key "${s}"`}))),l.length===0||n?{ok:!0,value:d}:{ok:!1,errors:l}}function ean(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(i,n)=>_w_({extensionKeys:t._getRawProperties(),value:i,transformBase:a=>e.parse(a,n),transformExtension:a=>t.parse(a,n)}),json:(i,n)=>_w_({extensionKeys:t._getParsedProperties(),value:i,transformBase:a=>e.json(a,n),transformExtension:a=>t.json(a,n)}),getType:()=>Zj.OBJECT};return{...r,...mT(r),...bQt(r),...ean(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:()=>Zj.OBJECT};return{...t,...mT(t),...bQt(t),...ean(t)}}}}function _w_({extensionKeys:e,value:t,transformBase:r,transformExtension:i}){let n=new Set(e),[a,u]=fw_(F5a(t),s=>n.has(s)),l=r(N5a(t,u)),d=i(N5a(t,a));return l.ok&&d.ok?{ok:!0,value:{...l.value,...d.value}}:{ok:!1,errors:[...l.ok?[]:l.errors,...d.ok?[]:d.errors]}}function hw_(e){return!qxE(e)}function qxE(e){switch(e.getType()){case Zj.ANY:case Zj.UNKNOWN:case Zj.OPTIONAL:return!0;default:return!1}}function yw_(e){return biu(e)}function vw_(e){let t={...L1c(e),_getRawProperties:()=>ZJn(e)._getRawProperties(),_getParsedProperties:()=>ZJn(e)._getParsedProperties()};return{...t,...mT(t),...bQt(t),...ean(t)}}function giu(e){let t={parse:(r,i)=>bw_(r,(n,a)=>e.parse(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),json:(r,i)=>bw_(r,(n,a)=>e.json(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),getType:()=>Zj.LIST};return{...KL(t),...mT(t)}}function bw_(e,t){return Array.isArray(e)?e.map((i,n)=>t(i,n)).reduce((i,n)=>{if(i.ok&&n.ok)return{ok:!0,value:[...i.value,n.value]};let a=[];return i.ok||a.push(...i.errors),n.ok||a.push(...n.errors),{ok:!1,errors:a}},{ok:!0,value:[]}):{ok:!1,errors:[{message:VA(e,"list"),path:[]}]}}function gw_(e){return oK(Zj.STRING_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:VA(r,`"${e}"`)}]})()}function Ow_(e){return oK(Zj.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:VA(r,`${e.toString()}`)}]})()}var mw_=oK(Zj.ANY,e=>({ok:!0,value:e}));var Pw_=oK(Zj.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:VA(e,"boolean")}]});var jw_=oK(Zj.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:VA(e,"number")}]});var ww_=oK(Zj.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:VA(e,"string")}]});var Sw_=oK(Zj.UNKNOWN,e=>({ok:!0,value:e}));function Ew_(e,t){let r={parse:(i,n)=>Dw_({value:i,isKeyNumeric:e.getType()===Zj.NUMBER,transformKey:a=>e.parse(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,u)=>t.parse(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${u}`]}),breadcrumbsPrefix:n?.breadcrumbsPrefix}),json:(i,n)=>Dw_({value:i,isKeyNumeric:e.getType()===Zj.NUMBER,transformKey:a=>e.json(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,u)=>t.json(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${u}`]}),breadcrumbsPrefix:n?.breadcrumbsPrefix}),getType:()=>Zj.RECORD};return{...KL(r),...mT(r)}}function Dw_({value:e,isKeyNumeric:t,transformKey:r,transformValue:i,breadcrumbsPrefix:n=[]}){return xNi(e)?x5a(e).reduce((a,[u,l])=>{if(l==null)return a;let d=a,s=u;if(t){let g=u.length>0?Number(u):NaN;isNaN(g)||(s=g)}let o=r(s),c=i(l,s);if(d.ok&&o.ok&&c.ok)return{ok:!0,value:{...d.value,[o.value]:c.value}};let b=[];return d.ok||b.push(...d.errors),o.ok||b.push(...o.errors),c.ok||b.push(...c.errors),{ok:!1,errors:b}},{ok:!0,value:{}}):{ok:!1,errors:[{path:n,message:VA(e,"object")}]}}function Mw_(e){let t=giu(e),r={parse:(i,n)=>{let a=t.parse(i,n);return a.ok?{ok:!0,value:new Set(a.value)}:a},json:(i,n)=>i instanceof Set?t.json([...i],n):{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:VA(i,"Set")}]},getType:()=>Zj.SET};return{...KL(r),...mT(r)}}function qw_(e){let t={parse:(r,i)=>Aw_((n,a)=>n.parse(r,a),e,i),json:(r,i)=>Aw_((n,a)=>n.json(r,a),e,i),getType:()=>Zj.UNDISCRIMINATED_UNION};return{...KL(t),...mT(t)}}function Aw_(e,t,r){let i=[];for(let[n,a]of t.entries()){let u=e(a,{...r,skipValidation:!1});if(u.ok)return u;for(let l of u.errors)i.push({path:l.path,message:`[Variant ${n}] ${l.message}`})}return{ok:!1,errors:i}}function Tw_(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}function Bw_(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,i=typeof e=="string"?e:e.parsedDiscriminant,n=viu(F5a(t)),a={parse:(u,l)=>Cw_({value:u,discriminant:r,transformedDiscriminant:i,transformDiscriminantValue:d=>n.parse(d,{allowUnrecognizedEnumValues:l?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...l?.breadcrumbsPrefix??[],r]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:l?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,s)=>s.parse(d,l),breadcrumbsPrefix:l?.breadcrumbsPrefix}),json:(u,l)=>Cw_({value:u,discriminant:i,transformedDiscriminant:r,transformDiscriminantValue:d=>n.json(d,{allowUnrecognizedEnumValues:l?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...l?.breadcrumbsPrefix??[],i]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:l?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,s)=>s.json(d,l),breadcrumbsPrefix:l?.breadcrumbsPrefix}),getType:()=>Zj.UNION};return{...KL(a),...mT(a),...bQt(a)}}function Cw_({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:i,getAdditionalPropertiesSchema:n,allowUnrecognizedUnionMembers:a=!1,transformAdditionalProperties:u,breadcrumbsPrefix:l=[]}){if(!xNi(e))return{ok:!1,errors:[{path:l,message:VA(e,"object")}]};let{[t]:d,...s}=e;if(d==null)return{ok:!1,errors:[{path:l,message:`Missing discriminant ("${t}")`}]};let o=i(d);if(!o.ok)return{ok:!1,errors:o.errors};let c=n(o.value);if(c==null)return a?{ok:!0,value:{[r]:o.value,...s}}:{ok:!1,errors:[{path:[...l,t],message:"Unexpected discriminant value"}]};let b=u(s,c);return b.ok?{ok:!0,value:{[r]:d,...b.value}}:b}var Em=gt.objectWithoutOptionalProperties({title:gt.string().optional()});var Oiu=gt.objectWithoutOptionalProperties({file:gt.string()});var miu=gt.objectWithoutOptionalProperties({file:gt.string()});var Piu=gt.union("type",{openapi:Oiu,protobuf:miu}).transform({transform:e=>{switch(e.type){case"openapi":return nK.openapi(e);case"protobuf":return nK.protobuf(e);default:return e}},untransform:({_visit:e,...t})=>t});var Oh=gt.objectWithoutOptionalProperties({source:Piu.optional()});var jiu=gt.objectWithoutOptionalProperties({typeName:gt.string()});var wiu=gt.union("type",{protobuf:jiu}).transform({transform:e=>{switch(e.type){case"protobuf":return KJn.protobuf(e);default:return e}},untransform:({_visit:e,...t})=>t});var lue=gt.objectWithoutOptionalProperties({encoding:wiu.optional()});var ff=gt.objectWithoutOptionalProperties({description:gt.string().optional()});var Siu=gt.enum_(["GenerallyAvailable","Beta","Deprecated"]);var Jh=gt.objectWithoutOptionalProperties({availability:Siu.optional()});var Oor=gt.number();var r7e=gt.objectWithoutOptionalProperties({statusCode:Oor.optional()});var k0=gt.objectWithoutOptionalProperties({nameOverride:gt.string().optional(),generatedName:gt.string()});var bM=gt.objectWithoutOptionalProperties({inline:gt.boolean().optional()});var oee=gt.string();var uee=gt.string();var Diu=gt.objectWithoutOptionalProperties({id:uee}).extend(ff);var Eiu=gt.string();var Miu=gt.objectWithoutOptionalProperties({usernameVariableName:gt.string().optional(),usernameEnvVar:gt.string().optional(),passwordVariableName:gt.string().optional(),passwordEnvVar:gt.string().optional()});var Aiu=gt.objectWithoutOptionalProperties({tokenVariableName:gt.string().optional(),tokenEnvVar:gt.string().optional()});var qiu=gt.objectWithoutOptionalProperties({headerName:gt.string(),prefix:gt.string().optional(),headerVariableName:gt.string().optional(),headerEnvVar:gt.string().optional()});var Tiu=gt.objectWithoutOptionalProperties({queryParameterName:gt.string()});var Ciu=gt.objectWithoutOptionalProperties({snake:gt.string().optional(),camel:gt.string().optional(),screamingSnake:gt.string().optional(),pascal:gt.string().optional()});var FNi=gt.objectWithoutOptionalProperties({nameOverride:gt.string().optional(),generatedName:gt.string(),value:gt.string(),casing:Ciu.optional()}).extend(ff).extend(Jh);var Biu=gt.objectWithoutOptionalProperties({type:gt.stringLiteral("namespace"),name:gt.string()});var Iiu=gt.undiscriminatedUnion([gt.string(),Biu]);var LNi=gt.list(Iiu);var Mm=gt.objectWithoutOptionalProperties({groupName:LNi.optional()});var P0=gt.objectWithoutOptionalProperties({namespace:gt.string().optional()});var kJn=gt.objectWithoutOptionalProperties({default:FNi.optional(),values:gt.list(FNi)}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(Oh).extend(Em).extend(bM);var ziu=gt.objectWithoutOptionalProperties({scopesEnum:kJn.optional()});var Riu=gt.union("type",{basic:Miu,bearer:Aiu,header:qiu,query:Tiu,oauth:ziu}).transform({transform:e=>{switch(e.type){case"basic":return JL.basic(e);case"bearer":return JL.bearer(e);case"header":return JL.header(e);case"query":return JL.query(e);case"oauth":return JL.oauth(e);default:return e}},untransform:({_visit:e,...t})=>t});var L5a=gt.objectWithoutOptionalProperties({name:gt.string().optional(),url:gt.string(),audiences:gt.list(gt.string()).optional()}).extend(ff);var xiu=gt.string();var mor=gt.objectWithoutOptionalProperties({sdkMethodName:gt.string().optional()});var W1c={};Po(W1c,{FullExample:()=>PT,FullObjectExample:()=>Fiu,FullOneOfExample:()=>Uiu,KeyValuePair:()=>Liu,LiteralExample:()=>Niu,PrimitiveExample:()=>tKn,PropertyKey:()=>eKn});var eKn=gt.string();var tKn=gt.union("type",{int:gt.object({value:gt.number()}),int64:gt.object({value:gt.number()}),uint:gt.object({value:gt.number()}),uint64:gt.object({value:gt.number()}),float:gt.object({value:gt.number()}),double:gt.object({value:gt.number()}),string:gt.object({value:gt.string()}),datetime:gt.object({value:gt.string()}),date:gt.object({value:gt.string()}),base64:gt.object({value:gt.string()}),boolean:gt.object({value:gt.boolean()})}).transform({transform:e=>{switch(e.type){case"int":return h_.int(e.value);case"int64":return h_.int64(e.value);case"uint":return h_.uint(e.value);case"uint64":return h_.uint64(e.value);case"float":return h_.float(e.value);case"double":return h_.double(e.value);case"string":return h_.string(e.value);case"datetime":return h_.datetime(e.value);case"date":return h_.date(e.value);case"base64":return h_.base64(e.value);case"boolean":return h_.boolean(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var Niu=gt.union("type",{boolean:gt.object({value:gt.boolean()}),string:gt.object({value:gt.string()})}).transform({transform:e=>{switch(e.type){case"boolean":return zNi.boolean(e.value);case"string":return zNi.string(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var PT=gt.union("type",{primitive:gt.object({value:tKn}),object:gt.lazyObject(()=>Fiu),array:gt.object({value:gt.list(gt.lazy(()=>PT))}),map:gt.object({value:gt.list(gt.lazyObject(()=>Liu))}),enum:gt.object({value:gt.string()}),literal:gt.object({value:Niu}),oneOf:gt.object({value:gt.lazy(()=>Uiu)}),unknown:gt.object({value:gt.lazy(()=>PT)})}).transform({transform:e=>{switch(e.type){case"primitive":return xg.primitive(e.value);case"object":return xg.object(e);case"array":return xg.array(e.value);case"map":return xg.map(e.value);case"enum":return xg.enum(e.value);case"literal":return xg.literal(e.value);case"oneOf":return xg.oneOf(e.value);case"unknown":return xg.unknown(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var Fiu=gt.objectWithoutOptionalProperties({properties:gt.record(eKn,gt.lazy(()=>PT))});var Liu=gt.objectWithoutOptionalProperties({key:tKn,value:gt.lazy(()=>PT)});var Uiu=gt.union("type",{discriminated:gt.object({value:gt.record(eKn,gt.lazy(()=>PT))}),undiscriminated:gt.object({value:gt.lazy(()=>PT)})}).transform({transform:e=>{switch(e.type){case"discriminated":return RNi.discriminated(e.value);case"undiscriminated":return RNi.undiscriminated(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var H1c={};Po(H1c,{AllOfPropertyConflict:()=>bKn,ArraySchema:()=>Cnu,Availability:()=>Siu,BooleanSchema:()=>Dnu,BytesResponse:()=>cKn,CasingOverrides:()=>Ciu,CommonProperty:()=>Lnu,CursorPagination:()=>cnu,CustomCodeSample:()=>unu,CustomCodeSampleLanguage:()=>nnu,CustomCodeSampleSdk:()=>onu,CustomPagination:()=>fnu,DiscriminatedOneOfSchema:()=>Nnu,DoubleSchema:()=>wnu,Endpoint:()=>dnu,EndpointExample:()=>pKn,EndpointResponseExample:()=>inu,EndpointSdkName:()=>Por,EnumSchema:()=>kJn,EnumValue:()=>FNi,ErrorExample:()=>Ziu,FernExample:()=>enu,FileResponse:()=>uKn,FileSchema:()=>Hiu,FormUrlEncodedRequest:()=>Kiu,FullEndpointExample:()=>snu,GlobalHeader:()=>Mnu,Header:()=>UNi,HeaderExample:()=>dKn,HttpEndpointServer:()=>lKn,HttpError:()=>kiu,HttpMethod:()=>rKn,IdempotencyHeader:()=>Anu,IntSchema:()=>Pnu,JsonRequest:()=>Jiu,JsonResponse:()=>sKn,LiteralSchema:()=>vKn,LiteralSchemaValue:()=>qnu,LongSchema:()=>jnu,MapSchema:()=>Bnu,MultipartRequest:()=>oKn,MultipartRequestProperty:()=>Qiu,MultipartRequestPropertyEncoding:()=>Giu,MultipartSchema:()=>$iu,NullableSchema:()=>znu,ObjectProperty:()=>xnu,ObjectPropertyConflictInfo:()=>gKn,ObjectSchema:()=>Tnu,OctetStreamRequest:()=>aKn,OffsetPagination:()=>lnu,OneOfSchema:()=>Rnu,OpenApiIntermediateRepresentation:()=>Iw_,OptionalSchema:()=>Inu,Pagination:()=>_Kn,PathParameter:()=>iKn,PathParameterExample:()=>tnu,PrimitiveSchema:()=>WNi,PrimitiveSchemaValue:()=>Enu,QueryParameter:()=>nKn,QueryParameterExample:()=>fKn,ReferencedSchema:()=>jor,Request:()=>Yiu,Response:()=>Xiu,Schema:()=>VO,Schemas:()=>mnu,SdkGroupInfo:()=>Viu,StreamingResponseExample:()=>rnu,StringSchema:()=>Snu,SupportedSdkLanguage:()=>anu,Tags:()=>Wiu,TextResponse:()=>VNi,UnDiscriminatedOneOfSchema:()=>Fnu,Webhook:()=>pnu,WebhookExampleCall:()=>yKn,WebhookHttpMethod:()=>hKn,WebsocketChannel:()=>Onu,WebsocketHandshake:()=>_nu,WebsocketMessageExample:()=>bnu,WebsocketMessageOrigin:()=>hnu,WebsocketMessageSchema:()=>ynu,WebsocketServer:()=>vnu,WebsocketSessionExample:()=>gnu});var Viu=gt.objectWithoutOptionalProperties({summary:gt.string().optional(),description:gt.string().optional()});var Wiu=gt.objectWithoutOptionalProperties({tagsById:gt.record(uee,Diu),orderedTagIds:gt.list(uee).optional()});var rKn=gt.enum_(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS","TRACE"]);var iKn=gt.objectWithoutOptionalProperties({name:gt.string(),schema:gt.lazy(()=>VO),variableReference:gt.string().optional(),parameterNameOverride:gt.string().optional()}).extend(ff).extend(Jh).extend(Oh);var nKn=gt.objectWithoutOptionalProperties({name:gt.string(),schema:gt.lazy(()=>VO),parameterNameOverride:gt.string().optional()}).extend(ff).extend(Jh).extend(Oh);var UNi=gt.objectWithoutOptionalProperties({name:gt.string(),schema:gt.lazy(()=>VO),env:gt.string().optional(),parameterNameOverride:gt.string().optional()}).extend(ff).extend(Jh).extend(Oh);var Por=gt.objectWithoutOptionalProperties({groupName:LNi,methodName:gt.string()});var aKn=gt.objectWithoutOptionalProperties({contentType:gt.string().optional()}).extend(ff).extend(Oh);var Hiu=gt.objectWithoutOptionalProperties({isOptional:gt.boolean(),isArray:gt.boolean()}).extend(ff);var $iu=gt.union("type",{file:Hiu,json:gt.object({value:gt.lazy(()=>VO)})}).transform({transform:e=>{switch(e.type){case"file":return Ymi.file(e);case"json":return Ymi.json(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var Giu=gt.enum_(["json","form"]);var Qiu=gt.objectWithoutOptionalProperties({key:gt.string(),schema:$iu,contentType:gt.string().optional(),exploded:gt.boolean().optional(),encoding:Giu.optional()}).extend(ff);var oKn=gt.objectWithoutOptionalProperties({name:gt.string().optional(),properties:gt.list(Qiu)}).extend(ff).extend(Oh);var Jiu=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>VO),contentType:gt.string().optional(),additionalProperties:gt.boolean()}).extend(ff).extend(Oh);var Kiu=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>VO),contentType:gt.string().optional(),additionalProperties:gt.boolean()}).extend(ff).extend(Oh);var Yiu=gt.union("type",{octetStream:aKn,multipart:oKn,json:Jiu,formUrlEncoded:Kiu}).transform({transform:e=>{switch(e.type){case"octetStream":return gor.octetStream(e);case"multipart":return gor.multipart(e);case"json":return gor.json(e);case"formUrlEncoded":return gor.formUrlEncoded(e);default:return e}},untransform:({_visit:e,...t})=>t});var uKn=gt.objectWithoutOptionalProperties({}).extend(ff).extend(Oh).extend(r7e);var sKn=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>VO),responseProperty:gt.string().optional()}).extend(ff).extend(Oh).extend(r7e);var VNi=gt.objectWithoutOptionalProperties({}).extend(ff).extend(Oh).extend(r7e);var cKn=gt.objectWithoutOptionalProperties({}).extend(ff).extend(Oh).extend(r7e);var Xiu=gt.union("type",{file:uKn,json:sKn,text:VNi,bytes:cKn,streamingSse:sKn,streamingText:VNi,streamingJson:sKn}).transform({transform:e=>{switch(e.type){case"file":return aK.file(e);case"json":return aK.json(e);case"text":return aK.text(e);case"bytes":return aK.bytes(e);case"streamingSse":return aK.streamingSse(e);case"streamingText":return aK.streamingText(e);case"streamingJson":return aK.streamingJson(e);default:return e}},untransform:({_visit:e,...t})=>t});var Ziu=gt.objectWithoutOptionalProperties({name:gt.string().optional(),description:gt.string().optional(),example:gt.lazy(()=>PT)});var kiu=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>VO).optional(),examples:gt.list(Ziu).optional()}).extend(ff).extend(k0).extend(Oh);var lKn=gt.objectWithoutOptionalProperties({name:gt.string().optional(),url:gt.string().optional(),audiences:gt.list(gt.string()).optional()});var enu=gt.unknown();var tnu=gt.objectWithoutOptionalProperties({name:gt.string(),parameterNameOverride:gt.string().optional(),value:gt.lazy(()=>PT)});var fKn=gt.objectWithoutOptionalProperties({name:gt.string(),value:gt.lazy(()=>PT)});var dKn=gt.objectWithoutOptionalProperties({name:gt.string(),value:gt.lazy(()=>PT)});var rnu=gt.objectWithoutOptionalProperties({sse:gt.boolean(),events:gt.list(gt.lazy(()=>PT))});var inu=gt.union("type",{withStreaming:rnu,withoutStreaming:gt.object({value:gt.lazy(()=>PT)})}).transform({transform:e=>{switch(e.type){case"withStreaming":return vQt.withStreaming(e);case"withoutStreaming":return vQt.withoutStreaming(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var nnu=gt.objectWithoutOptionalProperties({name:gt.string().optional(),language:gt.string(),code:gt.string(),install:gt.string().optional()}).extend(ff);var anu=gt.enum_(["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm"]);var onu=gt.objectWithoutOptionalProperties({name:gt.string().optional(),sdk:anu,code:gt.string()}).extend(ff);var unu=gt.union("type",{language:nnu,sdk:onu}).transform({transform:e=>{switch(e.type){case"language":return Kmi.language(e);case"sdk":return Kmi.sdk(e);default:return e}},untransform:({_visit:e,...t})=>t});var snu=gt.objectWithoutOptionalProperties({name:gt.string().optional(),pathParameters:gt.list(tnu).optional(),queryParameters:gt.list(fKn).optional(),headers:gt.list(dKn).optional(),request:gt.lazy(()=>PT).optional(),response:inu.optional(),codeSamples:gt.list(unu)}).extend(ff);var pKn=gt.union("type",{unknown:gt.object({value:enu}),full:snu}).transform({transform:e=>{switch(e.type){case"unknown":return yQt.unknown(e.value);case"full":return yQt.full(e);default:return e}},untransform:({_visit:e,...t})=>t});var cnu=gt.objectWithoutOptionalProperties({cursor:gt.string(),nextCursor:gt.property("next_cursor",gt.string()),results:gt.string()});var lnu=gt.objectWithoutOptionalProperties({offset:gt.string(),results:gt.string(),step:gt.string().optional(),hasNextPage:gt.string().optional()});var fnu=gt.objectWithoutOptionalProperties({results:gt.string()});var _Kn=gt.union("type",{cursor:cnu,offset:lnu,custom:fnu}).transform({transform:e=>{switch(e.type){case"cursor":return t7e.cursor(e);case"offset":return t7e.offset(e);case"custom":return t7e.custom(e);default:return e}},untransform:({_visit:e,...t})=>t});var dnu=gt.objectWithoutOptionalProperties({authed:gt.boolean(),internal:gt.boolean().optional(),idempotent:gt.boolean().optional(),method:rKn,audiences:gt.list(gt.string()),path:gt.string(),summary:gt.string().optional(),operationId:gt.string().optional(),tags:gt.list(uee),pathParameters:gt.list(iKn),queryParameters:gt.list(nKn),headers:gt.list(UNi),sdkName:Por.optional(),generatedRequestName:gt.string(),requestNameOverride:gt.string().optional(),request:Yiu.optional(),response:Xiu.optional(),errors:gt.record(Oor,kiu),servers:gt.list(lKn),examples:gt.list(pKn),pagination:_Kn.optional()}).extend(ff).extend(Jh).extend(Oh).extend(P0);var hKn=gt.enum_(["GET","POST"]);var yKn=gt.objectWithoutOptionalProperties({name:gt.string().optional(),payload:gt.lazy(()=>PT)}).extend(ff);var pnu=gt.objectWithoutOptionalProperties({audiences:gt.list(gt.string()),sdkName:Por.optional(),method:hKn,summary:gt.string().optional(),operationId:gt.string(),tags:gt.list(uee),headers:gt.list(UNi),generatedPayloadName:gt.string(),payload:gt.lazy(()=>VO),examples:gt.list(yKn)}).extend(ff).extend(Oh).extend(P0);var _nu=gt.objectWithoutOptionalProperties({queryParameters:gt.list(nKn),headers:gt.list(UNi),pathParameters:gt.list(iKn)});var hnu=gt.enum_(["client","server"]);var ynu=gt.objectWithoutOptionalProperties({name:gt.string(),origin:hnu,body:gt.lazy(()=>VO)});var vnu=gt.objectWithoutOptionalProperties({name:gt.string(),url:gt.string()});var bnu=gt.objectWithoutOptionalProperties({messageType:gt.string(),payload:gt.lazy(()=>PT)}).extend(ff);var gnu=gt.objectWithoutOptionalProperties({name:gt.string().optional(),queryParameters:gt.list(fKn).optional(),headers:gt.list(dKn).optional(),messages:gt.list(bnu)}).extend(ff);var Onu=gt.objectWithoutOptionalProperties({audiences:gt.list(gt.string()),path:gt.string(),groupName:LNi,summary:gt.string().optional(),handshake:_nu,messages:gt.list(ynu),servers:gt.list(vnu),examples:gt.list(gnu)}).extend(ff).extend(Oh);var mnu=gt.objectWithoutOptionalProperties({rootSchemas:gt.record(oee,gt.lazy(()=>VO)),namespacedSchemas:gt.record(xiu,gt.record(oee,gt.lazy(()=>VO)))});var Pnu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),minimum:gt.number().optional(),maximum:gt.number().optional(),exclusiveMinimum:gt.boolean().optional(),exclusiveMaximum:gt.boolean().optional(),multipleOf:gt.number().optional()});var jnu=gt.objectWithoutOptionalProperties({default:gt.number().optional()});var wnu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),minimum:gt.number().optional(),maximum:gt.number().optional(),exclusiveMinimum:gt.boolean().optional(),exclusiveMaximum:gt.boolean().optional(),multipleOf:gt.number().optional()});var Snu=gt.objectWithoutOptionalProperties({default:gt.string().optional(),pattern:gt.string().optional(),format:gt.string().optional(),minLength:gt.number().optional(),maxLength:gt.number().optional()});var Dnu=gt.objectWithoutOptionalProperties({default:gt.boolean().optional()});var Enu=gt.union("type",{int:Pnu,int64:jnu,uint:gt.object({}),uint64:gt.object({}),float:gt.object({}),double:wnu,string:Snu,datetime:gt.object({}),date:gt.object({}),base64:gt.object({}),boolean:Dnu}).transform({transform:e=>{switch(e.type){case"int":return jw.int(e);case"int64":return jw.int64(e);case"uint":return jw.uint();case"uint64":return jw.uint64();case"float":return jw.float();case"double":return jw.double(e);case"string":return jw.string(e);case"datetime":return jw.datetime();case"date":return jw.date();case"base64":return jw.base64();case"boolean":return jw.boolean(e);default:return e}},untransform:({_visit:e,...t})=>t});var WNi=gt.objectWithoutOptionalProperties({schema:Enu}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(Em);var Mnu=gt.objectWithoutOptionalProperties({header:gt.string(),name:gt.string().optional(),optional:gt.boolean().optional(),env:gt.string().optional(),schema:gt.lazy(()=>VO).optional()});var Anu=gt.objectWithoutOptionalProperties({header:gt.string(),name:gt.string().optional(),env:gt.string().optional(),schema:gt.lazy(()=>VO).optional()});var Iw_=gt.objectWithoutOptionalProperties({apiVersion:gt.unknown().optional(),title:gt.string().optional(),description:gt.string().optional(),basePath:gt.string().optional(),servers:gt.list(L5a),websocketServers:gt.list(L5a),groups:gt.record(gt.string(),Viu),tags:Wiu,hasEndpointsMarkedInternal:gt.boolean(),endpoints:gt.list(dnu),webhooks:gt.list(pnu),channels:gt.record(gt.string(),Onu),groupedSchemas:mnu,variables:gt.record(gt.string(),WNi),nonRequestReferencedSchemas:gt.set(oee),securitySchemes:gt.record(Eiu,Riu),globalHeaders:gt.list(Mnu).optional(),idempotencyHeaders:gt.list(Anu).optional()});var jor=gt.objectWithoutOptionalProperties({schema:oee}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(Oh).extend(Em);var qnu=gt.union("type",{boolean:gt.object({value:gt.boolean()}),string:gt.object({value:gt.string()})}).transform({transform:e=>{switch(e.type){case"boolean":return Kz.boolean(e.value);case"string":return Kz.string(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var vKn=gt.objectWithoutOptionalProperties({value:qnu}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(Em);var VO=gt.union("type",{primitive:WNi,object:gt.lazyObject(()=>Tnu),array:gt.lazyObject(()=>Cnu),map:gt.lazyObject(()=>Bnu),optional:gt.lazyObject(()=>Inu),enum:kJn,reference:jor,literal:vKn,oneOf:gt.object({value:gt.lazy(()=>Rnu)}),nullable:gt.lazyObject(()=>znu),unknown:k0}).transform({transform:e=>{switch(e.type){case"primitive":return cv.primitive(e);case"object":return cv.object(e);case"array":return cv.array(e);case"map":return cv.map(e);case"optional":return cv.optional(e);case"enum":return cv.enum(e);case"reference":return cv.reference(e);case"literal":return cv.literal(e);case"oneOf":return cv.oneOf(e.value);case"nullable":return cv.nullable(e);case"unknown":return cv.unknown(e);default:return e}},untransform:({_visit:e,...t})=>t});var bKn=gt.objectWithoutOptionalProperties({propertyKey:gt.string(),allOfSchemaIds:gt.list(oee),conflictingTypeSignatures:gt.boolean()});var Tnu=gt.objectWithoutOptionalProperties({allOf:gt.list(jor),properties:gt.list(gt.lazyObject(()=>xnu)),allOfPropertyConflicts:gt.list(bKn),additionalProperties:gt.boolean()}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(Oh).extend(Em).extend(bM);var gKn=gt.objectWithoutOptionalProperties({differentSchema:gt.boolean()});var xnu=gt.objectWithoutOptionalProperties({key:gt.string(),schema:gt.lazy(()=>VO),readonly:gt.boolean().optional(),writeonly:gt.boolean().optional(),conflict:gt.record(oee,gKn),generatedName:gt.string(),nameOverride:gt.string().optional(),audiences:gt.list(gt.string())}).extend(Jh);var Cnu=gt.objectWithoutOptionalProperties({value:gt.lazy(()=>VO)}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(Em).extend(bM);var Bnu=gt.objectWithoutOptionalProperties({key:WNi,value:gt.lazy(()=>VO)}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(lue).extend(Em).extend(bM);var Inu=gt.objectWithoutOptionalProperties({value:gt.lazy(()=>VO)}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(Em).extend(bM);var znu=gt.objectWithoutOptionalProperties({value:gt.lazy(()=>VO)}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(Em).extend(bM);var Rnu=gt.union("type",{discriminated:gt.lazyObject(()=>Nnu),undiscriminated:gt.lazyObject(()=>Fnu)}).transform({transform:e=>{switch(e.type){case"discriminated":return Xmi.discriminated(e);case"undiscriminated":return Xmi.undiscriminated(e);default:return e}},untransform:({_visit:e,...t})=>t});var Nnu=gt.objectWithoutOptionalProperties({discriminantProperty:gt.string(),commonProperties:gt.list(gt.lazyObject(()=>Lnu)),schemas:gt.record(gt.string(),gt.lazy(()=>VO))}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(lue).extend(Oh).extend(Em).extend(bM);var Lnu=gt.objectWithoutOptionalProperties({key:gt.string(),schema:gt.lazy(()=>VO)});var Fnu=gt.objectWithoutOptionalProperties({schemas:gt.list(gt.lazy(()=>VO))}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(lue).extend(Oh).extend(Em).extend(bM);var $1c={};Po($1c,{ArraySchemaWithExample:()=>cau,Base64WithExample:()=>nau,BooleanWithExample:()=>aau,CommonPropertyWithExample:()=>bau,DateWithExample:()=>iau,DatetimeWithExample:()=>rau,DiscriminatedOneOfSchemaWithExample:()=>yau,DoubleWithExample:()=>eau,EndpointWithExample:()=>Rw_,EnumSchemaWithExample:()=>uau,FloatWithExample:()=>knu,HeaderWithExample:()=>HNi,HttpErrorWithExample:()=>Jnu,Int64WithExample:()=>Ynu,IntWithExample:()=>Knu,JsonRequestWithExample:()=>Hnu,JsonResponseWithExample:()=>mKn,MapSchemaWithExample:()=>lau,NamedFullExample:()=>i7e,NullableSchemaWithExample:()=>dau,ObjectPropertyWithExample:()=>hau,ObjectSchemaWithExample:()=>pau,OneOfSchemaWithExample:()=>_au,OptionalSchemaWithExample:()=>fau,ParseFormUrlEncodedRequest:()=>$nu,ParseMultipartRequest:()=>Wnu,ParseOctetStreamRequest:()=>Vnu,PathParameterWithExample:()=>Unu,PrimitiveSchemaValueWithExample:()=>oau,PrimitiveSchemaWithExample:()=>PKn,QueryParameterWithExample:()=>OKn,RequestWithExample:()=>Gnu,ResponseWithExample:()=>Qnu,SchemaWithExample:()=>gM,StringSchemaWithExample:()=>tau,Uint64WithExample:()=>Znu,UintWithExample:()=>Xnu,UnDiscriminatedOneOfSchemaWithExample:()=>vau,UnknownSchemaWithExample:()=>sau,WebhookWithExample:()=>xw_,WebsocketHandshakeWithExample:()=>zw_});var i7e=gt.objectWithoutOptionalProperties({name:gt.string().optional(),value:gt.unknown()}).extend(ff);var OKn=gt.objectWithoutOptionalProperties({name:gt.string(),schema:gt.lazy(()=>gM),parameterNameOverride:gt.string().optional()}).extend(ff).extend(Jh).extend(Oh);var HNi=gt.objectWithoutOptionalProperties({name:gt.string(),schema:gt.lazy(()=>gM),env:gt.string().optional(),parameterNameOverride:gt.string().optional()}).extend(ff).extend(Jh).extend(Oh);var zw_=gt.objectWithoutOptionalProperties({queryParameters:gt.list(OKn),headers:gt.list(HNi)});var Unu=gt.objectWithoutOptionalProperties({name:gt.string(),schema:gt.lazy(()=>gM),variableReference:gt.string().optional(),parameterNameOverride:gt.string().optional()}).extend(ff).extend(Jh).extend(Oh);var Vnu=gt.objectWithoutOptionalProperties({}).extend(aKn).extend(mor);var Wnu=gt.objectWithoutOptionalProperties({}).extend(oKn).extend(mor);var Hnu=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>gM),contentType:gt.string().optional(),fullExamples:gt.list(i7e).optional(),additionalProperties:gt.boolean()}).extend(ff).extend(Oh).extend(mor);var $nu=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>gM),contentType:gt.string().optional(),fullExamples:gt.list(i7e).optional(),additionalProperties:gt.boolean()}).extend(ff).extend(Oh).extend(mor);var Gnu=gt.union("type",{octetStream:Vnu,multipart:Wnu,json:Hnu,formUrlEncoded:$nu}).transform({transform:e=>{switch(e.type){case"octetStream":return nee.octetStream(e);case"multipart":return nee.multipart(e);case"json":return nee.json(e);case"formUrlEncoded":return nee.formUrlEncoded(e);default:return e}},untransform:({_visit:e,...t})=>t});var mKn=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>gM),responseProperty:gt.string().optional(),fullExamples:gt.list(i7e).optional()}).extend(ff).extend(Oh).extend(r7e);var Qnu=gt.union("type",{file:uKn,json:mKn,text:VNi,bytes:cKn,streamingSse:mKn,streamingText:VNi,streamingJson:mKn}).transform({transform:e=>{switch(e.type){case"file":return iB.file(e);case"json":return iB.json(e);case"text":return iB.text(e);case"bytes":return iB.bytes(e);case"streamingSse":return iB.streamingSse(e);case"streamingText":return iB.streamingText(e);case"streamingJson":return iB.streamingJson(e);default:return e}},untransform:({_visit:e,...t})=>t});var Jnu=gt.objectWithoutOptionalProperties({statusCode:Oor,schema:gt.lazy(()=>gM),fullExamples:gt.list(i7e).optional()}).extend(ff).extend(k0).extend(Oh);var Rw_=gt.objectWithoutOptionalProperties({authed:gt.boolean(),internal:gt.boolean().optional(),idempotent:gt.boolean().optional(),method:rKn,audiences:gt.list(gt.string()),path:gt.string(),summary:gt.string().optional(),operationId:gt.string().optional(),tags:gt.list(uee),pathParameters:gt.list(Unu),queryParameters:gt.list(OKn),headers:gt.list(HNi),sdkName:Por.optional(),generatedRequestName:gt.string(),requestNameOverride:gt.string().optional(),request:Gnu.optional(),response:Qnu.optional(),errors:gt.record(Oor,Jnu),servers:gt.list(lKn),examples:gt.list(pKn),pagination:_Kn.optional()}).extend(ff).extend(Jh).extend(Oh).extend(P0);var xw_=gt.objectWithoutOptionalProperties({audiences:gt.list(gt.string()),sdkName:Por.optional(),method:hKn,summary:gt.string().optional(),operationId:gt.string(),tags:gt.list(uee),headers:gt.list(HNi),generatedPayloadName:gt.string(),payload:gt.lazy(()=>gM),examples:gt.list(yKn)}).extend(ff).extend(Oh).extend(P0);var Knu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),minimum:gt.number().optional(),maximum:gt.number().optional(),exclusiveMinimum:gt.boolean().optional(),exclusiveMaximum:gt.boolean().optional(),multipleOf:gt.number().optional(),example:gt.number().optional()});var Ynu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),example:gt.number().optional()});var Xnu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),example:gt.number().optional()});var Znu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),example:gt.number().optional()});var knu=gt.objectWithoutOptionalProperties({example:gt.number().optional()});var eau=gt.objectWithoutOptionalProperties({default:gt.number().optional(),minimum:gt.number().optional(),maximum:gt.number().optional(),exclusiveMinimum:gt.boolean().optional(),exclusiveMaximum:gt.boolean().optional(),multipleOf:gt.number().optional(),example:gt.number().optional()});var tau=gt.objectWithoutOptionalProperties({default:gt.string().optional(),pattern:gt.string().optional(),format:gt.string().optional(),minLength:gt.number().optional(),maxLength:gt.number().optional(),example:gt.string().optional()});var rau=gt.objectWithoutOptionalProperties({example:gt.string().optional()});var iau=gt.objectWithoutOptionalProperties({example:gt.string().optional()});var nau=gt.objectWithoutOptionalProperties({example:gt.string().optional()});var aau=gt.objectWithoutOptionalProperties({default:gt.boolean().optional(),example:gt.boolean().optional()});var oau=gt.union("type",{int:Knu,int64:Ynu,uint:Xnu,uint64:Znu,float:knu,double:eau,string:tau,datetime:rau,date:iau,base64:nau,boolean:aau}).transform({transform:e=>{switch(e.type){case"int":return ap.int(e);case"int64":return ap.int64(e);case"uint":return ap.uint(e);case"uint64":return ap.uint64(e);case"float":return ap.float(e);case"double":return ap.double(e);case"string":return ap.string(e);case"datetime":return ap.datetime(e);case"date":return ap.date(e);case"base64":return ap.base64(e);case"boolean":return ap.boolean(e);default:return e}},untransform:({_visit:e,...t})=>t});var PKn=gt.objectWithoutOptionalProperties({schema:oau}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(Em);var uau=gt.objectWithoutOptionalProperties({default:FNi.optional(),values:gt.list(FNi),example:gt.string().optional()}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(Oh).extend(Em).extend(bM);var sau=gt.objectWithoutOptionalProperties({example:gt.unknown()}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(Em);var gM=gt.union("type",{primitive:PKn,object:gt.lazyObject(()=>pau),array:gt.lazyObject(()=>cau),map:gt.lazyObject(()=>lau),optional:gt.lazyObject(()=>fau),enum:uau,reference:jor,literal:vKn,oneOf:gt.object({value:gt.lazy(()=>_au)}),nullable:gt.lazyObject(()=>dau),unknown:sau}).transform({transform:e=>{switch(e.type){case"primitive":return Al.primitive(e);case"object":return Al.object(e);case"array":return Al.array(e);case"map":return Al.map(e);case"optional":return Al.optional(e);case"enum":return Al.enum(e);case"reference":return Al.reference(e);case"literal":return Al.literal(e);case"oneOf":return Al.oneOf(e.value);case"nullable":return Al.nullable(e);case"unknown":return Al.unknown(e);default:return e}},untransform:({_visit:e,...t})=>t});var cau=gt.objectWithoutOptionalProperties({value:gt.lazy(()=>gM),example:gt.list(gt.unknown()).optional()}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(Em).extend(bM);var lau=gt.objectWithoutOptionalProperties({key:PKn,value:gt.lazy(()=>gM),example:gt.unknown().optional()}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(lue).extend(Em).extend(bM);var fau=gt.objectWithoutOptionalProperties({value:gt.lazy(()=>gM)}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(Em).extend(bM);var dau=gt.objectWithoutOptionalProperties({value:gt.lazy(()=>gM)}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(Em).extend(bM);var pau=gt.objectWithoutOptionalProperties({allOf:gt.list(jor),properties:gt.list(gt.lazyObject(()=>hau)),allOfPropertyConflicts:gt.list(bKn),fullExamples:gt.list(i7e).optional(),additionalProperties:gt.boolean()}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(Oh).extend(Em).extend(bM);var hau=gt.objectWithoutOptionalProperties({key:gt.string(),schema:gt.lazy(()=>gM),readonly:gt.boolean().optional(),writeonly:gt.boolean().optional(),audiences:gt.list(gt.string()),conflict:gt.record(oee,gKn),nameOverride:gt.string().optional(),generatedName:gt.string()}).extend(Jh);var _au=gt.union("type",{discriminated:gt.lazyObject(()=>yau),undiscriminated:gt.lazyObject(()=>vau)}).transform({transform:e=>{switch(e.type){case"discriminated":return aee.discriminated(e);case"undiscriminated":return aee.undiscriminated(e);default:return e}},untransform:({_visit:e,...t})=>t});var yau=gt.objectWithoutOptionalProperties({discriminantProperty:gt.string(),commonProperties:gt.list(gt.lazyObject(()=>bau)),schemas:gt.record(gt.string(),gt.lazy(()=>gM))}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(lue).extend(Oh).extend(Em).extend(bM);var bau=gt.objectWithoutOptionalProperties({key:gt.string(),schema:gt.lazy(()=>gM)});var vau=gt.objectWithoutOptionalProperties({schemas:gt.list(gt.lazy(()=>gM))}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(lue).extend(Oh).extend(Em).extend(bM);var Nw_=/^(\d+)/,jKn=/^[a-zA-Z][a-zA-Z0-9_]*$/,Fw_={"<":"LESS_THAN",">":"GREATER_THAN",">=":"GREATER_THAN_OR_EQUAL_TO","<=":"LESS_THAN_OR_EQUAL_TO","!=":"NOT_EQUALS","=":"EQUAL_TO","==":"EQUAL_TO","*":"ALL","":"EMPTY",'""':"EMPTY_STRING","-":"HYPHEN","|":"PIPE",".":"DOT","/":"SLASH"};function $Ni(e){let t=["zero","one","two","three","four","five","six","seven","eight","nine"],r=["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],i=["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"];if(e<0||e>9999)return;if(e<10)return t[e];if(e<20)return r[e-10];if(e<100){let u=Math.floor(e/10),l=e%10;return l===0?i[u]:`${i[u]}_${t[l]}`}if(e<1e3){let u=Math.floor(e/100),l=e%100;return l===0?`${t[u]}_hundred`:`${t[u]}_hundred_${$Ni(l)}`}let n=Math.floor(e/1e3),a=e%1e3;return a===0?`${t[n]}_thousand`:`${t[n]}_thousand_${$Ni(a)}`}function U5a(e){let t=e.match(Nw_);if(t&&t[0]!=null){let r=t[0],i=e.substring(r.length),n=parseFloat(r);if(!isNaN(n)&&isFinite(n)){let a=$Ni(n);return i.length>0?`${a}_${i}`:a}}}function wKn(e){let t=U5a(e),r=Fw_[e];return t!=null?qB(S_(t)):r??(e.toLowerCase()==="n/a"?"NOT_APPLICABLE":qB(S_(e)))}function fue(e,t){return e.type==="primitive"&&t.type==="primitive"?Lw_(e.schema,t.schema):e.type==="enum"&&t.type==="enum"?TxE(e.values,t.values):e.type==="array"&&t.type==="array"?fue(e.value,t.value):e.type==="unknown"&&t.type==="unknown"?!0:e.type==="reference"&&t.type==="reference"?e.schema===t.schema:e.type==="optional"&&t.type==="optional"?fue(e.value,t.value):e.type==="oneOf"&&t.type==="oneOf"?CxE(e.value,t.value):e.type==="object"&&t.type==="object"?BxE(e,t):e.type==="map"&&t.type==="map"?Lw_(e.key.schema,t.key.schema)&&fue(e.value,t.value):e.type==="literal"&&t.type==="literal"?e.value===t.value:!1}function Lw_(e,t){return e.type===t.type}function TxE(e,t){let r=new Set(...e.map(n=>n.value)),i=new Set(...t.map(n=>n.value));return g8(r,i)}function CxE(e,t){return e.type==="discriminated"&&t.type==="discriminated"?e.discriminantProperty===t.discriminantProperty&&Object.keys(e.schemas).length===Object.keys(t.schemas).length&&Object.entries(e.schemas).every(([r,i])=>{let n=t.schemas[r];return n==null?!1:fue(i,n)}):e.type==="undiscriminated"&&t.type==="undiscriminated"?e.schemas.length===t.schemas.length&&e.schemas.every((r,i)=>{let n=t.schemas[i];return n==null?!1:fue(r,n)}):!1}function BxE(e,t){if(Object.keys(e.properties).length!==Object.keys(t.properties).length)return!1;let r=Object.fromEntries(e.properties.map(i=>[i.key,i.schema]));return Object.entries(t.properties).every(([i,n])=>{let a=r[i];return a==null?!1:fue(a,n.schema)})}function rx(e){switch(e){case $H.Deprecated:return"deprecated";case $H.Beta:return"pre-release";case $H.GenerallyAvailable:return"generally-available";default:return}}function IxE(e){let t=e.find(i=>typeof i=="object"&&i.type==="namespace"),r=e.filter(i=>typeof i=="string"||i.type!=="namespace");return t?[t,...r]:r}function Uw_(e){let t=e?IxE(e):void 0;if(t==null||t.length===0)return WZi;let r=[];for(let[i,n]of t.entries())if(typeof n=="string")r.push(S_(n));else if(typeof n=="object")switch(n.type){case"namespace":{i<t.length-1?r.push(S_(n.name)):r.push(n.name,WZi);break}default:So(n.type)}else So(n);return r.join("/")}function GNi(e){return fy.of(`${Uw_(e)}.yml`)}function G1c({sdkName:e,namespaceOverride:t}){let r;return e==null||e.groupName.length===0&&t==null?WZi:(t!=null?r=[{type:"namespace",name:t},...e.groupName.filter(i=>typeof i=="string"||i.type!=="namespace")]:r=e.groupName,Uw_(r))}function Vw_({sdkName:e,namespaceOverride:t}){return fy.of(`${G1c({sdkName:e,namespaceOverride:t})}.yml`)}function Ww_({location:e,namespaceOverride:t}){return t!=null?PF(fy.of(t),e):e}function gau(e){switch(e.type){case"protobuf":return{proto:{type:e.typeName}};default:So(e.type)}}function SKn(e){switch(e.type){case"object":case"enum":case"array":case"map":case"reference":case"literal":case"optional":case"nullable":case"primitive":return e.groupName??void 0;case"oneOf":return e.value.groupName??void 0;case"unknown":return;default:So(e)}}function WA(e){return typeof e=="string"?e:e.type}function DKn(e){if(typeof e!="string")return e.docs}function V5a(e){if(typeof e!="string")return e.default}function Q1c(e){if(typeof e!="string")return e.validation}var zxE=-2147483648,RxE=2147483647,xxE=-17976931348623157e292,NxE=17976931348623157e292;function Ng({schema:e,fileContainingReference:t,declarationFile:r=t,context:i,namespace:n,declarationDepth:a}){switch(i.shouldMarkSchemaAsReferenced()&&i.markSchemaAsReferenced(e,n),e.type){case"primitive":return Oau(e);case"array":return Y1c({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"map":return X1c({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"reference":return K1c({schema:e,fileContainingReference:t,context:i,namespace:n});case"unknown":return k1c();case"optional":return mau({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"nullable":return Z1c({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"enum":return QxE({schema:e,fileContainingReference:t,context:i,declarationFile:r,declarationDepth:a});case"literal":return e.value,eSc(e);case"object":return JxE({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"oneOf":return KxE({schema:e.value,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});default:So(e)}}function Oau(e){switch(e.schema.type){case"string":return UxE({description:e.description,schema:e.schema});case"int":return VxE({description:e.description,schema:e.schema});case"float":return WxE({description:e.description,schema:e.schema});case"double":return HxE({description:e.description,schema:e.schema});case"boolean":return FxE({description:e.description,schema:e.schema});case"int64":return LxE({description:e.description,schema:e.schema})}let t=e.schema._visit({int:()=>"integer",int64:()=>"long",uint:()=>"uint",uint64:()=>"uint64",float:()=>"double",double:()=>"double",string:()=>"string",datetime:()=>"datetime",date:()=>"date",base64:()=>"base64",boolean:()=>"boolean",_other:()=>"unknown"});return e.description==null&&e.title==null?t:{type:t,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:rx(e.availability)}:{}}}function FxE({description:e,schema:t}){let r="boolean";if(e==null&&t.default==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),i}function LxE({description:e,schema:t}){let r="long";if(e==null&&t.default==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),i}function UxE({description:e,schema:t}){let r="string",i=$xE(t);if(e==null&&t.default==null&&i==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),i!=null&&(n.validation=i),n}function VxE({description:e,schema:t}){let r="integer",i=$w_(t,r);if(e==null&&t.default==null&&i==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),i!=null&&(n.validation=i),n}function WxE({description:e,schema:t}){let r="float";if(e==null)return r;let i={type:r};return e!=null&&(i.docs=e),i}function HxE({description:e,schema:t}){let r="double",i=$w_(t,r);if(e==null&&t.default==null&&i==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),i!=null&&(n.validation=i),n}function $xE(e){if(e==null)return;let{format:t,pattern:r,minLength:i,maxLength:n}=e,a=GxE(t);if(!(a==null&&r==null&&i==null&&n==null))return{format:a,pattern:r,minLength:i,maxLength:n}}function GxE(e){switch(e){case"date":case"date-time":case"password":case"byte":case"bytes":case"binary":case"email":case"uuid":case"uri":case"hostname":case"ipv4":case"ipv6":return e;default:return}}function $w_(e,t){if(e==null)return;let{minimum:r,maximum:i,multipleOf:n}=e,{exclusiveMinimum:a,exclusiveMaximum:u}=e;if(r=J1c(r,t),i=J1c(i,t),n=J1c(n,t),!(r==null&&i==null&&a==null&&u==null&&n==null))return{min:r,max:i,exclusiveMin:a,exclusiveMax:u,multipleOf:n}}function J1c(e,t){if(e===void 0)return;let[r,i]=t==="integer"?[zxE,RxE]:[xxE,NxE];return e<r||e>i?void 0:e}function K1c({schema:e,fileContainingReference:t,context:r,namespace:i}){let n=r.getSchema(e.schema,i);if(n==null)return"unknown";let a=YxE(n)??e.schema,u=SKn(n),l=XxE(n),d=Pau({context:r,fileContainingReference:t,declarationFile:GNi(u),type:a}),s=n.type==="nullable"?`optional<${d}>`:d;return e.description==null&&l==null?s:{type:n.type==="nullable"?`optional<${d}>`:d,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:rx(e.availability)}:{}}}function Y1c({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=Ng({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),l=`list<${WA(u)}>`;return e.description==null&&e.title==null?l:{...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:rx(e.availability)}:{},type:l}}function X1c({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=Oau(e.key),l=Ng({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),d=e.encoding!=null?gau(e.encoding):void 0,s=`map<${WA(u)}, ${WA(l)}>`;if(e.description==null&&d==null&&e.title==null)return s;let o={type:s};return e.description!=null&&(o.docs=e.description),e.encoding!=null&&(o.encoding=d),e.availability!=null&&(o.availability=rx(e.availability)),o}function Z1c({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){if(!i.respectNullableSchemas)return mau({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});let u=Ng({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),l=WA(u),d=DKn(u),s=V5a(u),o=Q1c(u),c=l.startsWith("nullable<")?l:`nullable<${l}>`;if(e.availability==null&&e.description==null&&d==null&&s==null&&o==null&&e.title==null)return Hw_({typeReference:c,itemType:l});let b={type:c};return(e.description!=null||d!=null)&&(b.docs=e.description??d),s!=null&&(b.default=s),o!=null&&(b.validation=o),e.availability!=null&&(b.availability=rx(e.availability)),Hw_({typeReference:b,itemType:l})}function mau({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=Ng({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),l=WA(u),d=DKn(u),s=V5a(u),o=Q1c(u),c=l.startsWith("optional<")?l:`optional<${l}>`;if(e.availability==null&&e.description==null&&d==null&&s==null&&o==null&&e.title==null)return c;let b={type:c};return(e.description!=null||d!=null)&&(b.docs=e.description??d),s!=null&&(b.default=s),o!=null&&(b.validation=o),e.availability!=null&&(b.availability=rx(e.availability)),b}function k1c(){return"unknown"}function eSc(e){let t;switch(e.value.type){case"boolean":{t=`literal<${e.value.value}>`;break}case"string":{t=`literal<"${e.value.value}">`;break}default:So(e.value)}return e.description==null&&e.title==null?t:{type:t,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:rx(e.availability)}:{}}}function QxE({schema:e,fileContainingReference:t,declarationFile:r,context:i,declarationDepth:n}){let a=W5a(e,n),u=e.nameOverride??e.generatedName;i.builder.addType(r,{name:u,schema:a.schema});let l=Pau({type:u,fileContainingReference:t,declarationFile:r,context:i});if(e.description==null&&e.default==null&&e.title==null)return l;let d={type:l};return e.description!=null&&(d.docs=e.description),e.default!=null&&(d.default=e.default.value),e.availability!=null&&(d.availability=rx(e.availability)),d}function JxE({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=tSc({schema:e,declarationFile:r,context:i,namespace:n,declarationDepth:a}),l=e.nameOverride??e.generatedName;i.builder.addType(r,{name:l,schema:u.schema});let d=Pau({type:l,fileContainingReference:t,declarationFile:r,context:i});return e.description==null&&e.title==null?d:{type:d,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:rx(e.availability)}:{}}}function KxE({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=rSc({schema:e,declarationFile:r,context:i,namespace:n,declarationDepth:a}),l=e.nameOverride??e.generatedName;i.builder.addType(r,{name:l,schema:u.schema});let d=Pau({type:l,fileContainingReference:t,declarationFile:r,context:i});return e.description==null&&e.title==null?d:{...e.title!=null?{"display-name":e.title}:{},type:d,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:rx(e.availability)}:{}}}function Pau({type:e,fileContainingReference:t,declarationFile:r,context:i}){if(r===t)return e;let n=i.builder.addImport({file:t,fileToImport:r});return n!=null?`${n}.${e}`:e}function YxE(e){return cv._visit(e,{primitive:t=>t.nameOverride??t.generatedName,object:t=>t.nameOverride??t.generatedName,array:t=>t.nameOverride??t.generatedName,map:t=>t.nameOverride??t.generatedName,enum:t=>t.nameOverride??t.generatedName,reference:t=>t.nameOverride??t.generatedName,literal:t=>t.nameOverride??t.generatedName,oneOf:t=>t.nameOverride??t.generatedName,optional:t=>t.nameOverride??t.generatedName,nullable:t=>t.nameOverride??t.generatedName,unknown:t=>t.nameOverride??t.generatedName,_other:()=>{}})}function XxE(e){return cv._visit(e,{primitive:t=>t.title,object:t=>t.title,array:t=>t.title,map:t=>t.title,enum:t=>t.title,reference:t=>t.title,literal:t=>t.title,oneOf:t=>t.title,optional:t=>t.title,nullable:t=>t.title,unknown:t=>{},_other:()=>{}})}function Hw_({typeReference:e,itemType:t}){return t.startsWith("optional<")?e:typeof e=="string"?`optional<${e}>`:{...e,type:`optional<${e.type}>`}}var $8;(function(e){e[e.Channel=0]="Channel",e[e.Endpoint=1]="Endpoint",e[e.Request=2]="Request",e[e.Webhook=3]="Webhook"})($8||($8={}));function Zmi(e){switch(e.type){case"openapi":return{openapi:e.file};case"protobuf":return{proto:e.file};default:So(e)}}function Qw_({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){let a;switch(e.type){case"primitive":a=eNE(e);break;case"array":a=ZxE({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"map":a=kxE({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"reference":a=tNE({schema:e,context:t,declarationFile:r,namespace:i});break;case"unknown":a=iNE(e.nameOverride,e.generatedName);break;case"optional":a=Jw_({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"nullable":a=rNE({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"enum":a=W5a(e,n);break;case"literal":a=nNE(e,e.nameOverride,e.generatedName);break;case"object":a=tSc({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"oneOf":a=rSc({schema:e.value,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;default:So(e)}return a}function tSc({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){let a=t.isInState($8.Request)&&t.respectReadonlySchemas&&(t.getEndpointMethod()==="POST"||t.getEndpointMethod()==="PUT"||t.getEndpointMethod()==="PATCH"),u=!1,l={},d=new Set;for(let g of e.properties){if(g.readonly&&(u=!0),a&&g.readonly)continue;if(Object.keys(g.conflict).length>0){if(Object.entries(g.conflict).every(([D,C])=>!C.differentSchema))continue;Object.entries(g.conflict).forEach(([D])=>{iSc({property:g.key,schemaId:D,context:t,namespace:i}).forEach(R=>{d.add(R)})})}let O=Ng({schema:g.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1}),m=g.audiences,w=g.nameOverride,E=rx(g.availability),q=sNE(g);l[g.key]=uNE({typeReference:O,audiences:m,name:w,availability:E,propertyAccess:q})}let s=new Set;for(let g of e.allOfPropertyConflicts)g.allOfSchemaIds.forEach(O=>d.add(O)),g.conflictingTypeSignatures&&s.add(g.propertyKey);let o=[];for(let g of e.allOf){let O=Kw_({schema:g.schema,context:t,namespace:i});if(O==null||d.has(g.schema)||d.has(O))continue;let m=Ng({schema:cv.reference(g),context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1});o.push(WA(m))}for(let g of d){let O=nSc(t,g,i);for(let m of O.properties)l[m.key]==null&&(s.has(m.key)&&(l[m.key]="unknown"),l[m.key]=Ng({schema:m.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1}));for(let m of O.allOf){if(d.has(m.schema))continue;let w=Ng({schema:cv.reference(m),context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1});o.push(WA(w))}}let c={docs:e.description??void 0,properties:Object.fromEntries(Object.entries(l).map(([g,O])=>oNE(g)?[g,typeof O=="string"?{type:O,name:`_${g}`}:{...O,name:`_${g}`}]:[g,O]))};o.length>0&&(c.extends=o),e.additionalProperties&&(c["extra-properties"]=!0),e.availability!=null&&(c.availability=rx(e.availability)),e.source!=null&&(c.source=Zmi(e.source)),c.inline=aSc(e,n);let b=e.nameOverride??e.generatedName;return{name:u&&t.respectReadonlySchemas&&!a?`${b}Read`:b,schema:c}}function iSc({property:e,schemaId:t,context:r,namespace:i}){let n=r.getSchema(t,i);if(n==null)return[];if(n.type==="reference")return iSc({property:e,schemaId:n.schema,context:r,namespace:i});if(n.type==="object"){let{properties:a,allOf:u}=nSc(r,t,i),l=a.some(s=>s.key===e),d=[...u.flatMap(s=>iSc({property:e,context:r,schemaId:s.schema,namespace:i}))];if(l||d.length>0)return[t,...d]}return[]}function nSc(e,t,r){let i=e.getSchema(t,r);if(i==null)return{properties:[],allOf:[]};if(i.type==="object")return{properties:i.properties,allOf:i.allOf};if(i.type==="reference")return nSc(e,i.schema,r);throw new Error(`Cannot getAllProperties for a non-object schema. schemaId=${t}, type=${i.type}`)}function ZxE({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return{name:e.nameOverride??e.generatedName,schema:Y1c({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:i,declarationDepth:n})}}function kxE({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return{name:e.nameOverride??e.generatedName,schema:X1c({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:i,declarationDepth:n})}}function eNE(e){let t=Oau(e);if(typeof t=="string")return{name:e.nameOverride??e.generatedName,schema:t};let{default:r,...i}=t;return{name:e.nameOverride??e.generatedName,schema:{...i}}}function Gw_(e){return e.camel==null&&e.pascal==null&&e.screamingSnake==null&&e.snake==null}function W5a(e,t){let r={enum:e.values.map(a=>{let u=a.nameOverride??a.generatedName,l=a.value;if(u===l&&a.description==null&&(a.casing==null||Gw_(a.casing)))return u;let d={value:a.value};if(u!==l&&(d.name=u),a.description!=null&&(d.docs=a.description),a.casing!=null&&!Gw_(a.casing)){let s={},o=!1;a.casing.camel!=null&&(s.camel=a.casing.camel,o=!0),a.casing.screamingSnake!=null&&(s["screaming-snake"]=a.casing.screamingSnake,o=!0),a.casing.snake!=null&&(s.snake=a.casing.snake,o=!0),a.casing.pascal!=null&&(s.pascal=a.casing.pascal,o=!0),o&&(d.casing=s)}return d})};e.description!=null&&(r.docs=e.description),e.default!=null&&(r.default=e.default.value),r.inline=aSc(e,t);let i=new Set,n={...r,enum:[],source:e.source!=null?Zmi(e.source):void 0};for(let a of r.enum){let u=typeof a=="string"?a:a.name??a.value;i.has(u.toLowerCase())||(n.enum.push(a),i.add(u.toLowerCase()))}return{name:e.nameOverride??e.generatedName,schema:n}}function tNE({schema:e,context:t,declarationFile:r,namespace:i}){return{name:e.nameOverride??e.generatedName,schema:K1c({schema:e,context:t,fileContainingReference:r,namespace:i})}}function rNE({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return t.respectNullableSchemas?{name:e.nameOverride??e.generatedName,schema:Z1c({schema:e,context:t,fileContainingReference:r,declarationFile:r,namespace:i,declarationDepth:n})}:Jw_({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n})}function Jw_({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return{name:e.nameOverride??e.generatedName,schema:mau({schema:e,context:t,fileContainingReference:r,declarationFile:r,namespace:i,declarationDepth:n})}}function iNE(e,t){return{name:e??t,schema:k1c()}}function nNE(e,t,r){return{name:t??r,schema:eSc(e)}}function rSc({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){let a=e.encoding!=null?gau(e.encoding):void 0;if(e.type==="discriminated"){let l={};for(let s of e.commonProperties)l[s.key]=Ng({schema:s.schema,fileContainingReference:r,context:t,namespace:i,declarationDepth:n+1});let d={};for(let[s,o]of Object.entries(e.schemas))d[s]=Ng({schema:o,context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1});return{name:e.nameOverride??e.generatedName,schema:{discriminant:e.discriminantProperty,"base-properties":l,docs:e.description??void 0,availability:e.availability!=null?rx(e.availability):void 0,union:d,encoding:a,source:e.source!=null?Zmi(e.source):void 0}}}let u=[];for(let l of e.schemas)u.push(Ng({schema:l,fileContainingReference:r,context:t,namespace:i,declarationDepth:n+1}));return{name:e.nameOverride??e.generatedName,schema:{discriminated:!1,docs:e.description??void 0,union:u,encoding:a,source:e.source!=null?Zmi(e.source):void 0,inline:aSc(e,n)}}}var aNE=/^[0-9]/;function oNE(e){return aNE.test(e)}function Kw_({schema:e,context:t,namespace:r}){let i=t.getSchema(e,r);if(i!=null)return i.type==="reference"?Kw_({context:t,schema:i.schema,namespace:r}):e}function uNE({typeReference:e,audiences:t,name:r,availability:i,propertyAccess:n}){return t.length===0&&r==null&&i==null&&n==null?e:{...typeof e=="string"?{type:e}:{...e},...t.length>0?{audiences:t}:{},...r!=null?{name:r}:{},...i!=null?{availability:i}:{},...n!=null?{access:n}:{}}}function aSc(e,t){return e.inline===!0||t>0?!0:void 0}function sNE(e){if(!(e.readonly&&e.writeonly)){if(e.readonly)return MF.ObjectPropertyAccess.ReadOnly;if(e.writeonly)return MF.ObjectPropertyAccess.WriteOnly}}function Yw_(e){let t=e.replace(/^x-|^X-/,"");return S_(t)}var Xw_="BasicAuthScheme",jau="BearerAuthScheme";function Zw_(e){if(e.authOverrides!=null){for(let[r,i]of Object.entries(e.authOverrides["auth-schemes"]??{}))e.builder.addAuthScheme({name:r,schema:i});e.authOverrides.auth!=null&&e.builder.setAuth(e.authOverrides.auth);return}let t=!1;for(let[r,i]of Object.entries(e.ir.securitySchemes))if(i.type==="basic"){let n={scheme:"basic"};i.usernameVariableName!=null&&(n.username===void 0?n.username={name:i.usernameVariableName}:n.username.name=i.usernameVariableName),i.usernameEnvVar!=null&&(n.username===void 0?n.username={env:i.usernameEnvVar}:n.username.env=i.usernameEnvVar),i.passwordVariableName!=null&&(n.password===void 0?n.password={name:i.passwordVariableName}:n.password.name=i.passwordVariableName),i.passwordEnvVar!=null&&(n.password===void 0?n.password={env:i.passwordEnvVar}:n.password.env=i.passwordEnvVar),e.builder.addAuthScheme({name:Xw_,schema:n}),t||(e.builder.setAuth(Xw_),t=!0)}else if(i.type==="bearer"){let n={scheme:"bearer"};i.tokenVariableName!=null&&(n.token===void 0?n.token={name:i.tokenVariableName}:n.token.name=i.tokenVariableName),i.tokenEnvVar!=null&&(n.token===void 0?n.token={env:i.tokenEnvVar}:n.token.env=i.tokenEnvVar),e.builder.addAuthScheme({name:jau,schema:n}),t||(e.builder.setAuth(jau),t=!0)}else if(i.type==="header")if(t)e.builder.addGlobalHeader({name:i.headerName,schema:{type:"string",name:i.headerVariableName??Yw_(i.headerName),env:i.headerEnvVar}});else{let n={header:i.headerName,name:i.headerVariableName??"apiKey",type:"string"};i.headerEnvVar!=null&&(n.env=i.headerEnvVar),i.prefix!=null&&(n.prefix=i.prefix),e.builder.addAuthScheme({name:r,schema:n}),e.builder.setAuth(r),t=!0}else if(i.type==="oauth"){let n={scheme:"bearer"};e.builder.addAuthScheme({name:jau,schema:n}),t||(e.builder.setAuth(jau),t=!0),i.scopesEnum!=null&&i.scopesEnum.values.length>0&&e.builder.addType(fy.of("__package__.yml"),{name:"OauthScope",schema:W5a(i.scopesEnum,0).schema})}}function wor({header:e,context:t,fileContainingReference:r,namespace:i}){let n=Ng({schema:e.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),a=WA(n),u=e.name.replace(/^x-|^X-/,""),l=e.parameterNameOverride!=null?e.parameterNameOverride:S_(u);if(e.description==null&&e.name===l&&e.env==null&&e.availability==null)return a;let d={type:a};return l!==e.name&&(d.name=l),e.description!=null&&(d.docs=e.description),e.env!=null&&(d.env=e.env),e.availability!=null&&(d.availability=rx(e.availability)),d}function wau({pathParameter:e,context:t,fileContainingReference:r,namespace:i}){let n=Ng({schema:e.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:0});if(e.variableReference==null&&e.description==null&&e.availability==null)return WA(n);let a=e.variableReference!=null?{variable:`$${e.variableReference}`}:{type:WA(n)};return e.description!=null&&(a.docs=e.description),e.availability!=null&&(a.availability=rx(e.availability)),a}function Dau({queryParameter:e,context:t,fileContainingReference:r,namespace:i}){let n=oSc({schema:e.schema,context:t,fileContainingReference:r,namespace:i});if(n==null)return;let a=WA(n.value),u=V5a(n.value);a==="unknown"?a="string":a==="optional<unknown>"&&(a="optional<string>");let l={type:a};return u!=null&&(l.default=u),n.allowMultiple&&(l["allow-multiple"]=!0),e.description!=null&&(l.docs=e.description),e.parameterNameOverride!=null&&(l.name=e.parameterNameOverride),e.availability!=null&&(l.availability=rx(e.availability)),cNE(n.value)&&n.value.validation!==void 0&&(l.validation=n.value.validation),l.default==null&&l["allow-multiple"]==null&&l.docs==null&&l.name==null&&l.availability==null&&l.validation==null?a:l}function oSc({schema:e,context:t,fileContainingReference:r,namespace:i}){if(e.type==="reference"){let n=t.getSchema(e.schema,i);if(n==null)return;if(n.type==="array")return{value:Ng({schema:cv.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:n.value,description:e.description??n.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:void 0}),context:t,declarationFile:fy.of(fS),fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(n.type==="oneOf"&&n.value.type==="undiscriminated"){let a=[],u=!1;for(let[l,d]of Object.entries(n.value.schemas))d.type==="primitive"&&d.schema.type==="string"&&(u=!0),d.type==="literal"&&d.value.type==="string"&&(jKn.test(d.value.value)?a.push(d.value.value):a.push({value:d.value.value,name:wKn(d.value.value)}));if(a.length>0)return t.builder.addType(r,{name:e.generatedName,schema:{enum:a}}),u&&t.respectForwardCompatibleEnums?(t.builder.addType(r,{name:`${e.generatedName}OrString`,schema:{discriminated:!1,union:[{type:"string"},{type:e.generatedName}]}}),{value:`${e.generatedName}OrString`,allowMultiple:!1}):{value:e.generatedName,allowMultiple:!1};if(n.value.schemas.length===2){let[l,d]=n.value.schemas;if(l!=null&&d!=null&&Sau({array:l,primitive:d}))return{value:Ng({schema:cv.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:d,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:void 0}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(l!=null&&d!=null&&Sau({array:l,primitive:d}))return{value:Ng({schema:cv.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:l,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:void 0}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0}}for(let[l,d]of Object.entries(n.value.schemas))return oSc({schema:d,context:t,fileContainingReference:r,namespace:i})}else if(t.objectQueryParameters)return{value:Ng({schema:e,context:t,fileContainingReference:r,declarationFile:fy.of(fS),namespace:i,declarationDepth:0}),allowMultiple:!1}}if(e.type==="optional"||e.type==="nullable"){if(e.value.type==="reference"){let n=t.getSchema(e.value.schema,i);if(n==null)return;if(n.type==="array")return{value:Ng({schema:cv.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:n.value,description:e.description??n.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,declarationFile:fy.of(fS),namespace:i,declarationDepth:0}),allowMultiple:!0};if(t.objectQueryParameters)return{value:Ng({schema:e,context:t,fileContainingReference:r,declarationFile:fy.of(fS),namespace:i,declarationDepth:0}),allowMultiple:!1}}if(e.value.type==="array")return{value:Ng({schema:cv.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value.value,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(e.value.type==="oneOf"&&e.value.value.type==="undiscriminated"){let n=[],a=!1;for(let[u,l]of Object.entries(e.value.value.schemas))l.type==="primitive"&&l.schema.type==="string"&&(a=!0),l.type==="literal"&&l.value.type==="string"&&(jKn.test(l.value.value)?n.push(l.value.value):n.push({value:l.value.value,name:wKn(l.value.value)}));if(n.length>0)return t.builder.addType(r,{name:e.generatedName,schema:{enum:n}}),a&&t.respectForwardCompatibleEnums?(t.builder.addType(r,{name:`${e.generatedName}OrString`,schema:{discriminated:!1,union:[{type:"string"},{type:`optional<${e.value.value.generatedName}>`}]}}),{value:`optional<${e.value.value.generatedName}OrString>`,allowMultiple:!1}):{value:`optional<${e.value.value.generatedName}>`,allowMultiple:!1};if(e.value.value.schemas.length===2){let[u,l]=e.value.value.schemas;if(u!=null&&l!=null&&Sau({array:u,primitive:l}))return{value:Ng({schema:cv.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:l,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(u!=null&&l!=null&&Sau({array:l,primitive:u}))return{value:Ng({schema:cv.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:u,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0}}if(t.objectQueryParameters)return{value:Ng({schema:e,context:t,fileContainingReference:r,declarationFile:fy.of(fS),namespace:i,declarationDepth:0}),allowMultiple:!1};for(let[u,l]of Object.entries(e.value.value.schemas))return oSc({schema:cv.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:l,description:void 0,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i})}else if(e.value.type==="object")return t.objectQueryParameters?{value:Ng({schema:e,context:t,fileContainingReference:r,declarationFile:fy.of(fS),namespace:i,declarationDepth:0}),allowMultiple:!1}:void 0;return{value:Ng({schema:e,context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!1}}return e.type==="array"?{value:Ng({schema:cv.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0}:{value:Ng({schema:e,context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!1}}function Sau({array:e,primitive:t}){return e?.type==="array"&&e.value.type==="primitive"&&t?.type==="primitive"&&e.value.schema.type===t.schema.type}function cNE(e){return e.type!=null}function kw_({websocketExample:e,context:t}){let r={messages:[]};e.name!=null&&(r.name=e.name),e.description!=null&&(r.docs=e.description),e.queryParameters!=null&&e.queryParameters.length>0&&(r["query-parameters"]=lNE(e.queryParameters)),e.headers!=null&&e.headers.length>0&&(r.headers=fNE({context:t,namedFullExamples:e.headers}));for(let i of e.messages){let n=QNi(i.payload);n!=null&&r.messages.push({type:i.messageType,body:n})}return r}function lNE(e){let t={};return e.forEach(r=>{let i=QNi(r.value);Array.isArray(i)?t[r.name]=i[0]:i!=null&&(t[r.name]=i)}),t}function fNE({context:e,namedFullExamples:t}){let r=e.builder.getGlobalHeaderNames(),i={};return t.forEach(n=>{let a=QNi(n.value);r.has(n.name)||a!=null&&(i[n.name]=a)}),i}function QNi(e){switch(e.type){case"primitive":return e1_(e.value);case"object":return t1_(e.properties);case"array":return dNE(e.value);case"map":return pNE(e.value);case"oneOf":return _NE(e.value);case"enum":return e.value;case"literal":return hNE(e.value);case"unknown":return QNi(e.value);default:So(e)}}function e1_(e){switch(e.type){case"int":return e.value;case"int64":return e.value;case"uint":return e.value;case"uint64":return e.value;case"float":return e.value;case"double":return e.value;case"string":return e.value.startsWith("$")?`${e.value.slice(1)}`:e.value;case"datetime":try{return new Date(e.value).toISOString().replace(/\.\d{3}Z$/,"Z")}catch{return"2024-01-15T09:30:00Z"}case"date":return e.value;case"base64":case"boolean":return e.value;default:So(e)}}function t1_(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,QNi(r)]))}function dNE(e){return e.map(t=>QNi(t))}function pNE(e){return Object.fromEntries(e.map(t=>[e1_(t.key),QNi(t.value)]))}function _NE(e){return e.type==="discriminated"?t1_(e.value):QNi(e.value)}function hNE(e){switch(e.type){case"string":return e.value;case"boolean":return e.value;default:So(e)}}function kmi(e){return e.find(t=>typeof t!="string"&&t.type==="namespace")?.name}function Eau(e,t){return t??(e?.groupName!=null?kmi(e.groupName):void 0)}function r1_({channel:e,context:t,declarationFile:r}){let i={path:e.path,url:e.servers[0]?.name,auth:!1};e.audiences!=null&&e.audiences.length>0&&(i.audiences=e.audiences),e.summary!=null&&(i["display-name"]=e.summary),e.description!=null&&(i.docs=e.description);let n=kmi(e.groupName),a={};if(e.handshake.pathParameters.length>0)for(let d of e.handshake.pathParameters)a[d.name]=wau({pathParameter:d,context:t,fileContainingReference:r,namespace:n});Object.keys(a).length>0&&(i["path-parameters"]=a);let u={};if(e.handshake.queryParameters.length>0)for(let d of e.handshake.queryParameters){let s=Dau({queryParameter:d,context:t,fileContainingReference:r,namespace:n});s!=null&&(u[d.name]=s)}Object.keys(u).length>0&&(i["query-parameters"]=u);let l={};if(e.handshake.headers.length>0)for(let d of e.handshake.headers){let s=wor({header:d,context:t,fileContainingReference:r,namespace:n});l[d.name]=s}Object.keys(l).length>0&&(i.headers=l),t.builder.addChannel(r,{channel:i});for(let d of e.messages)t.builder.addChannelMessage(r,{messageId:d.name,message:{origin:d.origin,body:Ng({schema:d.body,context:t,fileContainingReference:r,namespace:n,declarationDepth:0})}});for(let d of e.examples){let s=kw_({context:t,websocketExample:d});t.builder.addChannelExample(r,{example:s})}}var ePi="Base",yNE="Default";function JNi(e){return Object.entries(e).reduce((t,[r,i])=>(hUn(i)?Object.entries(i.urls).forEach(([n,a])=>{t[n]=a}):t[r]=typeof i=="string"?i:i.url,t),{})}function i1_(e){if(e.environmentOverrides!=null){for(let[g,O]of Object.entries(e.environmentOverrides.environments??{}))e.builder.addEnvironment({name:g,schema:O});e.environmentOverrides["default-environment"]!=null&&e.builder.setDefaultEnvironment(e.environmentOverrides["default-environment"]),e.environmentOverrides["default-url"]!=null&&e.builder.setDefaultUrl(e.environmentOverrides["default-url"]);return}let t={},r=[];for(let g of e.ir.servers){let O=g.audiences?{url:g.url,audiences:g.audiences}:g.url;if(g.name==null){r.push(O);continue}t[g.name]=O}let i={},n=[];for(let g of e.ir.endpoints)for(let O of g.servers){if(O.url==null)continue;let m=O.audiences?{url:O.url,audiences:O.audiences}:O.url;if(O.name==null){n.push(m);continue}i[O.name]=m}let a={},u=[];for(let g of e.ir.websocketServers){let O=g.audiences?{url:g.url,audiences:g.audiences}:g.url;if(g.name==null){u.push(O);continue}a[g.name]=O}let l=Object.keys(t).length,d=l>0,s=Object.keys(i).length>0,o=Object.keys(a).length>0;if(!d&&!s&&o&&e.ir.servers.length===0){for(let[g,O]of Object.entries(a))e.builder.addEnvironment({name:g,schema:O});e.builder.setDefaultEnvironment(Object.keys(a)[0]),e.builder.setDefaultUrl(ePi);return}if(n.length>0&&e.logger.error(`Skipping endpoint level servers ${n.map(g=>typeof g=="string"?g:g.url).join(", ")} because x-fern-server-name was not provided.`),!d){let g=e.ir.servers[0]?.url,O=e.ir.servers[0]?.audiences;if(g!=null){let m=O?{url:g,audiences:O}:g;t[yNE]=m}}let c=Object.values(t).map(g=>typeof g=="string"?g:g.url),b=r.filter(g=>{let O=typeof g=="string"?g:g.url;return!c.includes(O)});if(b.length>0&&e.logger.error(`Skipping top level servers ${b.map(g=>typeof g=="string"?g:g.url).join(", ")} because x-fern-server-name was not provided.`),s)if(l===1){let g=Object.keys(t)[0],O=Object.values(t)[0],m=typeof O=="string"?O:O.url;e.builder.addEnvironment({name:g,schema:{urls:{[ePi]:m,...JNi(i),...JNi(a)}}}),e.builder.setDefaultEnvironment(g),e.builder.setDefaultUrl(ePi)}else{let g=!0;for(let[O,m]of Object.entries(t))g?(e.builder.addEnvironment({name:O,schema:{urls:{[ePi]:typeof m=="string"?m:m.url,...JNi(i),...JNi(a)}}}),e.builder.setDefaultEnvironment(O),g=!1):e.builder.addEnvironment({name:O,schema:{urls:{[ePi]:typeof m=="string"?m:m.url,...JNi(i),...JNi(a)}}});e.builder.setDefaultUrl(ePi)}else{let g=!0;for(let[O,m]of Object.entries(t))g?(o?e.builder.addEnvironment({name:O,schema:{urls:{[ePi]:typeof m=="string"?m:m.url,...JNi(a)}}}):e.builder.addEnvironment({name:O,schema:m}),e.builder.setDefaultEnvironment(O),g=!1):o?e.builder.addEnvironment({name:O,schema:{urls:{[ePi]:typeof m=="string"?m:m.url,...JNi(a)}}}):e.builder.addEnvironment({name:O,schema:m});o&&e.builder.setDefaultUrl(ePi)}}function Mau(e){return WA(e).startsWith("optional")?e:typeof e=="string"?`optional<${e}>`:{...e,type:`optional<${e.type}>`}}var uSc=class{schema;count=0;constructor(t){this.schema=t}increment(){this.count+=1}},vNE=.75,bNE=new Set("authorization");function n1_(e){if(e.globalHeaderOverrides!=null){for(let[r,i]of Object.entries(e.globalHeaderOverrides.headers??{}))e.builder.addGlobalHeader({name:r,schema:i});return}let t=Object.fromEntries((e.ir.globalHeaders??[]).map(r=>[r.header,r]));for(let[r,i]of Object.entries(t)){let n="optional<string>";if(i.name==null&&i.env==null&&typeof i.schema=="string")n=i.schema;else if(i!=null){let a=i.schema?SKn(i.schema):void 0,u=a!=null?kmi(a):void 0,l=fy.of("api.yml");n={name:i.name,env:i.env,type:i.schema!=null?WA(Ng({schema:i.schema,context:e,fileContainingReference:u?PF(fy.of(S_(u)),l):l,namespace:u,declarationDepth:0}))??"optional<string>":"optional<string>"}}e.builder.addGlobalHeader({name:r,schema:n})}if(e.detectGlobalHeaders){let r={};for(let n of e.ir.endpoints)for(let a of n.headers){if(bNE.has(a.name.toLowerCase()))continue;let u=r[a.name];if(u==null){let l=t[a.name],d=wor({header:{...a,schema:l?.schema??a.schema,name:l?.name??a.name},fileContainingReference:fy.of(z3),context:e,namespace:void 0});u=new uSc(d),r[a.name]=u}u.increment()}let i=e.ir.endpoints.length*vNE;for(let[n,a]of Object.entries(r)){let u=t[n],l=a.count===e.ir.endpoints.length,d=a.count>=i;u==null&&(l?e.builder.addGlobalHeader({name:n,schema:a.schema}):d&&e.builder.addGlobalHeader({name:n,schema:Mau(a.schema)}))}}}function a1_(e){for(let t of e.ir.idempotencyHeaders??[]){let r=t.schema?SKn(t.schema):void 0,i=r!=null?kmi(r):void 0,n=wor({header:{...t,schema:t.schema??cv.primitive({description:void 0,availability:void 0,generatedName:"",title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0,schema:jw.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0})}),name:t.name??t.header,parameterNameOverride:void 0,description:void 0,availability:void 0,source:void 0},fileContainingReference:fy.of(z3),context:e,namespace:i});e.builder.addIdempotencyHeader({name:t.header,schema:Mau(n)})}}function uK(e){switch(e.type){case"primitive":return u1_(e.value);case"object":return s1_(e.properties);case"array":return c1_(e.value);case"map":return ONE(e.value);case"oneOf":return mNE(e.value);case"enum":return typeof e.value=="string"&&e.value.startsWith("$")?`\\${e.value}`:e.value;case"literal":return PNE(e.value);case"unknown":return uK(e.value);default:So(e)}}function o1_(e){switch(e.type){case"withStreaming":return e.sse?{stream:gNE(e.events)}:{stream:c1_(e.events)};case"withoutStreaming":return{body:uK(e.value)};default:So(e)}}function u1_(e){switch(e.type){case"int":return e.value;case"int64":return e.value;case"uint":return e.value;case"uint64":return e.value;case"float":return e.value;case"double":return e.value;case"string":return e.value.startsWith("$")?`\\${e.value}`:e.value;case"datetime":try{return!e.value.endsWith("Z")&&!e.value.includes("+")&&(e.value+="Z"),new Date(e.value).toISOString().replace(/\.\d{3}Z$/,"Z")}catch{return"2024-01-15T09:30:00Z"}case"date":return e.value;case"base64":case"boolean":return e.value;default:So(e)}}function s1_(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,uK(r)]))}function gNE(e){return e.map(t=>({event:"",data:uK(t)}))}function c1_(e){return e.map(t=>uK(t))}function ONE(e){return Object.fromEntries(e.map(t=>[u1_(t.key),uK(t.value)]))}function mNE(e){return e.type==="discriminated"?s1_(e.value):uK(e.value)}function PNE(e){switch(e.type){case"string":return e.value;case"boolean":return e.value;default:So(e)}}function l1_({endpointExample:e,context:t}){let r={};if(e.type!=="full")return e.value;e.name!=null&&(r.name=e.name),e.description!=null&&(r.docs=e.description),e.pathParameters!=null&&e.pathParameters.length>0&&(r["path-parameters"]=jNE(e.pathParameters)),e.queryParameters!=null&&e.queryParameters.length>0&&(r["query-parameters"]=wNE(e.queryParameters));let i=e.headers!=null&&e.headers.length>0,n=t.builder.getGlobalHeaders(),a=Object.keys(n).length>0,u=new Set(e.headers?.map(l=>l.name)??[]);if(i||a){let l=[];if(e.headers!=null)for(let d of e.headers)d.name!==t.builder.getAuthHeaderName()&&l.push(d);for(let[d,s]of Object.entries(n))if(!u.has(d))if(s!=null&&typeof s=="object"&&s.type!=null){let o=Y3({type:s.type,_default:void 0,validation:void 0,visitor:{primitive:c=>c.toString(),map:c=>c.toString(),list:c=>c,optional:c=>c,nullable:c=>c,set:c=>c,named:c=>c,literal:c=>{if(c.type==="string")return c.string;if(c.type==="boolean")return c.boolean.toString()},unknown:$o}});o!=null&&l.push({name:d,value:xg.literal(zNi.string(o))})}else l.push({name:d,value:xg.primitive(h_.string(d))});r.headers=SNE({context:t,namedFullExamples:l})}return e.request!=null&&(r.request=uK(e.request)),e.response!=null&&(r.response=o1_(e.response)),e.codeSamples!=null&&e.codeSamples.length>0&&(r["code-samples"]=e.codeSamples.map(l=>l.type==="language"?{name:l.name??void 0,docs:l.description??void 0,language:l.language,code:l.code,install:l.install??void 0}:{name:l.name??void 0,docs:l.description??void 0,sdk:l.sdk,code:l.code}).filter(iv)),r}function jNE(e){let t={};return e.forEach(r=>{let i=uK(r.value);i!=null&&(t[r.parameterNameOverride??r.name]=i)}),t}function wNE(e){let t={};return e.forEach(r=>{let i=uK(r.value);Array.isArray(i)?t[r.name]=i[0]:i!=null&&(t[r.name]=i)}),t}function SNE({context:e,namedFullExamples:t}){let r={};return t.forEach(i=>{let n=uK(i.value);n!=null&&(r[i.name]=n)}),r}function f1_(e){return QH._visit(e,{get:()=>MF.HttpMethodSchema.Get,post:()=>MF.HttpMethodSchema.Post,put:()=>MF.HttpMethodSchema.Put,patch:()=>MF.HttpMethodSchema.Patch,delete:()=>MF.HttpMethodSchema.Delete,head:()=>MF.HttpMethodSchema.Head,options:()=>{throw new Error("OPTIONS is unsupported")},trace:()=>{throw new Error("TRACE is unsupported")},_other:()=>{throw new Error("Unknown http method is unsupported")}})}function d1_(e){return e==="POST"||e==="PUT"||e==="PATCH"}function p1_({endpoint:e,declarationFile:t,context:r}){let{nonRequestReferencedSchemas:i}=r.ir,n=[],a=new Set,u=e.path,l=Eau(e.sdkName,e.namespace),d={};for(let w of e.pathParameters)w.parameterNameOverride&&(u=u.replace(w.name,w.parameterNameOverride)),d[w.parameterNameOverride??w.name]=wau({pathParameter:w,context:r,fileContainingReference:t,namespace:l}),a.add(w.name);let s={};for(let w of e.queryParameters){let E=Dau({queryParameter:w,context:r,fileContainingReference:t,namespace:l});E!=null&&(s[w.name]=E,a.add(w.name))}let o;if(e.pagination!=null)switch(e.pagination.type){case"cursor":o={cursor:e.pagination.cursor,next_cursor:e.pagination.nextCursor,results:e.pagination.results};break;case"offset":o={offset:e.pagination.offset,step:e.pagination.step,results:e.pagination.results,"has-next-page":e.pagination.hasNextPage};break;case"custom":o={type:"custom",results:e.pagination.results};break;default:So(e.pagination)}let c={path:u,method:f1_(e.method),auth:e.authed,docs:e.description??void 0,pagination:o,source:e.source!=null?Zmi(e.source):void 0};!MNE({context:r,request:e.request})&&Object.keys(d).length>0&&(c["path-parameters"]=d),e.summary!=null&&(c["display-name"]=e.summary);let b={},g=r.builder.getGlobalHeaderNames(),O=r.builder.getAuthHeaderName();O!=null&&g.add(O);let m=e.headers.filter(w=>!g.has(w.name));for(let w of m){let E=wor({header:w,context:r,fileContainingReference:t,namespace:l});b[w.name]=E,a.add(typeof E=="string"?w.name:E.name??w.name)}if(e.request!=null){r.setInState($8.Request);let w=ENE({endpoint:e,context:r,declarationFile:t,request:e.request,generatedRequestName:e.generatedRequestName,requestNameOverride:e.requestNameOverride??void 0,pathParameters:r.inlinePathParameters&&Object.keys(d).length>0?d:void 0,queryParameters:Object.keys(s).length>0?s:void 0,nonRequestReferencedSchemas:Array.from(i),headers:Object.keys(b).length>0?b:void 0,usedNames:a,namespace:l});c.request=w.value,n=[...n,...w.schemaIdsToExclude??[]],r.unsetInState($8.Request)}else{let w=r.inlinePathParameters&&Object.keys(d).length>0,E=Object.keys(s).length>0,q=Object.keys(b).length>0,M={};(w||E||q)&&(M.name=e.requestNameOverride??e.generatedRequestName),w&&(M["path-parameters"]=d),E&&(M["query-parameters"]=s),q&&(M.headers=b),Object.keys(M).length>0&&(c.request=M)}if(e.response!=null&&e.response._visit({json:w=>{let E=Ng({schema:w.schema,context:r,fileContainingReference:t,namespace:l,declarationDepth:0});c.response={docs:w.description??void 0,type:WA(E)},w.statusCode!=null&&(c.response["status-code"]=w.statusCode),w.responseProperty!=null&&(c.response.property=w.responseProperty)},streamingJson:w=>{let E=Ng({schema:w.schema,context:r,fileContainingReference:t,namespace:l,declarationDepth:0});c["response-stream"]={docs:w.description??void 0,type:WA(E),format:"json"}},streamingSse:w=>{let E=Ng({schema:w.schema,context:r,fileContainingReference:t,namespace:l,declarationDepth:0});c["response-stream"]={docs:w.description??void 0,type:WA(E),format:"sse"}},file:w=>{c.response={docs:w.description??void 0,type:"file","status-code":w.statusCode}},bytes:w=>{c.response={docs:w.description??void 0,type:"bytes","status-code":w.statusCode}},streamingText:w=>{c["response-stream"]={docs:w.description??void 0,type:"text"}},text:w=>{c.response={docs:w.description??void 0,type:"text","status-code":w.statusCode}},_other:()=>{throw new Error("Unrecognized Response type: "+e.response?.type)}}),r.builder.getEnvironmentType()==="multi"){let w=r.getDefaultServerName(),E=e.servers[0];E==null?w!=null&&(c.url=w):c.url=E.name??void 0}return e.idempotent&&(c.idempotent=!0),e.availability!=null&&(c.availability=rx(e.availability)),Object.entries(e.errors).forEach(([w,E])=>{let q=E.generatedName,M=fy.of(fS);r.builder.enableUniqueErrorsPerEndpoint&&(q=`${e.generatedRequestName}${E.generatedName}`,E.schema!=null&&(E.schema.type!=="reference"&&E.schema.type!=="oneOf"?E.schema.generatedName=`${e.generatedRequestName}${E.schema.generatedName}`:E.schema.type==="oneOf"&&(E.schema.value.generatedName=`${e.generatedRequestName}${E.schema.value.generatedName}`)));let D={"status-code":parseInt(w)},C=Ww_({location:_1_,namespaceOverride:l});if(E.schema!=null){let I=Ng({schema:E.schema,context:r,fileContainingReference:C,declarationFile:C,namespace:l,declarationDepth:0});D.type=WA(I),D.docs=E.description}r.builder.addError(C,{name:q,schema:r.isErrorUnknownSchema(parseInt(w))?{...D,type:"unknown"}:D}),c.errors==null&&(c.errors=[]);let R=r.builder.addImport({file:t,fileToImport:C});c.errors.push(R!=null?`${R}.${q}`:q),D.type!=null&&E.examples?.forEach(I=>{let L={value:uK(I.example),name:I.name,docs:I.description};r.builder.addErrorExample(C,{name:q,example:L})})}),e.examples.length>0&&(c.examples=DNE({endpointExamples:e.examples,context:r})),r.ir.hasEndpointsMarkedInternal&&(e.internal==null||!e.internal)?c.audiences=[sSc,...e.audiences]:e.audiences.length>0&&(c.audiences=e.audiences),{value:c,schemaIdsToExclude:n}}function DNE({endpointExamples:e,context:t}){return e.map(r=>{try{return l1_({endpointExample:r,context:t})}catch(i){throw console.error(`Error building endpoint example: ${i}`),i}})}function ENE({endpoint:e,declarationFile:t,context:r,request:i,requestNameOverride:n,generatedRequestName:a,pathParameters:u,queryParameters:l,nonRequestReferencedSchemas:d,headers:s,usedNames:o,namespace:c}){if(i.type==="json"||i.type==="formUrlEncoded"){let b=i.schema.type==="reference"?i.schema.schema:void 0,g=i.schema.type==="reference"?r.getSchema(i.schema.schema,c):i.schema;if(g?.type!=="object"||b!=null&&d.includes(b)){let q=Ng({schema:i.schema,fileContainingReference:t,context:r,namespace:c,declarationDepth:0}),M={schemaIdsToExclude:[],value:{body:q}},D=Object.keys(u??{}).length>0,C=Object.keys(l??{}).length>0,R=Object.keys(s??{}).length>0;return D&&(M.value["path-parameters"]=u),C&&(M.value["query-parameters"]=l),R&&(M.value.headers=s),(D||C||R)&&(M.value.name=n??a),i.contentType!=null&&(M.value["content-type"]=i.contentType),i.description!=null&&(M.value.docs=i.description),M}let O=Object.fromEntries(g.properties.filter(q=>q.readonly==null?!0:!(d1_(e.method)&&q.readonly)).map(q=>{let M=Ng({schema:q.schema,fileContainingReference:t,context:r,namespace:c,declarationDepth:1}),D=q.nameOverride??q.key,C=rx(q.availability);if(!o.has(D)&&q.audiences.length<=0)return o.add(D),q.nameOverride!=null?[q.key,{type:WA(M),docs:DKn(M),name:q.nameOverride,availability:C}]:[q.key,C?{...typeof M=="string"?{type:M}:M,availability:C}:M];let R={type:WA(M),docs:DKn(M)};return o.has(D)&&(R.name=q.generatedName),q.audiences.length>0&&(R.audiences=q.audiences),C!=null&&(R.availability=C),o.add(D),[q.key,R]})),m=g.allOf.map(q=>{let M=Ng({schema:cv.reference(q),fileContainingReference:t,context:r,namespace:c,declarationDepth:0});return WA(M)}).filter(q=>q!=="unknown"),w={properties:O};m.length>0&&(w.extends=m),i.additionalProperties&&(w["extra-properties"]=!0);let E={name:n??g.nameOverride??g.generatedName,"path-parameters":u,"query-parameters":l,headers:s,body:w};return i.contentType!=null&&(E["content-type"]=i.contentType),i.description!=null&&(E.docs=i.description),{schemaIdsToExclude:b!=null?[b]:[],value:E}}else{if(i.type==="octetStream")return{schemaIdsToExclude:[],value:{body:"bytes","content-type":i.contentType??hq.APPLICATION_OCTET_STREAM,"query-parameters":l,...i.description?{docs:i.description}:{}}};if(i.type==="multipart"){let b=Object.fromEntries(i.properties.map(g=>{if(g.schema.type==="file"){let O=g.schema.isArray?"list<file>":"file";if(O=g.schema.isOptional?`optional<${O}>`:O,g.description!=null||g.contentType!=null){let m={type:O};if(g.description!=null&&(m.docs=g.description),g.contentType!=null){let w=g.contentType.split(",")[0];m["content-type"]=w}return[g.key,m]}return[g.key,O]}else{let O=Ng({schema:g.schema.value,fileContainingReference:t,context:r,namespace:c,declarationDepth:1});if(g.contentType||g.exploded||g.encoding){let m=typeof O=="string"?{type:O}:O;g.contentType!=null&&(m["content-type"]=g.contentType),g.encoding==="form"?m.style="form":g.encoding==="json"?m.style="json":g.exploded&&(m.style="exploded"),O=m}return[g.key,O]}}));return{schemaIdsToExclude:i.name==null?[]:[i.name],value:{name:n??i.name??a,"path-parameters":u,"query-parameters":l,headers:s,body:{properties:b},"content-type":hq.MULTIPART_FORM_DATA,...i.description?{docs:i.description}:{}}}}else So(i)}}function MNE({context:e,request:t}){if(!e.inlinePathParameters)return!1;if(t==null)return!0;switch(t.type){case"octetStream":return!1;case"multipart":return!0;case"json":return!0;case"formUrlEncoded":return!0;default:So(t)}}function ANE({location:e,namespaceOverride:t}){return t!=null?{...e,file:PF(fy.of(t),e.file)}:e}function qNE(e){let t=e.namespace,r=e.tags.filter(d=>d!==t)[0],i=e.operationId;if(i==null)return r!=null?{file:fy.of(`${S_(r)}.yml`),endpointId:e.summary!=null?S_(e.summary):S_(`${e.method}_${e.path.split("/").join("_")}`)}:e.summary!=null?{file:fy.of(fS),endpointId:S_(e.summary)}:{file:fy.of(fS),endpointId:S_(`${e.method}_${e.path.split("/").join("_")}`)};if(r==null)return{file:fy.of(fS),endpointId:i};let n=H5a(r),a=H5a(i);if(g8(n,a))return{file:fy.of("__package__.yml"),endpointId:r};let u=BNE({operationId:i,tag:r,path:e.path,method:e.method});if(u!=null)return u;let l=[];for(let d=0;d<n.length;++d){let s=n[d];if(s!=null&&s===a[d])l.push(s);else{let o=S_(r);return{file:fy.of(`${o}.yml`),endpointId:i,tag:r}}}if(l.length>=a.length)throw new Error(`Cannot get file for endpoint ${JSON.stringify(e)}`);return{file:fy.of(S_(l.join("_"))+".yml"),endpointId:S_(a.slice(l.length).join("_")),tag:r}}function $5a(e){let t=e.tags[0];if(e.sdkName!=null){let r=G1c({sdkName:e.sdkName,namespaceOverride:e.namespace}),i=`${r}.yml`,n=r.toLowerCase()===t?.toLowerCase().replaceAll(" ","");return{file:fy.of(i),endpointId:e.sdkName.methodName,tag:n?t:void 0}}return ANE({namespaceOverride:e.namespace,location:qNE(e)})}function H5a(e){let t;return/^[a-z]+(?:[A-Z][a-z]+)*$/.test(e)?t=e.split(/(?=[A-Z])/):t=e.split(/[^a-zA-Z0-9]+/),t=t.map(r=>r.toLowerCase()),t=Gxe(t),t}var TNE=new RegExp("[^a-zA-Z0-9{}]+"),CNE=new RegExp("[{}]","g");function BNE({operationId:e,tag:t,path:r,method:i}){let a=`${r.split(TNE).join("_").replaceAll(CNE,"_")}_${i.toLowerCase()}`;if(e.endsWith(a))return{file:fy.of(S_(t)+".yml"),endpointId:S_(e.slice(0,-1*a.length)),tag:t}}function h1_(e){let t=new Set,{endpoints:r,tags:i}=e.ir,n=[];for(let a of r){let{endpointId:u,file:l,tag:d}=$5a(a),s=l.split(".")[0];s!=null&&t.add(s);let o;if(a.sdkName!=null){let g=e.ir.groups;for(let O of a.sdkName.groupName){let m=typeof O=="string"?O:O.name,w=g[m];if(w==null)break;if(w.summary!=null||w.description!=null){o=g[m];break}}}let c=d==null?void 0:i.tagsById[d];e.setInState($8.Endpoint),e.setEndpointMethod(a.method);let b=p1_({context:e,endpoint:a,declarationFile:l});e.unsetEndpointMethod(),e.unsetInState($8.Endpoint),n=[...n,...b.schemaIdsToExclude],e.builder.addEndpoint(l,{name:u,schema:b.value,source:a.source!=null?Zmi(a.source):void 0}),(c?.id!=null||c?.description!=null)&&e.builder.setServiceInfo(l,{"display-name":o?.summary??c?.id,docs:o?.description??c?.description??void 0})}return{schemaIdsToExclude:n,sdkGroups:t}}function y1_(e){for(let[t,r]of Object.entries(e.ir.variables)){let i=r.groupName!=null?kmi(r.groupName):void 0,n=Ng({schema:cv.primitive(r),context:e,fileContainingReference:fy.of(fS),namespace:i,declarationDepth:0});e.builder.addVariable({name:t,schema:{type:WA(n),docs:r.description??void 0}})}}function v1_(e){for(let t of e.ir.webhooks){let r=RNE({webhook:t,context:e});if(r==null)continue;let i=Eau(t.sdkName,t.namespace),n={};for(let u of t.headers)n[u.name]=wor({header:u,context:e,fileContainingReference:r.file,namespace:i});let a={audiences:t.audiences,method:t.method,"display-name":t.summary??void 0,headers:n,payload:Ng({schema:t.payload,context:e,fileContainingReference:r.file,namespace:i,declarationDepth:0}),examples:t.examples!=null?t.examples.map(u=>({docs:u.description,name:u.name,payload:uK(u.payload)})):void 0};e.builder.addWebhook(r.file,{name:r.endpointId,schema:a}),t.description!=null&&(a.docs=t.description)}}function INE({location:e,namespaceOverride:t}){if(e!=null)return t!=null?{...e,file:PF(fy.of(t),e.file)}:e}function zNE({webhook:e,context:t}){let r=e.tags[0],i=e.operationId;if(r==null)return{file:fy.of(fS),endpointId:i};let n=H5a(r),a=H5a(i);if(g8(n,a))return{file:fy.of("__package__.yml"),endpointId:r};let u=[];for(let l=0;l<n.length;++l){let d=n[l];if(d!=null&&d===a[l])u.push(d);else{let s=S_(r);return{file:fy.of(`${s}.yml`),endpointId:i,tag:r}}}if(u.length>=a.length){t.logger.warn(`Skipping webhook ${e.operationId} because couldn't compute file location`);return}return{file:fy.of(S_(u.join("_"))+".yml"),endpointId:S_(a.slice(u.length).join("_")),tag:r}}function RNE({webhook:e,context:t}){return e.sdkName!=null?{file:Vw_({sdkName:e.sdkName,namespaceOverride:e.namespace}),endpointId:e.sdkName.methodName}:INE({namespaceOverride:e.namespace,location:zNE({webhook:e,context:t})})}var xNE=fy.of(fS);function g1_(e){switch(e.type){case"object":case"primitive":case"enum":case"array":case"map":case"reference":case"literal":case"optional":case"nullable":return b1_({namespace:e.namespace,groupName:e.groupName});case"oneOf":return b1_({namespace:e.value.namespace,groupName:e.value.groupName});case"unknown":return xNE;default:So(e)}}function b1_({namespace:e,groupName:t}){return e!=null&&t!=null?GNi([{type:"namespace",name:e},...t]):e!=null?GNi([{type:"namespace",name:e}]):GNi(t)}var sSc="external",_1_=fy.of(fS);function O1_({schemas:e,schemaIdsToExclude:t,namespace:r,context:i}){for(let[n,a]of Object.entries(e)){if(t.includes(n))continue;let u=g1_(a),l=Qw_({schema:a,context:i,declarationFile:u,namespace:r,declarationDepth:0});if(yzi(l.schema)){let d=WA(l.schema);if(d===(l.name??n)||d===`optional<${l.name??n}>`)continue}i.builder.addType(u,{name:l.name??n,schema:l.schema})}}function m1_(e){e.ir.apiVersion!=null&&e.builder.setApiVersion(e.ir.apiVersion),i1_(e),n1_(e),a1_(e),Zw_(e),y1_(e),e.ir.basePath!=null&&e.builder.setBasePath(e.ir.basePath),e.ir.hasEndpointsMarkedInternal&&e.builder.addAudience(sSc);let t=h1_(e),r=t.sdkGroups;e.setInState($8.Webhook),v1_(e),e.unsetInState($8.Webhook),e.setInState($8.Channel);for(let n of Object.values(e.ir.channels)){let a=GNi(n.groupName);r1_({channel:n,context:e,declarationFile:a})}e.unsetInState($8.Channel);let i=NNE({context:e,schemaIdsToExcludeFromServices:t.schemaIdsToExclude});O1_({schemas:e.ir.groupedSchemas.rootSchemas,schemaIdsToExclude:i,namespace:void 0,context:e});for(let[n,a]of Object.entries(e.ir.groupedSchemas.namespacedSchemas))O1_({schemas:a,schemaIdsToExclude:i,namespace:n,context:e});return e.ir.tags.orderedTagIds!=null&&e.ir.tags.orderedTagIds.length>0&&e.ir.tags.orderedTagIds.every(a=>r.has(a))&&e.builder.addNavigation({navigation:e.ir.tags.orderedTagIds}),e.builder.build()}function NNE({context:e,schemaIdsToExcludeFromServices:t}){let r=e.getReferencedSchemaIds();if(r==null)return t;let i=new Set([...Object.keys(e.ir.groupedSchemas.rootSchemas),...Object.values(e.ir.groupedSchemas.namespacedSchemas).flatMap(a=>Object.keys(a))]),n=new Set(t);for(let a of i)r.includes(a)||n.add(a);return Array.from(n)}var G5a=class{context;constructor(t){this.context=t}};var Aau=class e{files={};directories={};getAllFiles(){let t={},r=(i,n)=>{for(let[u,l]of Object.entries(i.files)){let d=n!=null?fy.of(`${n}${b$t}${u}`):fy.of(u);t[d]=l}let a=Object.keys(i.directories).sort();for(let u of a){let l=n!=null?`${n}${b$t}${u}`:u,d=i.directories[u];r(d,l)}};return r(this),t}getOrCreateFile(t){return this.getOrCreateFileRecursive(t.split(b$t))}getOrCreateFileRecursive(t){if(t.length===1)return this.files[fy.of(t[0])]??={};let[r,...i]=t;if(r==null)throw new Error(`Internal error; cannot add file with path: ${t}`);return this.directories[r]||(this.directories[r]=new e),this.directories[r].getOrCreateFileRecursive(i)}};var tan=class{enableUniqueErrorsPerEndpoint;root;rootApiFile;packageMarkerFile={};basePath=void 0;constructor(t){this.enableUniqueErrorsPerEndpoint=t,this.root=new Aau,this.rootApiFile={name:"api","error-discrimination":{strategy:"status-code"}}}setDisplayName({displayName:t}){this.rootApiFile["display-name"]=t}addNavigation({navigation:t}){this.packageMarkerFile.navigation=t}setServiceInfo(t,{auth:r,"base-path":i,"display-name":n,docs:a}){let u=this.getOrCreateFile(t);u.service==null&&(u.service={auth:!1,"base-path":"",endpoints:{}}),r!=null&&(u.service.auth=r),i!=null&&(u.service["base-path"]=i),n!=null&&(u.service["display-name"]=n),a!=null&&(u.docs=a)}addAudience(t){this.rootApiFile.audiences==null&&(this.rootApiFile.audiences=[]),this.rootApiFile.audiences.push(t)}setAuth(t){this.rootApiFile.auth=t}addAuthScheme({name:t,schema:r}){this.rootApiFile["auth-schemes"]==null&&(this.rootApiFile["auth-schemes"]={}),this.rootApiFile["auth-schemes"][t]==null&&(this.rootApiFile["auth-schemes"][t]=r)}setDefaultEnvironment(t){this.rootApiFile["default-environment"]=t}setDefaultUrl(t){this.rootApiFile["default-url"]=t}setBasePath(t){this.basePath=t}setApiVersion(t){this.rootApiFile.version=t}getEnvironmentType(){let t=Object.entries(this.rootApiFile.environments??{})[0];if(t!=null)return Krr(t[1],{singleBaseUrl:()=>"single",multipleBaseUrls:()=>"multi"})}addEnvironment({name:t,schema:r}){this.rootApiFile.environments==null&&(this.rootApiFile.environments={}),this.rootApiFile.environments[t]=r}getGlobalHeaderNames(){let t=Object.keys(this.rootApiFile.headers??{});if(this.rootApiFile["auth-schemes"]!=null)for(let i of Object.values(this.rootApiFile["auth-schemes"]))P1_(i)&&t.push(i.header);let r=this.getVersionHeader();return r!=null&&t.push(r),new Set(t)}getAuthHeaderName(){if(this.rootApiFile["auth-schemes"]!=null){for(let t of Object.values(this.rootApiFile["auth-schemes"]))if(P1_(t))return t.header;return"Authorization"}}addGlobalHeader({name:t,schema:r}){let i=this.getVersionHeader();i!=null&&i===t||(this.rootApiFile.headers==null&&(this.rootApiFile.headers={}),this.rootApiFile.headers[t]=r)}getGlobalHeaders(){return this.rootApiFile.headers??{}}addIdempotencyHeader({name:t,schema:r}){this.rootApiFile["idempotency-headers"]==null&&(this.rootApiFile["idempotency-headers"]={}),this.rootApiFile["idempotency-headers"][t]=r}addVariable({name:t,schema:r}){this.rootApiFile.variables==null&&(this.rootApiFile.variables={}),this.rootApiFile.variables[t]=r}addImport({file:t,fileToImport:r,alias:i}){if(t===r)return;let n=i??S_((iNe(r)+"/"+lki(r,{stripExtension:!0})).replaceAll("__package__","root"));if(t===fy.of(z3))return this.rootApiFile.imports==null&&(this.rootApiFile.imports={}),this.rootApiFile.imports[n]=OBo(iNe(w5n.of(`/${t}`)),w5n.of(`/${r}`)),n;let a=this.getOrCreateFile(t);return a.imports==null&&(a.imports={}),a.imports[n]=OBo(iNe(w5n.of(`/${t}`)),w5n.of(`/${r}`)),n}addType(t,{name:r,schema:i}){if(t===fy.of(z3))return;let n=this.getOrCreateFile(t);n.types==null&&(n.types={}),n.types[r]=i}addTypeExample(t,r,i){let n=this.getOrCreateFile(t);n.types==null&&(n.types={});let a=n.types[r];a!=null&&(typeof a=="string"?n.types[r]={type:a,examples:[i]}:(a.examples==null&&(a.examples=[]),a.examples.push(i)))}addError(t,{name:r,schema:i}){let n=this.getOrCreateFile(t);n.errors==null&&(n.errors={}),n.errors[r]==null?n.errors[r]=i:n.errors[r]?.type!==i.type&&(n.errors[r]={"status-code":i["status-code"],type:"unknown"})}addErrorExample(t,{name:r,example:i}){let n=this.getOrCreateFile(t);if(n.errors==null)return;let a=n.errors[r];if(a==null)return;a.examples==null&&(a.examples=[]),(a.examples.some(l=>g8(l,i))??!1)||a.examples?.push(i)}addEndpoint(t,{name:r,schema:i,source:n}){let a=this.getOrCreateFile(t);a.service==null&&(a.service={auth:!1,"base-path":"",endpoints:{}}),n!=null&&(a.service.source=n),a.service.endpoints[r]=i}addWebhook(t,{name:r,schema:i}){let n=this.getOrCreateFile(t);n.webhooks==null&&(n.webhooks={}),n.webhooks[r]=i}addChannel(t,{channel:r}){let i=this.getOrCreateFile(t);i.channel=r;let n=this.basePath;n!=null&&(i.channel.path=PF(n,r.path))}addChannelExample(t,{example:r}){let i=this.getOrCreateFile(t);i.channel==null&&(i.channel={path:"",auth:!1}),i.channel.messages==null&&(i.channel.messages={}),i.channel.examples==null&&(i.channel.examples=[]),i.channel.examples.push(r)}addChannelMessage(t,{messageId:r,message:i}){let n=this.getOrCreateFile(t);n.channel==null&&(n.channel={path:"",auth:!1}),n.channel.messages==null&&(n.channel.messages={}),n.channel.messages[r]=i}build(){let t=this.root.getAllFiles(),r=this.basePath;if(r!=null){this.packageMarkerFile.service!=null&&(this.packageMarkerFile.service={...this.packageMarkerFile.service,endpoints:Object.fromEntries(Object.entries(this.packageMarkerFile.service.endpoints).map(([n,a])=>[n,{...a,path:PF(r,a.path)}]))});for(let n of Object.values(t))n.service!=null&&(n.service={...n.service,endpoints:Object.fromEntries(Object.entries(n.service.endpoints).map(([a,u])=>[a,{...u,path:PF(r,u.path)}]))})}return{rootApiFile:this.rootApiFile,packageMarkerFile:this.packageMarkerFile,definitionFiles:t}}getOrCreateFile(t){return t===fS?this.packageMarkerFile:this.root.getOrCreateFile(t)}getVersionHeader(){if(this.rootApiFile.version!=null)return typeof this.rootApiFile.version.header=="string"?this.rootApiFile.version.header:this.rootApiFile.version.header.value}};function P1_(e){return e?.header!=null}var qau=class{logger;taskContext;ir;builder;environmentOverrides;authOverrides;globalHeaderOverrides;detectGlobalHeaders;objectQueryParameters;respectReadonlySchemas;respectNullableSchemas;onlyIncludeReferencedSchemas;inlinePathParameters;useBytesForBinaryResponse;respectForwardCompatibleEnums;enableUniqueErrorsPerEndpoint;defaultServerName=void 0;unknownSchema=new Set;referencedSchemaIds;endpointMethod;state=new Set;constructor({taskContext:t,ir:r,options:i,environmentOverrides:n,globalHeaderOverrides:a,authOverrides:u}){this.logger=t.logger,this.taskContext=t,this.ir=r,this.environmentOverrides=n,this.authOverrides=u,this.globalHeaderOverrides=a,this.detectGlobalHeaders=i?.detectGlobalHeaders??!0,this.objectQueryParameters=i?.objectQueryParameters??!1,this.respectReadonlySchemas=i?.respectReadonlySchemas??!1,this.respectNullableSchemas=i?.respectNullableSchemas??!1,this.onlyIncludeReferencedSchemas=i?.onlyIncludeReferencedSchemas??!1,this.inlinePathParameters=i?.inlinePathParameters??!1,this.useBytesForBinaryResponse=i?.useBytesForBinaryResponse??!1,this.respectForwardCompatibleEnums=i?.respectForwardCompatibleEnums??!1,this.referencedSchemaIds=i?.onlyIncludeReferencedSchemas?new Set:void 0,this.enableUniqueErrorsPerEndpoint=i?.enableUniqueErrorsPerEndpoint??!1,this.builder=new tan(this.enableUniqueErrorsPerEndpoint),r.title!=null&&this.builder.setDisplayName({displayName:r.title});let l={};if(!this.enableUniqueErrorsPerEndpoint)for(let d of r.endpoints)for(let[s,o]of Object.entries(d.errors)){let c=parseInt(s),b=l[c];b==null&&o.schema!=null?l[c]=o.schema:b!=null&&o.schema!=null&&fue(b,o.schema)||this.unknownSchema.add(c)}}getReferencedSchemaIds(){if(this.referencedSchemaIds!=null)return Array.from(this.referencedSchemaIds)}getSchema(t,r){return r==null?this.ir.groupedSchemas.rootSchemas[t]:this.ir.groupedSchemas.namespacedSchemas[r]?.[t]}getDefaultServerName(){return this.defaultServerName}setDefaultServerName(t){this.defaultServerName=t}isErrorUnknownSchema(t){return this.unknownSchema.has(t)}getEndpointMethod(){return this.endpointMethod}setEndpointMethod(t){this.endpointMethod=t}unsetEndpointMethod(){this.endpointMethod=void 0}isInState(t){return this.state.has(t)}setInState(t){this.state.add(t)}unsetInState(t){this.state.delete(t)}shouldMarkSchemaAsReferenced(){return this.onlyIncludeReferencedSchemas&&this.isInAnyState($8.Channel,$8.Endpoint,$8.Webhook)}markSchemaAsReferenced(t,r){switch(t.type){case"primitive":return;case"object":this.markObjectSchemaAsReferenced(t,r);return;case"array":this.markSchemaAsReferenced(t.value,r);return;case"map":this.markSchemaAsReferenced(t.value,r);return;case"optional":this.markSchemaAsReferenced(t.value,r);return;case"reference":this.markSchemaIdAsReferenced(t.schema,r);return;case"oneOf":this.markOneofSchemaAsReferenced(t.value,r);return;case"nullable":this.markSchemaAsReferenced(t.value,r);return;case"enum":return;case"literal":return;case"unknown":return;default:So(t)}}markObjectSchemaAsReferenced(t,r){for(let i of t.allOf)this.markSchemaIdAsReferenced(i.schema,r);for(let i of t.properties)this.markSchemaAsReferenced(i.schema,r)}markOneofSchemaAsReferenced(t,r){switch(t.type){case"discriminated":for(let i of Object.values(t.schemas))this.markSchemaAsReferenced(i,r);return;case"undiscriminated":for(let i of t.schemas)this.markSchemaAsReferenced(i,r);return;default:So(t)}}markSchemaIdAsReferenced(t,r){if(this.referencedSchemaIds!=null&&!this.referencedSchemaIds.has(t)){this.referencedSchemaIds.add(t);let i=this.getSchema(t,r);i!=null&&this.markSchemaAsReferenced(i,r)}}isInAnyState(...t){return t.some(r=>this.isInState(r))}};function cSc(e){let t=new qau(e);return m1_(t)}var Tau=class{args;constructor(t){this.args=t}convert({context:t,ir:r,settings:i,absoluteFilePath:n}){let a=cSc({taskContext:t,ir:r,options:R5a({overrides:{...i,respectReadonlySchemas:i?.respectReadonlySchemas??this.args.respectReadonlySchemas,respectNullableSchemas:i?.respectNullableSchemas??this.args.respectNullableSchemas,onlyIncludeReferencedSchemas:i?.onlyIncludeReferencedSchemas??this.args.onlyIncludeReferencedSchemas,inlinePathParameters:i?.inlinePathParameters??this.args.inlinePathParameters,objectQueryParameters:i?.objectQueryParameters??this.args.objectQueryParameters,useBytesForBinaryResponse:i?.useBytesForBinaryResponse??this.args.useBytesForBinaryResponse,respectForwardCompatibleEnums:i?.respectForwardCompatibleEnums??this.args.respectForwardCompatibleEnums}}),authOverrides:i?.auth!=null?{auth:i.auth}:this.args.generatorsConfiguration?.api?.auth!=null?{...this.args.generatorsConfiguration.api}:void 0,environmentOverrides:this.args.generatorsConfiguration?.api?.environments!=null?{...this.args.generatorsConfiguration?.api}:void 0,globalHeaderOverrides:this.args.generatorsConfiguration?.api?.headers!=null?{...this.args.generatorsConfiguration?.api}:void 0});return{absoluteFilePath:n??this.args.absoluteFilePath,rootApiFile:{defaultUrl:a.rootApiFile["default-url"],contents:a.rootApiFile,rawContents:wd.dump(a.rootApiFile)},namedDefinitionFiles:{..._d(a.definitionFiles,u=>({absoluteFilepath:n??this.args.absoluteFilePath,rawContents:wd.dump(u),contents:u})),[fy.of(fS)]:{absoluteFilepath:n??this.args.absoluteFilePath,rawContents:wd.dump(a.packageMarkerFile),contents:a.packageMarkerFile}},packageMarkers:{},importedDefinitions:{}}}};var Q5a=class extends hQt{inlinePathParameters;objectQueryParameters;onlyIncludeReferencedSchemas;respectReadonlySchemas;respectNullableSchemas;exampleGeneration;useBytesForBinaryResponse;respectForwardCompatibleEnums;converter;constructor(t){super(t),this.inlinePathParameters=t.inlinePathParameters,this.objectQueryParameters=t.objectQueryParameters,this.onlyIncludeReferencedSchemas=t.onlyIncludeReferencedSchemas,this.respectReadonlySchemas=t.respectReadonlySchemas,this.respectNullableSchemas=t.respectNullableSchemas,this.exampleGeneration=t.exampleGeneration,this.useBytesForBinaryResponse=t.useBytesForBinaryResponse,this.respectForwardCompatibleEnums=t.respectForwardCompatibleEnums,this.converter=new Tau(t)}async getDefinition({context:t,absoluteFilePath:r,relativePathToDependency:i},n){let a=await this.getOpenAPIIr({context:t,relativePathToDependency:i},n);return this.converter.convert({context:t,ir:a,settings:n,absoluteFilePath:r})}async toFernWorkspace({context:t},r){let i=await this.getDefinition({context:t},r);return new ZAe({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:i,cliVersion:this.cliVersion})}};var JH={BEARER_FORMAT:"x-bearer-format",ENUM_VAR_NAMES:"x-enum-varnames",INTERNAL:"x-internal",EXAMPLES:"x-examples",TAGS:"x-tags",REDOCLY_CODE_SAMPLES_KEBAB:"x-code-samples",REDOCLY_CODE_SAMPLES_CAMEL:"x-codeSamples"};var EKn={of(e){return e}};var j1_={properties:{"stream-condition":{type:"string"},response:"Schema","response-stream":"Schema"},required:["stream-condition","response","response-stream"],extensionsPrefix:"x-"},lSc={id:"",typeExtension:{oas3:e=>({...e,XFernStreaming:j1_,Operation:{...e.Operation,properties:{...e.Operation?.properties,"x-fern-streaming":"XFernStreaming"}}})}},Kf={SOURCE:EKn.of("source"),SDK_NAMESPACE:EKn.of("x-fern-sdk-namespace"),SDK_METHOD_NAME:EKn.of("x-fern-sdk-method-name"),SDK_GROUP_NAME:EKn.of("x-fern-sdk-group-name"),REQUEST_NAME_V1:"x-request-name",REQUEST_NAME_V2:"x-fern-request-name",TYPE_NAME:"x-fern-type-name",BOOLEAN_LITERAL:"x-fern-boolean-literal",SERVER_NAME_V1:"x-name",SERVER_NAME_V2:"x-fern-server-name",BASE_PATH:"x-fern-base-path",GROUPS:EKn.of("x-fern-groups"),OPENAPI_OVERIDES_FILEPATH:"x-fern-overrides-filepath",TYPE_DEFINITION:"x-fern-type",STREAMING:"x-fern-streaming",PAGINATION:"x-fern-pagination",WEBHOOK:"x-fern-webhook",ASYNC_CONFIG:"x-fern-async-config",SDK_VARIABLES:"x-fern-sdk-variables",SDK_VARIABLE:"x-fern-sdk-variable",PARAMETER_NAME:"x-fern-parameter-name",BASIC_AUTH_USERNAME_VARIABLE_NAME:"x-fern-username-variable-name",BASIC_AUTH_PASSWORD_VARIABLE_NAME:"x-fern-password-variable-name",BEARER_TOKEN_VARIABLE_NAME:"x-fern-token-variable-name",HEADER_VARIABLE_NAME:"x-fern-header-variable-name",FERN_ENUM:"x-fern-enum",AUDIENCES:"x-fern-audiences",IGNORE:"x-fern-ignore",AVAILABILITY:"x-fern-availability",RESPONSE_PROPERTY:"x-fern-sdk-return-value",RESOLUTIONS:"x-fern-resolutions",EXAMPLES:"x-fern-examples",FERN_BEARER_TOKEN:"x-fern-bearer",FERN_HEADER_AUTH:"x-fern-header",FERN_BASIC_AUTH:"x-fern-basic",FERN_GLOBAL_HEADERS:"x-fern-global-headers",FERN_IDEMPOTENCY_HEADERS:"x-fern-idempotency-headers",IDEMPOTENT:"x-fern-idempotent",FERN_PROPERTY_NAME:"x-fern-property-name",IS_UNDISCRIMINATED:"x-fern-undiscriminated",FERN_VERSION:"x-fern-version",ENCODING:"x-fern-encoding",TRANSPORT:"x-fern-transport",IS_DISCRIMINATED:"x-fern-discriminated"};var b7={disableExamples:!1,discriminatedUnionV2:!1,useTitlesAsName:!0,audiences:void 0,optionalAdditionalProperties:!0,coerceEnumsToLiterals:!0,respectReadonlySchemas:!1,respectNullableSchemas:!1,onlyIncludeReferencedSchemas:!1,inlinePathParameters:!1,preserveSchemaIds:!1,objectQueryParameters:!1,shouldUseUndiscriminatedUnionsWithLiterals:!1,shouldUseIdiomaticRequestNames:!1,filter:void 0,asyncApiNaming:"v1",exampleGeneration:void 0,defaultFormParameterEncoding:"json",useBytesForBinaryResponse:!1,respectForwardCompatibleEnums:!1,additionalPropertiesDefaultsTo:!1,typeDatesAsStrings:!0,preserveSingleSchemaOneOf:!1};function gQt({options:e,overrides:t}){return{disableExamples:t?.disableExamples??b7.disableExamples,discriminatedUnionV2:t?.discriminatedUnionV2??e?.discriminatedUnionV2??b7.discriminatedUnionV2,useTitlesAsName:t?.useTitlesAsName??e?.useTitlesAsName??b7.useTitlesAsName,audiences:t?.audiences??e?.audiences??b7.audiences,optionalAdditionalProperties:t?.optionalAdditionalProperties??e?.optionalAdditionalProperties??b7.optionalAdditionalProperties,coerceEnumsToLiterals:t?.coerceEnumsToLiterals??e?.coerceEnumsToLiterals??b7.coerceEnumsToLiterals,respectReadonlySchemas:t?.respectReadonlySchemas??e?.respectReadonlySchemas??b7.respectReadonlySchemas,respectNullableSchemas:t?.respectNullableSchemas??e?.respectNullableSchemas??b7.respectNullableSchemas,onlyIncludeReferencedSchemas:t?.onlyIncludeReferencedSchemas??e?.onlyIncludeReferencedSchemas??b7.onlyIncludeReferencedSchemas,inlinePathParameters:t?.inlinePathParameters??e?.inlinePathParameters??b7.inlinePathParameters,preserveSchemaIds:t?.preserveSchemaIds??b7.preserveSchemaIds,shouldUseUndiscriminatedUnionsWithLiterals:t?.shouldUseUndiscriminatedUnionsWithLiterals??e?.shouldUseUndiscriminatedUnionsWithLiterals??b7.shouldUseUndiscriminatedUnionsWithLiterals,shouldUseIdiomaticRequestNames:t?.shouldUseIdiomaticRequestNames??e?.shouldUseIdiomaticRequestNames??b7.shouldUseIdiomaticRequestNames,objectQueryParameters:t?.objectQueryParameters??e?.objectQueryParameters??b7.objectQueryParameters,filter:t?.filter??e?.filter??b7.filter,asyncApiNaming:t?.asyncApiNaming??e?.asyncApiNaming??b7.asyncApiNaming,useBytesForBinaryResponse:t?.useBytesForBinaryResponse??e?.useBytesForBinaryResponse??b7.useBytesForBinaryResponse,exampleGeneration:t?.exampleGeneration??e?.exampleGeneration??void 0,defaultFormParameterEncoding:t?.defaultFormParameterEncoding??e?.defaultFormParameterEncoding??void 0,respectForwardCompatibleEnums:t?.respectForwardCompatibleEnums??e?.respectForwardCompatibleEnums??b7.respectForwardCompatibleEnums,additionalPropertiesDefaultsTo:t?.additionalPropertiesDefaultsTo??e?.additionalPropertiesDefaultsTo??b7.additionalPropertiesDefaultsTo,typeDatesAsStrings:t?.typeDatesAsStrings??e?.typeDatesAsStrings??b7.typeDatesAsStrings,preserveSingleSchemaOneOf:t?.preserveSingleSchemaOneOf??e?.preserveSingleSchemaOneOf??b7.preserveSingleSchemaOneOf}}var w1_={naming:"v1"};function of(e,t){let r=Array.isArray(t)?t:[t];for(let i of r){let n=e[i];if(n!=null)return n}}function J5a(e,t,r,i,n=[]){try{let a=of(e,t);if(a!=null)return r.parse(a)}catch{let u=Gxe(n).join(" -> ");i.error(`${u.length>0?`${u}: `:""}Failed to parse ${t}`)}}function ran(e){let t=of(e,"examples");return t!=null&&Array.isArray(t)?t:[]}function S1_({schema:e,logger:t}){return of(e,Kf.ENCODING)??void 0}function D1_(e){return of(e,Kf.FERN_ENUM)}function E1_({nameOverride:e,generatedName:t,title:r,schema:i,description:n,availability:a}){let u=of(i,Kf.SDK_NAMESPACE),l=of(i,Kf.SDK_GROUP_NAME),d=of(i,Kf.TYPE_DEFINITION);if(d!=null)return K5a({fernType:d,nameOverride:e,generatedName:t,title:r,description:n,availability:a,namespace:u,groupName:typeof l=="string"?[l]:l})}function K5a({fernType:e,nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:l}){return Y3({type:e,_default:void 0,validation:void 0,visitor:{primitive:d=>{switch(d.v1){case"BASE_64":return Al.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:l,schema:ap.base64({example:void 0})});case"BOOLEAN":return Al.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:l,schema:ap.boolean({default:void 0,example:void 0})});case"DATE":return Al.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:l,schema:ap.date({example:void 0})});case"DATE_TIME":return Al.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:l,schema:ap.datetime({example:void 0})});case"FLOAT":return Al.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:l,schema:ap.float({example:void 0})});case"DOUBLE":return Al.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:l,schema:ap.double({default:void 0,minimum:void 0,maximum:void 0,exclusiveMinimum:void 0,exclusiveMaximum:void 0,multipleOf:void 0,example:void 0})});case"UINT":return Al.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:l,schema:ap.uint({default:void 0,example:void 0})});case"INTEGER":return Al.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:l,schema:ap.int({default:void 0,minimum:void 0,maximum:void 0,exclusiveMinimum:void 0,exclusiveMaximum:void 0,multipleOf:void 0,example:void 0})});case"UINT_64":return Al.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:l,schema:ap.uint64({default:void 0,example:void 0})});case"LONG":return Al.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:l,schema:ap.int64({default:void 0,example:void 0})});case"STRING":case"UUID":case"BIG_INTEGER":return Al.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:l,schema:ap.string({default:void 0,pattern:void 0,maxLength:void 0,minLength:void 0,example:void 0,format:void 0})});default:So(d.v1)}},unknown:()=>Al.unknown({nameOverride:t,generatedName:r,title:i,example:void 0,description:n,availability:a,namespace:u,groupName:l}),map:({keyType:d,valueType:s})=>d?.type==="primitive"&&s!=null?Al.map({nameOverride:t,generatedName:r,title:i,key:d,value:s,description:n,availability:a,namespace:u,groupName:l,encoding:void 0,example:void 0,inline:void 0}):void 0,list:d=>d!=null?Al.array({nameOverride:t,generatedName:r,title:i,value:d,description:n,availability:a,namespace:u,groupName:l,example:void 0,inline:void 0}):void 0,optional:d=>d!=null?Al.optional({nameOverride:t,generatedName:r,title:i,value:d,description:n,availability:a,namespace:u,groupName:l,inline:void 0}):void 0,nullable:d=>d!=null?Al.nullable({nameOverride:t,generatedName:r,title:i,value:d,description:n,availability:a,namespace:u,groupName:l,inline:void 0}):void 0,set:d=>d!=null?Al.array({nameOverride:t,generatedName:r,title:i,value:d,description:n,availability:a,namespace:u,groupName:l,example:void 0,inline:void 0}):void 0,literal:d=>Al.literal({nameOverride:t,generatedName:r,title:i,value:d._visit({string:s=>Kz.string(s),boolean:s=>Kz.boolean(s),_other:()=>{throw new Error("Unexpected literal type")}}),description:n,availability:a,namespace:u,groupName:l}),named:d=>Al.reference({schema:d,nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:l,source:nK.openapi({file:"<memory>"})})}})}function M1_(e){let t=of(e,Kf.SOURCE);if(t!=null)return t.endsWith(".proto")?nK.protobuf({file:t}):nK.openapi({file:t})}function ian(e){if(e!=null&&typeof e=="boolean")return e}function Kd(e){return e.$ref!=null}function A1_({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,additionalProperties:n,description:a,availability:u,wrapAsNullable:l,context:d,namespace:s,groupName:o,example:c,encoding:b,source:g}){return n===void 0&&(n=d.options.additionalPropertiesDefaultsTo),typeof n=="boolean"||MKn(n,d.options)?Cau({nameOverride:e,generatedName:t,title:r,wrapAsNullable:l,description:a,availability:u,keySchema:{nameOverride:void 0,generatedName:`${t}Key`,title:void 0,description:void 0,availability:void 0,schema:ap.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:void 0}),namespace:void 0,groupName:void 0},valueSchema:Al.unknown({nameOverride:void 0,generatedName:`${t}Value`,title:void 0,description:void 0,availability:void 0,example:void 0,namespace:void 0,groupName:void 0}),namespace:s,groupName:o,example:c,encoding:b}):Cau({nameOverride:e,generatedName:t,title:r,wrapAsNullable:l,description:a,availability:u,keySchema:{nameOverride:void 0,generatedName:`${t}Key`,title:void 0,description:void 0,availability:void 0,schema:ap.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:void 0}),namespace:void 0,groupName:void 0},valueSchema:q1_(j0(n,d.options.optionalAdditionalProperties?l:!1,d,[...i,"Value"],g,s,void 0,void 0,void 0)),namespace:s,groupName:o,example:c,encoding:b})}function q1_(e){switch(e.type){case"array":case"enum":case"map":case"object":e.inline=!0;break;case"literal":case"primitive":case"reference":case"unknown":break;case"nullable":case"optional":e.inline=!0,e.value=q1_(e.value);break;case"oneOf":e.value.inline=!0;break;default:So(e)}return e}function Cau({nameOverride:e,generatedName:t,title:r,keySchema:i,valueSchema:n,wrapAsNullable:a,description:u,availability:l,namespace:d,groupName:s,example:o,encoding:c}){return a?Al.nullable({nameOverride:e,generatedName:t,title:r,value:Al.map({nameOverride:e,generatedName:t,title:r,description:u,availability:i.availability,key:i,value:n,namespace:d,groupName:s,encoding:c,example:o,inline:void 0}),description:u,availability:l,namespace:d,groupName:s,inline:void 0}):Al.map({nameOverride:e,generatedName:t,title:r,description:u,availability:l,key:i,value:n,namespace:d,groupName:s,encoding:c,example:o,inline:void 0})}function MKn(e,t){return e==null?t.additionalPropertiesDefaultsTo:typeof e=="boolean"?e:!Kd(e)&&Object.keys(e).length===0}function T1_({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,item:n,description:a,availability:u,wrapAsNullable:l,context:d,namespace:s,groupName:o,example:c,source:b}){let g=n==null?Al.unknown({nameOverride:e,generatedName:t,title:r,description:void 0,availability:void 0,example:void 0,namespace:s,groupName:o}):j0(n,!1,d,[...i,"Item"],b,s);return FNE({nameOverride:e,generatedName:t,title:r,namespace:s,groupName:o,itemSchema:g,wrapAsNullable:l,description:a,availability:u,example:c})}function FNE({nameOverride:e,generatedName:t,title:r,itemSchema:i,wrapAsNullable:n,description:a,availability:u,namespace:l,groupName:d,example:s}){return n?Al.nullable({nameOverride:e,generatedName:t,title:r,value:Al.array({nameOverride:e,generatedName:t,title:r,value:i,description:a,availability:u,namespace:l,groupName:d,example:s,inline:void 0}),description:a,availability:u,namespace:l,groupName:d,inline:void 0}):Al.array({nameOverride:e,generatedName:t,title:r,value:i,description:a,availability:u,namespace:l,groupName:d,example:s,inline:void 0})}function sK(e){switch(of(e,Kf.AVAILABILITY)){case"deprecated":return $H.Deprecated;case"beta":return $H.Beta;case"generally-available":return $H.GenerallyAvailable;default:break}if(!Kd(e)&&e.deprecated)return $H.Deprecated}function fSc({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,properties:n,description:a,availability:u,required:l,wrapAsNullable:d,discriminator:s,context:o,namespace:c,groupName:b,encoding:g,source:O}){let m=s.propertyName,w=Object.fromEntries(Object.entries(s.mapping??{}).map(([q,M])=>{let D=tPi({$ref:M},!1,o,[M],g,O,c);return o.markReferencedByDiscriminatedUnion({$ref:M},m,1),[q,D]})),E=Object.entries(n).filter(([q])=>q!==m).map(([q,M])=>{let D=l!=null&&l.includes(q),C=j0(M,!D,o,[...i,q],O,c);return{key:q,schema:C}});return C1_({nameOverride:e,generatedName:t,title:r,wrapAsNullable:d,properties:E,description:a,availability:u,discriminant:m,subtypes:w,namespace:c,groupName:b,source:O})}function dSc({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,properties:n,description:a,availability:u,required:l,wrapAsNullable:d,discriminant:s,variants:o,context:c,namespace:b,groupName:g,encoding:O,source:m}){let w=Object.fromEntries(Object.entries(o).map(([q,M])=>{if(Kd(M)){let D=tPi(M,!1,c,[M.$ref],O,m,b);return c.markReferencedByDiscriminatedUnion(M,s,1),[q,D]}else{let D=AKn(M,!1,c,[...i,q],O,m,b,new Set([s]));return[q,D]}})),E=Object.entries(n).filter(([q])=>q!==s).map(([q,M])=>{let D=l!=null&&l.includes(q),C=j0(M,!D,c,[...i,q],m,b);return{key:q,schema:C}});return C1_({nameOverride:e,generatedName:t,title:r,wrapAsNullable:d,properties:E,description:a,availability:u,discriminant:s,subtypes:w,namespace:b,groupName:g,source:m})}function C1_({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,properties:n,description:a,availability:u,discriminant:l,subtypes:d,namespace:s,groupName:o,source:c}){return i?Al.nullable({nameOverride:e,generatedName:t,title:r,value:Al.oneOf(aee.discriminated({description:a,availability:u,discriminantProperty:l,nameOverride:e,generatedName:t,title:r,schemas:d,commonProperties:n,namespace:s,groupName:o,encoding:void 0,source:c,inline:void 0})),namespace:s,groupName:o,description:a,availability:u,inline:void 0}):Al.oneOf(aee.discriminated({description:a,availability:u,discriminantProperty:l,nameOverride:e,generatedName:t,title:r,schemas:d,commonProperties:n,namespace:s,groupName:o,encoding:void 0,source:c,inline:void 0}))}function B1_(e){if(e.proto!=null)return KJn.protobuf({typeName:e.proto.type})}function KNi({nameOverride:e,generatedName:t,title:r,fernEnum:i,enumVarNames:n,enumValues:a,_default:u,description:l,availability:d,wrapAsNullable:s,namespace:o,groupName:c,context:b,source:g,inline:O}){let m=UNE(n??[]),w=new Set(a),E=Array.from(w).map((M,D)=>{let C=i?.[M],R=m[D],G=jKn.test(M),I=C?.name??R,L=G?M:wKn(M);return I!=null&&!jKn.test(I)&&(b?.logger.warn(`Enum name override ${I} is not a valid name. Falling back on ${L}.`),I=void 0),{nameOverride:I,generatedName:L,value:M,description:C?.description,availability:d,casing:{snake:C?.casing?.snake??void 0,pascal:C?.casing?.pascal??void 0,screamingSnake:C?.casing?.screamingSnake??void 0,camel:C?.casing?.camel??void 0}}}),q=u!=null?E.find(M=>M.value===u):void 0;return LNE({wrapAsNullable:s,nameOverride:e,generatedName:t,title:r,values:E,_default:q,description:l,availability:d,namespace:o,groupName:c,source:g,inline:O})}function LNE({wrapAsNullable:e,nameOverride:t,generatedName:r,title:i,values:n,_default:a,description:u,availability:l,namespace:d,groupName:s,source:o,inline:c}){return e?Al.nullable({nameOverride:t,generatedName:r,title:i,value:Al.enum({nameOverride:t,generatedName:r,title:i,values:n,description:u,default:a,availability:l,example:void 0,namespace:d,groupName:s,source:o,inline:c}),description:u,availability:l,namespace:d,groupName:s,inline:c}):Al.enum({nameOverride:t,generatedName:r,title:i,values:n,description:u,availability:l,default:a,example:void 0,namespace:d,groupName:s,source:o,inline:c})}function UNE(e){if(e.length<=1||e[0]==null)return e;let t=e[0],r=0;for(;t[r]!=null&&e.every(i=>i[r]===t[r]);)r++;return e.map(i=>i.substring(r))}function I1_({nameOverride:e,generatedName:t,title:r,format:i,_default:n,minimum:a,maximum:u,exclusiveMinimum:l,exclusiveMaximum:d,multipleOf:s,description:o,availability:c,wrapAsNullable:b,example:g,namespace:O,groupName:m}){return i==="int64"?G8({nameOverride:e,generatedName:t,title:r,primitive:ap.int64({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,namespace:O,groupName:m}):i==="uint32"?G8({nameOverride:e,generatedName:t,title:r,primitive:ap.uint({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,namespace:O,groupName:m}):i==="uint64"?G8({nameOverride:e,generatedName:t,title:r,primitive:ap.uint64({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,namespace:O,groupName:m}):G8({nameOverride:e,generatedName:t,title:r,primitive:ap.int({default:n,minimum:a,maximum:u,exclusiveMinimum:l,exclusiveMaximum:d,multipleOf:s,example:g}),wrapAsNullable:b,description:o,availability:c,namespace:O,groupName:m})}function z1_(e){return typeof e=="string"?Kz.string(e):typeof e=="boolean"?Kz.boolean(e):Kz.string(`${e}`)}function R1_({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,value:n,description:a,availability:u,namespace:l,groupName:d}){return i?Al.nullable({nameOverride:e,generatedName:t,title:r,value:Al.literal({nameOverride:e,generatedName:t,title:r,value:z1_(n),description:a,availability:u,namespace:l,groupName:d}),description:a,availability:u,namespace:l,groupName:d,inline:void 0}):Al.literal({nameOverride:e,generatedName:t,title:r,value:z1_(n),description:a,availability:u,namespace:l,groupName:d})}function pSc({nameOverride:e,generatedName:t,title:r,format:i,_default:n,minimum:a,maximum:u,exclusiveMinimum:l,exclusiveMaximum:d,multipleOf:s,description:o,availability:c,wrapAsNullable:b,example:g,namespace:O,groupName:m}){return i==null||i==="double"?G8({nameOverride:e,generatedName:t,title:r,primitive:ap.double({default:n,minimum:a,maximum:u,exclusiveMinimum:l,exclusiveMaximum:d,multipleOf:s,example:g}),wrapAsNullable:b,description:o,availability:c,namespace:O,groupName:m}):i==="float"?G8({nameOverride:e,generatedName:t,title:r,primitive:ap.float({example:g}),wrapAsNullable:b,description:o,availability:c,namespace:O,groupName:m}):i==="int32"?G8({nameOverride:e,generatedName:t,title:r,primitive:ap.int({default:n,minimum:a,maximum:u,exclusiveMinimum:l,exclusiveMaximum:d,multipleOf:s,example:g}),wrapAsNullable:b,description:o,availability:c,namespace:O,groupName:m}):i==="int64"?G8({nameOverride:e,generatedName:t,title:r,primitive:ap.int64({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,namespace:O,groupName:m}):i==="uint32"?G8({nameOverride:e,generatedName:t,title:r,primitive:ap.uint({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,namespace:O,groupName:m}):i==="uint64"?G8({nameOverride:e,generatedName:t,title:r,primitive:ap.uint64({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,namespace:O,groupName:m}):i==="time-delta"?G8({nameOverride:e,generatedName:t,title:r,primitive:ap.float({example:g}),wrapAsNullable:b,description:o,availability:c,namespace:O,groupName:m}):G8({nameOverride:e,generatedName:t,title:r,primitive:ap.float({example:g}),wrapAsNullable:b,description:o,availability:c,namespace:O,groupName:m})}var VNE={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="schemas",applyStrategy:e=>{let t=[e[3]??""];return{refUnderProcessing:e.slice(4),newBreadcrumbs:t}}},WNE={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="responses",applyStrategy:e=>{let t=[e[3]??""];return e=e.slice(4),{refUnderProcessing:e.slice(4),newBreadcrumbs:t}}},HNE={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="parameters",applyStrategy:e=>{let t=[e[3]??""];return e=e.slice(4),e[0]==="schema"&&(e=e.slice(1)),{refUnderProcessing:e,newBreadcrumbs:t}}},$NE={isApplicable:e=>e[0]==="properties",applyStrategy:e=>{let t=[e[1]??""];return{refUnderProcessing:e.slice(2),newBreadcrumbs:t}}},GNE={isApplicable:e=>e[0]==="items",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},QNE={isApplicable:e=>e[0]==="allOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},JNE={isApplicable:e=>e[0]==="anyOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},KNE={isApplicable:e=>e[0]==="oneOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})};function Bau(e){let t=e.split("/").map(a=>a.replace(/~1/g,"/")),r=[],i=[VNE,WNE,HNE,$NE,GNE,QNE,JNE,KNE],n;do{n=t;for(let a of i)if(a.isApplicable(t)){let{refUnderProcessing:u,newBreadcrumbs:l}=a.applyStrategy(t);t=u,r=[...r,...l]}}while(t.join("")!==n.join(""));return r}function Q8(e,t){let i=e.map(n=>/^[^a-zA-Z0-9]+$/.test(n)?n:qB(S_(n))).join("");return/^\d/.test(i)?U5a(i)??i:i}function _Sc(e){let t=e.join("_");return S_(t)}function iA(e){switch(e.type){case"object":return cv.object({allOf:e.allOf,properties:e.properties.map(t=>XNE(t)),allOfPropertyConflicts:e.allOfPropertyConflicts,description:e.description,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName,additionalProperties:e.additionalProperties,availability:e.availability,source:e.source,inline:e.inline});case"array":return cv.array({description:e.description,availability:e.availability,value:iA(e.value),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName,inline:e.inline});case"enum":return cv.enum({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,values:e.values,default:e.default,namespace:e.namespace,groupName:e.groupName,source:e.source,inline:e.inline});case"literal":return cv.literal({description:e.description,availability:e.availability,value:e.value,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName});case"nullable":return cv.nullable({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:iA(e.value),namespace:e.namespace,groupName:e.groupName,inline:e.inline});case"optional":return cv.optional({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:iA(e.value),namespace:e.namespace,groupName:e.groupName,inline:e.inline});case"primitive":return cv.primitive({description:e.description,availability:e.availability,schema:x1_(e.schema),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName});case"map":return cv.map({description:e.description,availability:e.availability,key:cv.primitive({description:e.key.description,availability:e.key.availability,schema:x1_(e.key.schema),generatedName:e.key.generatedName,title:e.key.title,nameOverride:e.key.nameOverride,namespace:e.namespace,groupName:e.groupName}),value:iA(e.value),generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,inline:e.inline});case"reference":return cv.reference({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schema:e.schema,namespace:e.namespace,groupName:e.groupName,source:e.source});case"oneOf":return cv.oneOf(YNE(e.value));case"unknown":return cv.unknown({nameOverride:e.nameOverride,generatedName:e.generatedName});default:So(e)}}function YNE(e){switch(e.type){case"discriminated":return Xmi.discriminated({commonProperties:e.commonProperties.map(t=>({key:t.key,schema:iA(t.schema)})),description:e.description,availability:e.availability,discriminantProperty:e.discriminantProperty,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schemas:Object.fromEntries(Object.entries(e.schemas).map(([t,r])=>[t,iA(r)])),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:e.inline});case"undiscriminated":return Xmi.undiscriminated({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schemas:e.schemas.map(t=>iA(t)),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:e.inline});default:So(e)}}function x1_(e){switch(e.type){case"string":return jw.string(e);case"base64":return jw.base64();case"boolean":return jw.boolean(e);case"date":return jw.date();case"datetime":return jw.datetime();case"double":return jw.double(e);case"float":return jw.float();case"int":return jw.int(e);case"int64":return jw.int64(e);case"uint":return jw.uint();case"uint64":return jw.uint64();default:So(e)}}function XNE(e){return{conflict:e.conflict,generatedName:e.generatedName,key:e.key,schema:iA(e.schema),audiences:e.audiences,nameOverride:e.nameOverride,availability:e.availability,readonly:e.readonly,writeonly:e.writeonly}}function Iau(e,t){return fue(iA(e),iA(t))}function N1_({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,properties:n,description:a,required:u,wrapAsNullable:l,allOf:d,context:s,propertiesToExclude:o,namespace:c,groupName:b,fullExamples:g,additionalProperties:O,availability:m,source:w}){let E=[...u??[]],q={...n},M=[],D=[];for(let I of d)if(Kd(I)){let L=s.resolveSchemaReference(I);if(L.discriminator!=null&&L.discriminator.mapping!=null)continue;if(L.oneOf!=null||L.anyOf!=null){let Y=L.oneOf??L.anyOf;if(Y!=null){for(let K of Y){let X=Kd(K)?s.resolveSchemaReference(K):K,oe=j0(X,!1,s.DUMMY,i,w,c);oe.type==="object"&&M.push(...oe.properties.map(pe=>pe.schema.type!=="optional"&&pe.schema.type!=="nullable"?{...pe,schema:Al.optional({nameOverride:void 0,generatedName:"",title:void 0,value:pe.schema,description:void 0,availability:pe.availability,namespace:void 0,groupName:void 0,inline:void 0})}:pe))}continue}}let V=YNi(I);if(V==null)continue;D.push({schemaId:V,convertedSchema:hSc(I,[V],w,s.options.preserveSchemaIds),properties:F1_({schema:I,context:s,breadcrumbs:i,source:w,namespace:c})}),s.markSchemaAsReferencedByNonRequest(V)}else{let L=j0(I,!1,s,i,w,c);L.type==="object"&&M.push(...L.properties)}let C={};for(let I of D)for(let[L,V]of Object.entries(I.properties)){let Y=C[L];Y!=null?(Y.schemaIds.push(I.schemaId),Y.schemas.some(X=>Iau(X,V))||Y.schemas.push(V)):C[L]={schemaIds:[I.schemaId],schemas:[V]}}let R=[];for(let[I,L]of Object.entries(C))L.schemaIds.length>1&&R.push({propertyKey:I,allOfSchemaIds:L.schemaIds,conflictingTypeSignatures:L.schemas.length>1});let G=Object.entries(q).map(([I,L])=>{let V=of(L,Kf.AUDIENCES)??[],Y=sK(L),K=Kd(L)?!1:L.readOnly,X=Kd(L)?!1:L.writeOnly,oe=E.includes(I)&&!K,pe=of(L,Kf.FERN_PROPERTY_NAME),de=[...i,I],Oe=_Sc(de),Ue=oe?j0(L,!1,s,de,w,c):Al.optional({nameOverride:e,generatedName:Oe,title:r,description:void 0,availability:Y,value:j0(L,!1,s,de,w,c),namespace:c,groupName:b,inline:void 0}),bt={};for(let De of D){let Te=De.properties[I];Te!=null&&!Iau(Ue,Te)?bt[De.schemaId]={differentSchema:!0}:Te!=null&&(bt[De.schemaId]={differentSchema:!1})}return{key:I,schema:Ue,nameOverride:pe,audiences:V,conflict:bt,generatedName:_Sc([...i,I]),availability:Y,readonly:K,writeonly:X}});return G.push(...M.map(I=>{let L=I.conflict;for(let V of D){let Y=V.properties[I.key];Y!=null&&!Iau(I.schema,Y)?L[V.schemaId]={differentSchema:!0}:Y!=null&&(L[V.schemaId]={differentSchema:!1})}return{...I,conflict:L}})),ZNE({nameOverride:e,generatedName:t,title:r,wrapAsNullable:l,properties:G.filter(I=>!o.has(I.key)),description:a,allOf:D.map(I=>I.convertedSchema),allOfPropertyConflicts:R,namespace:c,groupName:b,fullExamples:g,additionalProperties:O,availability:m,source:w,context:s})}function ZNE({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,properties:n,description:a,allOf:u,allOfPropertyConflicts:l,namespace:d,groupName:s,fullExamples:o,additionalProperties:c,availability:b,source:g,context:O}){return i?Al.nullable({nameOverride:e,generatedName:t,title:r,value:Al.object({description:a,properties:n,nameOverride:e,generatedName:t,title:r,allOf:u,allOfPropertyConflicts:l,namespace:d,groupName:s,fullExamples:o,additionalProperties:MKn(c,O.options),availability:void 0,source:g,inline:void 0}),description:a,availability:b,namespace:d,groupName:s,inline:void 0}):Al.object({description:a,properties:n,nameOverride:e,generatedName:t,title:r,allOf:u,allOfPropertyConflicts:l,namespace:d,groupName:s,fullExamples:o,additionalProperties:MKn(c,O.options),availability:b,source:g,inline:void 0})}function F1_({schema:e,context:t,breadcrumbs:r,source:i,namespace:n}){let a={},[u,l]=Kd(e)?[t.resolveSchemaReference(e),Bau(e.$ref)]:[e,r];for(let d of u.allOf??[])a={...a,...F1_({schema:d,context:t,breadcrumbs:l,source:i,namespace:n})};for(let[d,s]of Object.entries(u.properties??{})){let o=j0(s,!1,t,[...l,d],i,n);a[d]=o}return a}function XNi({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,description:n,availability:a,wrapAsNullable:u,context:l,subtypes:d,namespace:s,groupName:o,encoding:c,source:b,subtypePrefixOverrides:g}){let O=tFE({schemas:d}),m=d.flatMap((E,q)=>{if(!Kd(E)&&E.enum!=null&&l.options.coerceEnumsToLiterals&&E.type==="string")return E.enum.map(D=>Al.literal({nameOverride:void 0,generatedName:Q8([t,D],l.options.preserveSchemaIds),title:void 0,value:Kz.string(String(D)),namespace:s,groupName:void 0,description:void 0,availability:D.availability}));let M=O[q];if(g!=null){let D=g[q];D!=null&&"name"in D&&(M=D.name)}return[j0(E,!1,l,[...i,M??`${q}`],b,s)]}),w=kNE(m);return eFE({uniqueSubtypes:w,nameOverride:e,generatedName:t,title:r,wrapAsNullable:u,description:n,availability:a,namespace:s,groupName:o,context:l,encoding:c,source:b})}function kNE(e){let t=[];for(let r=0;r<e.length;++r){let i=e[r],n=!1;for(let a=r+1;a<e.length;++a){let u=e[a];if(i!=null&&u!=null&&fue(i,u)){n=!0;break}}i!=null&&!n&&t.push(i)}return t}function eFE({uniqueSubtypes:e,nameOverride:t,generatedName:r,title:i,wrapAsNullable:n,description:a,availability:u,namespace:l,groupName:d,context:s,encoding:o,source:c}){if(Object.entries(e).every(([g,O])=>O.type==="literal")){let g={},O=[];return Object.entries(e).forEach(([m,w])=>{w.type==="literal"&&w.value.type==="string"&&(O.push(w.value.value),w.description!=null&&(g[w.value.value]={description:w.description}))}),KNi({nameOverride:t,generatedName:r,title:i,wrapAsNullable:n,description:a,availability:u,fernEnum:g,enumVarNames:void 0,enumValues:O,_default:void 0,namespace:l,groupName:d,context:s,source:c,inline:void 0})}return e.length===1&&e[0]!=null&&!s.options.preserveSingleSchemaOneOf?e[0]:L1_({nameOverride:t,generatedName:r,title:i,wrapAsNullable:n,description:a,availability:u,subtypes:e,namespace:l,groupName:d,encoding:o,source:c})}function ySc({nameOverride:e,generatedName:t,title:r,description:i,availability:n,wrapAsNullable:a,context:u,namespace:l,groupName:d,discriminator:s,encoding:o,source:c}){let b=Object.entries(s.mapping??{}).map(([m,w],E)=>{let q={$ref:w},M=tPi(q,!1,u,[w],o,c,l);return u.markSchemaWithDiscriminantValue(q,s.propertyName,m),M.type==="object"&&(M.properties={[s.propertyName]:Al.literal({nameOverride:void 0,generatedName:Q8([t,m],u.options.preserveSchemaIds),title:void 0,value:Kz.string(m),namespace:void 0,groupName:void 0,description:void 0,availability:void 0}),...M.properties.filter(D=>D.key!==s.propertyName)}),M}),g=[];for(let m=0;m<b.length;++m){let w=b[m],E=!1;for(let q=m+1;q<b.length;++q){let M=b[q];if(w!=null&&M!=null&&fue(w,M)){E=!0;break}}w!=null&&!E&&g.push(w)}if(Object.entries(g).every(([m,w])=>w.type==="literal")){let m={},w=[];return Object.entries(g).forEach(([E,q])=>{q.type==="literal"&&q.value.type==="string"&&(w.push(q.value.value),q.description!=null&&(m[q.value.value]={description:q.description}))}),KNi({nameOverride:e,generatedName:t,title:r,wrapAsNullable:a,description:i,availability:n,fernEnum:m,enumVarNames:void 0,enumValues:w,_default:void 0,namespace:l,groupName:d,context:u,source:c,inline:void 0})}return g.length===1&&g[0]!=null&&!u.options.preserveSingleSchemaOneOf?g[0]:L1_({nameOverride:e,generatedName:t,title:r,wrapAsNullable:a,description:i,availability:n,subtypes:g,namespace:l,groupName:d,encoding:o,source:c})}function tFE({schemas:e}){let t={},r=0;for(let a of e){if(!Kd(a)){if(a.properties!=null&&Object.entries(a.properties).length>0){let u=Object.keys(a.properties),l={},d=u;for(let[s,o]of Object.entries(t)){let c=RAo(o,u);d=RAo(d,o),l[s]=c}l[r]=d,t=l}}r++}let i=[],n=0;for(let a of e){let u=t[n];if(u!=null&&u.length>0){let l=u.sort();if(l[0]!=null){i.push(l[0]),++n;continue}}Kd(a)?i.push($Ni(n)??`${n}`):a.type==="array"||a.type==="boolean"||a.type==="integer"||a.type==="number"||a.type==="string"?i.push(""):i.push($Ni(n)??`${n}`),++n}return i}function L1_({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,description:n,availability:a,subtypes:u,namespace:l,groupName:d,encoding:s,source:o}){return i?Al.nullable({nameOverride:e,generatedName:t,title:r,value:Al.oneOf(aee.undiscriminated({description:n,availability:a,nameOverride:e,generatedName:t,title:r,schemas:u,namespace:l,groupName:d,encoding:s,source:o,inline:void 0})),description:n,availability:a,namespace:l,groupName:d,inline:void 0}):Al.oneOf(aee.undiscriminated({description:n,availability:a,nameOverride:e,generatedName:t,title:r,schemas:u,namespace:l,groupName:d,encoding:s,source:o,inline:void 0}))}function qKn(e){if(e.default!=null&&typeof e.default=="string")return e.default}function zau({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="number")return e.example;let i=ran(e);for(let n of i??[])if(typeof n=="number")return n;if(r&&typeof r=="number")return r}function U1_({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="boolean")return e.example;let i=ran(e);for(let n of i??[])if(typeof n=="boolean")return n;if(r&&typeof r=="boolean")return r}function Sor({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="string")return e.example;let i=ran(e);for(let n of i??[])if(typeof n=="string")return n;if(r&&typeof r=="string")return r}function V1_({schema:e,logger:t,fallback:r}){if(e.example!=null&&Array.isArray(e.example))return e.example;let i=ran(e);for(let n of i??[])if(Array.isArray(n))return n;if(r&&Array.isArray(r))return r}var nan="#/components/schemas/";function j0(e,t,r,i,n,a,u=!1,l=new Set,d){let s=M1_(e)??n,o=cFE({schema:e,logger:r.logger});if(Kd(e)){let c=YNi(e);return c!=null?(u?r.markSchemaAsReferencedByRequest(c):r.markSchemaAsReferencedByNonRequest(c),tPi(e,t,r,i,o,s,a)):AKn(r.resolveSchemaReference(e),t,r,Bau(e.$ref),o,s,a,l,u,d)}return AKn(e,t,r,i,o,s,a,l,u,d)}function tPi(e,t,r,i,n,a,u){let l=e.$ref.includes("properties")?AKn(r.resolveSchemaReference(e),t,r,i,n,a,u,new Set):Al.reference(hSc(e,i,a,r.options.preserveSchemaIds));return t?Al.nullable({title:void 0,nameOverride:void 0,generatedName:Q8(i,r.options.preserveSchemaIds),value:l,description:void 0,availability:void 0,namespace:void 0,groupName:void 0,inline:void 0}):l}function rFE(e){if(e!=null&&!e.includes(" ")&&/^[a-zA-Z]+$/.test(e))return e}function AKn(e,t,r,i,n,a,u,l=new Set,d=!1,s){typeof e=="string"&&(e={type:e});let o=of(e,Kf.TYPE_NAME)??(r.options.useTitlesAsName?rFE(e.title):void 0),c=of(e,Kf.SDK_GROUP_NAME)??of(e,JH.TAGS)?.[0],b=(typeof c=="string"?[c]:c)??[];b=r.resolveGroupName(b);let g=Q8(i,r.options.preserveSchemaIds),O=e.title,m=e.description,w=sK(e),E=[];e.example!=null&&E.push({name:void 0,value:e.example,description:void 0});let q=of(e,JH.EXAMPLES);q!=null&&Object.keys(q).length>0&&E.push(...Object.entries(q).map(([C,R])=>({name:R?.summary??C,value:R.value,description:R.description})));let M=ran(e);M!=null&&Object.keys(M).length>0&&E.push(...M.map(C=>({name:void 0,value:C,description:void 0})));let D=E1_({schema:e,description:m,title:O,nameOverride:o,generatedName:g,availability:w});if(D!=null)return D;if(Array.isArray(e.type)){let C=e.type.indexOf("null"),R=C!==-1;if(e.type.length===1)e.type=e.type[0];else if(e.type.length===2&&R)e.type.splice(C,1),e.type=e.type[0],e.nullable=!0;else if(R&&(e.type.splice(C,1),e.nullable=!0),e.oneOf==null)e.oneOf=[...new Set(e.type)];else{let G=new Set([...e.oneOf,...e.type]);e.oneOf=[...G]}}if(!t&&e.nullable===!0)return AKn(e,!0,r,i,n,a,u,l,d,s);if(e.enum!=null&&(e.type==="string"||e.type==null||e.type==="enum")){if(!Nau(e.enum))return G8({nameOverride:o,generatedName:g,title:O,primitive:ap.string({default:qKn(e),minLength:e.minLength,maxLength:e.maxLength,pattern:e.pattern,format:e.format,example:Sor({schema:e,logger:r.logger,fallback:s})}),namespace:u,groupName:b,wrapAsNullable:t,description:m,availability:w});let C=D1_(e);return e.enum.length===1&&e.enum[0]!=null&&C==null?R1_({nameOverride:o,generatedName:g,title:O,wrapAsNullable:t,value:e.enum[0],description:m,availability:w,namespace:u,groupName:b}):KNi({nameOverride:o,generatedName:g,title:O,fernEnum:C,enumVarNames:of(e,[JH.ENUM_VAR_NAMES]),enumValues:e.enum,_default:e.default,description:m,availability:w,wrapAsNullable:t,namespace:u,groupName:b,context:r,source:a,inline:void 0})}if(Nau(e.type)&&e.type.length>1){let C=e.type.includes("null"),R=e.type.filter(G=>G!=="null").map(G=>({type:G,nullable:C}));return XNi({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,wrapAsNullable:t,context:r,subtypes:R,namespace:u,groupName:b,encoding:n,source:a})}if(e.type==="boolean"){let C=of(e,Kf.BOOLEAN_LITERAL);return C!=null?W1_({nameOverride:o,generatedName:g,title:O,literal:Kz.boolean(C),wrapAsNullable:t,description:m,availability:w,namespace:u,groupName:b}):G8({nameOverride:o,generatedName:g,title:O,primitive:ap.boolean({default:iFE(e.default),example:U1_({schema:e,logger:r.logger,fallback:s})}),wrapAsNullable:t,description:m,availability:w,namespace:u,groupName:b})}if(e.type==="number")return pSc({nameOverride:o,generatedName:g,title:O,format:e.format,_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:ian(e.exclusiveMinimum),exclusiveMaximum:ian(e.exclusiveMaximum),multipleOf:e.multipleOf,description:m,availability:w,wrapAsNullable:t,example:zau({schema:e,logger:r.logger,fallback:s}),namespace:u,groupName:b});if(e.type==="integer")return I1_({nameOverride:o,generatedName:g,title:O,format:e.format,_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:ian(e.exclusiveMinimum),exclusiveMaximum:ian(e.exclusiveMaximum),multipleOf:e.multipleOf,description:m,availability:w,wrapAsNullable:t,example:zau({schema:e,logger:r.logger,fallback:s}),namespace:u,groupName:b});if(e.type==="float")return pSc({nameOverride:o,generatedName:g,title:O,format:"float",_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:ian(e.exclusiveMinimum),exclusiveMaximum:ian(e.exclusiveMaximum),multipleOf:e.multipleOf,description:m,availability:w,wrapAsNullable:t,example:zau({schema:e,logger:r.logger,fallback:s}),namespace:u,groupName:b});if(e.type==="string"){if(e.format==="date-time")return G8({nameOverride:o,generatedName:g,title:O,primitive:ap.datetime({example:Sor({schema:e,logger:r.logger,fallback:s})}),wrapAsNullable:t,description:m,availability:w,namespace:u,groupName:b});if(e.format==="date"&&r.options.typeDatesAsStrings===!1)return G8({nameOverride:o,generatedName:g,title:O,primitive:ap.date({example:Sor({schema:e,logger:r.logger,fallback:s})}),wrapAsNullable:t,description:m,availability:w,namespace:u,groupName:b});if(e.format==="json-string")return Al.unknown({nameOverride:o,generatedName:g,title:O,description:m,availability:w,namespace:u,groupName:b,example:void 0});let C=G1_(e,"const");return C!=null?W1_({nameOverride:o,generatedName:g,title:O,literal:Kz.string(C),wrapAsNullable:t,description:m,availability:w,namespace:u,groupName:b}):G8({nameOverride:o,generatedName:g,title:O,primitive:ap.string({default:qKn(e),pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:Sor({schema:e,logger:r.logger,fallback:s})}),namespace:u,groupName:b,wrapAsNullable:t,description:m,availability:w})}if(e.type==="array")return T1_({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,item:e.items,description:m,availability:w,wrapAsNullable:t,context:r,namespace:u,groupName:b,example:V1_({schema:e,logger:r.logger,fallback:s}),source:a});if(e.additionalProperties!=null&&e.additionalProperties!==!1&&Rau(e))return A1_({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,additionalProperties:e.additionalProperties,description:m,availability:w,wrapAsNullable:t,context:r,namespace:u,groupName:b,encoding:n,example:e.example,source:a});if(e.oneOf!=null&&e.oneOf.length>0&&of(e,Kf.IS_DISCRIMINATED)===!1)return XNi({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,wrapAsNullable:t,context:r,subtypes:e.oneOf,namespace:u,groupName:b,encoding:n,source:a});if(e.type==="object"&&e.discriminator!=null&&e.discriminator.mapping!=null)return r.options.discriminatedUnionV2?ySc({nameOverride:o,generatedName:g,title:O,description:m,availability:w,wrapAsNullable:t,context:r,namespace:u,groupName:b,discriminator:e.discriminator,encoding:n,source:a}):fSc({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,discriminator:e.discriminator,properties:e.properties??{},required:e.required,wrapAsNullable:t,context:r,namespace:u,groupName:b,encoding:n,source:a});if(e.oneOf!=null&&e.oneOf.length>0){let C=of(e,Kf.IS_UNDISCRIMINATED);if(e.discriminator!=null&&e.discriminator.mapping!=null&&Object.keys(e.discriminator.mapping).length>0)return r.options.discriminatedUnionV2||C?ySc({nameOverride:o,generatedName:g,title:O,description:m,availability:w,wrapAsNullable:t,context:r,namespace:u,groupName:b,discriminator:e.discriminator,encoding:n,source:a}):fSc({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,discriminator:e.discriminator,properties:e.properties??{},required:e.required,wrapAsNullable:t,context:r,namespace:u,groupName:b,encoding:n,source:a});if(e.oneOf.length===1&&e.oneOf[0]!=null){if(r.options.preserveSingleSchemaOneOf)return XNi({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,wrapAsNullable:t,context:r,subtypes:e.oneOf.filter(G=>Kd(G)||G.type!=="null"),encoding:n,namespace:u,groupName:b,source:a});let R=j0(e.oneOf[0],t,r,i,a,u,d);return TKn(R,m,u,b)}else if(e.oneOf.length>1){if(e.oneOf.length===2&&e.oneOf[0]!=null&&e.oneOf[1]!=null){let L=e.oneOf[0],V=e.oneOf[1];if(!Kd(L)&&L.type==="null")return j0(V,!0,r,i,a,u);if(!Kd(V)&&V.type==="null")return j0(L,!0,r,i,a,u)}let R=oFE({schemas:e.oneOf});if(R!=null)return KNi({nameOverride:o,generatedName:g,title:O,fernEnum:void 0,enumVarNames:void 0,enumValues:R,_default:e.default,description:m,availability:w,wrapAsNullable:t,namespace:u,groupName:b,context:r,source:a,inline:void 0});let G=H1_({schemas:e.oneOf,context:r});if(G!=null&&!r.options.discriminatedUnionV2&&!C)return dSc({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,properties:e.properties??{},required:e.required,description:m,availability:w,wrapAsNullable:t,discriminant:G.discriminant,variants:G.schemas,context:r,namespace:u,groupName:b,encoding:n,source:a});let I=e.oneOf.filter(L=>!Kd(L)&&L.type==="null").length>0;return XNi({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,wrapAsNullable:t||I,context:r,subtypes:e.oneOf.filter(L=>Kd(L)||L.type!=="null"),encoding:n,namespace:u,groupName:b,source:a})}}if(e.anyOf!=null&&e.anyOf.length>0){if(e.anyOf.length===1&&e.anyOf[0]!=null){let G=j0(e.anyOf[0],t,r,i,a,u,d);return TKn(G,m,u,b)}if(e.anyOf.length===2){let[G,I]=e.anyOf;if(G!=null&&I!=null){if(!Kd(G)&&G.type==="null"){let L=j0(I,!0,r,i,a,u);return TKn(L,m,u,b)}else if(!Kd(I)&&I.type==="null"){let L=j0(G,!0,r,i,a,u);return TKn(L,m,u,b)}}}let C=H1_({schemas:e.anyOf,context:r});if(C!=null&&!r.options.discriminatedUnionV2)return dSc({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,properties:e.properties??{},required:e.required,description:m,availability:w,wrapAsNullable:t,discriminant:C.discriminant,variants:C.schemas,context:r,namespace:u,groupName:b,encoding:n,source:a});let R=e.anyOf.filter(G=>!Kd(G)&&G.type==="null").length>0;return XNi({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,wrapAsNullable:t||R,context:r,subtypes:e.anyOf.filter(G=>Kd(G)||G.type!=="null"),encoding:n,namespace:u,groupName:b,source:a})}if(e.allOf!=null||e.properties!=null){let C=[];for(let G of e.allOf??[])(Kd(G)||Object.keys(G).length>0)&&C.push(G);if((e.properties==null||Rau(e))&&C.length===1&&C[0]!=null){let G=j0(C[0],t,r,i,a,u,d);return TKn(G,m,u,b)}let R=C.filter(G=>{let I=xau(G);return I||r.logger.warn(`Skipping non-object allOf element: ${JSON.stringify(G)}`),I});if((e.properties==null||Rau(e))&&R.length===1&&R[0]!=null){let G=j0(R[0],t,r,i,a,u,d);return TKn(G,m,u,b)}return N1_({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,properties:e.properties??{},description:m,required:e.required,wrapAsNullable:t,allOf:R,context:r,propertiesToExclude:l,namespace:u,groupName:b,fullExamples:E,additionalProperties:e.additionalProperties,availability:w,encoding:n,source:a})}if(e.type==="object"&&nFE(e)&&aFE(e)&&Rau(e))return Cau({nameOverride:o,generatedName:g,title:O,description:m,availability:w,wrapAsNullable:t,keySchema:{nameOverride:void 0,generatedName:`${g}Key`,title:void 0,description:void 0,availability:void 0,schema:ap.string({default:qKn(e),pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:Sor({schema:e,logger:r.logger,fallback:s})}),namespace:u,groupName:b},valueSchema:Al.unknown({nameOverride:void 0,generatedName:`${g}Value`,title:void 0,description:void 0,availability:void 0,example:void 0,namespace:u,groupName:b}),namespace:u,groupName:b,encoding:n,example:e.example});if(e.type==null){let C=e.example??e.default;return Al.unknown({nameOverride:o,generatedName:g,title:O,description:m,availability:w,namespace:u,groupName:b,example:C})}throw new Error(`Failed to convert schema breadcrumbs=${JSON.stringify(i)} value=${JSON.stringify(e)}`)}function iFE(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 YNi(e){if(e.$ref.startsWith(nan))return e.$ref.replace(nan,"")}function hSc(e,t,r,i){let n=of(e,Kf.TYPE_NAME),a=Q8(t,i),u=e.description,l=sK(e),d=YNi(e);if(d==null)throw new Error(`Invalid schema reference ${JSON.stringify(e)}`);return cv.reference({generatedName:a,nameOverride:n,title:void 0,schema:d,description:u??void 0,availability:l,namespace:void 0,groupName:void 0,source:r})}function nFE(e){return e.oneOf==null||e.oneOf.length===0}function aFE(e){return e.allOf==null||e.allOf.length===0}function Rau(e){return e.properties==null||yq(e.properties)===0}function Nau(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function TKn(e,t,r,i){return e.type==="reference"?Al.reference({...e,description:t,availability:e.availability,namespace:r,groupName:i}):e.type==="optional"?Al.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:t,availability:e.availability,namespace:r,groupName:i,inline:void 0}):e.type==="nullable"?Al.nullable({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:t,availability:e.availability,namespace:r,groupName:i,inline:void 0}):e}function xau(e){return Kd(e)||e.type==="object"||e.properties!=null?!0:e.allOf!=null?e.allOf.every(t=>xau(t)):e.oneOf!=null?e.oneOf.every(t=>xau(t)):e.anyOf!=null?e.anyOf.every(t=>xau(t)):!1}function W1_({literal:e,wrapAsNullable:t,namespace:r,groupName:i,description:n,availability:a,nameOverride:u,generatedName:l,title:d}){return t?Al.nullable({nameOverride:u,generatedName:l,title:d,value:Al.literal({nameOverride:u,generatedName:l,title:d,value:e,description:n,availability:a,namespace:r,groupName:i}),namespace:r,groupName:i,description:n,availability:a,inline:void 0}):Al.literal({nameOverride:u,generatedName:l,title:d,value:e,namespace:r,groupName:i,description:n,availability:a})}function G8({primitive:e,wrapAsNullable:t,namespace:r,groupName:i,description:n,availability:a,generatedName:u,nameOverride:l,title:d}){return i=typeof i=="string"?[i]:i,t?Al.nullable({nameOverride:l,generatedName:u,title:d,value:Al.primitive({nameOverride:l,generatedName:u,title:d,schema:e,description:n,availability:a,namespace:r,groupName:i}),namespace:r,groupName:i,description:n,availability:a,inline:void 0}):Al.primitive({nameOverride:l,generatedName:u,title:d,schema:e,description:n,availability:a,namespace:r,groupName:i})}function oFE({schemas:e}){let t=new Set;for(let r of e){if(Kd(r))return;if(r.enum!=null&&Nau(r.enum))r.enum.forEach(i=>t.add(i));else return}return Array.from(t)}function H1_({schemas:e,context:t}){let r={};for(let i of e){let n=$1_({schema:i,context:t});for(let[a,u]of Object.entries(n)){let l=r[a];l!=null?l[u]=i:r[a]={[u]:i}}}for(let[i,n]of Object.entries(r))if(Object.keys(n).length===e.length)return{discriminant:i,schemas:n}}function $1_({schema:e,context:t}){let r=Kd(e)?t.resolveSchemaReference(e):e;return uFE({schema:r,context:t})}function uFE({schema:e,context:t}){let r={};if(e.anyOf!=null){for(let i of e.anyOf){let n=$1_({schema:i,context:t});for(let[a,u]of Object.entries(n??{}))r[a]=u}return r}for(let[i,n]of Object.entries(e.properties??{})){let a=Kd(n)?t.resolveSchemaReference(n):n;a.type==="string"&&a.enum!=null&&Nau(a.enum)&&sFE(a.enum).length===1&&a.enum[0]!=null&&(r[i]=a.enum[0]);let u=G1_(a,"const");a.type==="string"&&u!=null&&(r[i]=u),i==="type"&&a.example!=null&&(r[i]=a.example)}return r}function sFE(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 G1_(e,t){let r=e[t];if(r!=null)return r}function cFE({schema:e,logger:t}){let r=S1_({schema:e,logger:t});if(r!=null)return B1_(r)}var CKn=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(nan))throw new Error(`Failed to resolve schema reference: ${t.$ref}`);let i=t.$ref.substring(nan.length).split("/"),n=this.document.components;if(n==null||n.schemas==null)throw new Error("Document does not have components.schemas.");let[a,u,l]=i;if(a==null||a==="")throw new Error(`${t.$ref} cannot be resolved. No schema key provided.`);let d=n.schemas[a];if(d==null)throw new Error(`Schema "${a}" is undefined in document.components.schemas.`);if(Kd(d)&&(d=this.resolveSchemaReference(d)),u==="properties"&&l!=null){let s=d.properties?.[l];if(s==null)throw new Error(`Property "${l}" not found on "${a}". Full ref: ${t.$ref}`);Kd(s)?d=this.resolveSchemaReference(s):d=s}return d}referenceExists(t){let r=t.substring(2).split("/").map(n=>n.replace(/~1/g,"/")),i=this.document;for(let n of r){if(typeof i!="object"||i==null)return!1;i=i[n]}return!0}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}markReferencedByDiscriminatedUnion(t,r,i){}markSchemaWithDiscriminantValue(t,r,i){}};var Fau=class extends CKn{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 BKn(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 u=a.namespace;i[u]??={},i[u][n]=a;continue}case"oneOf":case"unknown":r[n]=a;continue;default:So(a)}return{rootSchemas:r,namespacedSchemas:i}}function ZNi(e){if(typeof e=="string")return xg.primitive(h_.string(e));if(typeof e=="number")return Number.isInteger(e)?xg.primitive(h_.int(e)):xg.primitive(h_.double(e));if(typeof e=="boolean")return xg.primitive(h_.boolean(e));if(Array.isArray(e)){let t=e.map(r=>ZNi(r));return t.length===0?void 0:xg.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=ZNi(i);n!=null&&t.push({key:h_.string(r),value:n})}return xg.map(t)}}function Y5a(e){if(e!=null&&typeof e=="object"&&Object.keys(e).every(t=>typeof t=="string"))return e}function Q1_(e){if(e!=null&&Array.isArray(e))return e}var kNi=class{schemas;nonRequestReferencedSchemas;context;constructor(t,r,i){this.schemas=t,this.nonRequestReferencedSchemas=r,this.context=i}buildExample({schema:t,exampleId:r,example:i,options:n,skipReadonly:a}){return this.buildExampleHelper({schema:t,visitedSchemaIds:new Set,exampleId:r,example:i,options:{...n,maxCheckerDepth:n.maxCheckerDepth??5},depth:0,skipReadonly:a??!1})}buildExampleHelper({exampleId:t,example:r,schema:i,depth:n,visitedSchemaIds:a,options:u,skipReadonly:l}){switch(i.type){case"enum":return typeof r=="string"&&J1_({schema:i,value:r})?xg.enum(r):i.values[0]!=null?xg.enum(i.values[0]?.value):void 0;case"literal":return xg.literal(i.value);case"nullable":{if(r==null&&!this.hasExample(i.value,0,a,u)&&(u.ignoreOptionals||this.exceedsMaxDepth(n,u)))return;let d=this.buildExampleHelper({schema:i.value,visitedSchemaIds:a,exampleId:t,example:r,depth:n,options:u,skipReadonly:l});return d!=null&&d.type==="array"&&d.value.length===0||d!=null&&d.type==="map"&&d.value.length===0||d!=null&&d.type==="object"&&Object.keys(d.properties).length===0?void 0:d}case"optional":{if(r==null&&!this.hasExample(i.value,0,a,u)&&(u.ignoreOptionals||this.exceedsMaxDepth(n,u))||Object.is(r,null))return;let d=this.buildExampleHelper({schema:i.value,visitedSchemaIds:a,exampleId:t,example:r,depth:n,options:u,skipReadonly:l});return d!=null&&d.type==="array"&&d.value.length===0||d!=null&&d.type==="map"&&d.value.length===0||d!=null&&d.type==="object"&&Object.keys(d.properties).length===0?void 0:d}case"primitive":{let d=this.buildExampleFromPrimitive({schema:i.schema,example:r,options:u});return xg.primitive(d)}case"reference":{let d=this.schemas[i.schema];if(d!=null&&!a.has(i.schema)){a.add(i.schema);let s=d?.type==="object"&&!this.nonRequestReferencedSchemas.has(i.schema),o=this.buildExampleHelper({example:r,schema:d,exampleId:t,visitedSchemaIds:a,depth:n,options:u,skipReadonly:s||this.context.options.respectReadonlySchemas?l:!1});return a.delete(i.schema),o}return}case"oneOf":switch(i.value.type){case"discriminated":{let d={},s={},o={},c=Y5a(r),b=c?.[i.value.discriminantProperty],g=i.value.schemas[b],O=[],m=this.getDiscriminatedUnionVariantSchema(i.value,c);m!=null&&O.push(m),O.push(...Object.entries(i.value.schemas));for(let w of O)if(b!=null&&g!=null&&g.type==="object"){s=this.getAllProperties(g),o=this.getAllRequiredProperties(g),d[i.value.discriminantProperty]=xg.primitive(h_.string(b));break}else{let E=this.buildExampleHelper({exampleId:t,schema:w[1],example:void 0,visitedSchemaIds:a,depth:n,options:u,skipReadonly:l});if(E!=null){this.mergeExampleWith(E,d),d[i.value.discriminantProperty]=xg.primitive(h_.string(w[0]));break}}for(let w of i.value.commonProperties){s[w.key]={schema:w.schema,readonly:!1};let E=this.getResolvedSchema(w.schema);E.type!=="optional"&&E.type!=="nullable"&&(o[w.key]=w.schema)}for(let[w,E]of Object.entries(s)){let q=w in o;if(q&&c?.[w]!=null){let M=this.buildExampleHelper({schema:E.schema,exampleId:t,example:c[w],visitedSchemaIds:a,depth:n+1,options:u,skipReadonly:l});if(M!=null)d[w]=M;else return}else{let M=this.buildExampleHelper({exampleId:t,schema:E.schema,example:c?.[w],visitedSchemaIds:a,depth:n+1,options:u,skipReadonly:l});if(M!=null)d[w]=M;else if(q)return}}return xg.oneOf(RNi.discriminated(d))}case"undiscriminated":{let d=this.getUnDiscriminatedUnionVariantSchema(i.value,r);if(d!=null)return this.buildExampleHelper({exampleId:t,example:r,schema:d,visitedSchemaIds:a,depth:n,options:u,skipReadonly:l});break}}return;case"unknown":if(r!=null){let d=ZNi(r);if(d!=null)return xg.unknown(d)}return u.ignoreOptionals||this.exceedsMaxDepth(n,u)?void 0:u.isParameter?xg.primitive(h_.string(u.name??"string")):xg.map([{key:h_.string("key"),value:xg.primitive(h_.string("value"))}]);case"array":{let d=Q1_(r),s=[];if(d!=null&&d.length>0)for(let o of d){let c=this.buildExampleHelper({exampleId:t,example:o,schema:i.value,depth:n+1,visitedSchemaIds:a,options:u,skipReadonly:l});c!=null&&s.push(c)}else if(i.example!=null&&i.example.length>0)for(let o of i.example){let c=this.buildExampleHelper({exampleId:t,example:o,schema:i.value,depth:n+1,visitedSchemaIds:a,options:u,skipReadonly:l});c!=null&&s.push(c)}else{let o=this.buildExampleHelper({exampleId:t,example:void 0,schema:i.value,depth:n+1,visitedSchemaIds:a,options:u,skipReadonly:l});o!=null&&s.push(o)}return xg.array(s)}case"map":{let d=Y5a(r??i.example);if(d!=null&&Object.entries(d).length>0){let c=[];for(let[b,g]of Object.entries(d)){let O=this.buildExampleFromPrimitive({schema:i.key.schema,example:b,options:u}),m=this.buildExampleHelper({exampleId:t,example:g,schema:i.value,visitedSchemaIds:a,depth:n+1,options:u,skipReadonly:l});m!=null&&c.push({key:O,value:m})}return xg.map(c)}if(i.key.schema.type==="string"&&i.value.type==="unknown")return xg.map([{key:h_.string("key"),value:xg.unknown(xg.primitive(h_.string("value")))}]);let s=this.buildExampleFromPrimitive({schema:i.key.schema,example:void 0,options:{...u,name:"key"}}),o=this.buildExampleHelper({exampleId:t,example:void 0,schema:i.value,visitedSchemaIds:a,depth:n+1,options:{...u,name:"value"},skipReadonly:l});return o!=null?xg.map([{key:s,value:o}]):xg.map([])}case"object":{let d={},s=i.fullExamples?.find(g=>g.name===t)??i.fullExamples?.find(g=>g.name==null)??i.fullExamples?.[0],o=Y5a(r)??(s!=null?Y5a(s.value):{})??{},c=this.getAllProperties(i),b=this.getAllRequiredProperties(i);for(let[g,O]of Object.entries(c)){if(l&&O.readonly||O.schema._visit({optional:q=>typeof q.availability=="string"&&q.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 m=g in b,w=Object.keys(o).includes(g),E=this.buildExampleHelper({schema:O.schema,exampleId:t,example:o[g],visitedSchemaIds:a,depth:n+1,options:{...u,name:g},skipReadonly:l});if(m&&E!=null)d[g]=E;else{if(m)return;(w&&E!=null||!u.ignoreOptionals&&E!=null)&&(d[g]=E)}}if(i.additionalProperties){for(let[g,O]of Object.entries(o))if(!(g in d)){let m=this.buildExampleHelper({schema:Al.unknown({example:O,title:void 0,availability:void 0,description:void 0,generatedName:"",nameOverride:void 0,namespace:void 0,groupName:void 0}),exampleId:t,example:O,visitedSchemaIds:a,depth:n+1,options:{...u,name:g},skipReadonly:l});m!=null&&(d[g]=m)}}return xg.object({properties:d})}default:So(i)}}mergeExampleWith(t,r){t._visit({array:$o,enum:$o,literal:$o,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:$o,unknown:$o,_other:$o})}getObjectSchema(t){if(t.type==="object")return t;if(t.type==="reference"){let r=this.schemas[t.schema];if(r!=null)return this.getObjectSchema(r)}}getDiscriminatedUnionVariantSchema(t,r){let i=r?.[t.discriminantProperty];if(i==null||typeof i!="string")return Object.entries(t.schemas)[0];let n=t.schemas[i];return n==null?Object.entries(t.schemas)[0]:[i,n]}getUnDiscriminatedUnionVariantSchema(t,r){return r==null?t.schemas[0]:t.schemas.map(a=>({schema:a,heuristic:this.calcExampleHeuristic(a,r)})).sort((a,u)=>u.heuristic-a.heuristic)[0]?.schema}calcExampleHeuristic(t,r){switch(t.type){case"literal":return t.value.value===r?5:0;case"enum":return J1_({schema:t,value:r})?5:0;case"object":{if(!vw(r))return 0;let i=this.getAllProperties(t),n=0;for(let[a,u]of Object.entries(i))r[a]!=null?(n++,n+=this.calcExampleHeuristic(u.schema,r[a])):n--;return n}case"array":{if(!Array.isArray(r))return 0;let i=0;for(let n of r)i+=this.calcExampleHeuristic(t.value,n);return i}case"map":{if(!vw(r))return 0;let i=0;for(let[,n]of Object.entries(r))i+=this.calcExampleHeuristic(t.value,n);return i}case"nullable":case"optional":return this.calcExampleHeuristic(t.value,r);case"reference":{let i=this.getResolvedSchema(t);return i==null?0:this.calcExampleHeuristic(i,r)}case"oneOf":return Object.values(t.value.schemas).map(n=>this.calcExampleHeuristic(n,r)).sort((n,a)=>a-n)[0]??0;case"primitive":return r==null?0:t.schema._visit({int:()=>typeof r=="number",int64:()=>typeof r=="number",uint:()=>typeof r=="number",uint64:()=>typeof r=="number",float:()=>typeof r=="number",double:()=>typeof r=="number",string:()=>typeof r=="string",datetime:()=>typeof r=="string",date:()=>typeof r=="string",base64:()=>typeof r=="string",boolean:()=>typeof r=="boolean",_other:()=>!0})?1:-1;default:return 0}}hasExample(t,r,i=new Set,n){if(this.exceedsMaxCheckerDepth(r,n))return!1;switch(t.type){case"array":return this.hasExample(t.value,r+1,i,n);case"enum":return t.example!=null;case"literal":return!1;case"map":return t.example!=null||t.key.schema.example!=null&&this.hasExample(t.value,r+1,i,n);case"object":{if(t.fullExamples!=null&&t.fullExamples.length>0)return!0;for(let u of t.properties)if(this.hasExample(u.schema,r+1,i,n))return!0;return!1}case"primitive":return t.schema.example!=null;case"reference":{let a=this.schemas[t.schema];if(a!=null&&!i.has(t.schema)){i.add(t.schema);let u=this.hasExample(a,r,i,n);return i.delete(t.schema),u}return!1}case"unknown":return t.example!=null;case"oneOf":return Object.values(t.value.schemas).some(a=>this.hasExample(a,r,i,n));default:return!1}}exceedsMaxCheckerDepth(t,r){return t>(r.maxCheckerDepth??0)}exceedsMaxDepth(t,r){return t>(r.maxDepth??0)}getAllProperties(t){let r={};for(let i of t.properties)r[i.key]={schema:i.schema,readonly:i.readonly??!1};for(let i of t.allOf){let n=this.schemas[i.schema];if(n==null)continue;let a=this.getResolvedSchema(n);a.type==="object"&&(r={...this.getAllProperties(a),...r})}return r}getAllRequiredProperties(t){let r={};for(let i of t.properties){let n=this.getResolvedSchema(i.schema);n.type!=="optional"&&n.type!=="nullable"&&(r[i.key]=i.schema)}for(let i of t.allOf){let n=this.schemas[i.schema];if(n==null)continue;let a=this.getResolvedSchema(n);a.type==="object"&&(r={...this.getAllRequiredProperties(a),...r})}return r}getResolvedSchema(t){for(;t.type==="reference";){let r=this.schemas[t.schema];if(r==null)throw new Error(`Unexpected error: Failed to resolve schema reference: ${t.schema}`);t=r}return t}buildExampleFromPrimitive({example:t,schema:r,options:i}){switch(r.type){case"string":return t!=null&&typeof t=="string"?h_.string(t):r.example!=null?h_.string(r.example):h_.string(i.name??Ch.STRING);case"base64":return t!=null&&typeof t=="string"?h_.base64(t):r.example!=null?h_.base64(r.example):h_.base64(Ch.BASE64);case"boolean":return t!=null&&typeof t=="boolean"?h_.boolean(t):r.example!=null?h_.boolean(r.example):h_.boolean(Ch.BOOLEAN);case"date":return t!=null&&typeof t=="string"?h_.date(t):r.example!=null?h_.date(r.example):h_.date(Ch.DATE);case"datetime":return t!=null&&typeof t=="string"?h_.datetime(t):r.example!=null?h_.datetime(r.example):h_.datetime(Ch.DATE_TIME);case"double":return t!=null&&typeof t=="number"?h_.double(t):r.example!=null?h_.double(r.example):h_.double(Ch.DOUBLE);case"float":return t!=null&&typeof t=="number"?h_.float(t):r.example!=null?h_.float(r.example):h_.float(Ch.FLOAT);case"int":return t!=null&&typeof t=="number"?h_.int(t):r.example!=null?h_.int(r.example):h_.int(Ch.INT);case"int64":return t!=null&&typeof t=="number"?h_.int64(t):r.example!=null?h_.int64(r.example):h_.int64(Ch.INT64);case"uint":return t!=null&&typeof t=="number"?h_.uint(t):r.example!=null?h_.uint(r.example):h_.uint(Ch.UINT);case"uint64":return t!=null&&typeof t=="number"?h_.uint64(t):r.example!=null?h_.uint64(r.example):h_.uint64(Ch.UINT64);default:So(r)}}};function J1_({schema:e,value:t}){return e.values.map(r=>r.value).includes(t)}function OQt(e){switch(e.type){case"object":return Al.object({allOf:e.allOf,properties:e.properties.map(t=>fFE(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});case"array":return Al.array({description:e.description,availability:e.availability,value:OQt(e.value),generatedName:e.generatedName,title:e.title,namespace:e.namespace,nameOverride:e.nameOverride,groupName:e.groupName,example:void 0,inline:void 0});case"enum":return Al.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 Al.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 Al.nullable({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:OQt(e.value),namespace:e.namespace,groupName:e.groupName,inline:void 0});case"optional":return Al.optional({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:OQt(e.value),namespace:e.namespace,groupName:e.groupName,inline:void 0});case"primitive":return Al.primitive({description:e.description,availability:e.availability,schema:K1_(e.schema),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName});case"map":return Al.map({description:e.description,availability:e.availability,key:Al.primitive({description:e.key.description,availability:e.key.availability,schema:K1_(e.key.schema),generatedName:e.key.generatedName,nameOverride:e.key.nameOverride,title:e.key.title,namespace:e.namespace,groupName:e.groupName}),value:OQt(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});case"reference":return Al.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 Al.oneOf(lFE(e.value));case"unknown":return Al.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:So(e)}}function lFE(e){switch(e.type){case"discriminated":return aee.discriminated({commonProperties:e.commonProperties.map(t=>({key:t.key,schema:OQt(t.schema)})),description:e.description,availability:e.availability,discriminantProperty:e.discriminantProperty,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schemas:Object.fromEntries(Object.entries(e.schemas).map(([t,r])=>[t,OQt(r)])),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:void 0});case"undiscriminated":return aee.undiscriminated({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schemas:e.schemas.map(t=>OQt(t)),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:void 0});default:So(e)}}function K1_(e){switch(e.type){case"string":return ap.string({default:e.default,pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:void 0});case"base64":return ap.base64({example:void 0});case"boolean":return ap.boolean({default:e.default,example:void 0});case"date":return ap.date({example:void 0});case"datetime":return ap.datetime({example:void 0});case"double":return ap.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 ap.float({example:void 0});case"int":return ap.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 ap.int64({default:e.default,example:void 0});case"uint":return ap.uint({default:void 0,example:void 0});case"uint64":return ap.uint64({default:void 0,example:void 0});default:So(e)}}function fFE(e){return{conflict:e.conflict,generatedName:e.generatedName,key:e.key,schema:OQt(e.schema),audiences:e.audiences,nameOverride:e.nameOverride,availability:e.availability,readonly:e.readonly,writeonly:e.writeonly}}function Lau(e){return e.type!=="optional"&&e.type!=="nullable"}function vSc(e){return e==="POST"||e==="PUT"||e==="PATCH"}function X5a(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 Uau=class{schemas;context;globalHeaders;exampleTypeFactory;logger;constructor(t,r,i){this.schemas=t,this.context=r,this.globalHeaders=i,this.schemas=t,this.exampleTypeFactory=new kNi(t,r.nonRequestReferencedSchemas,r),this.logger=r.logger}buildEndpointExample(t){this.logger.debug(`Building endpoint example for ${t.method.toUpperCase()} ${t.path}`);let r=pFE(t.request),i=_FE(t.response);if(r?.type==="unsupported"||i?.type==="unsupported")return[];let n=[];if(r!=null&&r.type==="present"){let c=this.isSchemaRequired(r.schema);if(r.examples.length===0){let b=this.exampleTypeFactory.buildExample({skipReadonly:vSc(t.method),schema:r.schema,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});b!=null&&n.push([void 0,b])}else for(let{name:b,value:g}of r.examples){let O=this.exampleTypeFactory.buildExample({skipReadonly:vSc(t.method),schema:r.schema,exampleId:b,example:g,options:{isParameter:!1,ignoreOptionals:!0}});O!=null&&n.push([b,O])}if(c&&n.length===0)return this.logger.trace(`Failed to generate required request example for ${t.method.toUpperCase()} ${t.path}`),[]}let a=[];if(i!=null&&i.type==="present"){let c=this.isSchemaRequired(i.schema);if(i.examples.length===0){let b=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:i.schema,exampleId:void 0,example:void 0,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});b!=null&&(t.response?.type==="json"?a.push([void 0,vQt.withoutStreaming(b)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&a.push([void 0,vQt.withStreaming({sse:t.response?.type==="streamingSse",events:[b]})]))}else for(let{name:b,value:g}of i.examples){let O=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:i.schema,exampleId:b,example:g,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});O!=null&&(t.response?.type==="json"?a.push([b,vQt.withoutStreaming(O)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&a.push([void 0,vQt.withStreaming({sse:t.response?.type==="streamingSse",events:[O]})]))}if(c&&a.length===0)return this.logger.trace(`Failed to generate required response example for ${t.method.toUpperCase()} ${t.path}`),[]}let u=[];for(let c of t.pathParameters){let b=this.isSchemaRequired(c.schema),g=this.exampleTypeFactory.buildExample({schema:c.schema,exampleId:void 0,example:void 0,options:{name:c.name,isParameter:!0,ignoreOptionals:!0}});if(g!=null&&!mQt(g)&&(this.logger.warn(`Expected a primitive example but got ${g.type} for path parameter ${c.name} for ${t.method.toUpperCase()} ${t.path}`),g=void 0),b&&g==null)return[];g!=null&&u.push({name:c.name,parameterNameOverride:c.parameterNameOverride,value:g})}let l=[];for(let c of t.queryParameters){let b=this.isSchemaRequired(c.schema),g=this.exampleTypeFactory.buildExample({schema:c.schema,exampleId:void 0,example:void 0,options:{name:c.name,isParameter:!0,ignoreOptionals:!0}});if(g!=null&&!mQt(g)&&(this.logger.warn(`Expected a primitive example but got ${g.type} for query parameter ${c.name} for ${t.method.toUpperCase()} ${t.path}`),g=void 0),b&&g==null)return[];g!=null&&l.push({name:c.name,value:g})}let d=[];for(let c of t.headers){let b=this.isSchemaRequired(c.schema),g=this.exampleTypeFactory.buildExample({schema:c.schema,exampleId:void 0,example:void 0,options:{name:c.name,isParameter:!0,ignoreOptionals:!0}});if(g!=null&&!mQt(g)&&(this.logger.warn(`Expected a primitive example but got ${g.type} for header ${c.name} for ${t.method.toUpperCase()} ${t.path}`),g=void 0),b&&g==null)return[];g!=null&&d.push({name:c.name,value:g})}for(let c of this.globalHeaders){let b=c.schema!=null?OQt(c.schema):Al.primitive({nameOverride:void 0,generatedName:"",title:void 0,description:void 0,availability:void 0,namespace:void 0,groupName:void 0,schema:ap.string({default:void 0,pattern:void 0,maxLength:void 0,minLength:void 0,example:void 0,format:void 0})}),g=this.exampleTypeFactory.buildExample({schema:b,exampleId:void 0,example:void 0,options:{name:c.header,isParameter:!0,ignoreOptionals:!0}});if(g!=null&&!mQt(g)&&(this.logger.warn(`Expected a primitive example but got ${g.type} for global header ${c.header} for ${t.method.toUpperCase()} ${t.path}`),g=void 0),g==null)return[];g!=null&&d.push({name:c.header,value:g})}let s=[];t.request!=null&&t.response!=null?s=dFE(n,a):t.request!=null?s=n.map(([c,b])=>({id:c,request:b,response:void 0})):t.response!=null&&(s=a.map(([c,b])=>({id:c,request:void 0,response:b})));let o=t.examples.filter(c=>X5a(c)).flatMap(c=>{if(c.type==="unknown"){if(c.value!=null){let b=c.value["code-samples"];if(b!=null)return this.convertCodeSamples(b)}return}else return c.codeSamples}).filter(c=>iv(c));return s.length===0?[yQt.full({name:void 0,description:void 0,pathParameters:u,queryParameters:l,headers:d,request:void 0,response:void 0,codeSamples:o})]:s.map(({id:c,request:b,response:g})=>yQt.full({name:c,description:void 0,pathParameters:u,queryParameters:l,headers:d,request:b,response:g,codeSamples:o}))}convertCodeSamples(t){return t.map(r=>"language"in r?Kmi.language({name:r.name??void 0,description:r.docs??void 0,language:r.language,code:r.code,install:r.install??void 0}):Kmi.sdk({name:r.name??void 0,description:r.docs??void 0,sdk:r.sdk==="c#"?GH.Csharp:r.sdk,code:r.code})).filter(iv)}isSchemaRequired(t){return Lau(this.getResolvedSchema(t))}getResolvedSchema(t){return t}};function dFE(e,t){let r=[];if(e.length<=1){let[n,a]=e[0]??[];if(t.length===0)return r.push({id:n,request:a,response:void 0}),r;for(let[u,l]of t)r.push({id:u??n,request:a,response:l});return r}if(t.length<=1){let[n,a]=t[0]??[];if(t.length===0)return r.push({id:n,request:void 0,response:a}),r;for(let[u,l]of e)r.push({id:u??n,request:l,response:a});return r}let i=new Set;for(let[n,a]of e){let u=t.find(([d])=>d==null)?.[1]??t[0]?.[1];if(n==null){if(u==null)continue;r.push({id:void 0,request:a,response:u});continue}let l=!1;for(let d=0;d<t.length;d++){let[s,o]=t[d];s==null||i.has(d)||n===s&&(r.push({id:n,request:a,response:o}),s!=null&&i.add(d),l=!0)}!l&&u!=null&&r.push({id:n,request:a,response:u})}for(let n=0;n<t.length;n++){if(i.has(n))continue;let[a,u]=t[n],l=e.find(([d])=>d==null)?.[1]??e[0]?.[1];l!=null&&r.push({id:a,request:l,response:u})}return r}function pFE(e){if(e!=null)return e.type==="multipart"?{type:"present",schema:hFE(e),examples:[]}:e.type==="json"||e.type==="formUrlEncoded"?{type:"present",schema:e.schema,examples:e.fullExamples??[]}:{type:"unsupported"}}function _FE(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 mQt(e){switch(e.type){case"primitive":case"enum":case"literal":return!0;case"unknown":return mQt(e);case"array":case"object":case"map":return!1;case"oneOf":switch(e.value.type){case"discriminated":return!1;case"undiscriminated":return mQt(e.value.value);default:return!1}default:So(e)}}function hFE(e){return Al.object({properties:e.properties.map(t=>t.schema.type==="file"?null:{key:t.key,schema:OQt(t.schema.value),audiences:[],conflict:{},generatedName:t.key,nameOverride:void 0,availability:void 0,readonly:void 0,writeonly:void 0,inline:void 0}).filter(iv),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})}var IKn=class{exampleTypeFactory;schemas;constructor(t,r){this.exampleTypeFactory=new kNi(t,new Set,r),this.schemas=t}buildWebsocketSessionExamplesForExtension({context:t,extensionExamples:r,handshake:i,source:n,namespace:a}){let u=[];for(let l of r){let d=[];for(let c of i.queryParameters){let b=this.isSchemaRequired(c.schema),g=this.exampleTypeFactory.buildExample({schema:c.schema,exampleId:void 0,example:l.queryParameters?.[c.name],options:{name:c.name,isParameter:!0,ignoreOptionals:!0}});g!=null&&!mQt(g)&&(g=void 0),!(b&&g==null)&&g!=null&&d.push({name:c.name,value:g})}let s=[];for(let c of i.headers){let b=this.isSchemaRequired(c.schema),g=this.exampleTypeFactory.buildExample({schema:c.schema,exampleId:void 0,example:l.headers?.[c.name],options:{name:c.name,isParameter:!0,ignoreOptionals:!0}});g!=null&&!mQt(g)&&(g=void 0),!(b&&g==null)&&g!=null&&s.push({name:c.name,value:g})}let o=[];for(let c of l.messages){let b=t.getExampleMessageReference(c),g=t.resolveMessageReference({$ref:b}),O=Kd(g.payload)?t.resolveSchemaReference(g.payload):g.payload,m=this.exampleTypeFactory.buildExample({schema:j0(O,!1,t,[c.messageId],n,a),exampleId:void 0,example:c.value,options:{isParameter:!1,ignoreOptionals:!0}});m!=null&&o.push({messageType:c.type,payload:m,description:void 0})}u.push({name:l.summary,queryParameters:d,headers:s,description:l.description,messages:o})}return u}buildWebsocketSessionExample({handshake:t,messages:r}){let i={name:void 0,queryParameters:[],headers:[],description:void 0,messages:[]},n=[];for(let u of t.queryParameters){let l=this.isSchemaRequired(u.schema),d=this.exampleTypeFactory.buildExample({schema:u.schema,exampleId:void 0,example:void 0,options:{name:u.name,isParameter:!0,ignoreOptionals:!0}});if(d!=null&&!mQt(d)&&(d=void 0),l&&d==null)return;d!=null&&n.push({name:u.name,value:d})}let a=[];for(let u of t.headers){let l=this.isSchemaRequired(u.schema),d=this.exampleTypeFactory.buildExample({schema:u.schema,exampleId:void 0,example:void 0,options:{name:u.name,isParameter:!0,ignoreOptionals:!0}});if(d!=null&&!mQt(d)&&(d=void 0),l&&d==null)return;d!=null&&a.push({name:u.name,value:d})}for(let u of r){let l=this.exampleTypeFactory.buildExample({schema:u.payload,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});l!=null&&i.messages.push({messageType:u.type,payload:l,description:void 0})}return i}isSchemaRequired(t){return Lau(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 see={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_EXAMPLES:"x-fern-examples",BASE_PATH:"x-fern-base-path",FERN_ENUM:"x-fern-enum",IGNORE:"x-fern-ignore"};function Vau(e){return of(e,see.FERN_EXAMPLES)??[]}function Wau(e,t){return t.includes("://")?t:`${e}://${t}`}function Hau(e){return e.startsWith("/")?e:"/"+e}function Z1_({context:e,breadcrumbs:t,source:r,asyncApiOptions:i,document:n}){let a={},u={};for(let[s,o]of Object.entries(n.components?.schemas??{})){let c=j0(o,!1,e,[s],r,e.namespace);a[s]=c}let l=new IKn(a,e),d={};for(let[s,o]of Object.entries(n.servers??{}))d[s]={name:s,url:Wau(o.protocol,o.url)};for(let[s,o]of Object.entries(n.channels??{})){let c=of(o,see.IGNORE);if(c!=null&&c){e.logger.debug(`Channel ${s} is marked with x-fern-ignore. Skipping.`);continue}let b=[];if(o.parameters!=null)for(let[E,q]of Object.entries(o.parameters??{}))b.push({name:E,description:q.description,parameterNameOverride:void 0,schema:q.schema!=null?j0(q.schema,!1,e,t,r,e.namespace):Al.primitive({schema:ap.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:sK(q),source:r});let g=[],O=[];if(o.bindings?.ws!=null){if(o.bindings.ws.headers!=null){let E=o.bindings.ws.headers.required??[];for(let[q,M]of Object.entries(o.bindings.ws.headers.properties??{})){if(Kd(M)){let D=e.resolveSchemaReference(M);g.push({name:q,schema:tPi(M,!1,e,t,void 0,r,e.namespace),description:D.description,parameterNameOverride:void 0,env:void 0,availability:sK(D),source:r});continue}g.push({name:q,schema:j0(M,!E.includes(q),e,[...t,q],r,e.namespace),description:M.description,parameterNameOverride:void 0,env:void 0,availability:sK(M),source:r})}}if(o.bindings.ws.query!=null){let E=o.bindings.ws.query.required??[];for(let[q,M]of Object.entries(o.bindings.ws.query.properties??{})){if(Kd(M)){let D=e.resolveSchemaReference(M);O.push({name:q,schema:tPi(M,!1,e,t,void 0,r,e.namespace),description:D.description,parameterNameOverride:void 0,availability:sK(D),source:r});continue}O.push({name:q,schema:j0(M,!E.includes(q),e,[...t,q],r,e.namespace),description:M.description,parameterNameOverride:void 0,availability:sK(M),source:r})}}}let m;o.publish!=null&&("oneOf"in o.publish.message?m=Y1_({generatedName:o.publish.operationId??"PublishEvent",event:o.publish,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:i}):m=X1_({action:"Publish",channelPath:s,message:o.publish.message,context:e,source:r}));let w;if(o.subscribe!=null&&("oneOf"in o.subscribe.message?w=Y1_({generatedName:o.subscribe.operationId??"SubscribeEvent",event:o.subscribe,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:i}):w=X1_({action:"Subscribe",channelPath:s,message:o.subscribe.message,context:e,source:r})),g.length>0||O.length>0||m!=null||w!=null){let E=Vau(o),q=[];if(E.length>0)q=l.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:E,handshake:{headers:g,queryParameters:O},source:r,namespace:e.namespace});else{let R=[];m!=null&&R.push({type:"publish",payload:m}),w!=null&&R.push({type:"subscribe",payload:w});let G=l.buildWebsocketSessionExample({handshake:{headers:g,queryParameters:O},messages:R});G!=null&&q.push(G)}let M=of(o,see.FERN_CHANNEL_ADDRESS),D=M??Hau(s),C=[];m!=null&&C.push({origin:"client",name:"publish",body:iA(m)}),w!=null&&C.push({origin:"server",name:"subscribe",body:iA(w)}),u[s]={audiences:of(o,Kf.AUDIENCES)??[],handshake:{headers:g.map(R=>({...R,schema:iA(R.schema),env:R.env})),queryParameters:O.map(R=>({...R,schema:iA(R.schema)})),pathParameters:b.map(R=>({...R,parameterNameOverride:void 0,schema:iA(R.schema)}))},groupName:e.resolveGroupName([of(o,see.FERN_SDK_GROUP_NAME)??s]),messages:C,servers:(o.servers?.map(R=>d[R])??Object.values(d)).filter(R=>R!=null),summary:of(o,see.FERN_DISPLAY_NAME),path:D,description:o.description,examples:q,source:r}}}return{groupedSchemas:BKn(e.namespace,a),channels:u??void 0,servers:Object.values(d),basePath:of(n,see.BASE_PATH)}}function Y1_({generatedName:e,event:t,context:r,breadcrumbs:i,source:n,options:a,asyncApiOptions:u}){if("oneOf"in t.message&&t.message.oneOf!=null){let l=[],d=[];for(let s of t.message.oneOf){let o,c={type:"notFound"};if(Kd(s)){let b=r.resolveMessageReference(s);!Kd(b.payload)&&u.naming==="v2"?(c=b.name?{type:"name",name:b.name}:c,o={...b.payload,title:b.name??b.payload.title,description:b.name??b.payload.description}):o=b.payload}else o=s;d.push(c),l.push(o)}return XNi({description:t.description??t.message.description,availability:sK(t.message),subtypes:l,nameOverride:t.operationId,generatedName:e,title:t.message.title,groupName:void 0,wrapAsNullable:!1,breadcrumbs:i,context:r,encoding:void 0,source:n,namespace:r.namespace,subtypePrefixOverrides:u.naming==="v2"?d:[]})}}function X1_({action:e,channelPath:t,message:r,context:i,source:n}){if(r.payload!=null){let a=r.payload;return Kd(r.payload)&&(a=i.resolveSchemaReference(r.payload)),j0(a,!1,i,[t,e],n,i.namespace)}}var $au=class extends CKn{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){let r="#/channels/",i="#/components/messages/";if(t.$ref.startsWith(r)){let l=t.$ref.split("/"),d=l[2],s=l[4];if(d==null||s==null||!this.document.channels?.[d])throw new Error(`Failed to resolve message reference ${t.$ref} in channel ${d}`);let c=this.document.channels[d].messages?.[s];if(c==null)throw new Error(`${t.$ref} is undefined`);return"$ref"in c?this.resolveMessageReference(c):{name:s,...c}}let n=this.document.components;if(!t.$ref.startsWith(i)||!n?.messages)throw new Error(`Failed to resolve message reference: ${t.$ref} in v3 components`);let a=t.$ref.substring(i.length),u=n.messages[a];if(u==null)throw new Error(`${t.$ref} is undefined`);return{name:a,...u}}isMessageWithPayload(t){return t!=null&&typeof t=="object"&&"payload"in t}isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}};var k1_="#/channels/",eS_="#/servers/",bSc="$message.";function rS_({context:e,breadcrumbs:t,source:r,asyncApiOptions:i,document:n}){let a={},u={},l={},d=[],s={};for(let[O,m]of Object.entries(n.components?.schemas??{}))a[O]=j0(m,!1,e,[O],r,e.namespace);for(let[O,m]of Object.entries(n.channels??{}))if(u[O]||(u[O]={}),m.messages){for(let[w,E]of Object.entries(m.messages))if(e.isReferenceObject(E)||e.isMessageWithPayload(E))if(l[w]||(l[w]=[]),e.isReferenceObject(E)){let q=e.resolveMessageReference(E);l[w].push({channelId:O,payload:q.payload})}else l[w].push({channelId:O,payload:E.payload})}for(let[O,m]of Object.entries(l))if(m.length===1){let w=m[0],E=w.channelId;u[E]=u[E]||{},u[E][O]=j0(w.payload,!1,e,[O],r,e.namespace)}else{d.push(O);for(let{channelId:w,payload:E}of m){let q=`${w}_${O}`;u[w]||(u[w]={}),u[w][q]=j0(E,!1,e,[q],r,e.namespace)}}let o=Object.values(u).reduce((O,m)=>({...O,...m}),{}),c=new IKn(o,e),b={};for(let[O,m]of Object.entries(n.servers??{}))b[O]={name:O,url:Wau(m.protocol,m.host)};let g={};for(let[O,m]of Object.entries(n.operations??{})){if(of(m,see.IGNORE))continue;let w=yFE(m);if(g[w]||(g[w]={subscribe:[],publish:[],__parsedMessages:[]}),m.action==="receive")g[w].subscribe.push(...m.messages);else if(m.action==="send")g[w].publish.push(...m.messages);else throw new Error(`Operation ${O} has an invalid action: ${m.action}`)}for(let[O,m]of Object.entries(g)){let w=[];w.push(...tS_({messages:m.subscribe,channelPath:O,origin:"server",messageSchemas:u[O]??{},duplicatedMessageIds:d,context:e})),w.push(...tS_({messages:m.publish,channelPath:O,origin:"client",messageSchemas:u[O]??{},duplicatedMessageIds:d,context:e})),g[O]!=null&&(g[O].__parsedMessages=w)}for(let[O,m]of Object.entries(n.channels??{})){if(of(m,see.IGNORE))continue;let w=[],E=[],q=[];if(m.parameters!=null)for(let[M,D]of Object.entries(m.parameters)){let C=e.isReferenceObject(D)?e.resolveParameterReference(D):D,{type:R,parameterKey:G}=C.location!=null?vFE(C.location):{type:m.address?.includes(`={${M}}`)?"query":"path",parameterKey:M},I=of(C,see.FERN_PARAMETER_OPTIONAL),L=qB(S_(O))+qB(S_(M)),V={...C,type:"string",title:L,example:C.examples?.[0],default:C.default,enum:C.enum,required:void 0},Y=j0(V,!1,e,[G],r,e.namespace);I&&(Y=Al.optional({value:Y,description:void 0,availability:void 0,generatedName:"",title:L,namespace:void 0,groupName:void 0,nameOverride:void 0,inline:void 0}));let K={name:G,description:C.description,parameterNameOverride:void 0,schema:Y,variableReference:void 0,availability:sK(D),source:r};R==="header"?w.push({...K,env:void 0}):R==="path"?E.push(K):(R==="payload"||R==="query")&&q.push(K)}if(w.length>0||q.length>0||g[O]!=null&&(g[O].publish!=null||g[O].subscribe!=null)){let M=Vau(m),D=g[O]?.__parsedMessages??[],C=[];if(M.length>0)C=c.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:M,handshake:{headers:w,queryParameters:q},source:r,namespace:e.namespace});else{let R=[],{examplePublishMessage:G,exampleSubscribeMessage:I}=gFE({messages:D,messageSchemas:u[O]??{}});G!=null&&R.push(G),I!=null&&R.push(I);let L=c.buildWebsocketSessionExample({handshake:{headers:w,queryParameters:q},messages:R});L!=null&&C.push(L)}s[O]={audiences:of(m,Kf.AUDIENCES)??[],handshake:{headers:w.map(R=>({...R,schema:iA(R.schema),env:R.env})),queryParameters:q.map(R=>({...R,schema:iA(R.schema)})),pathParameters:E.map(R=>({...R,parameterNameOverride:void 0,schema:iA(R.schema)}))},groupName:e.resolveGroupName([of(m,see.FERN_SDK_GROUP_NAME)??O]),messages:D,summary:of(m,see.FERN_DISPLAY_NAME),servers:m.servers?.map(R=>bFE(b,R))??Object.values(b),path:m.address?.split("?")[0]??Hau(O),description:m.description,examples:C,source:r}}}return{groupedSchemas:BKn(e.namespace,a),channels:s,servers:Object.values(b),basePath:of(n,see.BASE_PATH)}}function yFE(e){if(!e.channel.$ref.startsWith(k1_))throw new Error(`Failed to resolve channel path from operation ${e.channel.$ref}`);return e.channel.$ref.substring(k1_.length)}function vFE(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(bSc))throw new Error(`Invalid location format: ${e}; expected ${bSc} prefix`);let i=t.substring(bSc.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 bFE(e,t){if(!t.$ref.startsWith(eS_))throw new Error(`Failed to resolve server name from server ref ${t.$ref}`);let r=t.$ref.substring(eS_.length),i=e[r];if(i==null)throw new Error(`Failed to find server with name ${r}`);return i}function tS_({messages:e,channelPath:t,origin:r,messageSchemas:i,duplicatedMessageIds:n,context:a}){let u=[];return e.forEach((l,d)=>{let o=a.resolveMessageReference(l).name;n.includes(o)&&(o=`${t}_${o}`);let c=i[o];c!=null&&u.push({origin:r,name:o??`${r}Message${d+1}`,body:iA(c)})}),u}function gFE({messages:e,messageSchemas:t}){let r=e.find(u=>u.origin==="client")?.name,i=e.find(u=>u.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 iS_({document:e,taskContext:t,options:r,source:i,asyncApiOptions:n,namespace:a}){let u=[];if(a!=null&&u.push(a),parseFloat(e.asyncapi)<3){let l=e;l.tags?.[0]!=null?u.push(l.tags[0].name):n.naming!=="v2"&&u.push("websocket");let d=new Fau({document:l,taskContext:t,options:r,namespace:a});return Z1_({context:d,breadcrumbs:u,source:i,asyncApiOptions:n,document:l})}else{let l=e,d=new $au({document:l,taskContext:t,options:r,namespace:a});return rS_({context:d,breadcrumbs:u,source:i,asyncApiOptions:n,document:l})}}function nS_(e){return of(e,Kf.ASYNC_CONFIG)}var aS_="$request.";function oS_(e){let t=of(e,Kf.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:OFE(t["stream-condition"]),responseStream:t["response-stream"],response:t.response}}function OFE(e){return e.startsWith(aS_)?e.slice(aS_.length):e}function uS_(e){let t=e;if(t.cursor!=null)return t7e.cursor({cursor:t.cursor,nextCursor:t.next_cursor,results:t.results});if("offset"in e){let r=e;return t7e.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 t7e.custom({results:r.results})}throw new Error("Invalid pagination extension")}function sS_(e,t){let r=of(t,Kf.PAGINATION);if(r!=null){if(typeof r=="boolean"){let i=of(e,Kf.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:uS_(i)}return uS_(r)}}function cS_(e){let t=mFE(e),r={};return gSc({obj:t,occurrences:r,breadcrumbs:[]}),r}function gSc({obj:e,occurrences:t,breadcrumbs:r}){if(e!=null){if(Array.isArray(e)){for(let i of e)gSc({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)gSc({obj:e[i],occurrences:t,breadcrumbs:[...r,i]})}}}function mFE(e){return{...e,paths:Object.fromEntries(Object.entries(e.paths??{}).map(([t,r])=>[t,{...r,get:r?.get!=null?Z5a(r.get):void 0,put:r?.put!=null?Z5a(r.put):void 0,post:r?.post!=null?Z5a(r.post):void 0,patch:r?.patch!=null?Z5a(r.patch):void 0,delete:r?.delete!=null?Z5a(r.delete):void 0}]))}}function Z5a(e){return{...e,requestBody:e.requestBody!=null?Kd(e.requestBody)?e.requestBody:PFE(e.requestBody):void 0}}function PFE(e){let t,r;for(let i in e.content){let n=hq.parse(i);n!=null&&(n.isJSON()?t=e.content[i]:n.isMultipart()&&(r=e.content[i]))}return r!=null&&t!=null?{...e,content:{[hq.MULTIPART_FORM_DATA]:r}}:e}var Gau=class{endpoints;parser=new Aen;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 lS_="#/components/parameters/",fS_="#/components/responses/",dS_="#/components/examples/",pS_="#/components/requestBodies/",zKn=class{logger;document;taskContext;authHeaders;refOccurrences;DUMMY;options;source;filter;namespace;constructor({document:t,taskContext:r,authHeaders:i,options:n,source:a,namespace:u}){this.document=t,this.logger=r.logger,this.taskContext=r,this.authHeaders=i,this.refOccurrences=cS_(t),this.options=n,this.source=a,this.filter=new Gau({context:r,options:n}),this.DUMMY=this.getDummy(),this.namespace=u}getNumberOfOccurrencesForRef(t){return this.refOccurrences[t.$ref]??0}resolveTagsToTagIds(t){let r=[];return this.namespace!=null&&r.push(this.namespace),r.concat(t??[])}resolveTags(t){let r=[];if(this.namespace!=null){let i={type:"namespace",name:this.namespace};r.push(i)}return r.concat(t??[])}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveSchemaReference(t){let r=t.$ref.substring(2).split("/").map(n=>n.replace(/~1/g,"/")),i=this.document;for(let n of r){if(typeof i!="object"||i==null)return{"x-fern-type":"unknown"};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.warn(`Encountered undefined reference: ${t.$ref}`),{"x-fern-type":"unknown"}):(Kd(i)&&(i=this.resolveSchemaReference(i)),i)}resolveParameterReference(t){if(this.document.components==null||this.document.components.parameters==null||!t.$ref.startsWith(lS_))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(lS_.length),i=this.document.components.parameters[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return Kd(i)?this.resolveParameterReference(i):i}resolveRequestBodyReference(t){if(this.document.components==null||this.document.components.requestBodies==null||!t.$ref.startsWith(pS_))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(pS_.length),i=this.document.components.requestBodies[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return Kd(i)?this.resolveRequestBodyReference(i):i}resolveResponseReference(t){if(this.document.components==null||this.document.components.responses==null||!t.$ref.startsWith(fS_))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(fS_.length),i=this.document.components.responses[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return Kd(i)?this.resolveResponseReference(i):i}resolveExampleReference(t){if(this.document.components==null||this.document.components.examples==null||!t.$ref.startsWith(dS_))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(dS_.length),i=this.document.components.examples[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return Kd(i)?this.resolveExampleReference(i):i}referenceExists(t){let r=t.substring(2).split("/").map(n=>n.replace(/~1/g,"/")),i=this.document;for(let n of r){if(typeof i!="object"||i==null)return!1;i=i[n]}return!0}};var aan=class extends zKn{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 jFE=Su.object({lang:Su.string(),label:Su.optional(Su.string()),source:Su.string()}),OSc=Su.array(jFE);var _S_={README_EXT:"x-readme"};function wFE(e){if(!Array.isArray(e))return!1;for(let t of e)if(!vw(t)||typeof t.language!="string"||typeof t.code!="string")return!1;return!0}function hS_(e){let t=of(e,_S_.README_EXT);if(!vw(t))return[];let r=t["code-samples"];if(!wFE(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 yS_(e,t,r){let n=(of(t,Kf.EXAMPLES)??[]).filter(s=>{let o=MF.serialization.ExampleEndpointCallSchema.parse(s);return o.ok||r.logger.error(`Failed to parse x-fern-example in ${e.path}/${e.method}`),o.ok}),a=J5a(t,JH.REDOCLY_CODE_SAMPLES_KEBAB,OSc,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],l=[...J5a(t,JH.REDOCLY_CODE_SAMPLES_CAMEL,OSc,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],...a];l.length>0&&n.push({"code-samples":l.map(s=>({name:s.label??s.lang,language:s.lang,code:s.source,install:void 0,docs:void 0}))});let d=hS_(t);return d.length>0&&n.push({"code-samples":d}),n.map(yQt.unknown)}function vS_(e){let t=of(e,Kf.AVAILABILITY);if(t==="ga"||t==="generally-available")return $H.GenerallyAvailable;if(t==="beta"||t==="pre-release")return $H.Beta;if(t==="deprecated")return $H.Deprecated;if(e.deprecated)return $H.Deprecated}function Qau(e){return{url:SFE({url:e.url,variables:e.variables??{}}),description:e.description,name:DFE(e),audiences:of(e,Kf.AUDIENCES)}}function SFE({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 DFE(e){let t=of(e,[Kf.SERVER_NAME_V1,Kf.SERVER_NAME_V2]);if(t!=null)return t;if(e.description?.toLowerCase()==="production")return"Production";if(e.description?.toLowerCase()==="sandbox")return"Sandbox"}function bS_(e){return of(e,Kf.PARAMETER_NAME)}function gS_(e){return of(e,Kf.SDK_VARIABLE)}function Jau({path:e,httpMethod:t,parameters:r,context:i,requestBreadcrumbs:n,source:a}){let u={pathParameters:[],queryParameters:[],headers:[]};for(let l of r){let d=of(l,Kf.IGNORE);if(d!=null&&d){i.logger.debug(`${t.toUpperCase()} ${e} has a parameter marked with x-fern-ignore. Skipping.`);continue}let s=Kd(l)?i.resolveParameterReference(l):l,o=s.required??!1,c=sK(s),b=[...n,s.name],g=Q8(b,i.options.preserveSchemaIds),O=s.schema!=null?j0(s.schema,!o,i,b,a,i.namespace,!1,new Set,Sor({schema:s,logger:i.logger})):o?Al.primitive({nameOverride:void 0,generatedName:g,title:void 0,schema:ap.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:Sor({schema:s,logger:i.logger})}),description:void 0,availability:c,namespace:void 0,groupName:void 0}):Al.optional({nameOverride:void 0,generatedName:g,title:void 0,value:Al.primitive({nameOverride:void 0,generatedName:g,title:void 0,schema:ap.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:Sor({schema:s,logger:i.logger})}),description:void 0,availability:void 0,namespace:void 0,groupName:void 0}),description:void 0,availability:c,namespace:void 0,groupName:void 0,inline:void 0});if(s.in==="header"&&s.schema!=null&&!Kd(s.schema)&&s.schema.default!=null){let w=s.schema.default;typeof w=="string"&&w.length>0&&(O=Al.literal({nameOverride:void 0,generatedName:g,title:void 0,value:Kz.string(w),description:void 0,availability:c,namespace:void 0,groupName:void 0}))}let m={name:s.name,schema:O,description:s.description,parameterNameOverride:bS_(s),availability:c,source:a};s.in==="query"?u.queryParameters.push(m):s.in==="path"?u.pathParameters.push({...m,variableReference:gS_(s)}):s.in==="header"?!EFE.has(s.name.toLowerCase())&&!i.authHeaders.has(s.name)?u.headers.push({...m,env:void 0}):i.logger.debug(`Ignoring ${s.name} header, in ${t.toUpperCase()} ${e}`):i.logger.warn(`Skipping ${s.in} parameter, ${s.name}, in ${t.toUpperCase()} ${e}`)}return u}var EFE=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]);function OS_(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:k5a(i,t)}}}function MFE(e){return e.includes("json")||e==="*/*"}function mSc({content:e,context:t}){for(let[r,i]of Object.entries(e))if(Kau({mediaType:r,mediaTypeObject:i,context:t})!=null)return[r,i]}function Kau({mediaType:e,mediaTypeObject:t,context:r}){if(!MFE(e))return;let i=t.schema;return{contentType:e.includes("*")?void 0:e,schema:i??{},examples:k5a(t,r)}}function Yau({content:e,context:t}){let r=mSc({content:e,context:t});if(!r)return;let[i,n]=r;return Kau({mediaType:i,mediaTypeObject:n,context:t})}function mS_(e,t){for(let r of Object.keys(e)){let i=e[r];if(i==null)continue;return{schema:i.schema??{},examples:k5a(i,t)}}}function k5a(e,t){let r=[];e.example!=null&&r.push({name:void 0,value:e.example,description:void 0});let i=of(e,JH.EXAMPLES);return i!=null&&Object.keys(i).length>0&&r.push(...Object.entries(i).map(([n,a])=>({name:a.summary??n,value:a.value,description:a.description}))),e.examples!=null&&Object.keys(e.examples).length>0&&r.push(...Object.entries(e.examples).map(([n,a])=>{let u=Kd(a)?t.resolveExampleReference(a):a;return{name:u.summary??n,value:u.value,description:u.description}})),r}function AFE({content:e,context:t}){for(let[r,i]of Object.entries(e))if(jS_({mediaType:r,mediaTypeObject:i,context:t}))return[r,i]}function jS_({mediaType:e,mediaTypeObject:t,context:r}){if(hq.parse(e)?.isURLEncoded())return{schema:t.schema,contentType:e,examples:k5a(t,r)}}function qFE({content:e}){for(let[t,r]of Object.entries(e))if(wS_({mediaType:t,mediaTypeObject:r}))return[t,r]}function wS_({mediaType:e,mediaTypeObject:t}){if(hq.parse(e)?.isMultipart())return{schema:t.schema,encoding:t.encoding}}function SS_({mediaType:e}){return hq.parse(e)?.isBinary()??!1}function TFE({content:e}){for(let[t,r]of Object.entries(e))if(SS_({mediaType:t}))return[t,r]}function CFE(e,t){let r=Kd(e)?PSc(e,t):{id:void 0,schema:e};return Object.entries(r.schema.properties??{}).find(([i,n])=>!Kd(n)&&n.type==="string"&&n.format==="binary")!=null}function Zau({content:e,description:t,document:r,context:i,requestBreadcrumbs:n,source:a,namespace:u}){let l=TFE({content:e});if(l){let[b,g]=l;return Dor({mediaType:b,mediaTypeObject:g,description:t,document:r,context:i,requestBreadcrumbs:n,source:a,namespace:u})}let d=qFE({content:e}),s=mSc({content:e,context:i}),o=BFE({json:s,multipart:d,document:r,visitor:{json:([b,g])=>Dor({mediaType:b,mediaTypeObject:g,description:t,document:r,context:i,requestBreadcrumbs:n,source:a,namespace:u}),multipart:([b,g])=>Dor({mediaType:b,mediaTypeObject:g,description:t,document:r,context:i,requestBreadcrumbs:n,source:a,namespace:u}),neither:()=>{}}});if(o)return o;let c=AFE({content:e,context:i});if(c){let[b,g]=c;return Dor({mediaType:b,mediaTypeObject:g,description:t,document:r,context:i,requestBreadcrumbs:n,source:a,namespace:u})}}function BFE({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&&CFE(n.schema,r)?i.multipart(t):i.json(e):n?.schema?i.json(e):a?.schema?i.multipart(t):i.neither()}function Dor({mediaType:e,mediaTypeObject:t,description:r,document:i,context:n,requestBreadcrumbs:a,source:u,namespace:l}){let d=IFE({mediaTypeObject:t});if(SS_({mediaType:e}))return nee.octetStream({description:r,source:u,sdkMethodName:d,contentType:e});let s=wS_({mediaType:e,mediaTypeObject:t}),o=s?.schema,c=s?.encoding;if(o){let O=Kd(o)?PSc(o,i):{id:void 0,schema:o},m=j0(O.schema,!1,n,a,u,l,!1),w=[];if(m.type==="object")for(let E of m.properties){let{isFile:q,isOptional:M,isArray:D,description:C}=Xau({schema:E.schema});if(q){let R=PS_(E.key,c);w.push({key:E.key,schema:Ymi.file({isOptional:M,isArray:D,description:C}),description:C,contentType:R,exploded:!1,encoding:R==null?n.options.defaultFormParameterEncoding:void 0})}else{let R=PS_(E.key,c);w.push({key:E.key,schema:Ymi.json(E.schema),description:void 0,contentType:R,exploded:c?.[E.key]?.explode,encoding:R==null?n.options.defaultFormParameterEncoding:RFE(R)})}}return nee.multipart({name:Kd(o)&&n.getNumberOfOccurrencesForRef(o)===1?O.id:void 0,description:O.schema.description,properties:w,source:u,sdkMethodName:d})}let b=Kau({mediaType:e,mediaTypeObject:t,context:n});if(b){let O=j0(b.schema,!1,n,a,u,l,!0);return nee.json({description:void 0,schema:O,contentType:b.contentType,fullExamples:b.examples,additionalProperties:!Kd(b.schema)&&MKn(b.schema.additionalProperties,n.options),source:u,sdkMethodName:d})}let g=jS_({mediaType:e,mediaTypeObject:t,context:n});if(g!=null&&g.schema!=null){let O=j0(g.schema,!1,n,a,u,l,!1);return nee.formUrlEncoded({schema:O,description:r,contentType:g.contentType,source:u,fullExamples:g.examples,additionalProperties:!1,sdkMethodName:d})}}function IFE({mediaTypeObject:e}){return of(e,Kf.SDK_METHOD_NAME)}var zFE={"application/json":"json"};function RFE(e){return e?zFE[e]:void 0}function PSc(e,t){if(!e.$ref.startsWith(nan))throw new Error(`Failed to resolve schema reference because of unsupported prefix: ${e.$ref}`);let r=YNi(e);if(r==null)throw new Error(`Failed to resolve schema reference because missing schema id: ${e.$ref}`);let i=t.components?.schemas?.[r];if(i==null)throw new Error(`Failed to resolve schema reference because missing: ${e.$ref}`);return Kd(i)?PSc(i,t):{id:r,schema:i}}function Xau({schema:e,isOptional:t,isArray:r,description:i}){return NFE(e)?Xau({schema:e.value,isOptional:!0,isArray:r,description:e.description}):FFE(e)?Xau({schema:e.value,isOptional:t,isArray:r,description:e.description}):LFE(e)?Xau({schema:e.value,isOptional:t,isArray:!0,description:e.description}):xFE(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 xFE(e){return e.type==="primitive"&&e.schema.type==="string"&&e.schema.format==="binary"}function NFE(e){return e.type==="optional"}function FFE(e){return e.type==="nullable"}function LFE(e){return e.type==="array"}function PS_(e,t){return t?.[e]?.contentType}var jSc={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"},DS_=new Set(Object.values(jSc));var UFE=["200","201","202","204"];function MS_({operationContext:e,responses:t,context:r,responseBreadcrumbs:i,responseStatusCode:n,streamFormat:a,source:u}){if(t==null)return{value:void 0,errors:{}};let l=VFE({responses:t,context:r,source:u,namespace:r.namespace}),d=!1,s;for(let o of n!=null?[n]:UFE){let c=t[o];c!=null&&(d=!0,s==null&&(s=ES_({operationContext:e,response:c,context:r,responseBreadcrumbs:i,streamFormat:a,source:u,namespace:r.namespace,statusCode:typeof o=="string"?parseInt(o):o})))}if(s==null&&!d&&t.default!=null&&(s=ES_({operationContext:e,response:t.default,context:r,responseBreadcrumbs:i,streamFormat:a,source:u,namespace:r.namespace})),s!=null)switch(s.type){case"json":return{value:s,errors:l};case"streamingJson":case"streamingSse":return{value:s,errors:l};case"bytes":case"file":case"text":case"streamingText":return{value:s,errors:l};default:So(s)}return{value:void 0,errors:l}}function ES_({operationContext:e,streamFormat:t,response:r,context:i,responseBreadcrumbs:n,source:a,namespace:u,statusCode:l}){let d=Kd(r)?i.resolveResponseReference(r):r;if(d.content!=null&&Object.entries(d.content).find(([b,g])=>{if(g.schema==null)return!1;let O=Kd(g.schema)?i.resolveSchemaReference(g.schema):g.schema;return O.type==="string"&&O.format==="binary"}))return i.options.useBytesForBinaryResponse&&t==null?iB.bytes({description:d.description,source:a,statusCode:l}):iB.file({description:d.description,source:a,statusCode:l});let s=OS_(d.content??{},i);if(s!=null&&t!=null)switch(t){case"json":return iB.streamingJson({statusCode:l,description:d.description,responseProperty:of(e.operation,Kf.RESPONSE_PROPERTY),fullExamples:s.examples,schema:j0(s.schema,!1,i,n,a,u),source:a});case"sse":return iB.streamingSse({description:d.description,responseProperty:void 0,fullExamples:s.examples,schema:j0(s.schema,!1,i,n,a,u),source:a,statusCode:l})}let o=Yau({context:i,content:d.content??{}});if(o){if(t!=null)switch(t){case"json":return iB.streamingJson({description:d.description,responseProperty:void 0,fullExamples:o.examples,schema:j0(o.schema,!1,i,n,a,u),source:a,statusCode:l});case"sse":return iB.streamingSse({description:d.description,responseProperty:void 0,fullExamples:o.examples,schema:j0(o.schema,!1,i,n,a,u),source:a,statusCode:l})}return iB.json({description:d.description,schema:j0(o.schema,!1,i,n,a,u),responseProperty:of(e.operation,Kf.RESPONSE_PROPERTY),fullExamples:o.examples,source:a,statusCode:l})}for(let[c,b]of Object.entries(d.content??{})){let g=hq.parse(c);if(g!=null){if(g.isOctetStream()||g.isPDF()||g.isAudio()||g.isImage()||g.isVideo())return iB.file({description:d.description,source:a,statusCode:l});if(g.isPlainText()){let O=b.schema;if(O==null)return iB.text({description:d.description,source:a,statusCode:l});let m=Kd(O)?i.resolveSchemaReference(O):O;return m.type==="string"&&m.format==="byte"?iB.file({description:d.description,source:a,statusCode:l}):iB.text({description:d.description,source:a,statusCode:l})}}}}function VFE({responses:e,context:t,source:r,namespace:i}){let n={};for(let[a,u]of Object.entries(e)){if(a==="default")continue;let l=parseInt(a);if(l<400||l>600)continue;let d=Kd(u)?t.resolveResponseReference(u):u,s=mS_(d.content??{},t),o=jSc[l];if(o==null){t.logger.warn(`No error name found for status code ${a}`);continue}n[l]={statusCode:l,nameOverride:void 0,generatedName:o,description:d.description,schema:j0(s?.schema??{},!1,t,[o,"Body"],r,i),fullExamples:s?.examples,source:r}}return n}function rPi({operationContext:e,context:t,responseStatusCode:r,suffix:i,streamFormat:n,source:a}){let{document:u,operation:l,path:d,method:s,baseBreadcrumbs:o}=e,c=of(l,Kf.IDEMPOTENT),b=of(l,[Kf.REQUEST_NAME_V1,Kf.REQUEST_NAME_V2]),g=[...o,"Request"],O=Jau({parameters:[...e.pathItemParameters,...e.operationParameters],context:t,requestBreadcrumbs:g,path:d,httpMethod:s,source:a}),m=/{([^}]+)}/g,E=[...d.matchAll(m)].map(I=>I[1]).filter(I=>!O.pathParameters.some(L=>L.name===I));if(E.length>0)for(let I of E)O.pathParameters.push({name:I??"",variableReference:void 0,parameterNameOverride:void 0,availability:void 0,source:a,schema:Al.primitive({schema:ap.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});let q=(()=>{if(e.method==="GET")return[void 0];if(!l.requestBody)return[void 0];let I=Kd(l.requestBody)?t.resolveRequestBodyReference(l.requestBody):l.requestBody,L=Object.values(I.content).every(Y=>WFE({mediaTypeObject:Y})!=null),V=[];if(L)return V.push(...Object.entries(I.content).map(([Y,K])=>{let X=Dor({mediaType:Y,mediaTypeObject:K,description:I.description,document:u,context:new aan({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:g,source:a,namespace:t.namespace});return AS_({context:t,convertedParameters:O})&&X!=null&&(X.type==="json"||X.type==="formUrlEncoded")&&X.schema.type!=="object"&&l.requestBody!=null?X=Dor({mediaType:Y,mediaTypeObject:K,description:I.description,document:u,context:t,requestBreadcrumbs:[...g,"Body"],source:a,namespace:t.namespace}):l.requestBody!=null&&(X=Dor({mediaType:Y,mediaTypeObject:K,description:I.description,document:u,context:t,requestBreadcrumbs:[...g],source:a,namespace:t.namespace})),X}).filter(Y=>Y!=null)),V.length===0?[void 0]:V;{let Y=Zau({content:I.content,description:I.description,document:u,context:new aan({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:g,source:a,namespace:t.namespace});return AS_({context:t,convertedParameters:O})&&Y!=null&&(Y.type==="json"||Y.type==="formUrlEncoded")&&Y.schema.type!=="object"&&l.requestBody!=null?Y=Zau({content:I.content,description:I.description,document:u,context:t,requestBreadcrumbs:[...g,"Body"],source:a,namespace:t.namespace}):l.requestBody!=null&&(Y=Zau({content:I.content,description:I.description,document:u,context:t,requestBreadcrumbs:[...g],source:a,namespace:t.namespace})),[Y]}})(),M=[...o,"Response"],D=MS_({operationContext:e,streamFormat:n,responses:l.responses,context:t,responseBreadcrumbs:M,responseStatusCode:r,source:a}),C=vS_(l),R=yS_(e,l,t),G=of(l,Kf.SERVER_NAME_V2);return q.map(I=>({summary:l.summary,internal:of(l,JH.INTERNAL),idempotent:c,audiences:of(l,Kf.AUDIENCES)??[],operationId:l.operationId!=null&&i!=null?l.operationId+"_"+i:l.operationId,tags:t.resolveTagsToTagIds(l.tags),namespace:t.namespace,sdkName:HFE({operationContext:e,request:I}),pathParameters:O.pathParameters,queryParameters:O.queryParameters,headers:O.headers,requestNameOverride:b??void 0,generatedRequestName:Q8(g,t.options.preserveSchemaIds),request:I,response:D.value,errors:D.errors,servers:G!=null?[{name:G,url:void 0,audiences:void 0}]:(l.servers??[]).map(L=>Qau(L)),description:l.description,authed:$FE(l,u),availability:C,method:s,path:d,examples:R,pagination:e.pagination,source:a}))}function WFE({mediaTypeObject:e}){return of(e,Kf.SDK_METHOD_NAME)}function HFE({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 $FE(e,t){return e.security!=null?Object.keys(e.security).length>0:t.security!=null?Object.keys(t.security).length>0:!1}function AS_({context:e,convertedParameters:t}){return e.options.inlinePathParameters&&t.pathParameters.length>0||t.queryParameters.length>0||t.headers.length>0}function TS_({operationContext:e,context:t,asyncExtension:r,source:i}){let{operation:n,pathItemParameters:a,operationParameters:u}=e,l=r.discriminant.name,d=r.discriminant.value,s=r["response-status-code"],o=qS_({context:t,headerToIgnore:l,parameters:a}),c=qS_({context:t,headerToIgnore:l,parameters:u}),b=rPi({operationContext:{...e,pathItemParameters:o,operationParameters:c,operation:{...n,responses:Object.fromEntries(Object.entries(n.responses).filter(([O])=>parseInt(O)!==s))}},context:t,streamFormat:void 0,source:i}),g=rPi({operationContext:{...e,pathItemParameters:o,operationParameters:c,baseBreadcrumbs:[...e.baseBreadcrumbs,"async"]},context:t,suffix:"async",responseStatusCode:s,streamFormat:void 0,source:i});return g.forEach(O=>{O.headers.push({name:l,schema:Al.literal({nameOverride:void 0,generatedName:Q8([l],t.options.preserveSchemaIds),title:void 0,description:void 0,availability:void 0,value:Kz.string(d),namespace:void 0,groupName:void 0}),description:void 0,parameterNameOverride:void 0,env:void 0,availability:void 0,source:i})}),{sync:b,async:g}}function qS_({context:e,headerToIgnore:t,parameters:r}){return r.filter(i=>{let n=Kd(i)?e.resolveParameterReference(i):i;return!(n.in==="header"&&n.name===t)})}var wSc="stream";function zS_({operationContext:e,context:t,streamingExtension:r}){switch(r.type){case"stream":return{streaming:rPi({operationContext:e,context:t,streamFormat:r.format,source:t.source}),nonStreaming:[]};case"streamCondition":{let i=CS_({context:t,operation:e.operation,streamingExtension:r,isStreaming:!0});if(i?.schemaReference!=null){let s=YNi(i.schemaReference);s!=null&&t.excludeSchema(s)}let n=BS_({operation:e.operation,response:r.responseStream}),a=rPi({operationContext:{...e,sdkMethodName:e.sdkMethodName!=null?{groupName:e.sdkMethodName.groupName,methodName:e.sdkMethodName.methodName+"_"+wSc}:void 0,operation:{...e.operation,description:r.streamDescription??e.operation.description,requestBody:i?.requestBody,responses:n},baseBreadcrumbs:[...e.baseBreadcrumbs,wSc]},context:t,streamFormat:r.format,suffix:wSc,source:t.source});a.forEach(s=>{s.examples=s.examples.filter(o=>IS_(o,t)!==!1)});let u=CS_({context:t,operation:e.operation,streamingExtension:r,isStreaming:!1}),l=BS_({operation:e.operation,response:r.response}),d=rPi({streamFormat:void 0,operationContext:{...e,operation:{...e.operation,requestBody:u?.requestBody,responses:l}},context:t,source:t.source});return d.forEach(s=>{s.examples=s.examples.filter(o=>IS_(o,t)!==!0)}),{streaming:a,nonStreaming:d}}default:So(r)}}function CS_({context:e,operation:t,streamingExtension:r,isStreaming:i}){if(t.requestBody==null)return;let n=Kd(t.requestBody)?e.resolveRequestBodyReference(t.requestBody):t.requestBody,a=Yau({content:n.content,context:e});if(a==null)return;let u=Kd(a.schema)?e.resolveSchemaReference(a.schema):a.schema;if(u.allOf==null&&u.properties==null)return;let l=u.properties?.[r.streamConditionProperty];l!=null&&Kd(l)&&(l=void 0);let d={...u,properties:{...u.properties,[r.streamConditionProperty]:{type:"boolean","x-fern-boolean-literal":i,...l??{}}},title:void 0,required:[...u.required??[],r.streamConditionProperty]};return{requestBody:{content:{[hq.APPLICATION_JSON]:{schema:d}}},schemaReference:Kd(a.schema)?a.schema:void 0}}function BS_({operation:e,response:t}){return{...e.responses,200:{description:"",content:{[hq.APPLICATION_JSON]:{schema:t}}}}}function IS_(e,t){return e._visit({unknown:r=>{let i=MF.serialization.ExampleEndpointCallSchema.parse(r);if(i.ok&&i.value.response!=null)return i.value.response.stream!=null},full:()=>{},_other:()=>{}})}function RS_({context:e,operationContext:t,source:r}){let{document:i,operation:n,path:a,method:u,baseBreadcrumbs:l,sdkMethodName:d}=t,s=[...l,"Payload"],o=Jau({parameters:[...t.pathItemParameters,...t.operationParameters],context:e,requestBreadcrumbs:s,path:a,httpMethod:u,source:r});if(n.requestBody==null)return e.logger.error(`Skipping webhook ${u.toUpperCase()} ${a}: Missing a request body`),[];let c=n.operationId;if(c==null)return e.logger.error(`Skipping webhook ${a} because no operation id present`),[];if(u!=="POST"&&u!=="GET")return e.logger.error(`Skipping webhook ${u.toUpperCase()} ${a}: Not POST or GET`),[];let b=Kd(n.requestBody)?e.resolveRequestBodyReference(n.requestBody):n.requestBody;return Object.entries(b.content).map(([g,O])=>Dor({mediaType:g,mediaTypeObject:O,description:b.description,document:i,context:e,requestBreadcrumbs:[...l,"Payload"],source:r,namespace:e.namespace})).filter(g=>g!=null).map(g=>{if(g==null||g.type!=="json"&&g.type!=="formUrlEncoded"){e.logger.error(`Skipping webhook ${a} because non-json and non-formUrlEncoded request body`);return}return{summary:n.summary,audiences:of(n,Kf.AUDIENCES)??[],sdkName:d,namespace:e.namespace,method:u,operationId:c,tags:e.resolveTagsToTagIds(n.tags),headers:o.headers,generatedPayloadName:Q8(s,e.options.preserveSchemaIds),payload:g.schema,description:n.description,examples:GFE(g.fullExamples),source:r}}).filter(g=>g!=null)}function GFE(e){if(e==null)return[];let t=[];for(let r of e){let i=ZNi(r.value);i!=null&&t.push({description:r.description,name:r.name,payload:i})}return t}function SSc({context:e,pathItemContext:t,operation:r,convertToWebhook:i}){let n=of(r,Kf.IGNORE);if(n!=null&&n){e.logger.debug(`${t.method.toUpperCase()} ${t.path} is marked with x-fern-ignore. Skipping.`);return}let a=QFE(r,e),u=sS_(e.document,r),l={...t,sdkMethodName:a,baseBreadcrumbs:JFE({operation:r,sdkMethodName:a,httpMethod:t.method,path:t.path,shouldUseIdiomaticRequestNames:e.options.shouldUseIdiomaticRequestNames}),operation:r,operationParameters:r.parameters??[],pagination:u};if(i)return{type:"webhook",value:RS_({context:e,operationContext:l,source:e.source})};let d=oS_(r);if(d!=null){let c=zS_({context:e,operationContext:l,streamingExtension:d});return c!=null?{type:"streaming",streaming:c.streaming,nonStreaming:c.nonStreaming}:void 0}let s=nS_(r);if(s!=null){let c=TS_({context:e,operationContext:l,asyncExtension:s,source:e.source});return{type:"async",async:c.async,sync:c.sync}}return{type:"http",value:rPi({context:e,operationContext:l,streamFormat:void 0,source:e.source})}}function QFE(e,t){let r=of(e,Kf.SDK_METHOD_NAME),i=of(e,Kf.SDK_GROUP_NAME)??[];if(r!=null){let n=typeof i=="string"?[i]:i;return n=t.resolveGroupName(n),{groupName:n,methodName:r}}}function JFE({sdkMethodName:e,operation:t,httpMethod:r,path:i,shouldUseIdiomaticRequestNames:n}){let a=[];if(e!=null){if(n&&a.push(e.methodName),e.groupName.length>0){let u=e.groupName[e.groupName.length-1];u!=null&&a.push(typeof u=="string"?u:u.name)}n||a.push(e.methodName)}else t.operationId!=null?a.push(t.operationId):a.push(S_(`${r}_${i.split("/").join("_")}`));return a}function xS_(e,t,r,i){let n=[],a=FS_(t),u={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let l of a){if(i.filter.skipEndpoint({method:l.method,path:e})){i.logger.debug(`Skipping endpoint "${l.method} ${e}"`);continue}let d=KFE({operation:l.operation}),s=SSc({context:i,pathItemContext:{...u,method:l.method},operation:l.operation,convertToWebhook:d});s&&n.push(s)}return n}function NS_(e,t,r,i){let n=[],a=FS_(t),u={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let l of a){if(i.filter.skipEndpoint({method:l.method,path:e})){i.logger.debug(`Skipping endpoint "${l.method} ${e}"`);continue}let d=SSc({context:i,pathItemContext:{...u,method:l.method},operation:l.operation,convertToWebhook:!0});d&&n.push(d)}return n}function FS_(e){let t=[];return e.get!=null&&t.push({method:QH.Get,operation:e.get}),e.post!=null&&t.push({method:QH.Post,operation:e.post}),e.put!=null&&t.push({method:QH.Put,operation:e.put}),e.delete!=null&&t.push({method:QH.Delete,operation:e.delete}),e.patch!=null&&t.push({method:QH.Patch,operation:e.patch}),e.head!=null&&t.push({method:QH.Head,operation:e.head}),t}function KFE({operation:e}){return of(e,[Kf.WEBHOOK])??!1}function LS_(e){let t=of(e,Kf.BASIC_AUTH_USERNAME_VARIABLE_NAME),r=of(e,Kf.BASIC_AUTH_PASSWORD_VARIABLE_NAME);return{usernameVariable:t,passwordVariable:r}}function US_(e){return of(e,Kf.FERN_BASIC_AUTH)}function DSc(e,t){if(Kd(e))throw new Error(`Converting referenced security schemes is unsupported: ${JSON.stringify(e)}`);return YFE(e,t)}function YFE(e,t){if(e.type==="apiKey"&&e.in==="header"){let r=of(e,JH.BEARER_FORMAT),i=of(e,Kf.FERN_HEADER_AUTH);return JL.header({headerName:e.name,prefix:r!=null?"Bearer":i?.prefix,headerVariableName:i?.name??of(e,Kf.HEADER_VARIABLE_NAME),headerEnvVar:i?.env})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="bearer"){let r=of(e,Kf.FERN_BEARER_TOKEN);return JL.bearer({tokenVariableName:r?.name??of(e,Kf.BEARER_TOKEN_VARIABLE_NAME),tokenEnvVar:r?.env})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="basic"){let r=US_(e),i=LS_(e);return JL.basic({usernameVariableName:r?.username?.name??i.usernameVariable,usernameEnvVar:r?.username?.env,passwordVariableName:r?.password?.name??i.passwordVariable,passwordEnvVar:r?.password?.env})}else{if(e.type==="openIdConnect")return JL.bearer({tokenVariableName:void 0,tokenEnvVar:void 0});if(e.type==="oauth2")return JL.oauth({scopesEnum:XFE(e,t)})}}function XFE(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=KNi({nameOverride:void 0,generatedName:"OauthScope",title:void 0,enumValues:Object.keys(r),fernEnum:Object.fromEntries(Object.entries(r).map(([a,u])=>[a,{description:u}])),_default:void 0,description:void 0,availability:void 0,enumVarNames:void 0,wrapAsNullable:!1,namespace:void 0,groupName:void 0,context:void 0,source:t,inline:void 0}),n=iA(i);if(n.type==="enum")return n}}function VS_(e){return of(e,Kf.BASE_PATH)}var ZFE=Su.record(Su.string(),Su.object({summary:Su.string().optional(),description:Su.string().optional()}));function WS_({document:e,context:t}){return J5a(e,Kf.GROUPS,ZFE,t.logger)}function HS_({context:e,document:t}){return of(t,Kf.FERN_VERSION)??void 0}function $S_(e){let t=of(e,Kf.FERN_GLOBAL_HEADERS),r=[];for(let i of t??[])r.push({...i,schema:i.type!=null?K5a({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 GS_(e){let t=of(e,Kf.FERN_IDEMPOTENCY_HEADERS),r=[];for(let i of t??[])r.push({...i,schema:i.type!=null?K5a({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 QS_(e,t){let r=of(e,Kf.SDK_VARIABLES);return r==null?{}:Object.fromEntries(Object.entries(r).map(([i,n])=>{if(n.type==="string")return[i,{nameOverride:void 0,generatedName:Q8([i],t),title:n.title,schema:jw.string({default:qKn(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 kFE="webhooks";function JS_(e){return of(e,kFE)??{}}var kau=class extends zKn{nonRequestReferencedSchemas=new Set;twoOrMoreRequestsReferencedSchemas=new Set;singleRequestReferencedSchemas=new Set;discriminatedUnionReferences={};discriminatedUnionMetadata={};schemasToExclude=new Set;constructor({document:t,taskContext:r,authHeaders:i,options:n,source:a,namespace:u}){super({document:t,taskContext:r,authHeaders:i,options:n,source:a,namespace:u})}getDummy(){return new aan({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 KS_(e){return of(e,Kf.RESOLUTIONS)}function YS_({openapi:e}){let t=KS_(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=e3E({openapi:e,schemaReference:a,schemaName:i.name}),e=XS_({openapi:e,replaceReference:a,schemaReference:n,replacedReferences:r}),r={...r,...Object.fromEntries(i.resolutions.map(u=>[n,u]))}}return e}function e3E({openapi:e,schemaReference:t,schemaName:r}){let i=t.replace("#/","").split("/").map(a=>a.replaceAll("~1","/")),n=e;for(let a of i){let u=n[a];if(u==null)return e;n=u}return e.components==null&&(e.components={}),e.components.schemas==null&&(e.components.schemas={}),e.components.schemas[r]=n,e}function XS_({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 XS_({openapi:e,replaceReference:t,schemaReference:s,replacedReferences:{}})}}let a=t.replace("#/","").split("/").map(d=>d.replaceAll("~1","/")),u=e;for(let d of a.slice(0,-1)){let s=u[d];if(s==null)return e;u=s}let l=a[a.length-1];return l==null||(u[l]={$ref:r}),e}function kS_({openApi:e,taskContext:t,options:r,source:i,namespace:n}){e=YS_({openapi:e});let a=Object.fromEntries(Object.entries(e.components?.securitySchemes??{}).map(([I,L])=>DSc(L,i)==null?[]:[I,DSc(L,i)])),u=new Set(...Object.entries(a).map(([I,L])=>L.type==="basic"||L.type==="bearer"?"Authorization":L.type==="header"?L.headerName:null)),l=QS_(e,r.preserveSchemaIds),d=$S_(e),s=GS_(e),o=r.audiences??[],c=[],b=[],g=new kau({document:e,taskContext:t,authHeaders:u,options:r,source:i,namespace:n});g.filter.hasEndpoints()&&t.logger.debug("Endpoint filter applied..."),Object.entries(e.paths??{}).forEach(([I,L])=>{if(L==null)return;t.logger.debug(`Converting path ${I}`);let V=xS_(I,L,e,g);for(let Y of V){let K=ZS_({operation:Y});if(!(o.length>0&&!o.some(X=>K.includes(X))))switch(Y.type){case"async":c.push(...Y.sync),c.push(...Y.async);break;case"http":c.push(...Y.value);break;case"streaming":c.push(...Y.streaming),Y.nonStreaming&&c.push(...Y.nonStreaming);break;case"webhook":b.push(...Y.value);break;default:So(Y)}}}),Object.entries(JS_(e)).forEach(([I,L])=>{if(L==null)return;t.logger.debug(`Converting path ${I}`);let V=NS_(I,L,e,g);for(let Y of V){let K=ZS_({operation:Y});o.length>0&&!o.some(X=>K.includes(X))||b.push(...Y.value)}});let O=Object.fromEntries(Object.entries(e.components?.schemas??{}).map(([I,L])=>{let V=of(L,Kf.SDK_NAMESPACE);if(!Kd(L)){let Y=of(L,Kf.IGNORE);if(Y!=null&&Y)return[];if(DS_.has(I))return[I,j0({...L,"x-fern-type-name":`${I}Body`},!1,g,[I],i,V??n)]}return[I,j0(L,!1,g,[I],i,V??n)]}).filter(I=>I.length>0)),m=t3E(O,g,i),w=r3E(m,g),E={};for(let[I,L]of Object.entries(w)){let V=iA(L);g.isSchemaExcluded(I)||(E[I]=V,t.logger.debug(`Converted schema ${I}`))}let q=new kNi(w,g.nonRequestReferencedSchemas,g),M=b.map(I=>{let V=I.examples;if(!r.disableExamples&&V.length===0){let Y=q.buildExample({schema:I.payload,exampleId:void 0,example:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});Y!=null&&(V=[{name:void 0,description:void 0,payload:Y}])}return{...I,payload:iA(I.payload),examples:V}}),D=new Uau(w,g,d),C=c.map(I=>{let L=I.examples,V=L;if(!r.disableExamples&&(L.length===0||L.every(X5a))){let X=D.buildEndpointExample(I);X.length>0&&(V=[...X,...L.filter(oe=>!X5a(oe))])}let Y=I.request,K=I.response;return{...I,request:Y?.type==="json"||Y?.type==="formUrlEncoded"?{...Y,schema:iA(Y.schema)}:Y,response:K?.type==="json"?{...K,schema:iA(K.schema)}:K,queryParameters:I.queryParameters.map(X=>({description:X.description,name:X.name,schema:iA(X.schema),parameterNameOverride:X.parameterNameOverride,availability:X.availability,source:X.source})),pathParameters:I.pathParameters.map(X=>({description:X.description,name:X.name,schema:iA(X.schema),parameterNameOverride:X.parameterNameOverride,variableReference:X.variableReference,availability:X.availability,source:X.source})),headers:I.headers.map(X=>({description:X.description,name:X.name,schema:iA(X.schema),parameterNameOverride:X.parameterNameOverride,env:X.env,availability:X.availability,source:X.source})),examples:V,errors:_d(I.errors,X=>{let oe=X.fullExamples?.map(pe=>{let de=ZNi(pe.value);if(de!=null)return{name:pe.name,description:pe.description,example:de}}).filter(iv);if(oe?.length===0){let pe=q.buildExample({schema:X.schema,example:void 0,exampleId:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});pe!=null&&oe.push({name:void 0,description:void 0,example:pe})}return{generatedName:X.generatedName,nameOverride:X.nameOverride,schema:iA(X.schema),description:X.description,source:X.source,examples:oe}})}}),R=WS_({document:e,context:g});return{apiVersion:HS_({context:g,document:e}),basePath:VS_(e),title:e.info.title??"",description:e.info.description,groups:Object.fromEntries(Object.entries(R??{}).map(([I,L])=>[I,{summary:L.summary??void 0,description:L.description??void 0}])),servers:(e.servers??[]).map(I=>Qau(I)),websocketServers:[],tags:{tagsById:Object.fromEntries((e.tags??[]).map(I=>[I.name,{id:I.name,description:I.description}])),orderedTagIds:e.tags?.map(I=>I.name)},endpoints:C,webhooks:M,channels:{},groupedSchemas:BKn(n,E),securitySchemes:a,hasEndpointsMarkedInternal:C.some(I=>I.internal),nonRequestReferencedSchemas:g.getReferencedSchemas(),variables:l,globalHeaders:d,idempotencyHeaders:s}}function t3E(e,t,r){let i={};for(let[n,a]of Object.entries(e)){if(a.type!=="object"){i[n]=a;continue}let u={$ref:`#/components/schemas/${n}`},l=t.getReferencesFromDiscriminatedUnion(u);if(l==null){i[n]=a;continue}let d={...a,type:"object",properties:a.properties.filter(o=>!l.discriminants.has(o.key)),allOfPropertyConflicts:a.allOfPropertyConflicts.filter(o=>!l.discriminants.has(o.propertyKey)),source:r};i[n]=d;let s=eD_({schema:a,schemas:e});for(let o of[...new Set(s)]){let c=i[o]??e[o];c==null||c.type!=="object"||(i[o]={...c,type:"object",properties:c.properties.filter(b=>!l.discriminants.has(b.key)),allOfPropertyConflicts:c.allOfPropertyConflicts.filter(b=>!l.discriminants.has(b.propertyKey))})}}return i}function r3E(e,t){let r={};for(let[i,n]of Object.entries(e)){if(n.type!=="object"){r[i]=n;continue}let a={$ref:`#/components/schemas/${i}`},u=t.getDiscriminatedUnionMetadata(a);if(u==null){r[i]=n;continue}let l=[];for(let s of n.properties)if(u.discriminants.has(s.key)){let o=u.discriminants.get(s.key);o!=null&&l.push({...s,schema:Al.literal({nameOverride:void 0,generatedName:Q8([n.generatedName,o],t.options.preserveSchemaIds),title:void 0,value:Kz.string(o),namespace:void 0,groupName:void 0,description:void 0,availability:n.availability})})}else l.push(s);let d={...n,type:"object",properties:l};r[i]=d}return r}function eD_({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(...eD_({schema:n,schemas:t}))}return r}function eou(e){return[...new Set(e)]}function ZS_({operation:e}){let t=[];switch(e.type){case"async":t=eou(e.async.flatMap(r=>r.audiences));break;case"http":t=eou(e.value.flatMap(r=>r.audiences));break;case"streaming":t=eou(e.streaming.flatMap(r=>r.audiences));break;case"webhook":t=eou(e.value.flatMap(r=>r.audiences));break;default:So(e)}return t}function oan({context:e,documents:t,options:r}){let i={apiVersion:void 0,title:void 0,description:void 0,basePath:void 0,servers:[],websocketServers:[],tags:{tagsById:{},orderedTagIds:void 0},hasEndpointsMarkedInternal:!1,endpoints:[],webhooks:[],channels:{},groupedSchemas:{rootSchemas:{},namespacedSchemas:{}},variables:{},nonRequestReferencedSchemas:new Set,securitySchemes:{},globalHeaders:[],idempotencyHeaders:[],groups:{}};for(let n of t){let a=n.source!=null?n.source:nK.openapi({file:"<memory>"});switch(n.type){case"openapi":{let u=kS_({taskContext:e,openApi:n.value,options:gQt({options:n.settings,overrides:r}),source:a,namespace:n.namespace});i=n3E(i,u);break}case"asyncapi":{let u=iS_({document:n.value,taskContext:e,options:gQt({options:n.settings,overrides:r}),source:a,asyncApiOptions:i3E({options:n.settings}),namespace:n.namespace});u.servers!=null&&(i.websocketServers=[...i.websocketServers,...u.servers.map(l=>({...l,audiences:void 0,description:void 0}))]),u.channels!=null&&(i.channels={...i.channels,...u.channels}),u.groupedSchemas!=null&&(i.groupedSchemas=tD_(i.groupedSchemas,u.groupedSchemas)),u.basePath!=null&&(i.basePath=u.basePath);break}default:So(n)}}return i}function i3E({options:e,overrides:t}){return{naming:t?.naming??e?.asyncApiNaming??w1_.naming}}function n3E(e,t){return{apiVersion:e.apiVersion??t.apiVersion,title:e.title??t.title,description:e.description??t.description,basePath:e.basePath??t.basePath,servers:[...e.servers,...t.servers],websocketServers:[...e.websocketServers,...t.websocketServers],tags:{tagsById:{...e.tags.tagsById,...t.tags.tagsById},orderedTagIds:e.tags.orderedTagIds==null&&t.tags.orderedTagIds==null?void 0:[...e.tags.orderedTagIds??[],...t.tags.orderedTagIds??[]]},hasEndpointsMarkedInternal:e.hasEndpointsMarkedInternal||t.hasEndpointsMarkedInternal,endpoints:[...e.endpoints,...t.endpoints],webhooks:[...e.webhooks,...t.webhooks],channels:{...e.channels,...t.channels},groupedSchemas:tD_(e.groupedSchemas,t.groupedSchemas),variables:{...e.variables,...t.variables},nonRequestReferencedSchemas:new Set([...e.nonRequestReferencedSchemas,...t.nonRequestReferencedSchemas]),securitySchemes:{...e.securitySchemes,...t.securitySchemes},globalHeaders:e.globalHeaders!=null?[...e.globalHeaders,...t.globalHeaders??[]]:void 0,idempotencyHeaders:e.idempotencyHeaders!=null?[...e.idempotencyHeaders,...t.idempotencyHeaders??[]]:void 0,groups:{...e.groups,...t.groups}}}function tD_(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 Dz_=ui(Ycu(),1),Xcu={config:new Dz_.Config({apis:{},styleguide:{plugins:[lSc],rules:{struct:"warn"}}},void 0),dereference:!1,removeUnusedComponents:!1,keepUrlRefs:!0};function CYn(e){if(e.settings==null&&e.raw?.api?.auth==null)return;let t={detectGlobalHeaders:!0};return e.settings?.unions==="v1"&&(t.discriminatedUnionV2=!0),e.raw?.api?.auth!=null&&(t.auth=e.raw?.api?.auth),t}function nLa(e){return e.swagger!=null}function Fqc(e){return e.openapi!=null}function aLa({options:e,overrides:t}={}){return{...gQt({options:e,overrides:t}),...R5a({options:e,overrides:t})}}function EFi(e,t={}){return{...Object.fromEntries(B3(e.namedDefinitionFiles).map(([r,i])=>[r,{...i,defaultUrl:t.defaultURL}])),...B3(e.importedDefinitions).reduce((r,[i,n])=>({...r,...Dza(EFi(n.definition,{defaultURL:n.url}),(a,u)=>PF(i,fy.of(u)))}),{})}}function oLa(e,t={}){return{...Object.fromEntries(B3(e.packageMarkers).map(([r,i])=>[r,{...i,defaultUrl:t.defaultURL}])),...B3(e.importedDefinitions).reduce((r,[i,n])=>({...r,...Dza(oLa(n.definition,{defaultURL:n.url}),(a,u)=>PF(i,fy.of(u)))}),{})}}function OPi(e){return{...oLa(e),...EFi(e)}}function gue(e,t){return OPi(e.definition)[t]?.contents}function m7(e,t){for(let[r,i]of B3(OPi(e.definition)))t(r,i.contents,{isPackageMarker:lki(r)===fS,defaultUrl:i.defaultUrl})}function Can(e,t){for(let[r,i]of B3(oLa(e.definition)))t(r,i.contents)}function p7e({breadcrumbs:e=[],title:t,subtitle:r}){let i=[];return e.length>0&&i.push(Ds.blue(e.join(" -> "))),i.push(t),r!=null&&i.push(Ds.dim(r)),i.join(`
1959
+ `)),{ok:!0,value:t}):i}}function yiu(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var YJn=class e extends Error{errors;constructor(t){super(t.map(yiu).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var XJn=class e extends Error{errors;constructor(t){super(t.map(yiu).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function mT(e){return{optional:()=>N1c(e),transform:t=>F1c(e,t),parseOrThrow:(t,r)=>{let i=e.parse(t,r);if(i.ok)return i.value;throw new XJn(i.errors)},jsonOrThrow:(t,r)=>{let i=e.json(t,r);if(i.ok)return i.value;throw new YJn(i.errors)}}}function N1c(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:()=>Zj.OPTIONAL};return{...t,...mT(t)}}function F1c(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,...mT(r)}}function sw_(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:VA(t,"string")}]}:{ok:!0,value:BigInt(t)},json:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t=="bigint"?{ok:!0,value:t.toString()}:{ok:!1,errors:[{path:r,message:VA(t,"bigint")}]},getType:()=>Zj.BIGINT};return{...KL(e),...mT(e)}}var AxE=/^([+-]?\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 cw_(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:VA(t,"string")}]}:AxE.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:VA(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:VA(t,"Date object")}]},getType:()=>Zj.DATE};return{...KL(e),...mT(e)}}function oK(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{...KL(r),...mT(r)}}}function viu(e){let t=new Set(e);return oK(Zj.ENUM,(i,{allowUnrecognizedEnumValues:n,breadcrumbsPrefix:a=[]}={})=>typeof i!="string"?{ok:!1,errors:[{path:a,message:VA(i,"string")}]}:!t.has(i)&&!n?{ok:!1,errors:[{path:a,message:VA(i,"enum")}]}:{ok:!0,value:i})()}function lw_(e){let t=L1c(e);return{...t,...mT(t)}}function L1c(e){return{parse:(t,r)=>ZJn(e).parse(t,r),json:(t,r)=>ZJn(e).json(t,r),getType:()=>ZJn(e).getType()}}function ZJn(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function x5a(e){return Object.entries(e)}function N5a(e,t){let r=new Set(t);return Object.entries(e).reduce((i,[n,a])=>(r.has(n)&&(i[n]=a),i),{})}function xNi(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 F5a(e){return Object.keys(e)}function fw_(e,t){let r=[],i=[];for(let n of e)t(n)?r.push(n):i.push(n);return[r,i]}function bQt(e){return{withParsedProperties:t=>U1c(e,t)}}function U1c(e,t){let r={parse:(i,n)=>{let a=e.parse(i,n);if(!a.ok)return a;let u=Object.entries(t).reduce((l,[d,s])=>({...l,[d]:typeof s=="function"?s(a.value):s}),{});return{ok:!0,value:{...a.value,...u}}},json:(i,n)=>{if(!xNi(i))return{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:VA(i,"object")}]};let a=new Set(Object.keys(t)),u=N5a(i,Object.keys(i).filter(l=>!a.has(l)));return e.json(u,n)},getType:()=>e.getType()};return{...r,...mT(r),...bQt(r)}}function dw_(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function NNi(e){return e.isProperty}function biu(e){let t={_getRawProperties:()=>Object.entries(e).map(([r,i])=>NNi(i)?i.rawKey:r),_getParsedProperties:()=>F5a(e),parse:(r,i)=>{let n={},a=[];for(let[u,l]of x5a(e)){let d=NNi(l)?l.rawKey:u,s=NNi(l)?l.valueSchema:l,o={rawKey:d,parsedKey:u,valueSchema:s};n[d]=o,hw_(s)&&a.push(d)}return pw_({value:r,requiredKeys:a,getProperty:u=>{let l=n[u];if(l!=null)return{transformedKey:l.parsedKey,transform:d=>l.valueSchema.parse(d,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],u]})}},unrecognizedObjectKeys:i?.unrecognizedObjectKeys,skipValidation:i?.skipValidation,breadcrumbsPrefix:i?.breadcrumbsPrefix,omitUndefined:i?.omitUndefined})},json:(r,i)=>{let n=[];for(let[a,u]of x5a(e)){let l=NNi(u)?u.valueSchema:u;hw_(l)&&n.push(a)}return pw_({value:r,requiredKeys:n,getProperty:a=>{let u=e[a];if(u!=null)return NNi(u)?{transformedKey:u.rawKey,transform:l=>u.valueSchema.json(l,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],a]})}:{transformedKey:a,transform:l=>u.json(l,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],a]})}},unrecognizedObjectKeys:i?.unrecognizedObjectKeys,skipValidation:i?.skipValidation,breadcrumbsPrefix:i?.breadcrumbsPrefix,omitUndefined:i?.omitUndefined})},getType:()=>Zj.OBJECT};return{...KL(t),...mT(t),...bQt(t),...ean(t)}}function pw_({value:e,requiredKeys:t,getProperty:r,unrecognizedObjectKeys:i="fail",skipValidation:n=!1,breadcrumbsPrefix:a=[]}){if(!xNi(e))return{ok:!1,errors:[{path:a,message:VA(e,"object")}]};let u=new Set(t),l=[],d={};for(let[s,o]of Object.entries(e)){let c=r(s);if(c!=null){u.delete(s);let b=c.transform(o);b.ok?d[c.transformedKey]=b.value:(d[s]=o,l.push(...b.errors))}else switch(i){case"fail":l.push({path:[...a,s],message:`Unexpected key "${s}"`});break;case"strip":break;case"passthrough":d[s]=o;break}}return l.push(...t.filter(s=>u.has(s)).map(s=>({path:a,message:`Missing required key "${s}"`}))),l.length===0||n?{ok:!0,value:d}:{ok:!1,errors:l}}function ean(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(i,n)=>_w_({extensionKeys:t._getRawProperties(),value:i,transformBase:a=>e.parse(a,n),transformExtension:a=>t.parse(a,n)}),json:(i,n)=>_w_({extensionKeys:t._getParsedProperties(),value:i,transformBase:a=>e.json(a,n),transformExtension:a=>t.json(a,n)}),getType:()=>Zj.OBJECT};return{...r,...mT(r),...bQt(r),...ean(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:()=>Zj.OBJECT};return{...t,...mT(t),...bQt(t),...ean(t)}}}}function _w_({extensionKeys:e,value:t,transformBase:r,transformExtension:i}){let n=new Set(e),[a,u]=fw_(F5a(t),s=>n.has(s)),l=r(N5a(t,u)),d=i(N5a(t,a));return l.ok&&d.ok?{ok:!0,value:{...l.value,...d.value}}:{ok:!1,errors:[...l.ok?[]:l.errors,...d.ok?[]:d.errors]}}function hw_(e){return!qxE(e)}function qxE(e){switch(e.getType()){case Zj.ANY:case Zj.UNKNOWN:case Zj.OPTIONAL:return!0;default:return!1}}function yw_(e){return biu(e)}function vw_(e){let t={...L1c(e),_getRawProperties:()=>ZJn(e)._getRawProperties(),_getParsedProperties:()=>ZJn(e)._getParsedProperties()};return{...t,...mT(t),...bQt(t),...ean(t)}}function giu(e){let t={parse:(r,i)=>bw_(r,(n,a)=>e.parse(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),json:(r,i)=>bw_(r,(n,a)=>e.json(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),getType:()=>Zj.LIST};return{...KL(t),...mT(t)}}function bw_(e,t){return Array.isArray(e)?e.map((i,n)=>t(i,n)).reduce((i,n)=>{if(i.ok&&n.ok)return{ok:!0,value:[...i.value,n.value]};let a=[];return i.ok||a.push(...i.errors),n.ok||a.push(...n.errors),{ok:!1,errors:a}},{ok:!0,value:[]}):{ok:!1,errors:[{message:VA(e,"list"),path:[]}]}}function gw_(e){return oK(Zj.STRING_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:VA(r,`"${e}"`)}]})()}function Ow_(e){return oK(Zj.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:VA(r,`${e.toString()}`)}]})()}var mw_=oK(Zj.ANY,e=>({ok:!0,value:e}));var Pw_=oK(Zj.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:VA(e,"boolean")}]});var jw_=oK(Zj.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:VA(e,"number")}]});var ww_=oK(Zj.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:VA(e,"string")}]});var Sw_=oK(Zj.UNKNOWN,e=>({ok:!0,value:e}));function Ew_(e,t){let r={parse:(i,n)=>Dw_({value:i,isKeyNumeric:e.getType()===Zj.NUMBER,transformKey:a=>e.parse(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,u)=>t.parse(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${u}`]}),breadcrumbsPrefix:n?.breadcrumbsPrefix}),json:(i,n)=>Dw_({value:i,isKeyNumeric:e.getType()===Zj.NUMBER,transformKey:a=>e.json(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,u)=>t.json(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${u}`]}),breadcrumbsPrefix:n?.breadcrumbsPrefix}),getType:()=>Zj.RECORD};return{...KL(r),...mT(r)}}function Dw_({value:e,isKeyNumeric:t,transformKey:r,transformValue:i,breadcrumbsPrefix:n=[]}){return xNi(e)?x5a(e).reduce((a,[u,l])=>{if(l==null)return a;let d=a,s=u;if(t){let g=u.length>0?Number(u):NaN;isNaN(g)||(s=g)}let o=r(s),c=i(l,s);if(d.ok&&o.ok&&c.ok)return{ok:!0,value:{...d.value,[o.value]:c.value}};let b=[];return d.ok||b.push(...d.errors),o.ok||b.push(...o.errors),c.ok||b.push(...c.errors),{ok:!1,errors:b}},{ok:!0,value:{}}):{ok:!1,errors:[{path:n,message:VA(e,"object")}]}}function Mw_(e){let t=giu(e),r={parse:(i,n)=>{let a=t.parse(i,n);return a.ok?{ok:!0,value:new Set(a.value)}:a},json:(i,n)=>i instanceof Set?t.json([...i],n):{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:VA(i,"Set")}]},getType:()=>Zj.SET};return{...KL(r),...mT(r)}}function qw_(e){let t={parse:(r,i)=>Aw_((n,a)=>n.parse(r,a),e,i),json:(r,i)=>Aw_((n,a)=>n.json(r,a),e,i),getType:()=>Zj.UNDISCRIMINATED_UNION};return{...KL(t),...mT(t)}}function Aw_(e,t,r){let i=[];for(let[n,a]of t.entries()){let u=e(a,{...r,skipValidation:!1});if(u.ok)return u;for(let l of u.errors)i.push({path:l.path,message:`[Variant ${n}] ${l.message}`})}return{ok:!1,errors:i}}function Tw_(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}function Bw_(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,i=typeof e=="string"?e:e.parsedDiscriminant,n=viu(F5a(t)),a={parse:(u,l)=>Cw_({value:u,discriminant:r,transformedDiscriminant:i,transformDiscriminantValue:d=>n.parse(d,{allowUnrecognizedEnumValues:l?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...l?.breadcrumbsPrefix??[],r]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:l?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,s)=>s.parse(d,l),breadcrumbsPrefix:l?.breadcrumbsPrefix}),json:(u,l)=>Cw_({value:u,discriminant:i,transformedDiscriminant:r,transformDiscriminantValue:d=>n.json(d,{allowUnrecognizedEnumValues:l?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...l?.breadcrumbsPrefix??[],i]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:l?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,s)=>s.json(d,l),breadcrumbsPrefix:l?.breadcrumbsPrefix}),getType:()=>Zj.UNION};return{...KL(a),...mT(a),...bQt(a)}}function Cw_({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:i,getAdditionalPropertiesSchema:n,allowUnrecognizedUnionMembers:a=!1,transformAdditionalProperties:u,breadcrumbsPrefix:l=[]}){if(!xNi(e))return{ok:!1,errors:[{path:l,message:VA(e,"object")}]};let{[t]:d,...s}=e;if(d==null)return{ok:!1,errors:[{path:l,message:`Missing discriminant ("${t}")`}]};let o=i(d);if(!o.ok)return{ok:!1,errors:o.errors};let c=n(o.value);if(c==null)return a?{ok:!0,value:{[r]:o.value,...s}}:{ok:!1,errors:[{path:[...l,t],message:"Unexpected discriminant value"}]};let b=u(s,c);return b.ok?{ok:!0,value:{[r]:d,...b.value}}:b}var Em=gt.objectWithoutOptionalProperties({title:gt.string().optional()});var Oiu=gt.objectWithoutOptionalProperties({file:gt.string()});var miu=gt.objectWithoutOptionalProperties({file:gt.string()});var Piu=gt.union("type",{openapi:Oiu,protobuf:miu}).transform({transform:e=>{switch(e.type){case"openapi":return nK.openapi(e);case"protobuf":return nK.protobuf(e);default:return e}},untransform:({_visit:e,...t})=>t});var Oh=gt.objectWithoutOptionalProperties({source:Piu.optional()});var jiu=gt.objectWithoutOptionalProperties({typeName:gt.string()});var wiu=gt.union("type",{protobuf:jiu}).transform({transform:e=>{switch(e.type){case"protobuf":return KJn.protobuf(e);default:return e}},untransform:({_visit:e,...t})=>t});var lue=gt.objectWithoutOptionalProperties({encoding:wiu.optional()});var ff=gt.objectWithoutOptionalProperties({description:gt.string().optional()});var Siu=gt.enum_(["GenerallyAvailable","Beta","Deprecated"]);var Jh=gt.objectWithoutOptionalProperties({availability:Siu.optional()});var Oor=gt.number();var r7e=gt.objectWithoutOptionalProperties({statusCode:Oor.optional()});var k0=gt.objectWithoutOptionalProperties({nameOverride:gt.string().optional(),generatedName:gt.string()});var bM=gt.objectWithoutOptionalProperties({inline:gt.boolean().optional()});var oee=gt.string();var uee=gt.string();var Diu=gt.objectWithoutOptionalProperties({id:uee}).extend(ff);var Eiu=gt.string();var Miu=gt.objectWithoutOptionalProperties({usernameVariableName:gt.string().optional(),usernameEnvVar:gt.string().optional(),passwordVariableName:gt.string().optional(),passwordEnvVar:gt.string().optional()});var Aiu=gt.objectWithoutOptionalProperties({tokenVariableName:gt.string().optional(),tokenEnvVar:gt.string().optional()});var qiu=gt.objectWithoutOptionalProperties({headerName:gt.string(),prefix:gt.string().optional(),headerVariableName:gt.string().optional(),headerEnvVar:gt.string().optional()});var Tiu=gt.objectWithoutOptionalProperties({queryParameterName:gt.string()});var Ciu=gt.objectWithoutOptionalProperties({snake:gt.string().optional(),camel:gt.string().optional(),screamingSnake:gt.string().optional(),pascal:gt.string().optional()});var FNi=gt.objectWithoutOptionalProperties({nameOverride:gt.string().optional(),generatedName:gt.string(),value:gt.string(),casing:Ciu.optional()}).extend(ff).extend(Jh);var Biu=gt.objectWithoutOptionalProperties({type:gt.stringLiteral("namespace"),name:gt.string()});var Iiu=gt.undiscriminatedUnion([gt.string(),Biu]);var LNi=gt.list(Iiu);var Mm=gt.objectWithoutOptionalProperties({groupName:LNi.optional()});var P0=gt.objectWithoutOptionalProperties({namespace:gt.string().optional()});var kJn=gt.objectWithoutOptionalProperties({default:FNi.optional(),values:gt.list(FNi)}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(Oh).extend(Em).extend(bM);var ziu=gt.objectWithoutOptionalProperties({scopesEnum:kJn.optional()});var Riu=gt.union("type",{basic:Miu,bearer:Aiu,header:qiu,query:Tiu,oauth:ziu}).transform({transform:e=>{switch(e.type){case"basic":return JL.basic(e);case"bearer":return JL.bearer(e);case"header":return JL.header(e);case"query":return JL.query(e);case"oauth":return JL.oauth(e);default:return e}},untransform:({_visit:e,...t})=>t});var L5a=gt.objectWithoutOptionalProperties({name:gt.string().optional(),url:gt.string(),audiences:gt.list(gt.string()).optional()}).extend(ff);var xiu=gt.string();var mor=gt.objectWithoutOptionalProperties({sdkMethodName:gt.string().optional()});var W1c={};Po(W1c,{FullExample:()=>PT,FullObjectExample:()=>Fiu,FullOneOfExample:()=>Uiu,KeyValuePair:()=>Liu,LiteralExample:()=>Niu,PrimitiveExample:()=>tKn,PropertyKey:()=>eKn});var eKn=gt.string();var tKn=gt.union("type",{int:gt.object({value:gt.number()}),int64:gt.object({value:gt.number()}),uint:gt.object({value:gt.number()}),uint64:gt.object({value:gt.number()}),float:gt.object({value:gt.number()}),double:gt.object({value:gt.number()}),string:gt.object({value:gt.string()}),datetime:gt.object({value:gt.string()}),date:gt.object({value:gt.string()}),base64:gt.object({value:gt.string()}),boolean:gt.object({value:gt.boolean()})}).transform({transform:e=>{switch(e.type){case"int":return h_.int(e.value);case"int64":return h_.int64(e.value);case"uint":return h_.uint(e.value);case"uint64":return h_.uint64(e.value);case"float":return h_.float(e.value);case"double":return h_.double(e.value);case"string":return h_.string(e.value);case"datetime":return h_.datetime(e.value);case"date":return h_.date(e.value);case"base64":return h_.base64(e.value);case"boolean":return h_.boolean(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var Niu=gt.union("type",{boolean:gt.object({value:gt.boolean()}),string:gt.object({value:gt.string()})}).transform({transform:e=>{switch(e.type){case"boolean":return zNi.boolean(e.value);case"string":return zNi.string(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var PT=gt.union("type",{primitive:gt.object({value:tKn}),object:gt.lazyObject(()=>Fiu),array:gt.object({value:gt.list(gt.lazy(()=>PT))}),map:gt.object({value:gt.list(gt.lazyObject(()=>Liu))}),enum:gt.object({value:gt.string()}),literal:gt.object({value:Niu}),oneOf:gt.object({value:gt.lazy(()=>Uiu)}),unknown:gt.object({value:gt.lazy(()=>PT)})}).transform({transform:e=>{switch(e.type){case"primitive":return xg.primitive(e.value);case"object":return xg.object(e);case"array":return xg.array(e.value);case"map":return xg.map(e.value);case"enum":return xg.enum(e.value);case"literal":return xg.literal(e.value);case"oneOf":return xg.oneOf(e.value);case"unknown":return xg.unknown(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var Fiu=gt.objectWithoutOptionalProperties({properties:gt.record(eKn,gt.lazy(()=>PT))});var Liu=gt.objectWithoutOptionalProperties({key:tKn,value:gt.lazy(()=>PT)});var Uiu=gt.union("type",{discriminated:gt.object({value:gt.record(eKn,gt.lazy(()=>PT))}),undiscriminated:gt.object({value:gt.lazy(()=>PT)})}).transform({transform:e=>{switch(e.type){case"discriminated":return RNi.discriminated(e.value);case"undiscriminated":return RNi.undiscriminated(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var H1c={};Po(H1c,{AllOfPropertyConflict:()=>bKn,ArraySchema:()=>Cnu,Availability:()=>Siu,BooleanSchema:()=>Dnu,BytesResponse:()=>cKn,CasingOverrides:()=>Ciu,CommonProperty:()=>Lnu,CursorPagination:()=>cnu,CustomCodeSample:()=>unu,CustomCodeSampleLanguage:()=>nnu,CustomCodeSampleSdk:()=>onu,CustomPagination:()=>fnu,DiscriminatedOneOfSchema:()=>Nnu,DoubleSchema:()=>wnu,Endpoint:()=>dnu,EndpointExample:()=>pKn,EndpointResponseExample:()=>inu,EndpointSdkName:()=>Por,EnumSchema:()=>kJn,EnumValue:()=>FNi,ErrorExample:()=>Ziu,FernExample:()=>enu,FileResponse:()=>uKn,FileSchema:()=>Hiu,FormUrlEncodedRequest:()=>Kiu,FullEndpointExample:()=>snu,GlobalHeader:()=>Mnu,Header:()=>UNi,HeaderExample:()=>dKn,HttpEndpointServer:()=>lKn,HttpError:()=>kiu,HttpMethod:()=>rKn,IdempotencyHeader:()=>Anu,IntSchema:()=>Pnu,JsonRequest:()=>Jiu,JsonResponse:()=>sKn,LiteralSchema:()=>vKn,LiteralSchemaValue:()=>qnu,LongSchema:()=>jnu,MapSchema:()=>Bnu,MultipartRequest:()=>oKn,MultipartRequestProperty:()=>Qiu,MultipartRequestPropertyEncoding:()=>Giu,MultipartSchema:()=>$iu,NullableSchema:()=>znu,ObjectProperty:()=>xnu,ObjectPropertyConflictInfo:()=>gKn,ObjectSchema:()=>Tnu,OctetStreamRequest:()=>aKn,OffsetPagination:()=>lnu,OneOfSchema:()=>Rnu,OpenApiIntermediateRepresentation:()=>Iw_,OptionalSchema:()=>Inu,Pagination:()=>_Kn,PathParameter:()=>iKn,PathParameterExample:()=>tnu,PrimitiveSchema:()=>WNi,PrimitiveSchemaValue:()=>Enu,QueryParameter:()=>nKn,QueryParameterExample:()=>fKn,ReferencedSchema:()=>jor,Request:()=>Yiu,Response:()=>Xiu,Schema:()=>VO,Schemas:()=>mnu,SdkGroupInfo:()=>Viu,StreamingResponseExample:()=>rnu,StringSchema:()=>Snu,SupportedSdkLanguage:()=>anu,Tags:()=>Wiu,TextResponse:()=>VNi,UnDiscriminatedOneOfSchema:()=>Fnu,Webhook:()=>pnu,WebhookExampleCall:()=>yKn,WebhookHttpMethod:()=>hKn,WebsocketChannel:()=>Onu,WebsocketHandshake:()=>_nu,WebsocketMessageExample:()=>bnu,WebsocketMessageOrigin:()=>hnu,WebsocketMessageSchema:()=>ynu,WebsocketServer:()=>vnu,WebsocketSessionExample:()=>gnu});var Viu=gt.objectWithoutOptionalProperties({summary:gt.string().optional(),description:gt.string().optional()});var Wiu=gt.objectWithoutOptionalProperties({tagsById:gt.record(uee,Diu),orderedTagIds:gt.list(uee).optional()});var rKn=gt.enum_(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS","TRACE"]);var iKn=gt.objectWithoutOptionalProperties({name:gt.string(),schema:gt.lazy(()=>VO),variableReference:gt.string().optional(),parameterNameOverride:gt.string().optional()}).extend(ff).extend(Jh).extend(Oh);var nKn=gt.objectWithoutOptionalProperties({name:gt.string(),schema:gt.lazy(()=>VO),parameterNameOverride:gt.string().optional()}).extend(ff).extend(Jh).extend(Oh);var UNi=gt.objectWithoutOptionalProperties({name:gt.string(),schema:gt.lazy(()=>VO),env:gt.string().optional(),parameterNameOverride:gt.string().optional()}).extend(ff).extend(Jh).extend(Oh);var Por=gt.objectWithoutOptionalProperties({groupName:LNi,methodName:gt.string()});var aKn=gt.objectWithoutOptionalProperties({contentType:gt.string().optional()}).extend(ff).extend(Oh);var Hiu=gt.objectWithoutOptionalProperties({isOptional:gt.boolean(),isArray:gt.boolean()}).extend(ff);var $iu=gt.union("type",{file:Hiu,json:gt.object({value:gt.lazy(()=>VO)})}).transform({transform:e=>{switch(e.type){case"file":return Ymi.file(e);case"json":return Ymi.json(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var Giu=gt.enum_(["json","form"]);var Qiu=gt.objectWithoutOptionalProperties({key:gt.string(),schema:$iu,contentType:gt.string().optional(),exploded:gt.boolean().optional(),encoding:Giu.optional()}).extend(ff);var oKn=gt.objectWithoutOptionalProperties({name:gt.string().optional(),properties:gt.list(Qiu)}).extend(ff).extend(Oh);var Jiu=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>VO),contentType:gt.string().optional(),additionalProperties:gt.boolean()}).extend(ff).extend(Oh);var Kiu=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>VO),contentType:gt.string().optional(),additionalProperties:gt.boolean()}).extend(ff).extend(Oh);var Yiu=gt.union("type",{octetStream:aKn,multipart:oKn,json:Jiu,formUrlEncoded:Kiu}).transform({transform:e=>{switch(e.type){case"octetStream":return gor.octetStream(e);case"multipart":return gor.multipart(e);case"json":return gor.json(e);case"formUrlEncoded":return gor.formUrlEncoded(e);default:return e}},untransform:({_visit:e,...t})=>t});var uKn=gt.objectWithoutOptionalProperties({}).extend(ff).extend(Oh).extend(r7e);var sKn=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>VO),responseProperty:gt.string().optional()}).extend(ff).extend(Oh).extend(r7e);var VNi=gt.objectWithoutOptionalProperties({}).extend(ff).extend(Oh).extend(r7e);var cKn=gt.objectWithoutOptionalProperties({}).extend(ff).extend(Oh).extend(r7e);var Xiu=gt.union("type",{file:uKn,json:sKn,text:VNi,bytes:cKn,streamingSse:sKn,streamingText:VNi,streamingJson:sKn}).transform({transform:e=>{switch(e.type){case"file":return aK.file(e);case"json":return aK.json(e);case"text":return aK.text(e);case"bytes":return aK.bytes(e);case"streamingSse":return aK.streamingSse(e);case"streamingText":return aK.streamingText(e);case"streamingJson":return aK.streamingJson(e);default:return e}},untransform:({_visit:e,...t})=>t});var Ziu=gt.objectWithoutOptionalProperties({name:gt.string().optional(),description:gt.string().optional(),example:gt.lazy(()=>PT)});var kiu=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>VO).optional(),examples:gt.list(Ziu).optional()}).extend(ff).extend(k0).extend(Oh);var lKn=gt.objectWithoutOptionalProperties({name:gt.string().optional(),url:gt.string().optional(),audiences:gt.list(gt.string()).optional()});var enu=gt.unknown();var tnu=gt.objectWithoutOptionalProperties({name:gt.string(),parameterNameOverride:gt.string().optional(),value:gt.lazy(()=>PT)});var fKn=gt.objectWithoutOptionalProperties({name:gt.string(),value:gt.lazy(()=>PT)});var dKn=gt.objectWithoutOptionalProperties({name:gt.string(),value:gt.lazy(()=>PT)});var rnu=gt.objectWithoutOptionalProperties({sse:gt.boolean(),events:gt.list(gt.lazy(()=>PT))});var inu=gt.union("type",{withStreaming:rnu,withoutStreaming:gt.object({value:gt.lazy(()=>PT)})}).transform({transform:e=>{switch(e.type){case"withStreaming":return vQt.withStreaming(e);case"withoutStreaming":return vQt.withoutStreaming(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var nnu=gt.objectWithoutOptionalProperties({name:gt.string().optional(),language:gt.string(),code:gt.string(),install:gt.string().optional()}).extend(ff);var anu=gt.enum_(["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm"]);var onu=gt.objectWithoutOptionalProperties({name:gt.string().optional(),sdk:anu,code:gt.string()}).extend(ff);var unu=gt.union("type",{language:nnu,sdk:onu}).transform({transform:e=>{switch(e.type){case"language":return Kmi.language(e);case"sdk":return Kmi.sdk(e);default:return e}},untransform:({_visit:e,...t})=>t});var snu=gt.objectWithoutOptionalProperties({name:gt.string().optional(),pathParameters:gt.list(tnu).optional(),queryParameters:gt.list(fKn).optional(),headers:gt.list(dKn).optional(),request:gt.lazy(()=>PT).optional(),response:inu.optional(),codeSamples:gt.list(unu)}).extend(ff);var pKn=gt.union("type",{unknown:gt.object({value:enu}),full:snu}).transform({transform:e=>{switch(e.type){case"unknown":return yQt.unknown(e.value);case"full":return yQt.full(e);default:return e}},untransform:({_visit:e,...t})=>t});var cnu=gt.objectWithoutOptionalProperties({cursor:gt.string(),nextCursor:gt.property("next_cursor",gt.string()),results:gt.string()});var lnu=gt.objectWithoutOptionalProperties({offset:gt.string(),results:gt.string(),step:gt.string().optional(),hasNextPage:gt.string().optional()});var fnu=gt.objectWithoutOptionalProperties({results:gt.string()});var _Kn=gt.union("type",{cursor:cnu,offset:lnu,custom:fnu}).transform({transform:e=>{switch(e.type){case"cursor":return t7e.cursor(e);case"offset":return t7e.offset(e);case"custom":return t7e.custom(e);default:return e}},untransform:({_visit:e,...t})=>t});var dnu=gt.objectWithoutOptionalProperties({authed:gt.boolean(),internal:gt.boolean().optional(),idempotent:gt.boolean().optional(),method:rKn,audiences:gt.list(gt.string()),path:gt.string(),summary:gt.string().optional(),operationId:gt.string().optional(),tags:gt.list(uee),pathParameters:gt.list(iKn),queryParameters:gt.list(nKn),headers:gt.list(UNi),sdkName:Por.optional(),generatedRequestName:gt.string(),requestNameOverride:gt.string().optional(),request:Yiu.optional(),response:Xiu.optional(),errors:gt.record(Oor,kiu),servers:gt.list(lKn),examples:gt.list(pKn),pagination:_Kn.optional()}).extend(ff).extend(Jh).extend(Oh).extend(P0);var hKn=gt.enum_(["GET","POST"]);var yKn=gt.objectWithoutOptionalProperties({name:gt.string().optional(),payload:gt.lazy(()=>PT)}).extend(ff);var pnu=gt.objectWithoutOptionalProperties({audiences:gt.list(gt.string()),sdkName:Por.optional(),method:hKn,summary:gt.string().optional(),operationId:gt.string(),tags:gt.list(uee),headers:gt.list(UNi),generatedPayloadName:gt.string(),payload:gt.lazy(()=>VO),examples:gt.list(yKn)}).extend(ff).extend(Oh).extend(P0);var _nu=gt.objectWithoutOptionalProperties({queryParameters:gt.list(nKn),headers:gt.list(UNi),pathParameters:gt.list(iKn)});var hnu=gt.enum_(["client","server"]);var ynu=gt.objectWithoutOptionalProperties({name:gt.string(),origin:hnu,body:gt.lazy(()=>VO)});var vnu=gt.objectWithoutOptionalProperties({name:gt.string(),url:gt.string()});var bnu=gt.objectWithoutOptionalProperties({messageType:gt.string(),payload:gt.lazy(()=>PT)}).extend(ff);var gnu=gt.objectWithoutOptionalProperties({name:gt.string().optional(),queryParameters:gt.list(fKn).optional(),headers:gt.list(dKn).optional(),messages:gt.list(bnu)}).extend(ff);var Onu=gt.objectWithoutOptionalProperties({audiences:gt.list(gt.string()),path:gt.string(),groupName:LNi,summary:gt.string().optional(),handshake:_nu,messages:gt.list(ynu),servers:gt.list(vnu),examples:gt.list(gnu)}).extend(ff).extend(Oh);var mnu=gt.objectWithoutOptionalProperties({rootSchemas:gt.record(oee,gt.lazy(()=>VO)),namespacedSchemas:gt.record(xiu,gt.record(oee,gt.lazy(()=>VO)))});var Pnu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),minimum:gt.number().optional(),maximum:gt.number().optional(),exclusiveMinimum:gt.boolean().optional(),exclusiveMaximum:gt.boolean().optional(),multipleOf:gt.number().optional()});var jnu=gt.objectWithoutOptionalProperties({default:gt.number().optional()});var wnu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),minimum:gt.number().optional(),maximum:gt.number().optional(),exclusiveMinimum:gt.boolean().optional(),exclusiveMaximum:gt.boolean().optional(),multipleOf:gt.number().optional()});var Snu=gt.objectWithoutOptionalProperties({default:gt.string().optional(),pattern:gt.string().optional(),format:gt.string().optional(),minLength:gt.number().optional(),maxLength:gt.number().optional()});var Dnu=gt.objectWithoutOptionalProperties({default:gt.boolean().optional()});var Enu=gt.union("type",{int:Pnu,int64:jnu,uint:gt.object({}),uint64:gt.object({}),float:gt.object({}),double:wnu,string:Snu,datetime:gt.object({}),date:gt.object({}),base64:gt.object({}),boolean:Dnu}).transform({transform:e=>{switch(e.type){case"int":return jw.int(e);case"int64":return jw.int64(e);case"uint":return jw.uint();case"uint64":return jw.uint64();case"float":return jw.float();case"double":return jw.double(e);case"string":return jw.string(e);case"datetime":return jw.datetime();case"date":return jw.date();case"base64":return jw.base64();case"boolean":return jw.boolean(e);default:return e}},untransform:({_visit:e,...t})=>t});var WNi=gt.objectWithoutOptionalProperties({schema:Enu}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(Em);var Mnu=gt.objectWithoutOptionalProperties({header:gt.string(),name:gt.string().optional(),optional:gt.boolean().optional(),env:gt.string().optional(),schema:gt.lazy(()=>VO).optional()});var Anu=gt.objectWithoutOptionalProperties({header:gt.string(),name:gt.string().optional(),env:gt.string().optional(),schema:gt.lazy(()=>VO).optional()});var Iw_=gt.objectWithoutOptionalProperties({apiVersion:gt.unknown().optional(),title:gt.string().optional(),description:gt.string().optional(),basePath:gt.string().optional(),servers:gt.list(L5a),websocketServers:gt.list(L5a),groups:gt.record(gt.string(),Viu),tags:Wiu,hasEndpointsMarkedInternal:gt.boolean(),endpoints:gt.list(dnu),webhooks:gt.list(pnu),channels:gt.record(gt.string(),Onu),groupedSchemas:mnu,variables:gt.record(gt.string(),WNi),nonRequestReferencedSchemas:gt.set(oee),securitySchemes:gt.record(Eiu,Riu),globalHeaders:gt.list(Mnu).optional(),idempotencyHeaders:gt.list(Anu).optional()});var jor=gt.objectWithoutOptionalProperties({schema:oee}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(Oh).extend(Em);var qnu=gt.union("type",{boolean:gt.object({value:gt.boolean()}),string:gt.object({value:gt.string()})}).transform({transform:e=>{switch(e.type){case"boolean":return Kz.boolean(e.value);case"string":return Kz.string(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var vKn=gt.objectWithoutOptionalProperties({value:qnu}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(Em);var VO=gt.union("type",{primitive:WNi,object:gt.lazyObject(()=>Tnu),array:gt.lazyObject(()=>Cnu),map:gt.lazyObject(()=>Bnu),optional:gt.lazyObject(()=>Inu),enum:kJn,reference:jor,literal:vKn,oneOf:gt.object({value:gt.lazy(()=>Rnu)}),nullable:gt.lazyObject(()=>znu),unknown:k0}).transform({transform:e=>{switch(e.type){case"primitive":return cv.primitive(e);case"object":return cv.object(e);case"array":return cv.array(e);case"map":return cv.map(e);case"optional":return cv.optional(e);case"enum":return cv.enum(e);case"reference":return cv.reference(e);case"literal":return cv.literal(e);case"oneOf":return cv.oneOf(e.value);case"nullable":return cv.nullable(e);case"unknown":return cv.unknown(e);default:return e}},untransform:({_visit:e,...t})=>t});var bKn=gt.objectWithoutOptionalProperties({propertyKey:gt.string(),allOfSchemaIds:gt.list(oee),conflictingTypeSignatures:gt.boolean()});var Tnu=gt.objectWithoutOptionalProperties({allOf:gt.list(jor),properties:gt.list(gt.lazyObject(()=>xnu)),allOfPropertyConflicts:gt.list(bKn),additionalProperties:gt.boolean()}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(Oh).extend(Em).extend(bM);var gKn=gt.objectWithoutOptionalProperties({differentSchema:gt.boolean()});var xnu=gt.objectWithoutOptionalProperties({key:gt.string(),schema:gt.lazy(()=>VO),readonly:gt.boolean().optional(),writeonly:gt.boolean().optional(),conflict:gt.record(oee,gKn),generatedName:gt.string(),nameOverride:gt.string().optional(),audiences:gt.list(gt.string())}).extend(Jh);var Cnu=gt.objectWithoutOptionalProperties({value:gt.lazy(()=>VO)}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(Em).extend(bM);var Bnu=gt.objectWithoutOptionalProperties({key:WNi,value:gt.lazy(()=>VO)}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(lue).extend(Em).extend(bM);var Inu=gt.objectWithoutOptionalProperties({value:gt.lazy(()=>VO)}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(Em).extend(bM);var znu=gt.objectWithoutOptionalProperties({value:gt.lazy(()=>VO)}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(Em).extend(bM);var Rnu=gt.union("type",{discriminated:gt.lazyObject(()=>Nnu),undiscriminated:gt.lazyObject(()=>Fnu)}).transform({transform:e=>{switch(e.type){case"discriminated":return Xmi.discriminated(e);case"undiscriminated":return Xmi.undiscriminated(e);default:return e}},untransform:({_visit:e,...t})=>t});var Nnu=gt.objectWithoutOptionalProperties({discriminantProperty:gt.string(),commonProperties:gt.list(gt.lazyObject(()=>Lnu)),schemas:gt.record(gt.string(),gt.lazy(()=>VO))}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(lue).extend(Oh).extend(Em).extend(bM);var Lnu=gt.objectWithoutOptionalProperties({key:gt.string(),schema:gt.lazy(()=>VO)});var Fnu=gt.objectWithoutOptionalProperties({schemas:gt.list(gt.lazy(()=>VO))}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(lue).extend(Oh).extend(Em).extend(bM);var $1c={};Po($1c,{ArraySchemaWithExample:()=>cau,Base64WithExample:()=>nau,BooleanWithExample:()=>aau,CommonPropertyWithExample:()=>bau,DateWithExample:()=>iau,DatetimeWithExample:()=>rau,DiscriminatedOneOfSchemaWithExample:()=>yau,DoubleWithExample:()=>eau,EndpointWithExample:()=>Rw_,EnumSchemaWithExample:()=>uau,FloatWithExample:()=>knu,HeaderWithExample:()=>HNi,HttpErrorWithExample:()=>Jnu,Int64WithExample:()=>Ynu,IntWithExample:()=>Knu,JsonRequestWithExample:()=>Hnu,JsonResponseWithExample:()=>mKn,MapSchemaWithExample:()=>lau,NamedFullExample:()=>i7e,NullableSchemaWithExample:()=>dau,ObjectPropertyWithExample:()=>hau,ObjectSchemaWithExample:()=>pau,OneOfSchemaWithExample:()=>_au,OptionalSchemaWithExample:()=>fau,ParseFormUrlEncodedRequest:()=>$nu,ParseMultipartRequest:()=>Wnu,ParseOctetStreamRequest:()=>Vnu,PathParameterWithExample:()=>Unu,PrimitiveSchemaValueWithExample:()=>oau,PrimitiveSchemaWithExample:()=>PKn,QueryParameterWithExample:()=>OKn,RequestWithExample:()=>Gnu,ResponseWithExample:()=>Qnu,SchemaWithExample:()=>gM,StringSchemaWithExample:()=>tau,Uint64WithExample:()=>Znu,UintWithExample:()=>Xnu,UnDiscriminatedOneOfSchemaWithExample:()=>vau,UnknownSchemaWithExample:()=>sau,WebhookWithExample:()=>xw_,WebsocketHandshakeWithExample:()=>zw_});var i7e=gt.objectWithoutOptionalProperties({name:gt.string().optional(),value:gt.unknown()}).extend(ff);var OKn=gt.objectWithoutOptionalProperties({name:gt.string(),schema:gt.lazy(()=>gM),parameterNameOverride:gt.string().optional()}).extend(ff).extend(Jh).extend(Oh);var HNi=gt.objectWithoutOptionalProperties({name:gt.string(),schema:gt.lazy(()=>gM),env:gt.string().optional(),parameterNameOverride:gt.string().optional()}).extend(ff).extend(Jh).extend(Oh);var zw_=gt.objectWithoutOptionalProperties({queryParameters:gt.list(OKn),headers:gt.list(HNi)});var Unu=gt.objectWithoutOptionalProperties({name:gt.string(),schema:gt.lazy(()=>gM),variableReference:gt.string().optional(),parameterNameOverride:gt.string().optional()}).extend(ff).extend(Jh).extend(Oh);var Vnu=gt.objectWithoutOptionalProperties({}).extend(aKn).extend(mor);var Wnu=gt.objectWithoutOptionalProperties({}).extend(oKn).extend(mor);var Hnu=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>gM),contentType:gt.string().optional(),fullExamples:gt.list(i7e).optional(),additionalProperties:gt.boolean()}).extend(ff).extend(Oh).extend(mor);var $nu=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>gM),contentType:gt.string().optional(),fullExamples:gt.list(i7e).optional(),additionalProperties:gt.boolean()}).extend(ff).extend(Oh).extend(mor);var Gnu=gt.union("type",{octetStream:Vnu,multipart:Wnu,json:Hnu,formUrlEncoded:$nu}).transform({transform:e=>{switch(e.type){case"octetStream":return nee.octetStream(e);case"multipart":return nee.multipart(e);case"json":return nee.json(e);case"formUrlEncoded":return nee.formUrlEncoded(e);default:return e}},untransform:({_visit:e,...t})=>t});var mKn=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>gM),responseProperty:gt.string().optional(),fullExamples:gt.list(i7e).optional()}).extend(ff).extend(Oh).extend(r7e);var Qnu=gt.union("type",{file:uKn,json:mKn,text:VNi,bytes:cKn,streamingSse:mKn,streamingText:VNi,streamingJson:mKn}).transform({transform:e=>{switch(e.type){case"file":return iB.file(e);case"json":return iB.json(e);case"text":return iB.text(e);case"bytes":return iB.bytes(e);case"streamingSse":return iB.streamingSse(e);case"streamingText":return iB.streamingText(e);case"streamingJson":return iB.streamingJson(e);default:return e}},untransform:({_visit:e,...t})=>t});var Jnu=gt.objectWithoutOptionalProperties({statusCode:Oor,schema:gt.lazy(()=>gM),fullExamples:gt.list(i7e).optional()}).extend(ff).extend(k0).extend(Oh);var Rw_=gt.objectWithoutOptionalProperties({authed:gt.boolean(),internal:gt.boolean().optional(),idempotent:gt.boolean().optional(),method:rKn,audiences:gt.list(gt.string()),path:gt.string(),summary:gt.string().optional(),operationId:gt.string().optional(),tags:gt.list(uee),pathParameters:gt.list(Unu),queryParameters:gt.list(OKn),headers:gt.list(HNi),sdkName:Por.optional(),generatedRequestName:gt.string(),requestNameOverride:gt.string().optional(),request:Gnu.optional(),response:Qnu.optional(),errors:gt.record(Oor,Jnu),servers:gt.list(lKn),examples:gt.list(pKn),pagination:_Kn.optional()}).extend(ff).extend(Jh).extend(Oh).extend(P0);var xw_=gt.objectWithoutOptionalProperties({audiences:gt.list(gt.string()),sdkName:Por.optional(),method:hKn,summary:gt.string().optional(),operationId:gt.string(),tags:gt.list(uee),headers:gt.list(HNi),generatedPayloadName:gt.string(),payload:gt.lazy(()=>gM),examples:gt.list(yKn)}).extend(ff).extend(Oh).extend(P0);var Knu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),minimum:gt.number().optional(),maximum:gt.number().optional(),exclusiveMinimum:gt.boolean().optional(),exclusiveMaximum:gt.boolean().optional(),multipleOf:gt.number().optional(),example:gt.number().optional()});var Ynu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),example:gt.number().optional()});var Xnu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),example:gt.number().optional()});var Znu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),example:gt.number().optional()});var knu=gt.objectWithoutOptionalProperties({example:gt.number().optional()});var eau=gt.objectWithoutOptionalProperties({default:gt.number().optional(),minimum:gt.number().optional(),maximum:gt.number().optional(),exclusiveMinimum:gt.boolean().optional(),exclusiveMaximum:gt.boolean().optional(),multipleOf:gt.number().optional(),example:gt.number().optional()});var tau=gt.objectWithoutOptionalProperties({default:gt.string().optional(),pattern:gt.string().optional(),format:gt.string().optional(),minLength:gt.number().optional(),maxLength:gt.number().optional(),example:gt.string().optional()});var rau=gt.objectWithoutOptionalProperties({example:gt.string().optional()});var iau=gt.objectWithoutOptionalProperties({example:gt.string().optional()});var nau=gt.objectWithoutOptionalProperties({example:gt.string().optional()});var aau=gt.objectWithoutOptionalProperties({default:gt.boolean().optional(),example:gt.boolean().optional()});var oau=gt.union("type",{int:Knu,int64:Ynu,uint:Xnu,uint64:Znu,float:knu,double:eau,string:tau,datetime:rau,date:iau,base64:nau,boolean:aau}).transform({transform:e=>{switch(e.type){case"int":return ap.int(e);case"int64":return ap.int64(e);case"uint":return ap.uint(e);case"uint64":return ap.uint64(e);case"float":return ap.float(e);case"double":return ap.double(e);case"string":return ap.string(e);case"datetime":return ap.datetime(e);case"date":return ap.date(e);case"base64":return ap.base64(e);case"boolean":return ap.boolean(e);default:return e}},untransform:({_visit:e,...t})=>t});var PKn=gt.objectWithoutOptionalProperties({schema:oau}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(Em);var uau=gt.objectWithoutOptionalProperties({default:FNi.optional(),values:gt.list(FNi),example:gt.string().optional()}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(Oh).extend(Em).extend(bM);var sau=gt.objectWithoutOptionalProperties({example:gt.unknown()}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(Em);var gM=gt.union("type",{primitive:PKn,object:gt.lazyObject(()=>pau),array:gt.lazyObject(()=>cau),map:gt.lazyObject(()=>lau),optional:gt.lazyObject(()=>fau),enum:uau,reference:jor,literal:vKn,oneOf:gt.object({value:gt.lazy(()=>_au)}),nullable:gt.lazyObject(()=>dau),unknown:sau}).transform({transform:e=>{switch(e.type){case"primitive":return Al.primitive(e);case"object":return Al.object(e);case"array":return Al.array(e);case"map":return Al.map(e);case"optional":return Al.optional(e);case"enum":return Al.enum(e);case"reference":return Al.reference(e);case"literal":return Al.literal(e);case"oneOf":return Al.oneOf(e.value);case"nullable":return Al.nullable(e);case"unknown":return Al.unknown(e);default:return e}},untransform:({_visit:e,...t})=>t});var cau=gt.objectWithoutOptionalProperties({value:gt.lazy(()=>gM),example:gt.list(gt.unknown()).optional()}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(Em).extend(bM);var lau=gt.objectWithoutOptionalProperties({key:PKn,value:gt.lazy(()=>gM),example:gt.unknown().optional()}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(lue).extend(Em).extend(bM);var fau=gt.objectWithoutOptionalProperties({value:gt.lazy(()=>gM)}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(Em).extend(bM);var dau=gt.objectWithoutOptionalProperties({value:gt.lazy(()=>gM)}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(Em).extend(bM);var pau=gt.objectWithoutOptionalProperties({allOf:gt.list(jor),properties:gt.list(gt.lazyObject(()=>hau)),allOfPropertyConflicts:gt.list(bKn),fullExamples:gt.list(i7e).optional(),additionalProperties:gt.boolean()}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(Oh).extend(Em).extend(bM);var hau=gt.objectWithoutOptionalProperties({key:gt.string(),schema:gt.lazy(()=>gM),readonly:gt.boolean().optional(),writeonly:gt.boolean().optional(),audiences:gt.list(gt.string()),conflict:gt.record(oee,gKn),nameOverride:gt.string().optional(),generatedName:gt.string()}).extend(Jh);var _au=gt.union("type",{discriminated:gt.lazyObject(()=>yau),undiscriminated:gt.lazyObject(()=>vau)}).transform({transform:e=>{switch(e.type){case"discriminated":return aee.discriminated(e);case"undiscriminated":return aee.undiscriminated(e);default:return e}},untransform:({_visit:e,...t})=>t});var yau=gt.objectWithoutOptionalProperties({discriminantProperty:gt.string(),commonProperties:gt.list(gt.lazyObject(()=>bau)),schemas:gt.record(gt.string(),gt.lazy(()=>gM))}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(lue).extend(Oh).extend(Em).extend(bM);var bau=gt.objectWithoutOptionalProperties({key:gt.string(),schema:gt.lazy(()=>gM)});var vau=gt.objectWithoutOptionalProperties({schemas:gt.list(gt.lazy(()=>gM))}).extend(Mm).extend(P0).extend(k0).extend(ff).extend(Jh).extend(lue).extend(Oh).extend(Em).extend(bM);var Nw_=/^(\d+)/,jKn=/^[a-zA-Z][a-zA-Z0-9_]*$/,Fw_={"<":"LESS_THAN",">":"GREATER_THAN",">=":"GREATER_THAN_OR_EQUAL_TO","<=":"LESS_THAN_OR_EQUAL_TO","!=":"NOT_EQUALS","=":"EQUAL_TO","==":"EQUAL_TO","*":"ALL","":"EMPTY",'""':"EMPTY_STRING","-":"HYPHEN","|":"PIPE",".":"DOT","/":"SLASH"};function $Ni(e){let t=["zero","one","two","three","four","five","six","seven","eight","nine"],r=["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],i=["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"];if(e<0||e>9999)return;if(e<10)return t[e];if(e<20)return r[e-10];if(e<100){let u=Math.floor(e/10),l=e%10;return l===0?i[u]:`${i[u]}_${t[l]}`}if(e<1e3){let u=Math.floor(e/100),l=e%100;return l===0?`${t[u]}_hundred`:`${t[u]}_hundred_${$Ni(l)}`}let n=Math.floor(e/1e3),a=e%1e3;return a===0?`${t[n]}_thousand`:`${t[n]}_thousand_${$Ni(a)}`}function U5a(e){let t=e.match(Nw_);if(t&&t[0]!=null){let r=t[0],i=e.substring(r.length),n=parseFloat(r);if(!isNaN(n)&&isFinite(n)){let a=$Ni(n);return i.length>0?`${a}_${i}`:a}}}function wKn(e){let t=U5a(e),r=Fw_[e];return t!=null?qB(S_(t)):r??(e.toLowerCase()==="n/a"?"NOT_APPLICABLE":qB(S_(e)))}function fue(e,t){return e.type==="primitive"&&t.type==="primitive"?Lw_(e.schema,t.schema):e.type==="enum"&&t.type==="enum"?TxE(e.values,t.values):e.type==="array"&&t.type==="array"?fue(e.value,t.value):e.type==="unknown"&&t.type==="unknown"?!0:e.type==="reference"&&t.type==="reference"?e.schema===t.schema:e.type==="optional"&&t.type==="optional"?fue(e.value,t.value):e.type==="oneOf"&&t.type==="oneOf"?CxE(e.value,t.value):e.type==="object"&&t.type==="object"?BxE(e,t):e.type==="map"&&t.type==="map"?Lw_(e.key.schema,t.key.schema)&&fue(e.value,t.value):e.type==="literal"&&t.type==="literal"?e.value===t.value:!1}function Lw_(e,t){return e.type===t.type}function TxE(e,t){let r=new Set(...e.map(n=>n.value)),i=new Set(...t.map(n=>n.value));return g8(r,i)}function CxE(e,t){return e.type==="discriminated"&&t.type==="discriminated"?e.discriminantProperty===t.discriminantProperty&&Object.keys(e.schemas).length===Object.keys(t.schemas).length&&Object.entries(e.schemas).every(([r,i])=>{let n=t.schemas[r];return n==null?!1:fue(i,n)}):e.type==="undiscriminated"&&t.type==="undiscriminated"?e.schemas.length===t.schemas.length&&e.schemas.every((r,i)=>{let n=t.schemas[i];return n==null?!1:fue(r,n)}):!1}function BxE(e,t){if(Object.keys(e.properties).length!==Object.keys(t.properties).length)return!1;let r=Object.fromEntries(e.properties.map(i=>[i.key,i.schema]));return Object.entries(t.properties).every(([i,n])=>{let a=r[i];return a==null?!1:fue(a,n.schema)})}function rx(e){switch(e){case $H.Deprecated:return"deprecated";case $H.Beta:return"pre-release";case $H.GenerallyAvailable:return"generally-available";default:return}}function IxE(e){let t=e.find(i=>typeof i=="object"&&i.type==="namespace"),r=e.filter(i=>typeof i=="string"||i.type!=="namespace");return t?[t,...r]:r}function Uw_(e){let t=e?IxE(e):void 0;if(t==null||t.length===0)return WZi;let r=[];for(let[i,n]of t.entries())if(typeof n=="string")r.push(S_(n));else if(typeof n=="object")switch(n.type){case"namespace":{i<t.length-1?r.push(S_(n.name)):r.push(n.name,WZi);break}default:So(n.type)}else So(n);return r.join("/")}function GNi(e){return fy.of(`${Uw_(e)}.yml`)}function G1c({sdkName:e,namespaceOverride:t}){let r;return e==null||e.groupName.length===0&&t==null?WZi:(t!=null?r=[{type:"namespace",name:t},...e.groupName.filter(i=>typeof i=="string"||i.type!=="namespace")]:r=e.groupName,Uw_(r))}function Vw_({sdkName:e,namespaceOverride:t}){return fy.of(`${G1c({sdkName:e,namespaceOverride:t})}.yml`)}function Ww_({location:e,namespaceOverride:t}){return t!=null?PF(fy.of(t),e):e}function gau(e){switch(e.type){case"protobuf":return{proto:{type:e.typeName}};default:So(e.type)}}function SKn(e){switch(e.type){case"object":case"enum":case"array":case"map":case"reference":case"literal":case"optional":case"nullable":case"primitive":return e.groupName??void 0;case"oneOf":return e.value.groupName??void 0;case"unknown":return;default:So(e)}}function WA(e){return typeof e=="string"?e:e.type}function DKn(e){if(typeof e!="string")return e.docs}function V5a(e){if(typeof e!="string")return e.default}function Q1c(e){if(typeof e!="string")return e.validation}var zxE=-2147483648,RxE=2147483647,xxE=-17976931348623157e292,NxE=17976931348623157e292;function Ng({schema:e,fileContainingReference:t,declarationFile:r=t,context:i,namespace:n,declarationDepth:a}){switch(i.shouldMarkSchemaAsReferenced()&&i.markSchemaAsReferenced(e,n),e.type){case"primitive":return Oau(e);case"array":return Y1c({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"map":return X1c({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"reference":return K1c({schema:e,fileContainingReference:t,context:i,namespace:n});case"unknown":return k1c();case"optional":return mau({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"nullable":return Z1c({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"enum":return QxE({schema:e,fileContainingReference:t,context:i,declarationFile:r,declarationDepth:a});case"literal":return e.value,eSc(e);case"object":return JxE({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"oneOf":return KxE({schema:e.value,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});default:So(e)}}function Oau(e){switch(e.schema.type){case"string":return UxE({description:e.description,schema:e.schema});case"int":return VxE({description:e.description,schema:e.schema});case"float":return WxE({description:e.description,schema:e.schema});case"double":return HxE({description:e.description,schema:e.schema});case"boolean":return FxE({description:e.description,schema:e.schema});case"int64":return LxE({description:e.description,schema:e.schema})}let t=e.schema._visit({int:()=>"integer",int64:()=>"long",uint:()=>"uint",uint64:()=>"uint64",float:()=>"double",double:()=>"double",string:()=>"string",datetime:()=>"datetime",date:()=>"date",base64:()=>"base64",boolean:()=>"boolean",_other:()=>"unknown"});return e.description==null&&e.title==null?t:{type:t,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:rx(e.availability)}:{}}}function FxE({description:e,schema:t}){let r="boolean";if(e==null&&t.default==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),i}function LxE({description:e,schema:t}){let r="long";if(e==null&&t.default==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),i}function UxE({description:e,schema:t}){let r="string",i=$xE(t);if(e==null&&t.default==null&&i==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),i!=null&&(n.validation=i),n}function VxE({description:e,schema:t}){let r="integer",i=$w_(t,r);if(e==null&&t.default==null&&i==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),i!=null&&(n.validation=i),n}function WxE({description:e,schema:t}){let r="float";if(e==null)return r;let i={type:r};return e!=null&&(i.docs=e),i}function HxE({description:e,schema:t}){let r="double",i=$w_(t,r);if(e==null&&t.default==null&&i==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),i!=null&&(n.validation=i),n}function $xE(e){if(e==null)return;let{format:t,pattern:r,minLength:i,maxLength:n}=e,a=GxE(t);if(!(a==null&&r==null&&i==null&&n==null))return{format:a,pattern:r,minLength:i,maxLength:n}}function GxE(e){switch(e){case"date":case"date-time":case"password":case"byte":case"bytes":case"binary":case"email":case"uuid":case"uri":case"hostname":case"ipv4":case"ipv6":return e;default:return}}function $w_(e,t){if(e==null)return;let{minimum:r,maximum:i,multipleOf:n}=e,{exclusiveMinimum:a,exclusiveMaximum:u}=e;if(r=J1c(r,t),i=J1c(i,t),n=J1c(n,t),!(r==null&&i==null&&a==null&&u==null&&n==null))return{min:r,max:i,exclusiveMin:a,exclusiveMax:u,multipleOf:n}}function J1c(e,t){if(e===void 0)return;let[r,i]=t==="integer"?[zxE,RxE]:[xxE,NxE];return e<r||e>i?void 0:e}function K1c({schema:e,fileContainingReference:t,context:r,namespace:i}){let n=r.getSchema(e.schema,i);if(n==null)return"unknown";let a=YxE(n)??e.schema,u=SKn(n),l=XxE(n),d=Pau({context:r,fileContainingReference:t,declarationFile:GNi(u),type:a}),s=n.type==="nullable"?`optional<${d}>`:d;return e.description==null&&l==null?s:{type:n.type==="nullable"?`optional<${d}>`:d,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:rx(e.availability)}:{}}}function Y1c({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=Ng({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),l=`list<${WA(u)}>`;return e.description==null&&e.title==null?l:{...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:rx(e.availability)}:{},type:l}}function X1c({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=Oau(e.key),l=Ng({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),d=e.encoding!=null?gau(e.encoding):void 0,s=`map<${WA(u)}, ${WA(l)}>`;if(e.description==null&&d==null&&e.title==null)return s;let o={type:s};return e.description!=null&&(o.docs=e.description),e.encoding!=null&&(o.encoding=d),e.availability!=null&&(o.availability=rx(e.availability)),o}function Z1c({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){if(!i.respectNullableSchemas)return mau({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});let u=Ng({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),l=WA(u),d=DKn(u),s=V5a(u),o=Q1c(u),c=l.startsWith("nullable<")?l:`nullable<${l}>`;if(e.availability==null&&e.description==null&&d==null&&s==null&&o==null&&e.title==null)return Hw_({typeReference:c,itemType:l});let b={type:c};return(e.description!=null||d!=null)&&(b.docs=e.description??d),s!=null&&(b.default=s),o!=null&&(b.validation=o),e.availability!=null&&(b.availability=rx(e.availability)),Hw_({typeReference:b,itemType:l})}function mau({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=Ng({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),l=WA(u),d=DKn(u),s=V5a(u),o=Q1c(u),c=l.startsWith("optional<")?l:`optional<${l}>`;if(e.availability==null&&e.description==null&&d==null&&s==null&&o==null&&e.title==null)return c;let b={type:c};return(e.description!=null||d!=null)&&(b.docs=e.description??d),s!=null&&(b.default=s),o!=null&&(b.validation=o),e.availability!=null&&(b.availability=rx(e.availability)),b}function k1c(){return"unknown"}function eSc(e){let t;switch(e.value.type){case"boolean":{t=`literal<${e.value.value}>`;break}case"string":{t=`literal<"${e.value.value}">`;break}default:So(e.value)}return e.description==null&&e.title==null?t:{type:t,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:rx(e.availability)}:{}}}function QxE({schema:e,fileContainingReference:t,declarationFile:r,context:i,declarationDepth:n}){let a=W5a(e,n),u=e.nameOverride??e.generatedName;i.builder.addType(r,{name:u,schema:a.schema});let l=Pau({type:u,fileContainingReference:t,declarationFile:r,context:i});if(e.description==null&&e.default==null&&e.title==null)return l;let d={type:l};return e.description!=null&&(d.docs=e.description),e.default!=null&&(d.default=e.default.value),e.availability!=null&&(d.availability=rx(e.availability)),d}function JxE({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=tSc({schema:e,declarationFile:r,context:i,namespace:n,declarationDepth:a}),l=e.nameOverride??e.generatedName;i.builder.addType(r,{name:l,schema:u.schema});let d=Pau({type:l,fileContainingReference:t,declarationFile:r,context:i});return e.description==null&&e.title==null?d:{type:d,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:rx(e.availability)}:{}}}function KxE({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=rSc({schema:e,declarationFile:r,context:i,namespace:n,declarationDepth:a}),l=e.nameOverride??e.generatedName;i.builder.addType(r,{name:l,schema:u.schema});let d=Pau({type:l,fileContainingReference:t,declarationFile:r,context:i});return e.description==null&&e.title==null?d:{...e.title!=null?{"display-name":e.title}:{},type:d,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:rx(e.availability)}:{}}}function Pau({type:e,fileContainingReference:t,declarationFile:r,context:i}){if(r===t)return e;let n=i.builder.addImport({file:t,fileToImport:r});return n!=null?`${n}.${e}`:e}function YxE(e){return cv._visit(e,{primitive:t=>t.nameOverride??t.generatedName,object:t=>t.nameOverride??t.generatedName,array:t=>t.nameOverride??t.generatedName,map:t=>t.nameOverride??t.generatedName,enum:t=>t.nameOverride??t.generatedName,reference:t=>t.nameOverride??t.generatedName,literal:t=>t.nameOverride??t.generatedName,oneOf:t=>t.nameOverride??t.generatedName,optional:t=>t.nameOverride??t.generatedName,nullable:t=>t.nameOverride??t.generatedName,unknown:t=>t.nameOverride??t.generatedName,_other:()=>{}})}function XxE(e){return cv._visit(e,{primitive:t=>t.title,object:t=>t.title,array:t=>t.title,map:t=>t.title,enum:t=>t.title,reference:t=>t.title,literal:t=>t.title,oneOf:t=>t.title,optional:t=>t.title,nullable:t=>t.title,unknown:t=>{},_other:()=>{}})}function Hw_({typeReference:e,itemType:t}){return t.startsWith("optional<")?e:typeof e=="string"?`optional<${e}>`:{...e,type:`optional<${e.type}>`}}var $8;(function(e){e[e.Channel=0]="Channel",e[e.Endpoint=1]="Endpoint",e[e.Request=2]="Request",e[e.Webhook=3]="Webhook"})($8||($8={}));function Zmi(e){switch(e.type){case"openapi":return{openapi:e.file};case"protobuf":return{proto:e.file};default:So(e)}}function Qw_({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){let a;switch(e.type){case"primitive":a=eNE(e);break;case"array":a=ZxE({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"map":a=kxE({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"reference":a=tNE({schema:e,context:t,declarationFile:r,namespace:i});break;case"unknown":a=iNE(e.nameOverride,e.generatedName);break;case"optional":a=Jw_({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"nullable":a=rNE({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"enum":a=W5a(e,n);break;case"literal":a=nNE(e,e.nameOverride,e.generatedName);break;case"object":a=tSc({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"oneOf":a=rSc({schema:e.value,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;default:So(e)}return a}function tSc({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){let a=t.isInState($8.Request)&&t.respectReadonlySchemas&&(t.getEndpointMethod()==="POST"||t.getEndpointMethod()==="PUT"||t.getEndpointMethod()==="PATCH"),u=!1,l={},d=new Set;for(let g of e.properties){if(g.readonly&&(u=!0),a&&g.readonly)continue;if(Object.keys(g.conflict).length>0){if(Object.entries(g.conflict).every(([D,C])=>!C.differentSchema))continue;Object.entries(g.conflict).forEach(([D])=>{iSc({property:g.key,schemaId:D,context:t,namespace:i}).forEach(R=>{d.add(R)})})}let O=Ng({schema:g.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1}),m=g.audiences,w=g.nameOverride,E=rx(g.availability),q=sNE(g);l[g.key]=uNE({typeReference:O,audiences:m,name:w,availability:E,propertyAccess:q})}let s=new Set;for(let g of e.allOfPropertyConflicts)g.allOfSchemaIds.forEach(O=>d.add(O)),g.conflictingTypeSignatures&&s.add(g.propertyKey);let o=[];for(let g of e.allOf){let O=Kw_({schema:g.schema,context:t,namespace:i});if(O==null||d.has(g.schema)||d.has(O))continue;let m=Ng({schema:cv.reference(g),context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1});o.push(WA(m))}for(let g of d){let O=nSc(t,g,i);for(let m of O.properties)l[m.key]==null&&(s.has(m.key)&&(l[m.key]="unknown"),l[m.key]=Ng({schema:m.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1}));for(let m of O.allOf){if(d.has(m.schema))continue;let w=Ng({schema:cv.reference(m),context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1});o.push(WA(w))}}let c={docs:e.description??void 0,properties:Object.fromEntries(Object.entries(l).map(([g,O])=>oNE(g)?[g,typeof O=="string"?{type:O,name:`_${g}`}:{...O,name:`_${g}`}]:[g,O]))};o.length>0&&(c.extends=o),e.additionalProperties&&(c["extra-properties"]=!0),e.availability!=null&&(c.availability=rx(e.availability)),e.source!=null&&(c.source=Zmi(e.source)),c.inline=aSc(e,n);let b=e.nameOverride??e.generatedName;return{name:u&&t.respectReadonlySchemas&&!a?`${b}Read`:b,schema:c}}function iSc({property:e,schemaId:t,context:r,namespace:i}){let n=r.getSchema(t,i);if(n==null)return[];if(n.type==="reference")return iSc({property:e,schemaId:n.schema,context:r,namespace:i});if(n.type==="object"){let{properties:a,allOf:u}=nSc(r,t,i),l=a.some(s=>s.key===e),d=[...u.flatMap(s=>iSc({property:e,context:r,schemaId:s.schema,namespace:i}))];if(l||d.length>0)return[t,...d]}return[]}function nSc(e,t,r){let i=e.getSchema(t,r);if(i==null)return{properties:[],allOf:[]};if(i.type==="object")return{properties:i.properties,allOf:i.allOf};if(i.type==="reference")return nSc(e,i.schema,r);throw new Error(`Cannot getAllProperties for a non-object schema. schemaId=${t}, type=${i.type}`)}function ZxE({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return{name:e.nameOverride??e.generatedName,schema:Y1c({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:i,declarationDepth:n})}}function kxE({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return{name:e.nameOverride??e.generatedName,schema:X1c({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:i,declarationDepth:n})}}function eNE(e){let t=Oau(e);if(typeof t=="string")return{name:e.nameOverride??e.generatedName,schema:t};let{default:r,...i}=t;return{name:e.nameOverride??e.generatedName,schema:{...i}}}function Gw_(e){return e.camel==null&&e.pascal==null&&e.screamingSnake==null&&e.snake==null}function W5a(e,t){let r={enum:e.values.map(a=>{let u=a.nameOverride??a.generatedName,l=a.value;if(u===l&&a.description==null&&(a.casing==null||Gw_(a.casing)))return u;let d={value:a.value};if(u!==l&&(d.name=u),a.description!=null&&(d.docs=a.description),a.casing!=null&&!Gw_(a.casing)){let s={},o=!1;a.casing.camel!=null&&(s.camel=a.casing.camel,o=!0),a.casing.screamingSnake!=null&&(s["screaming-snake"]=a.casing.screamingSnake,o=!0),a.casing.snake!=null&&(s.snake=a.casing.snake,o=!0),a.casing.pascal!=null&&(s.pascal=a.casing.pascal,o=!0),o&&(d.casing=s)}return d})};e.description!=null&&(r.docs=e.description),e.default!=null&&(r.default=e.default.value),r.inline=aSc(e,t);let i=new Set,n={...r,enum:[],source:e.source!=null?Zmi(e.source):void 0};for(let a of r.enum){let u=typeof a=="string"?a:a.name??a.value;i.has(u.toLowerCase())||(n.enum.push(a),i.add(u.toLowerCase()))}return{name:e.nameOverride??e.generatedName,schema:n}}function tNE({schema:e,context:t,declarationFile:r,namespace:i}){return{name:e.nameOverride??e.generatedName,schema:K1c({schema:e,context:t,fileContainingReference:r,namespace:i})}}function rNE({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return t.respectNullableSchemas?{name:e.nameOverride??e.generatedName,schema:Z1c({schema:e,context:t,fileContainingReference:r,declarationFile:r,namespace:i,declarationDepth:n})}:Jw_({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n})}function Jw_({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return{name:e.nameOverride??e.generatedName,schema:mau({schema:e,context:t,fileContainingReference:r,declarationFile:r,namespace:i,declarationDepth:n})}}function iNE(e,t){return{name:e??t,schema:k1c()}}function nNE(e,t,r){return{name:t??r,schema:eSc(e)}}function rSc({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){let a=e.encoding!=null?gau(e.encoding):void 0;if(e.type==="discriminated"){let l={};for(let s of e.commonProperties)l[s.key]=Ng({schema:s.schema,fileContainingReference:r,context:t,namespace:i,declarationDepth:n+1});let d={};for(let[s,o]of Object.entries(e.schemas))d[s]=Ng({schema:o,context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1});return{name:e.nameOverride??e.generatedName,schema:{discriminant:e.discriminantProperty,"base-properties":l,docs:e.description??void 0,availability:e.availability!=null?rx(e.availability):void 0,union:d,encoding:a,source:e.source!=null?Zmi(e.source):void 0}}}let u=[];for(let l of e.schemas)u.push(Ng({schema:l,fileContainingReference:r,context:t,namespace:i,declarationDepth:n+1}));return{name:e.nameOverride??e.generatedName,schema:{discriminated:!1,docs:e.description??void 0,union:u,encoding:a,source:e.source!=null?Zmi(e.source):void 0,inline:aSc(e,n)}}}var aNE=/^[0-9]/;function oNE(e){return aNE.test(e)}function Kw_({schema:e,context:t,namespace:r}){let i=t.getSchema(e,r);if(i!=null)return i.type==="reference"?Kw_({context:t,schema:i.schema,namespace:r}):e}function uNE({typeReference:e,audiences:t,name:r,availability:i,propertyAccess:n}){return t.length===0&&r==null&&i==null&&n==null?e:{...typeof e=="string"?{type:e}:{...e},...t.length>0?{audiences:t}:{},...r!=null?{name:r}:{},...i!=null?{availability:i}:{},...n!=null?{access:n}:{}}}function aSc(e,t){return e.inline===!0||t>0?!0:void 0}function sNE(e){if(!(e.readonly&&e.writeonly)){if(e.readonly)return MF.ObjectPropertyAccess.ReadOnly;if(e.writeonly)return MF.ObjectPropertyAccess.WriteOnly}}function Yw_(e){let t=e.replace(/^x-|^X-/,"");return S_(t)}var Xw_="BasicAuthScheme",jau="BearerAuthScheme";function Zw_(e){if(e.authOverrides!=null){for(let[r,i]of Object.entries(e.authOverrides["auth-schemes"]??{}))e.builder.addAuthScheme({name:r,schema:i});e.authOverrides.auth!=null&&e.builder.setAuth(e.authOverrides.auth);return}let t=!1;for(let[r,i]of Object.entries(e.ir.securitySchemes))if(i.type==="basic"){let n={scheme:"basic"};i.usernameVariableName!=null&&(n.username===void 0?n.username={name:i.usernameVariableName}:n.username.name=i.usernameVariableName),i.usernameEnvVar!=null&&(n.username===void 0?n.username={env:i.usernameEnvVar}:n.username.env=i.usernameEnvVar),i.passwordVariableName!=null&&(n.password===void 0?n.password={name:i.passwordVariableName}:n.password.name=i.passwordVariableName),i.passwordEnvVar!=null&&(n.password===void 0?n.password={env:i.passwordEnvVar}:n.password.env=i.passwordEnvVar),e.builder.addAuthScheme({name:Xw_,schema:n}),t||(e.builder.setAuth(Xw_),t=!0)}else if(i.type==="bearer"){let n={scheme:"bearer"};i.tokenVariableName!=null&&(n.token===void 0?n.token={name:i.tokenVariableName}:n.token.name=i.tokenVariableName),i.tokenEnvVar!=null&&(n.token===void 0?n.token={env:i.tokenEnvVar}:n.token.env=i.tokenEnvVar),e.builder.addAuthScheme({name:jau,schema:n}),t||(e.builder.setAuth(jau),t=!0)}else if(i.type==="header")if(t)e.builder.addGlobalHeader({name:i.headerName,schema:{type:"string",name:i.headerVariableName??Yw_(i.headerName),env:i.headerEnvVar}});else{let n={header:i.headerName,name:i.headerVariableName??"apiKey",type:"string"};i.headerEnvVar!=null&&(n.env=i.headerEnvVar),i.prefix!=null&&(n.prefix=i.prefix),e.builder.addAuthScheme({name:r,schema:n}),e.builder.setAuth(r),t=!0}else if(i.type==="oauth"){let n={scheme:"bearer"};e.builder.addAuthScheme({name:jau,schema:n}),t||(e.builder.setAuth(jau),t=!0),i.scopesEnum!=null&&i.scopesEnum.values.length>0&&e.builder.addType(fy.of("__package__.yml"),{name:"OauthScope",schema:W5a(i.scopesEnum,0).schema})}}function wor({header:e,context:t,fileContainingReference:r,namespace:i}){let n=Ng({schema:e.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),a=WA(n),u=e.name.replace(/^x-|^X-/,""),l=e.parameterNameOverride!=null?e.parameterNameOverride:S_(u);if(e.description==null&&e.name===l&&e.env==null&&e.availability==null)return a;let d={type:a};return l!==e.name&&(d.name=l),e.description!=null&&(d.docs=e.description),e.env!=null&&(d.env=e.env),e.availability!=null&&(d.availability=rx(e.availability)),d}function wau({pathParameter:e,context:t,fileContainingReference:r,namespace:i}){let n=Ng({schema:e.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:0});if(e.variableReference==null&&e.description==null&&e.availability==null)return WA(n);let a=e.variableReference!=null?{variable:`$${e.variableReference}`}:{type:WA(n)};return e.description!=null&&(a.docs=e.description),e.availability!=null&&(a.availability=rx(e.availability)),a}function Dau({queryParameter:e,context:t,fileContainingReference:r,namespace:i}){let n=oSc({schema:e.schema,context:t,fileContainingReference:r,namespace:i});if(n==null)return;let a=WA(n.value),u=V5a(n.value);a==="unknown"?a="string":a==="optional<unknown>"&&(a="optional<string>");let l={type:a};return u!=null&&(l.default=u),n.allowMultiple&&(l["allow-multiple"]=!0),e.description!=null&&(l.docs=e.description),e.parameterNameOverride!=null&&(l.name=e.parameterNameOverride),e.availability!=null&&(l.availability=rx(e.availability)),cNE(n.value)&&n.value.validation!==void 0&&(l.validation=n.value.validation),l.default==null&&l["allow-multiple"]==null&&l.docs==null&&l.name==null&&l.availability==null&&l.validation==null?a:l}function oSc({schema:e,context:t,fileContainingReference:r,namespace:i}){if(e.type==="reference"){let n=t.getSchema(e.schema,i);if(n==null)return;if(n.type==="array")return{value:Ng({schema:cv.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:n.value,description:e.description??n.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:void 0}),context:t,declarationFile:fy.of(fS),fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(n.type==="oneOf"&&n.value.type==="undiscriminated"){let a=[],u=!1;for(let[l,d]of Object.entries(n.value.schemas))d.type==="primitive"&&d.schema.type==="string"&&(u=!0),d.type==="literal"&&d.value.type==="string"&&(jKn.test(d.value.value)?a.push(d.value.value):a.push({value:d.value.value,name:wKn(d.value.value)}));if(a.length>0)return t.builder.addType(r,{name:e.generatedName,schema:{enum:a}}),u&&t.respectForwardCompatibleEnums?(t.builder.addType(r,{name:`${e.generatedName}OrString`,schema:{discriminated:!1,union:[{type:"string"},{type:e.generatedName}]}}),{value:`${e.generatedName}OrString`,allowMultiple:!1}):{value:e.generatedName,allowMultiple:!1};if(n.value.schemas.length===2){let[l,d]=n.value.schemas;if(l!=null&&d!=null&&Sau({array:l,primitive:d}))return{value:Ng({schema:cv.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:d,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:void 0}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(l!=null&&d!=null&&Sau({array:l,primitive:d}))return{value:Ng({schema:cv.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:l,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:void 0}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0}}for(let[l,d]of Object.entries(n.value.schemas))return oSc({schema:d,context:t,fileContainingReference:r,namespace:i})}else if(t.objectQueryParameters)return{value:Ng({schema:e,context:t,fileContainingReference:r,declarationFile:fy.of(fS),namespace:i,declarationDepth:0}),allowMultiple:!1}}if(e.type==="optional"||e.type==="nullable"){if(e.value.type==="reference"){let n=t.getSchema(e.value.schema,i);if(n==null)return;if(n.type==="array")return{value:Ng({schema:cv.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:n.value,description:e.description??n.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,declarationFile:fy.of(fS),namespace:i,declarationDepth:0}),allowMultiple:!0};if(t.objectQueryParameters)return{value:Ng({schema:e,context:t,fileContainingReference:r,declarationFile:fy.of(fS),namespace:i,declarationDepth:0}),allowMultiple:!1}}if(e.value.type==="array")return{value:Ng({schema:cv.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value.value,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(e.value.type==="oneOf"&&e.value.value.type==="undiscriminated"){let n=[],a=!1;for(let[u,l]of Object.entries(e.value.value.schemas))l.type==="primitive"&&l.schema.type==="string"&&(a=!0),l.type==="literal"&&l.value.type==="string"&&(jKn.test(l.value.value)?n.push(l.value.value):n.push({value:l.value.value,name:wKn(l.value.value)}));if(n.length>0)return t.builder.addType(r,{name:e.generatedName,schema:{enum:n}}),a&&t.respectForwardCompatibleEnums?(t.builder.addType(r,{name:`${e.generatedName}OrString`,schema:{discriminated:!1,union:[{type:"string"},{type:`optional<${e.value.value.generatedName}>`}]}}),{value:`optional<${e.value.value.generatedName}OrString>`,allowMultiple:!1}):{value:`optional<${e.value.value.generatedName}>`,allowMultiple:!1};if(e.value.value.schemas.length===2){let[u,l]=e.value.value.schemas;if(u!=null&&l!=null&&Sau({array:u,primitive:l}))return{value:Ng({schema:cv.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:l,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(u!=null&&l!=null&&Sau({array:l,primitive:u}))return{value:Ng({schema:cv.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:u,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0}}if(t.objectQueryParameters)return{value:Ng({schema:e,context:t,fileContainingReference:r,declarationFile:fy.of(fS),namespace:i,declarationDepth:0}),allowMultiple:!1};for(let[u,l]of Object.entries(e.value.value.schemas))return oSc({schema:cv.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:l,description:void 0,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i})}else if(e.value.type==="object")return t.objectQueryParameters?{value:Ng({schema:e,context:t,fileContainingReference:r,declarationFile:fy.of(fS),namespace:i,declarationDepth:0}),allowMultiple:!1}:void 0;return{value:Ng({schema:e,context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!1}}return e.type==="array"?{value:Ng({schema:cv.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0}:{value:Ng({schema:e,context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!1}}function Sau({array:e,primitive:t}){return e?.type==="array"&&e.value.type==="primitive"&&t?.type==="primitive"&&e.value.schema.type===t.schema.type}function cNE(e){return e.type!=null}function kw_({websocketExample:e,context:t}){let r={messages:[]};e.name!=null&&(r.name=e.name),e.description!=null&&(r.docs=e.description),e.queryParameters!=null&&e.queryParameters.length>0&&(r["query-parameters"]=lNE(e.queryParameters)),e.headers!=null&&e.headers.length>0&&(r.headers=fNE({context:t,namedFullExamples:e.headers}));for(let i of e.messages){let n=QNi(i.payload);n!=null&&r.messages.push({type:i.messageType,body:n})}return r}function lNE(e){let t={};return e.forEach(r=>{let i=QNi(r.value);Array.isArray(i)?t[r.name]=i[0]:i!=null&&(t[r.name]=i)}),t}function fNE({context:e,namedFullExamples:t}){let r=e.builder.getGlobalHeaderNames(),i={};return t.forEach(n=>{let a=QNi(n.value);r.has(n.name)||a!=null&&(i[n.name]=a)}),i}function QNi(e){switch(e.type){case"primitive":return e1_(e.value);case"object":return t1_(e.properties);case"array":return dNE(e.value);case"map":return pNE(e.value);case"oneOf":return _NE(e.value);case"enum":return e.value;case"literal":return hNE(e.value);case"unknown":return QNi(e.value);default:So(e)}}function e1_(e){switch(e.type){case"int":return e.value;case"int64":return e.value;case"uint":return e.value;case"uint64":return e.value;case"float":return e.value;case"double":return e.value;case"string":return e.value.startsWith("$")?`${e.value.slice(1)}`:e.value;case"datetime":try{return new Date(e.value).toISOString().replace(/\.\d{3}Z$/,"Z")}catch{return"2024-01-15T09:30:00Z"}case"date":return e.value;case"base64":case"boolean":return e.value;default:So(e)}}function t1_(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,QNi(r)]))}function dNE(e){return e.map(t=>QNi(t))}function pNE(e){return Object.fromEntries(e.map(t=>[e1_(t.key),QNi(t.value)]))}function _NE(e){return e.type==="discriminated"?t1_(e.value):QNi(e.value)}function hNE(e){switch(e.type){case"string":return e.value;case"boolean":return e.value;default:So(e)}}function kmi(e){return e.find(t=>typeof t!="string"&&t.type==="namespace")?.name}function Eau(e,t){return t??(e?.groupName!=null?kmi(e.groupName):void 0)}function r1_({channel:e,context:t,declarationFile:r}){let i={path:e.path,url:e.servers[0]?.name,auth:!1};e.audiences!=null&&e.audiences.length>0&&(i.audiences=e.audiences),e.summary!=null&&(i["display-name"]=e.summary),e.description!=null&&(i.docs=e.description);let n=kmi(e.groupName),a={};if(e.handshake.pathParameters.length>0)for(let d of e.handshake.pathParameters)a[d.name]=wau({pathParameter:d,context:t,fileContainingReference:r,namespace:n});Object.keys(a).length>0&&(i["path-parameters"]=a);let u={};if(e.handshake.queryParameters.length>0)for(let d of e.handshake.queryParameters){let s=Dau({queryParameter:d,context:t,fileContainingReference:r,namespace:n});s!=null&&(u[d.name]=s)}Object.keys(u).length>0&&(i["query-parameters"]=u);let l={};if(e.handshake.headers.length>0)for(let d of e.handshake.headers){let s=wor({header:d,context:t,fileContainingReference:r,namespace:n});l[d.name]=s}Object.keys(l).length>0&&(i.headers=l),t.builder.addChannel(r,{channel:i});for(let d of e.messages)t.builder.addChannelMessage(r,{messageId:d.name,message:{origin:d.origin,body:Ng({schema:d.body,context:t,fileContainingReference:r,namespace:n,declarationDepth:0})}});for(let d of e.examples){let s=kw_({context:t,websocketExample:d});t.builder.addChannelExample(r,{example:s})}}var ePi="Base",yNE="Default";function JNi(e){return Object.entries(e).reduce((t,[r,i])=>(hUn(i)?Object.entries(i.urls).forEach(([n,a])=>{t[n]=a}):t[r]=typeof i=="string"?i:i.url,t),{})}function i1_(e){if(e.environmentOverrides!=null){for(let[g,O]of Object.entries(e.environmentOverrides.environments??{}))e.builder.addEnvironment({name:g,schema:O});e.environmentOverrides["default-environment"]!=null&&e.builder.setDefaultEnvironment(e.environmentOverrides["default-environment"]),e.environmentOverrides["default-url"]!=null&&e.builder.setDefaultUrl(e.environmentOverrides["default-url"]);return}let t={},r=[];for(let g of e.ir.servers){let O=g.audiences?{url:g.url,audiences:g.audiences}:g.url;if(g.name==null){r.push(O);continue}t[g.name]=O}let i={},n=[];for(let g of e.ir.endpoints)for(let O of g.servers){if(O.url==null)continue;let m=O.audiences?{url:O.url,audiences:O.audiences}:O.url;if(O.name==null){n.push(m);continue}i[O.name]=m}let a={},u=[];for(let g of e.ir.websocketServers){let O=g.audiences?{url:g.url,audiences:g.audiences}:g.url;if(g.name==null){u.push(O);continue}a[g.name]=O}let l=Object.keys(t).length,d=l>0,s=Object.keys(i).length>0,o=Object.keys(a).length>0;if(!d&&!s&&o&&e.ir.servers.length===0){for(let[g,O]of Object.entries(a))e.builder.addEnvironment({name:g,schema:O});e.builder.setDefaultEnvironment(Object.keys(a)[0]),e.builder.setDefaultUrl(ePi);return}if(n.length>0&&e.logger.error(`Skipping endpoint level servers ${n.map(g=>typeof g=="string"?g:g.url).join(", ")} because x-fern-server-name was not provided.`),!d){let g=e.ir.servers[0]?.url,O=e.ir.servers[0]?.audiences;if(g!=null){let m=O?{url:g,audiences:O}:g;t[yNE]=m}}let c=Object.values(t).map(g=>typeof g=="string"?g:g.url),b=r.filter(g=>{let O=typeof g=="string"?g:g.url;return!c.includes(O)});if(b.length>0&&e.logger.error(`Skipping top level servers ${b.map(g=>typeof g=="string"?g:g.url).join(", ")} because x-fern-server-name was not provided.`),s)if(l===1){let g=Object.keys(t)[0],O=Object.values(t)[0],m=typeof O=="string"?O:O.url;e.builder.addEnvironment({name:g,schema:{urls:{[ePi]:m,...JNi(i),...JNi(a)}}}),e.builder.setDefaultEnvironment(g),e.builder.setDefaultUrl(ePi)}else{let g=!0;for(let[O,m]of Object.entries(t))g?(e.builder.addEnvironment({name:O,schema:{urls:{[ePi]:typeof m=="string"?m:m.url,...JNi(i),...JNi(a)}}}),e.builder.setDefaultEnvironment(O),g=!1):e.builder.addEnvironment({name:O,schema:{urls:{[ePi]:typeof m=="string"?m:m.url,...JNi(i),...JNi(a)}}});e.builder.setDefaultUrl(ePi)}else{let g=!0;for(let[O,m]of Object.entries(t))g?(o?e.builder.addEnvironment({name:O,schema:{urls:{[ePi]:typeof m=="string"?m:m.url,...JNi(a)}}}):e.builder.addEnvironment({name:O,schema:m}),e.builder.setDefaultEnvironment(O),g=!1):o?e.builder.addEnvironment({name:O,schema:{urls:{[ePi]:typeof m=="string"?m:m.url,...JNi(a)}}}):e.builder.addEnvironment({name:O,schema:m});o&&e.builder.setDefaultUrl(ePi)}}function Mau(e){return WA(e).startsWith("optional")?e:typeof e=="string"?`optional<${e}>`:{...e,type:`optional<${e.type}>`}}var uSc=class{schema;count=0;constructor(t){this.schema=t}increment(){this.count+=1}},vNE=.75,bNE=new Set("authorization");function n1_(e){if(e.globalHeaderOverrides!=null){for(let[r,i]of Object.entries(e.globalHeaderOverrides.headers??{}))e.builder.addGlobalHeader({name:r,schema:i});return}let t=Object.fromEntries((e.ir.globalHeaders??[]).map(r=>[r.header,r]));for(let[r,i]of Object.entries(t)){let n="optional<string>";if(i.name==null&&i.env==null&&typeof i.schema=="string")n=i.schema;else if(i!=null){let a=i.schema?SKn(i.schema):void 0,u=a!=null?kmi(a):void 0,l=fy.of("api.yml");n={name:i.name,env:i.env,type:i.schema!=null?WA(Ng({schema:i.schema,context:e,fileContainingReference:u?PF(fy.of(S_(u)),l):l,namespace:u,declarationDepth:0}))??"optional<string>":"optional<string>"}}e.builder.addGlobalHeader({name:r,schema:n})}if(e.detectGlobalHeaders){let r={};for(let n of e.ir.endpoints)for(let a of n.headers){if(bNE.has(a.name.toLowerCase()))continue;let u=r[a.name];if(u==null){let l=t[a.name],d=wor({header:{...a,schema:l?.schema??a.schema,name:l?.name??a.name},fileContainingReference:fy.of(z3),context:e,namespace:void 0});u=new uSc(d),r[a.name]=u}u.increment()}let i=e.ir.endpoints.length*vNE;for(let[n,a]of Object.entries(r)){let u=t[n],l=a.count===e.ir.endpoints.length,d=a.count>=i;u==null&&(l?e.builder.addGlobalHeader({name:n,schema:a.schema}):d&&e.builder.addGlobalHeader({name:n,schema:Mau(a.schema)}))}}}function a1_(e){for(let t of e.ir.idempotencyHeaders??[]){let r=t.schema?SKn(t.schema):void 0,i=r!=null?kmi(r):void 0,n=wor({header:{...t,schema:t.schema??cv.primitive({description:void 0,availability:void 0,generatedName:"",title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0,schema:jw.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0})}),name:t.name??t.header,parameterNameOverride:void 0,description:void 0,availability:void 0,source:void 0},fileContainingReference:fy.of(z3),context:e,namespace:i});e.builder.addIdempotencyHeader({name:t.header,schema:Mau(n)})}}function uK(e){switch(e.type){case"primitive":return u1_(e.value);case"object":return s1_(e.properties);case"array":return c1_(e.value);case"map":return ONE(e.value);case"oneOf":return mNE(e.value);case"enum":return typeof e.value=="string"&&e.value.startsWith("$")?`\\${e.value}`:e.value;case"literal":return PNE(e.value);case"unknown":return uK(e.value);default:So(e)}}function o1_(e){switch(e.type){case"withStreaming":return e.sse?{stream:gNE(e.events)}:{stream:c1_(e.events)};case"withoutStreaming":return{body:uK(e.value)};default:So(e)}}function u1_(e){switch(e.type){case"int":return e.value;case"int64":return e.value;case"uint":return e.value;case"uint64":return e.value;case"float":return e.value;case"double":return e.value;case"string":return e.value.startsWith("$")?`\\${e.value}`:e.value;case"datetime":try{return!e.value.endsWith("Z")&&!e.value.includes("+")&&(e.value+="Z"),new Date(e.value).toISOString().replace(/\.\d{3}Z$/,"Z")}catch{return"2024-01-15T09:30:00Z"}case"date":return e.value;case"base64":case"boolean":return e.value;default:So(e)}}function s1_(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,uK(r)]))}function gNE(e){return e.map(t=>({event:"",data:uK(t)}))}function c1_(e){return e.map(t=>uK(t))}function ONE(e){return Object.fromEntries(e.map(t=>[u1_(t.key),uK(t.value)]))}function mNE(e){return e.type==="discriminated"?s1_(e.value):uK(e.value)}function PNE(e){switch(e.type){case"string":return e.value;case"boolean":return e.value;default:So(e)}}function l1_({endpointExample:e,context:t}){let r={};if(e.type!=="full")return e.value;e.name!=null&&(r.name=e.name),e.description!=null&&(r.docs=e.description),e.pathParameters!=null&&e.pathParameters.length>0&&(r["path-parameters"]=jNE(e.pathParameters)),e.queryParameters!=null&&e.queryParameters.length>0&&(r["query-parameters"]=wNE(e.queryParameters));let i=e.headers!=null&&e.headers.length>0,n=t.builder.getGlobalHeaders(),a=Object.keys(n).length>0,u=new Set(e.headers?.map(l=>l.name)??[]);if(i||a){let l=[];if(e.headers!=null)for(let d of e.headers)d.name!==t.builder.getAuthHeaderName()&&l.push(d);for(let[d,s]of Object.entries(n))if(!u.has(d))if(s!=null&&typeof s=="object"&&s.type!=null){let o=Y3({type:s.type,_default:void 0,validation:void 0,visitor:{primitive:c=>c.toString(),map:c=>c.toString(),list:c=>c,optional:c=>c,nullable:c=>c,set:c=>c,named:c=>c,literal:c=>{if(c.type==="string")return c.string;if(c.type==="boolean")return c.boolean.toString()},unknown:$o}});o!=null&&l.push({name:d,value:xg.literal(zNi.string(o))})}else l.push({name:d,value:xg.primitive(h_.string(d))});r.headers=SNE({context:t,namedFullExamples:l})}return e.request!=null&&(r.request=uK(e.request)),e.response!=null&&(r.response=o1_(e.response)),e.codeSamples!=null&&e.codeSamples.length>0&&(r["code-samples"]=e.codeSamples.map(l=>l.type==="language"?{name:l.name??void 0,docs:l.description??void 0,language:l.language,code:l.code,install:l.install??void 0}:{name:l.name??void 0,docs:l.description??void 0,sdk:l.sdk,code:l.code}).filter(iv)),r}function jNE(e){let t={};return e.forEach(r=>{let i=uK(r.value);i!=null&&(t[r.parameterNameOverride??r.name]=i)}),t}function wNE(e){let t={};return e.forEach(r=>{let i=uK(r.value);Array.isArray(i)?t[r.name]=i[0]:i!=null&&(t[r.name]=i)}),t}function SNE({context:e,namedFullExamples:t}){let r={};return t.forEach(i=>{let n=uK(i.value);n!=null&&(r[i.name]=n)}),r}function f1_(e){return QH._visit(e,{get:()=>MF.HttpMethodSchema.Get,post:()=>MF.HttpMethodSchema.Post,put:()=>MF.HttpMethodSchema.Put,patch:()=>MF.HttpMethodSchema.Patch,delete:()=>MF.HttpMethodSchema.Delete,head:()=>MF.HttpMethodSchema.Head,options:()=>{throw new Error("OPTIONS is unsupported")},trace:()=>{throw new Error("TRACE is unsupported")},_other:()=>{throw new Error("Unknown http method is unsupported")}})}function d1_(e){return e==="POST"||e==="PUT"||e==="PATCH"}function p1_({endpoint:e,declarationFile:t,context:r}){let{nonRequestReferencedSchemas:i}=r.ir,n=[],a=new Set,u=e.path,l=Eau(e.sdkName,e.namespace),d={};for(let w of e.pathParameters)w.parameterNameOverride&&(u=u.replace(w.name,w.parameterNameOverride)),d[w.parameterNameOverride??w.name]=wau({pathParameter:w,context:r,fileContainingReference:t,namespace:l}),a.add(w.name);let s={};for(let w of e.queryParameters){let E=Dau({queryParameter:w,context:r,fileContainingReference:t,namespace:l});E!=null&&(s[w.name]=E,a.add(w.name))}let o;if(e.pagination!=null)switch(e.pagination.type){case"cursor":o={cursor:e.pagination.cursor,next_cursor:e.pagination.nextCursor,results:e.pagination.results};break;case"offset":o={offset:e.pagination.offset,step:e.pagination.step,results:e.pagination.results,"has-next-page":e.pagination.hasNextPage};break;case"custom":o={type:"custom",results:e.pagination.results};break;default:So(e.pagination)}let c={path:u,method:f1_(e.method),auth:e.authed,docs:e.description??void 0,pagination:o,source:e.source!=null?Zmi(e.source):void 0};!MNE({context:r,request:e.request})&&Object.keys(d).length>0&&(c["path-parameters"]=d),e.summary!=null&&(c["display-name"]=e.summary);let b={},g=r.builder.getGlobalHeaderNames(),O=r.builder.getAuthHeaderName();O!=null&&g.add(O);let m=e.headers.filter(w=>!g.has(w.name));for(let w of m){let E=wor({header:w,context:r,fileContainingReference:t,namespace:l});b[w.name]=E,a.add(typeof E=="string"?w.name:E.name??w.name)}if(e.request!=null){r.setInState($8.Request);let w=ENE({endpoint:e,context:r,declarationFile:t,request:e.request,generatedRequestName:e.generatedRequestName,requestNameOverride:e.requestNameOverride??void 0,pathParameters:r.inlinePathParameters&&Object.keys(d).length>0?d:void 0,queryParameters:Object.keys(s).length>0?s:void 0,nonRequestReferencedSchemas:Array.from(i),headers:Object.keys(b).length>0?b:void 0,usedNames:a,namespace:l});c.request=w.value,n=[...n,...w.schemaIdsToExclude??[]],r.unsetInState($8.Request)}else{let w=r.inlinePathParameters&&Object.keys(d).length>0,E=Object.keys(s).length>0,q=Object.keys(b).length>0,M={};(w||E||q)&&(M.name=e.requestNameOverride??e.generatedRequestName),w&&(M["path-parameters"]=d),E&&(M["query-parameters"]=s),q&&(M.headers=b),Object.keys(M).length>0&&(c.request=M)}if(e.response!=null&&e.response._visit({json:w=>{let E=Ng({schema:w.schema,context:r,fileContainingReference:t,namespace:l,declarationDepth:0});c.response={docs:w.description??void 0,type:WA(E)},w.statusCode!=null&&(c.response["status-code"]=w.statusCode),w.responseProperty!=null&&(c.response.property=w.responseProperty)},streamingJson:w=>{let E=Ng({schema:w.schema,context:r,fileContainingReference:t,namespace:l,declarationDepth:0});c["response-stream"]={docs:w.description??void 0,type:WA(E),format:"json"}},streamingSse:w=>{let E=Ng({schema:w.schema,context:r,fileContainingReference:t,namespace:l,declarationDepth:0});c["response-stream"]={docs:w.description??void 0,type:WA(E),format:"sse"}},file:w=>{c.response={docs:w.description??void 0,type:"file","status-code":w.statusCode}},bytes:w=>{c.response={docs:w.description??void 0,type:"bytes","status-code":w.statusCode}},streamingText:w=>{c["response-stream"]={docs:w.description??void 0,type:"text"}},text:w=>{c.response={docs:w.description??void 0,type:"text","status-code":w.statusCode}},_other:()=>{throw new Error("Unrecognized Response type: "+e.response?.type)}}),r.builder.getEnvironmentType()==="multi"){let w=r.getDefaultServerName(),E=e.servers[0];E==null?w!=null&&(c.url=w):c.url=E.name??void 0}return e.idempotent&&(c.idempotent=!0),e.availability!=null&&(c.availability=rx(e.availability)),Object.entries(e.errors).forEach(([w,E])=>{let q=E.generatedName,M=fy.of(fS);r.builder.enableUniqueErrorsPerEndpoint&&(q=`${e.generatedRequestName}${E.generatedName}`,E.schema!=null&&(E.schema.type!=="reference"&&E.schema.type!=="oneOf"?E.schema.generatedName=`${e.generatedRequestName}${E.schema.generatedName}`:E.schema.type==="oneOf"&&(E.schema.value.generatedName=`${e.generatedRequestName}${E.schema.value.generatedName}`)));let D={"status-code":parseInt(w)},C=Ww_({location:_1_,namespaceOverride:l});if(E.schema!=null){let I=Ng({schema:E.schema,context:r,fileContainingReference:C,declarationFile:C,namespace:l,declarationDepth:0});D.type=WA(I),D.docs=E.description}r.builder.addError(C,{name:q,schema:r.isErrorUnknownSchema(parseInt(w))?{...D,type:"unknown"}:D}),c.errors==null&&(c.errors=[]);let R=r.builder.addImport({file:t,fileToImport:C});c.errors.push(R!=null?`${R}.${q}`:q),D.type!=null&&E.examples?.forEach(I=>{let L={value:uK(I.example),name:I.name,docs:I.description};r.builder.addErrorExample(C,{name:q,example:L})})}),e.examples.length>0&&(c.examples=DNE({endpointExamples:e.examples,context:r})),r.ir.hasEndpointsMarkedInternal&&(e.internal==null||!e.internal)?c.audiences=[sSc,...e.audiences]:e.audiences.length>0&&(c.audiences=e.audiences),{value:c,schemaIdsToExclude:n}}function DNE({endpointExamples:e,context:t}){return e.map(r=>{try{return l1_({endpointExample:r,context:t})}catch(i){throw console.error(`Error building endpoint example: ${i}`),i}})}function ENE({endpoint:e,declarationFile:t,context:r,request:i,requestNameOverride:n,generatedRequestName:a,pathParameters:u,queryParameters:l,nonRequestReferencedSchemas:d,headers:s,usedNames:o,namespace:c}){if(i.type==="json"||i.type==="formUrlEncoded"){let b=i.schema.type==="reference"?i.schema.schema:void 0,g=i.schema.type==="reference"?r.getSchema(i.schema.schema,c):i.schema;if(g?.type!=="object"||b!=null&&d.includes(b)){let q=Ng({schema:i.schema,fileContainingReference:t,context:r,namespace:c,declarationDepth:0}),M={schemaIdsToExclude:[],value:{body:q}},D=Object.keys(u??{}).length>0,C=Object.keys(l??{}).length>0,R=Object.keys(s??{}).length>0;return D&&(M.value["path-parameters"]=u),C&&(M.value["query-parameters"]=l),R&&(M.value.headers=s),(D||C||R)&&(M.value.name=n??a),i.contentType!=null&&(M.value["content-type"]=i.contentType),i.description!=null&&(M.value.docs=i.description),M}let O=Object.fromEntries(g.properties.filter(q=>q.readonly==null?!0:!(d1_(e.method)&&q.readonly)).map(q=>{let M=Ng({schema:q.schema,fileContainingReference:t,context:r,namespace:c,declarationDepth:1}),D=q.nameOverride??q.key,C=rx(q.availability);if(!o.has(D)&&q.audiences.length<=0)return o.add(D),q.nameOverride!=null?[q.key,{type:WA(M),docs:DKn(M),name:q.nameOverride,availability:C}]:[q.key,C?{...typeof M=="string"?{type:M}:M,availability:C}:M];let R={type:WA(M),docs:DKn(M)};return o.has(D)&&(R.name=q.generatedName),q.audiences.length>0&&(R.audiences=q.audiences),C!=null&&(R.availability=C),o.add(D),[q.key,R]})),m=g.allOf.map(q=>{let M=Ng({schema:cv.reference(q),fileContainingReference:t,context:r,namespace:c,declarationDepth:0});return WA(M)}).filter(q=>q!=="unknown"),w={properties:O};m.length>0&&(w.extends=m),i.additionalProperties&&(w["extra-properties"]=!0);let E={name:n??g.nameOverride??g.generatedName,"path-parameters":u,"query-parameters":l,headers:s,body:w};return i.contentType!=null&&(E["content-type"]=i.contentType),i.description!=null&&(E.docs=i.description),{schemaIdsToExclude:b!=null?[b]:[],value:E}}else{if(i.type==="octetStream")return{schemaIdsToExclude:[],value:{body:"bytes","content-type":i.contentType??hq.APPLICATION_OCTET_STREAM,"query-parameters":l,...i.description?{docs:i.description}:{}}};if(i.type==="multipart"){let b=Object.fromEntries(i.properties.map(g=>{if(g.schema.type==="file"){let O=g.schema.isArray?"list<file>":"file";if(O=g.schema.isOptional?`optional<${O}>`:O,g.description!=null||g.contentType!=null){let m={type:O};if(g.description!=null&&(m.docs=g.description),g.contentType!=null){let w=g.contentType.split(",")[0];m["content-type"]=w}return[g.key,m]}return[g.key,O]}else{let O=Ng({schema:g.schema.value,fileContainingReference:t,context:r,namespace:c,declarationDepth:1});if(g.contentType||g.exploded||g.encoding){let m=typeof O=="string"?{type:O}:O;g.contentType!=null&&(m["content-type"]=g.contentType),g.encoding==="form"?m.style="form":g.encoding==="json"?m.style="json":g.exploded&&(m.style="exploded"),O=m}return[g.key,O]}}));return{schemaIdsToExclude:i.name==null?[]:[i.name],value:{name:n??i.name??a,"path-parameters":u,"query-parameters":l,headers:s,body:{properties:b},"content-type":hq.MULTIPART_FORM_DATA,...i.description?{docs:i.description}:{}}}}else So(i)}}function MNE({context:e,request:t}){if(!e.inlinePathParameters)return!1;if(t==null)return!0;switch(t.type){case"octetStream":return!1;case"multipart":return!0;case"json":return!0;case"formUrlEncoded":return!0;default:So(t)}}function ANE({location:e,namespaceOverride:t}){return t!=null?{...e,file:PF(fy.of(t),e.file)}:e}function qNE(e){let t=e.namespace,r=e.tags.filter(d=>d!==t)[0],i=e.operationId;if(i==null)return r!=null?{file:fy.of(`${S_(r)}.yml`),endpointId:e.summary!=null?S_(e.summary):S_(`${e.method}_${e.path.split("/").join("_")}`)}:e.summary!=null?{file:fy.of(fS),endpointId:S_(e.summary)}:{file:fy.of(fS),endpointId:S_(`${e.method}_${e.path.split("/").join("_")}`)};if(r==null)return{file:fy.of(fS),endpointId:i};let n=H5a(r),a=H5a(i);if(g8(n,a))return{file:fy.of("__package__.yml"),endpointId:r};let u=BNE({operationId:i,tag:r,path:e.path,method:e.method});if(u!=null)return u;let l=[];for(let d=0;d<n.length;++d){let s=n[d];if(s!=null&&s===a[d])l.push(s);else{let o=S_(r);return{file:fy.of(`${o}.yml`),endpointId:i,tag:r}}}if(l.length>=a.length)throw new Error(`Cannot get file for endpoint ${JSON.stringify(e)}`);return{file:fy.of(S_(l.join("_"))+".yml"),endpointId:S_(a.slice(l.length).join("_")),tag:r}}function $5a(e){let t=e.tags[0];if(e.sdkName!=null){let r=G1c({sdkName:e.sdkName,namespaceOverride:e.namespace}),i=`${r}.yml`,n=r.toLowerCase()===t?.toLowerCase().replaceAll(" ","");return{file:fy.of(i),endpointId:e.sdkName.methodName,tag:n?t:void 0}}return ANE({namespaceOverride:e.namespace,location:qNE(e)})}function H5a(e){let t;return/^[a-z]+(?:[A-Z][a-z]+)*$/.test(e)?t=e.split(/(?=[A-Z])/):t=e.split(/[^a-zA-Z0-9]+/),t=t.map(r=>r.toLowerCase()),t=Gxe(t),t}var TNE=new RegExp("[^a-zA-Z0-9{}]+"),CNE=new RegExp("[{}]","g");function BNE({operationId:e,tag:t,path:r,method:i}){let a=`${r.split(TNE).join("_").replaceAll(CNE,"_")}_${i.toLowerCase()}`;if(e.endsWith(a))return{file:fy.of(S_(t)+".yml"),endpointId:S_(e.slice(0,-1*a.length)),tag:t}}function h1_(e){let t=new Set,{endpoints:r,tags:i}=e.ir,n=[];for(let a of r){let{endpointId:u,file:l,tag:d}=$5a(a),s=l.split(".")[0];s!=null&&t.add(s);let o;if(a.sdkName!=null){let g=e.ir.groups;for(let O of a.sdkName.groupName){let m=typeof O=="string"?O:O.name,w=g[m];if(w==null)break;if(w.summary!=null||w.description!=null){o=g[m];break}}}let c=d==null?void 0:i.tagsById[d];e.setInState($8.Endpoint),e.setEndpointMethod(a.method);let b=p1_({context:e,endpoint:a,declarationFile:l});e.unsetEndpointMethod(),e.unsetInState($8.Endpoint),n=[...n,...b.schemaIdsToExclude],e.builder.addEndpoint(l,{name:u,schema:b.value,source:a.source!=null?Zmi(a.source):void 0}),(c?.id!=null||c?.description!=null)&&e.builder.setServiceInfo(l,{"display-name":o?.summary??c?.id,docs:o?.description??c?.description??void 0})}return{schemaIdsToExclude:n,sdkGroups:t}}function y1_(e){for(let[t,r]of Object.entries(e.ir.variables)){let i=r.groupName!=null?kmi(r.groupName):void 0,n=Ng({schema:cv.primitive(r),context:e,fileContainingReference:fy.of(fS),namespace:i,declarationDepth:0});e.builder.addVariable({name:t,schema:{type:WA(n),docs:r.description??void 0}})}}function v1_(e){for(let t of e.ir.webhooks){let r=RNE({webhook:t,context:e});if(r==null)continue;let i=Eau(t.sdkName,t.namespace),n={};for(let u of t.headers)n[u.name]=wor({header:u,context:e,fileContainingReference:r.file,namespace:i});let a={audiences:t.audiences,method:t.method,"display-name":t.summary??void 0,headers:n,payload:Ng({schema:t.payload,context:e,fileContainingReference:r.file,namespace:i,declarationDepth:0}),examples:t.examples!=null?t.examples.map(u=>({docs:u.description,name:u.name,payload:uK(u.payload)})):void 0};e.builder.addWebhook(r.file,{name:r.endpointId,schema:a}),t.description!=null&&(a.docs=t.description)}}function INE({location:e,namespaceOverride:t}){if(e!=null)return t!=null?{...e,file:PF(fy.of(t),e.file)}:e}function zNE({webhook:e,context:t}){let r=e.tags[0],i=e.operationId;if(r==null)return{file:fy.of(fS),endpointId:i};let n=H5a(r),a=H5a(i);if(g8(n,a))return{file:fy.of("__package__.yml"),endpointId:r};let u=[];for(let l=0;l<n.length;++l){let d=n[l];if(d!=null&&d===a[l])u.push(d);else{let s=S_(r);return{file:fy.of(`${s}.yml`),endpointId:i,tag:r}}}if(u.length>=a.length){t.logger.warn(`Skipping webhook ${e.operationId} because couldn't compute file location`);return}return{file:fy.of(S_(u.join("_"))+".yml"),endpointId:S_(a.slice(u.length).join("_")),tag:r}}function RNE({webhook:e,context:t}){return e.sdkName!=null?{file:Vw_({sdkName:e.sdkName,namespaceOverride:e.namespace}),endpointId:e.sdkName.methodName}:INE({namespaceOverride:e.namespace,location:zNE({webhook:e,context:t})})}var xNE=fy.of(fS);function g1_(e){switch(e.type){case"object":case"primitive":case"enum":case"array":case"map":case"reference":case"literal":case"optional":case"nullable":return b1_({namespace:e.namespace,groupName:e.groupName});case"oneOf":return b1_({namespace:e.value.namespace,groupName:e.value.groupName});case"unknown":return xNE;default:So(e)}}function b1_({namespace:e,groupName:t}){return e!=null&&t!=null?GNi([{type:"namespace",name:e},...t]):e!=null?GNi([{type:"namespace",name:e}]):GNi(t)}var sSc="external",_1_=fy.of(fS);function O1_({schemas:e,schemaIdsToExclude:t,namespace:r,context:i}){for(let[n,a]of Object.entries(e)){if(t.includes(n))continue;let u=g1_(a),l=Qw_({schema:a,context:i,declarationFile:u,namespace:r,declarationDepth:0});if(yzi(l.schema)){let d=WA(l.schema);if(d===(l.name??n)||d===`optional<${l.name??n}>`)continue}i.builder.addType(u,{name:l.name??n,schema:l.schema})}}function m1_(e){e.ir.apiVersion!=null&&e.builder.setApiVersion(e.ir.apiVersion),i1_(e),n1_(e),a1_(e),Zw_(e),y1_(e),e.ir.basePath!=null&&e.builder.setBasePath(e.ir.basePath),e.ir.hasEndpointsMarkedInternal&&e.builder.addAudience(sSc);let t=h1_(e),r=t.sdkGroups;e.setInState($8.Webhook),v1_(e),e.unsetInState($8.Webhook),e.setInState($8.Channel);for(let n of Object.values(e.ir.channels)){let a=GNi(n.groupName);r1_({channel:n,context:e,declarationFile:a})}e.unsetInState($8.Channel);let i=NNE({context:e,schemaIdsToExcludeFromServices:t.schemaIdsToExclude});O1_({schemas:e.ir.groupedSchemas.rootSchemas,schemaIdsToExclude:i,namespace:void 0,context:e});for(let[n,a]of Object.entries(e.ir.groupedSchemas.namespacedSchemas))O1_({schemas:a,schemaIdsToExclude:i,namespace:n,context:e});return e.ir.tags.orderedTagIds!=null&&e.ir.tags.orderedTagIds.length>0&&e.ir.tags.orderedTagIds.every(a=>r.has(a))&&e.builder.addNavigation({navigation:e.ir.tags.orderedTagIds}),e.builder.build()}function NNE({context:e,schemaIdsToExcludeFromServices:t}){let r=e.getReferencedSchemaIds();if(r==null)return t;let i=new Set([...Object.keys(e.ir.groupedSchemas.rootSchemas),...Object.values(e.ir.groupedSchemas.namespacedSchemas).flatMap(a=>Object.keys(a))]),n=new Set(t);for(let a of i)r.includes(a)||n.add(a);return Array.from(n)}var G5a=class{context;constructor(t){this.context=t}};var Aau=class e{files={};directories={};getAllFiles(){let t={},r=(i,n)=>{for(let[u,l]of Object.entries(i.files)){let d=n!=null?fy.of(`${n}${b$t}${u}`):fy.of(u);t[d]=l}let a=Object.keys(i.directories).sort();for(let u of a){let l=n!=null?`${n}${b$t}${u}`:u,d=i.directories[u];r(d,l)}};return r(this),t}getOrCreateFile(t){return this.getOrCreateFileRecursive(t.split(b$t))}getOrCreateFileRecursive(t){if(t.length===1)return this.files[fy.of(t[0])]??={};let[r,...i]=t;if(r==null)throw new Error(`Internal error; cannot add file with path: ${t}`);return this.directories[r]||(this.directories[r]=new e),this.directories[r].getOrCreateFileRecursive(i)}};var tan=class{enableUniqueErrorsPerEndpoint;root;rootApiFile;packageMarkerFile={};basePath=void 0;constructor(t){this.enableUniqueErrorsPerEndpoint=t,this.root=new Aau,this.rootApiFile={name:"api","error-discrimination":{strategy:"status-code"}}}setDisplayName({displayName:t}){this.rootApiFile["display-name"]=t}addNavigation({navigation:t}){this.packageMarkerFile.navigation=t}setServiceInfo(t,{auth:r,"base-path":i,"display-name":n,docs:a}){let u=this.getOrCreateFile(t);u.service==null&&(u.service={auth:!1,"base-path":"",endpoints:{}}),r!=null&&(u.service.auth=r),i!=null&&(u.service["base-path"]=i),n!=null&&(u.service["display-name"]=n),a!=null&&(u.docs=a)}addAudience(t){this.rootApiFile.audiences==null&&(this.rootApiFile.audiences=[]),this.rootApiFile.audiences.push(t)}setAuth(t){this.rootApiFile.auth=t}addAuthScheme({name:t,schema:r}){this.rootApiFile["auth-schemes"]==null&&(this.rootApiFile["auth-schemes"]={}),this.rootApiFile["auth-schemes"][t]==null&&(this.rootApiFile["auth-schemes"][t]=r)}setDefaultEnvironment(t){this.rootApiFile["default-environment"]=t}setDefaultUrl(t){this.rootApiFile["default-url"]=t}setBasePath(t){this.basePath=t}setApiVersion(t){this.rootApiFile.version=t}getEnvironmentType(){let t=Object.entries(this.rootApiFile.environments??{})[0];if(t!=null)return Krr(t[1],{singleBaseUrl:()=>"single",multipleBaseUrls:()=>"multi"})}addEnvironment({name:t,schema:r}){this.rootApiFile.environments==null&&(this.rootApiFile.environments={}),this.rootApiFile.environments[t]=r}getGlobalHeaderNames(){let t=Object.keys(this.rootApiFile.headers??{});if(this.rootApiFile["auth-schemes"]!=null)for(let i of Object.values(this.rootApiFile["auth-schemes"]))P1_(i)&&t.push(i.header);let r=this.getVersionHeader();return r!=null&&t.push(r),new Set(t)}getAuthHeaderName(){if(this.rootApiFile["auth-schemes"]!=null){for(let t of Object.values(this.rootApiFile["auth-schemes"]))if(P1_(t))return t.header;return"Authorization"}}addGlobalHeader({name:t,schema:r}){let i=this.getVersionHeader();i!=null&&i===t||(this.rootApiFile.headers==null&&(this.rootApiFile.headers={}),this.rootApiFile.headers[t]=r)}getGlobalHeaders(){return this.rootApiFile.headers??{}}addIdempotencyHeader({name:t,schema:r}){this.rootApiFile["idempotency-headers"]==null&&(this.rootApiFile["idempotency-headers"]={}),this.rootApiFile["idempotency-headers"][t]=r}addVariable({name:t,schema:r}){this.rootApiFile.variables==null&&(this.rootApiFile.variables={}),this.rootApiFile.variables[t]=r}addImport({file:t,fileToImport:r,alias:i}){if(t===r)return;let n=i??S_((iNe(r)+"/"+lki(r,{stripExtension:!0})).replaceAll("__package__","root"));if(t===fy.of(z3))return this.rootApiFile.imports==null&&(this.rootApiFile.imports={}),this.rootApiFile.imports[n]=OBo(iNe(w5n.of(`/${t}`)),w5n.of(`/${r}`)),n;let a=this.getOrCreateFile(t);return a.imports==null&&(a.imports={}),a.imports[n]=OBo(iNe(w5n.of(`/${t}`)),w5n.of(`/${r}`)),n}addType(t,{name:r,schema:i}){if(t===fy.of(z3))return;let n=this.getOrCreateFile(t);n.types==null&&(n.types={}),n.types[r]=i}addTypeExample(t,r,i){let n=this.getOrCreateFile(t);n.types==null&&(n.types={});let a=n.types[r];a!=null&&(typeof a=="string"?n.types[r]={type:a,examples:[i]}:(a.examples==null&&(a.examples=[]),a.examples.push(i)))}addError(t,{name:r,schema:i}){let n=this.getOrCreateFile(t);n.errors==null&&(n.errors={}),n.errors[r]==null?n.errors[r]=i:n.errors[r]?.type!==i.type&&(n.errors[r]={"status-code":i["status-code"],type:"unknown"})}addErrorExample(t,{name:r,example:i}){let n=this.getOrCreateFile(t);if(n.errors==null)return;let a=n.errors[r];if(a==null)return;a.examples==null&&(a.examples=[]),(a.examples.some(l=>g8(l,i))??!1)||a.examples?.push(i)}addEndpoint(t,{name:r,schema:i,source:n}){let a=this.getOrCreateFile(t);a.service==null&&(a.service={auth:!1,"base-path":"",endpoints:{}}),n!=null&&(a.service.source=n),a.service.endpoints[r]=i}addWebhook(t,{name:r,schema:i}){let n=this.getOrCreateFile(t);n.webhooks==null&&(n.webhooks={}),n.webhooks[r]=i}addChannel(t,{channel:r}){let i=this.getOrCreateFile(t);i.channel=r;let n=this.basePath;n!=null&&(i.channel.path=PF(n,r.path))}addChannelExample(t,{example:r}){let i=this.getOrCreateFile(t);i.channel==null&&(i.channel={path:"",auth:!1}),i.channel.messages==null&&(i.channel.messages={}),i.channel.examples==null&&(i.channel.examples=[]),i.channel.examples.push(r)}addChannelMessage(t,{messageId:r,message:i}){let n=this.getOrCreateFile(t);n.channel==null&&(n.channel={path:"",auth:!1}),n.channel.messages==null&&(n.channel.messages={}),n.channel.messages[r]=i}build(){let t=this.root.getAllFiles(),r=this.basePath;if(r!=null){this.packageMarkerFile.service!=null&&(this.packageMarkerFile.service={...this.packageMarkerFile.service,endpoints:Object.fromEntries(Object.entries(this.packageMarkerFile.service.endpoints).map(([n,a])=>[n,{...a,path:PF(r,a.path)}]))});for(let n of Object.values(t))n.service!=null&&(n.service={...n.service,endpoints:Object.fromEntries(Object.entries(n.service.endpoints).map(([a,u])=>[a,{...u,path:PF(r,u.path)}]))})}return{rootApiFile:this.rootApiFile,packageMarkerFile:this.packageMarkerFile,definitionFiles:t}}getOrCreateFile(t){return t===fS?this.packageMarkerFile:this.root.getOrCreateFile(t)}getVersionHeader(){if(this.rootApiFile.version!=null)return typeof this.rootApiFile.version.header=="string"?this.rootApiFile.version.header:this.rootApiFile.version.header.value}};function P1_(e){return e?.header!=null}var qau=class{logger;taskContext;ir;builder;environmentOverrides;authOverrides;globalHeaderOverrides;detectGlobalHeaders;objectQueryParameters;respectReadonlySchemas;respectNullableSchemas;onlyIncludeReferencedSchemas;inlinePathParameters;useBytesForBinaryResponse;respectForwardCompatibleEnums;enableUniqueErrorsPerEndpoint;defaultServerName=void 0;unknownSchema=new Set;referencedSchemaIds;endpointMethod;state=new Set;constructor({taskContext:t,ir:r,options:i,environmentOverrides:n,globalHeaderOverrides:a,authOverrides:u}){this.logger=t.logger,this.taskContext=t,this.ir=r,this.environmentOverrides=n,this.authOverrides=u,this.globalHeaderOverrides=a,this.detectGlobalHeaders=i?.detectGlobalHeaders??!0,this.objectQueryParameters=i?.objectQueryParameters??!1,this.respectReadonlySchemas=i?.respectReadonlySchemas??!1,this.respectNullableSchemas=i?.respectNullableSchemas??!1,this.onlyIncludeReferencedSchemas=i?.onlyIncludeReferencedSchemas??!1,this.inlinePathParameters=i?.inlinePathParameters??!1,this.useBytesForBinaryResponse=i?.useBytesForBinaryResponse??!1,this.respectForwardCompatibleEnums=i?.respectForwardCompatibleEnums??!1,this.referencedSchemaIds=i?.onlyIncludeReferencedSchemas?new Set:void 0,this.enableUniqueErrorsPerEndpoint=i?.enableUniqueErrorsPerEndpoint??!1,this.builder=new tan(this.enableUniqueErrorsPerEndpoint),r.title!=null&&this.builder.setDisplayName({displayName:r.title});let l={};if(!this.enableUniqueErrorsPerEndpoint)for(let d of r.endpoints)for(let[s,o]of Object.entries(d.errors)){let c=parseInt(s),b=l[c];b==null&&o.schema!=null?l[c]=o.schema:b!=null&&o.schema!=null&&fue(b,o.schema)||this.unknownSchema.add(c)}}getReferencedSchemaIds(){if(this.referencedSchemaIds!=null)return Array.from(this.referencedSchemaIds)}getSchema(t,r){return r==null?this.ir.groupedSchemas.rootSchemas[t]:this.ir.groupedSchemas.namespacedSchemas[r]?.[t]}getDefaultServerName(){return this.defaultServerName}setDefaultServerName(t){this.defaultServerName=t}isErrorUnknownSchema(t){return this.unknownSchema.has(t)}getEndpointMethod(){return this.endpointMethod}setEndpointMethod(t){this.endpointMethod=t}unsetEndpointMethod(){this.endpointMethod=void 0}isInState(t){return this.state.has(t)}setInState(t){this.state.add(t)}unsetInState(t){this.state.delete(t)}shouldMarkSchemaAsReferenced(){return this.onlyIncludeReferencedSchemas&&this.isInAnyState($8.Channel,$8.Endpoint,$8.Webhook)}markSchemaAsReferenced(t,r){switch(t.type){case"primitive":return;case"object":this.markObjectSchemaAsReferenced(t,r);return;case"array":this.markSchemaAsReferenced(t.value,r);return;case"map":this.markSchemaAsReferenced(t.value,r);return;case"optional":this.markSchemaAsReferenced(t.value,r);return;case"reference":this.markSchemaIdAsReferenced(t.schema,r);return;case"oneOf":this.markOneofSchemaAsReferenced(t.value,r);return;case"nullable":this.markSchemaAsReferenced(t.value,r);return;case"enum":return;case"literal":return;case"unknown":return;default:So(t)}}markObjectSchemaAsReferenced(t,r){for(let i of t.allOf)this.markSchemaIdAsReferenced(i.schema,r);for(let i of t.properties)this.markSchemaAsReferenced(i.schema,r)}markOneofSchemaAsReferenced(t,r){switch(t.type){case"discriminated":for(let i of Object.values(t.schemas))this.markSchemaAsReferenced(i,r);return;case"undiscriminated":for(let i of t.schemas)this.markSchemaAsReferenced(i,r);return;default:So(t)}}markSchemaIdAsReferenced(t,r){if(this.referencedSchemaIds!=null&&!this.referencedSchemaIds.has(t)){this.referencedSchemaIds.add(t);let i=this.getSchema(t,r);i!=null&&this.markSchemaAsReferenced(i,r)}}isInAnyState(...t){return t.some(r=>this.isInState(r))}};function cSc(e){let t=new qau(e);return m1_(t)}var Tau=class{args;constructor(t){this.args=t}convert({context:t,ir:r,settings:i,absoluteFilePath:n}){let a=cSc({taskContext:t,ir:r,options:R5a({overrides:{...i,respectReadonlySchemas:i?.respectReadonlySchemas??this.args.respectReadonlySchemas,respectNullableSchemas:i?.respectNullableSchemas??this.args.respectNullableSchemas,onlyIncludeReferencedSchemas:i?.onlyIncludeReferencedSchemas??this.args.onlyIncludeReferencedSchemas,inlinePathParameters:i?.inlinePathParameters??this.args.inlinePathParameters,objectQueryParameters:i?.objectQueryParameters??this.args.objectQueryParameters,useBytesForBinaryResponse:i?.useBytesForBinaryResponse??this.args.useBytesForBinaryResponse,respectForwardCompatibleEnums:i?.respectForwardCompatibleEnums??this.args.respectForwardCompatibleEnums}}),authOverrides:i?.auth!=null?{auth:i.auth}:this.args.generatorsConfiguration?.api?.auth!=null?{...this.args.generatorsConfiguration.api}:void 0,environmentOverrides:this.args.generatorsConfiguration?.api?.environments!=null?{...this.args.generatorsConfiguration?.api}:void 0,globalHeaderOverrides:this.args.generatorsConfiguration?.api?.headers!=null?{...this.args.generatorsConfiguration?.api}:void 0});return{absoluteFilePath:n??this.args.absoluteFilePath,rootApiFile:{defaultUrl:a.rootApiFile["default-url"],contents:a.rootApiFile,rawContents:wd.dump(a.rootApiFile)},namedDefinitionFiles:{..._d(a.definitionFiles,u=>({absoluteFilepath:n??this.args.absoluteFilePath,rawContents:wd.dump(u),contents:u})),[fy.of(fS)]:{absoluteFilepath:n??this.args.absoluteFilePath,rawContents:wd.dump(a.packageMarkerFile),contents:a.packageMarkerFile}},packageMarkers:{},importedDefinitions:{}}}};var Q5a=class extends hQt{inlinePathParameters;objectQueryParameters;onlyIncludeReferencedSchemas;respectReadonlySchemas;respectNullableSchemas;exampleGeneration;useBytesForBinaryResponse;respectForwardCompatibleEnums;converter;constructor(t){super(t),this.inlinePathParameters=t.inlinePathParameters,this.objectQueryParameters=t.objectQueryParameters,this.onlyIncludeReferencedSchemas=t.onlyIncludeReferencedSchemas,this.respectReadonlySchemas=t.respectReadonlySchemas,this.respectNullableSchemas=t.respectNullableSchemas,this.exampleGeneration=t.exampleGeneration,this.useBytesForBinaryResponse=t.useBytesForBinaryResponse,this.respectForwardCompatibleEnums=t.respectForwardCompatibleEnums,this.converter=new Tau(t)}async getDefinition({context:t,absoluteFilePath:r,relativePathToDependency:i},n){let a=await this.getOpenAPIIr({context:t,relativePathToDependency:i},n);return this.converter.convert({context:t,ir:a,settings:n,absoluteFilePath:r})}async toFernWorkspace({context:t},r){let i=await this.getDefinition({context:t},r);return new ZAe({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:i,cliVersion:this.cliVersion})}};var JH={BEARER_FORMAT:"x-bearer-format",ENUM_VAR_NAMES:"x-enum-varnames",INTERNAL:"x-internal",EXAMPLES:"x-examples",TAGS:"x-tags",REDOCLY_CODE_SAMPLES_KEBAB:"x-code-samples",REDOCLY_CODE_SAMPLES_CAMEL:"x-codeSamples"};var EKn={of(e){return e}};var j1_={properties:{"stream-condition":{type:"string"},response:"Schema","response-stream":"Schema"},required:["stream-condition","response","response-stream"],extensionsPrefix:"x-"},lSc={id:"",typeExtension:{oas3:e=>({...e,XFernStreaming:j1_,Operation:{...e.Operation,properties:{...e.Operation?.properties,"x-fern-streaming":"XFernStreaming"}}})}},Kf={SOURCE:EKn.of("source"),SDK_NAMESPACE:EKn.of("x-fern-sdk-namespace"),SDK_METHOD_NAME:EKn.of("x-fern-sdk-method-name"),SDK_GROUP_NAME:EKn.of("x-fern-sdk-group-name"),REQUEST_NAME_V1:"x-request-name",REQUEST_NAME_V2:"x-fern-request-name",TYPE_NAME:"x-fern-type-name",BOOLEAN_LITERAL:"x-fern-boolean-literal",SERVER_NAME_V1:"x-name",SERVER_NAME_V2:"x-fern-server-name",BASE_PATH:"x-fern-base-path",GROUPS:EKn.of("x-fern-groups"),OPENAPI_OVERIDES_FILEPATH:"x-fern-overrides-filepath",TYPE_DEFINITION:"x-fern-type",STREAMING:"x-fern-streaming",PAGINATION:"x-fern-pagination",WEBHOOK:"x-fern-webhook",ASYNC_CONFIG:"x-fern-async-config",SDK_VARIABLES:"x-fern-sdk-variables",SDK_VARIABLE:"x-fern-sdk-variable",PARAMETER_NAME:"x-fern-parameter-name",BASIC_AUTH_USERNAME_VARIABLE_NAME:"x-fern-username-variable-name",BASIC_AUTH_PASSWORD_VARIABLE_NAME:"x-fern-password-variable-name",BEARER_TOKEN_VARIABLE_NAME:"x-fern-token-variable-name",HEADER_VARIABLE_NAME:"x-fern-header-variable-name",FERN_ENUM:"x-fern-enum",AUDIENCES:"x-fern-audiences",IGNORE:"x-fern-ignore",AVAILABILITY:"x-fern-availability",RESPONSE_PROPERTY:"x-fern-sdk-return-value",RESOLUTIONS:"x-fern-resolutions",EXAMPLES:"x-fern-examples",FERN_BEARER_TOKEN:"x-fern-bearer",FERN_HEADER_AUTH:"x-fern-header",FERN_BASIC_AUTH:"x-fern-basic",FERN_GLOBAL_HEADERS:"x-fern-global-headers",FERN_IDEMPOTENCY_HEADERS:"x-fern-idempotency-headers",IDEMPOTENT:"x-fern-idempotent",FERN_PROPERTY_NAME:"x-fern-property-name",IS_UNDISCRIMINATED:"x-fern-undiscriminated",FERN_VERSION:"x-fern-version",ENCODING:"x-fern-encoding",TRANSPORT:"x-fern-transport",IS_DISCRIMINATED:"x-fern-discriminated"};var b7={disableExamples:!1,discriminatedUnionV2:!1,useTitlesAsName:!0,audiences:void 0,optionalAdditionalProperties:!0,coerceEnumsToLiterals:!0,respectReadonlySchemas:!1,respectNullableSchemas:!1,onlyIncludeReferencedSchemas:!1,inlinePathParameters:!1,preserveSchemaIds:!1,objectQueryParameters:!1,shouldUseUndiscriminatedUnionsWithLiterals:!1,shouldUseIdiomaticRequestNames:!1,filter:void 0,asyncApiNaming:"v1",exampleGeneration:void 0,defaultFormParameterEncoding:"json",useBytesForBinaryResponse:!1,respectForwardCompatibleEnums:!1,additionalPropertiesDefaultsTo:!1,typeDatesAsStrings:!0,preserveSingleSchemaOneOf:!1};function gQt({options:e,overrides:t}){return{disableExamples:t?.disableExamples??b7.disableExamples,discriminatedUnionV2:t?.discriminatedUnionV2??e?.discriminatedUnionV2??b7.discriminatedUnionV2,useTitlesAsName:t?.useTitlesAsName??e?.useTitlesAsName??b7.useTitlesAsName,audiences:t?.audiences??e?.audiences??b7.audiences,optionalAdditionalProperties:t?.optionalAdditionalProperties??e?.optionalAdditionalProperties??b7.optionalAdditionalProperties,coerceEnumsToLiterals:t?.coerceEnumsToLiterals??e?.coerceEnumsToLiterals??b7.coerceEnumsToLiterals,respectReadonlySchemas:t?.respectReadonlySchemas??e?.respectReadonlySchemas??b7.respectReadonlySchemas,respectNullableSchemas:t?.respectNullableSchemas??e?.respectNullableSchemas??b7.respectNullableSchemas,onlyIncludeReferencedSchemas:t?.onlyIncludeReferencedSchemas??e?.onlyIncludeReferencedSchemas??b7.onlyIncludeReferencedSchemas,inlinePathParameters:t?.inlinePathParameters??e?.inlinePathParameters??b7.inlinePathParameters,preserveSchemaIds:t?.preserveSchemaIds??b7.preserveSchemaIds,shouldUseUndiscriminatedUnionsWithLiterals:t?.shouldUseUndiscriminatedUnionsWithLiterals??e?.shouldUseUndiscriminatedUnionsWithLiterals??b7.shouldUseUndiscriminatedUnionsWithLiterals,shouldUseIdiomaticRequestNames:t?.shouldUseIdiomaticRequestNames??e?.shouldUseIdiomaticRequestNames??b7.shouldUseIdiomaticRequestNames,objectQueryParameters:t?.objectQueryParameters??e?.objectQueryParameters??b7.objectQueryParameters,filter:t?.filter??e?.filter??b7.filter,asyncApiNaming:t?.asyncApiNaming??e?.asyncApiNaming??b7.asyncApiNaming,useBytesForBinaryResponse:t?.useBytesForBinaryResponse??e?.useBytesForBinaryResponse??b7.useBytesForBinaryResponse,exampleGeneration:t?.exampleGeneration??e?.exampleGeneration??void 0,defaultFormParameterEncoding:t?.defaultFormParameterEncoding??e?.defaultFormParameterEncoding??void 0,respectForwardCompatibleEnums:t?.respectForwardCompatibleEnums??e?.respectForwardCompatibleEnums??b7.respectForwardCompatibleEnums,additionalPropertiesDefaultsTo:t?.additionalPropertiesDefaultsTo??e?.additionalPropertiesDefaultsTo??b7.additionalPropertiesDefaultsTo,typeDatesAsStrings:t?.typeDatesAsStrings??e?.typeDatesAsStrings??b7.typeDatesAsStrings,preserveSingleSchemaOneOf:t?.preserveSingleSchemaOneOf??e?.preserveSingleSchemaOneOf??b7.preserveSingleSchemaOneOf}}var w1_={naming:"v1"};function of(e,t){let r=Array.isArray(t)?t:[t];for(let i of r){let n=e[i];if(n!=null)return n}}function J5a(e,t,r,i,n=[]){try{let a=of(e,t);if(a!=null)return r.parse(a)}catch{let u=Gxe(n).join(" -> ");i.error(`${u.length>0?`${u}: `:""}Failed to parse ${t}`)}}function ran(e){let t=of(e,"examples");return t!=null&&Array.isArray(t)?t:[]}function S1_({schema:e,logger:t}){return of(e,Kf.ENCODING)??void 0}function D1_(e){return of(e,Kf.FERN_ENUM)}function E1_({nameOverride:e,generatedName:t,title:r,schema:i,description:n,availability:a}){let u=of(i,Kf.SDK_NAMESPACE),l=of(i,Kf.SDK_GROUP_NAME),d=of(i,Kf.TYPE_DEFINITION);if(d!=null)return K5a({fernType:d,nameOverride:e,generatedName:t,title:r,description:n,availability:a,namespace:u,groupName:typeof l=="string"?[l]:l})}function K5a({fernType:e,nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:l}){return Y3({type:e,_default:void 0,validation:void 0,visitor:{primitive:d=>{switch(d.v1){case"BASE_64":return Al.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:l,schema:ap.base64({example:void 0})});case"BOOLEAN":return Al.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:l,schema:ap.boolean({default:void 0,example:void 0})});case"DATE":return Al.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:l,schema:ap.date({example:void 0})});case"DATE_TIME":return Al.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:l,schema:ap.datetime({example:void 0})});case"FLOAT":return Al.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:l,schema:ap.float({example:void 0})});case"DOUBLE":return Al.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:l,schema:ap.double({default:void 0,minimum:void 0,maximum:void 0,exclusiveMinimum:void 0,exclusiveMaximum:void 0,multipleOf:void 0,example:void 0})});case"UINT":return Al.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:l,schema:ap.uint({default:void 0,example:void 0})});case"INTEGER":return Al.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:l,schema:ap.int({default:void 0,minimum:void 0,maximum:void 0,exclusiveMinimum:void 0,exclusiveMaximum:void 0,multipleOf:void 0,example:void 0})});case"UINT_64":return Al.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:l,schema:ap.uint64({default:void 0,example:void 0})});case"LONG":return Al.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:l,schema:ap.int64({default:void 0,example:void 0})});case"STRING":case"UUID":case"BIG_INTEGER":return Al.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:l,schema:ap.string({default:void 0,pattern:void 0,maxLength:void 0,minLength:void 0,example:void 0,format:void 0})});default:So(d.v1)}},unknown:()=>Al.unknown({nameOverride:t,generatedName:r,title:i,example:void 0,description:n,availability:a,namespace:u,groupName:l}),map:({keyType:d,valueType:s})=>d?.type==="primitive"&&s!=null?Al.map({nameOverride:t,generatedName:r,title:i,key:d,value:s,description:n,availability:a,namespace:u,groupName:l,encoding:void 0,example:void 0,inline:void 0}):void 0,list:d=>d!=null?Al.array({nameOverride:t,generatedName:r,title:i,value:d,description:n,availability:a,namespace:u,groupName:l,example:void 0,inline:void 0}):void 0,optional:d=>d!=null?Al.optional({nameOverride:t,generatedName:r,title:i,value:d,description:n,availability:a,namespace:u,groupName:l,inline:void 0}):void 0,nullable:d=>d!=null?Al.nullable({nameOverride:t,generatedName:r,title:i,value:d,description:n,availability:a,namespace:u,groupName:l,inline:void 0}):void 0,set:d=>d!=null?Al.array({nameOverride:t,generatedName:r,title:i,value:d,description:n,availability:a,namespace:u,groupName:l,example:void 0,inline:void 0}):void 0,literal:d=>Al.literal({nameOverride:t,generatedName:r,title:i,value:d._visit({string:s=>Kz.string(s),boolean:s=>Kz.boolean(s),_other:()=>{throw new Error("Unexpected literal type")}}),description:n,availability:a,namespace:u,groupName:l}),named:d=>Al.reference({schema:d,nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:l,source:nK.openapi({file:"<memory>"})})}})}function M1_(e){let t=of(e,Kf.SOURCE);if(t!=null)return t.endsWith(".proto")?nK.protobuf({file:t}):nK.openapi({file:t})}function ian(e){if(e!=null&&typeof e=="boolean")return e}function Kd(e){return e.$ref!=null}function A1_({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,additionalProperties:n,description:a,availability:u,wrapAsNullable:l,context:d,namespace:s,groupName:o,example:c,encoding:b,source:g}){return n===void 0&&(n=d.options.additionalPropertiesDefaultsTo),typeof n=="boolean"||MKn(n,d.options)?Cau({nameOverride:e,generatedName:t,title:r,wrapAsNullable:l,description:a,availability:u,keySchema:{nameOverride:void 0,generatedName:`${t}Key`,title:void 0,description:void 0,availability:void 0,schema:ap.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:void 0}),namespace:void 0,groupName:void 0},valueSchema:Al.unknown({nameOverride:void 0,generatedName:`${t}Value`,title:void 0,description:void 0,availability:void 0,example:void 0,namespace:void 0,groupName:void 0}),namespace:s,groupName:o,example:c,encoding:b}):Cau({nameOverride:e,generatedName:t,title:r,wrapAsNullable:l,description:a,availability:u,keySchema:{nameOverride:void 0,generatedName:`${t}Key`,title:void 0,description:void 0,availability:void 0,schema:ap.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:void 0}),namespace:void 0,groupName:void 0},valueSchema:q1_(j0(n,d.options.optionalAdditionalProperties?l:!1,d,[...i,"Value"],g,s,void 0,void 0,void 0)),namespace:s,groupName:o,example:c,encoding:b})}function q1_(e){switch(e.type){case"array":case"enum":case"map":case"object":e.inline=!0;break;case"literal":case"primitive":case"reference":case"unknown":break;case"nullable":case"optional":e.inline=!0,e.value=q1_(e.value);break;case"oneOf":e.value.inline=!0;break;default:So(e)}return e}function Cau({nameOverride:e,generatedName:t,title:r,keySchema:i,valueSchema:n,wrapAsNullable:a,description:u,availability:l,namespace:d,groupName:s,example:o,encoding:c}){return a?Al.nullable({nameOverride:e,generatedName:t,title:r,value:Al.map({nameOverride:e,generatedName:t,title:r,description:u,availability:i.availability,key:i,value:n,namespace:d,groupName:s,encoding:c,example:o,inline:void 0}),description:u,availability:l,namespace:d,groupName:s,inline:void 0}):Al.map({nameOverride:e,generatedName:t,title:r,description:u,availability:l,key:i,value:n,namespace:d,groupName:s,encoding:c,example:o,inline:void 0})}function MKn(e,t){return e==null?t.additionalPropertiesDefaultsTo:typeof e=="boolean"?e:!Kd(e)&&Object.keys(e).length===0}function T1_({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,item:n,description:a,availability:u,wrapAsNullable:l,context:d,namespace:s,groupName:o,example:c,source:b}){let g=n==null?Al.unknown({nameOverride:e,generatedName:t,title:r,description:void 0,availability:void 0,example:void 0,namespace:s,groupName:o}):j0(n,!1,d,[...i,"Item"],b,s);return FNE({nameOverride:e,generatedName:t,title:r,namespace:s,groupName:o,itemSchema:g,wrapAsNullable:l,description:a,availability:u,example:c})}function FNE({nameOverride:e,generatedName:t,title:r,itemSchema:i,wrapAsNullable:n,description:a,availability:u,namespace:l,groupName:d,example:s}){return n?Al.nullable({nameOverride:e,generatedName:t,title:r,value:Al.array({nameOverride:e,generatedName:t,title:r,value:i,description:a,availability:u,namespace:l,groupName:d,example:s,inline:void 0}),description:a,availability:u,namespace:l,groupName:d,inline:void 0}):Al.array({nameOverride:e,generatedName:t,title:r,value:i,description:a,availability:u,namespace:l,groupName:d,example:s,inline:void 0})}function sK(e){switch(of(e,Kf.AVAILABILITY)){case"deprecated":return $H.Deprecated;case"beta":return $H.Beta;case"generally-available":return $H.GenerallyAvailable;default:break}if(!Kd(e)&&e.deprecated)return $H.Deprecated}function fSc({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,properties:n,description:a,availability:u,required:l,wrapAsNullable:d,discriminator:s,context:o,namespace:c,groupName:b,encoding:g,source:O}){let m=s.propertyName,w=Object.fromEntries(Object.entries(s.mapping??{}).map(([q,M])=>{let D=tPi({$ref:M},!1,o,[M],g,O,c);return o.markReferencedByDiscriminatedUnion({$ref:M},m,1),[q,D]})),E=Object.entries(n).filter(([q])=>q!==m).map(([q,M])=>{let D=l!=null&&l.includes(q),C=j0(M,!D,o,[...i,q],O,c);return{key:q,schema:C}});return C1_({nameOverride:e,generatedName:t,title:r,wrapAsNullable:d,properties:E,description:a,availability:u,discriminant:m,subtypes:w,namespace:c,groupName:b,source:O})}function dSc({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,properties:n,description:a,availability:u,required:l,wrapAsNullable:d,discriminant:s,variants:o,context:c,namespace:b,groupName:g,encoding:O,source:m}){let w=Object.fromEntries(Object.entries(o).map(([q,M])=>{if(Kd(M)){let D=tPi(M,!1,c,[M.$ref],O,m,b);return c.markReferencedByDiscriminatedUnion(M,s,1),[q,D]}else{let D=AKn(M,!1,c,[...i,q],O,m,b,new Set([s]));return[q,D]}})),E=Object.entries(n).filter(([q])=>q!==s).map(([q,M])=>{let D=l!=null&&l.includes(q),C=j0(M,!D,c,[...i,q],m,b);return{key:q,schema:C}});return C1_({nameOverride:e,generatedName:t,title:r,wrapAsNullable:d,properties:E,description:a,availability:u,discriminant:s,subtypes:w,namespace:b,groupName:g,source:m})}function C1_({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,properties:n,description:a,availability:u,discriminant:l,subtypes:d,namespace:s,groupName:o,source:c}){return i?Al.nullable({nameOverride:e,generatedName:t,title:r,value:Al.oneOf(aee.discriminated({description:a,availability:u,discriminantProperty:l,nameOverride:e,generatedName:t,title:r,schemas:d,commonProperties:n,namespace:s,groupName:o,encoding:void 0,source:c,inline:void 0})),namespace:s,groupName:o,description:a,availability:u,inline:void 0}):Al.oneOf(aee.discriminated({description:a,availability:u,discriminantProperty:l,nameOverride:e,generatedName:t,title:r,schemas:d,commonProperties:n,namespace:s,groupName:o,encoding:void 0,source:c,inline:void 0}))}function B1_(e){if(e.proto!=null)return KJn.protobuf({typeName:e.proto.type})}function KNi({nameOverride:e,generatedName:t,title:r,fernEnum:i,enumVarNames:n,enumValues:a,_default:u,description:l,availability:d,wrapAsNullable:s,namespace:o,groupName:c,context:b,source:g,inline:O}){let m=UNE(n??[]),w=new Set(a),E=Array.from(w).map((M,D)=>{let C=i?.[M],R=m[D],G=jKn.test(M),I=C?.name??R,L=G?M:wKn(M);return I!=null&&!jKn.test(I)&&(b?.logger.warn(`Enum name override ${I} is not a valid name. Falling back on ${L}.`),I=void 0),{nameOverride:I,generatedName:L,value:M,description:C?.description,availability:d,casing:{snake:C?.casing?.snake??void 0,pascal:C?.casing?.pascal??void 0,screamingSnake:C?.casing?.screamingSnake??void 0,camel:C?.casing?.camel??void 0}}}),q=u!=null?E.find(M=>M.value===u):void 0;return LNE({wrapAsNullable:s,nameOverride:e,generatedName:t,title:r,values:E,_default:q,description:l,availability:d,namespace:o,groupName:c,source:g,inline:O})}function LNE({wrapAsNullable:e,nameOverride:t,generatedName:r,title:i,values:n,_default:a,description:u,availability:l,namespace:d,groupName:s,source:o,inline:c}){return e?Al.nullable({nameOverride:t,generatedName:r,title:i,value:Al.enum({nameOverride:t,generatedName:r,title:i,values:n,description:u,default:a,availability:l,example:void 0,namespace:d,groupName:s,source:o,inline:c}),description:u,availability:l,namespace:d,groupName:s,inline:c}):Al.enum({nameOverride:t,generatedName:r,title:i,values:n,description:u,availability:l,default:a,example:void 0,namespace:d,groupName:s,source:o,inline:c})}function UNE(e){if(e.length<=1||e[0]==null)return e;let t=e[0],r=0;for(;t[r]!=null&&e.every(i=>i[r]===t[r]);)r++;return e.map(i=>i.substring(r))}function I1_({nameOverride:e,generatedName:t,title:r,format:i,_default:n,minimum:a,maximum:u,exclusiveMinimum:l,exclusiveMaximum:d,multipleOf:s,description:o,availability:c,wrapAsNullable:b,example:g,namespace:O,groupName:m}){return i==="int64"?G8({nameOverride:e,generatedName:t,title:r,primitive:ap.int64({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,namespace:O,groupName:m}):i==="uint32"?G8({nameOverride:e,generatedName:t,title:r,primitive:ap.uint({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,namespace:O,groupName:m}):i==="uint64"?G8({nameOverride:e,generatedName:t,title:r,primitive:ap.uint64({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,namespace:O,groupName:m}):G8({nameOverride:e,generatedName:t,title:r,primitive:ap.int({default:n,minimum:a,maximum:u,exclusiveMinimum:l,exclusiveMaximum:d,multipleOf:s,example:g}),wrapAsNullable:b,description:o,availability:c,namespace:O,groupName:m})}function z1_(e){return typeof e=="string"?Kz.string(e):typeof e=="boolean"?Kz.boolean(e):Kz.string(`${e}`)}function R1_({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,value:n,description:a,availability:u,namespace:l,groupName:d}){return i?Al.nullable({nameOverride:e,generatedName:t,title:r,value:Al.literal({nameOverride:e,generatedName:t,title:r,value:z1_(n),description:a,availability:u,namespace:l,groupName:d}),description:a,availability:u,namespace:l,groupName:d,inline:void 0}):Al.literal({nameOverride:e,generatedName:t,title:r,value:z1_(n),description:a,availability:u,namespace:l,groupName:d})}function pSc({nameOverride:e,generatedName:t,title:r,format:i,_default:n,minimum:a,maximum:u,exclusiveMinimum:l,exclusiveMaximum:d,multipleOf:s,description:o,availability:c,wrapAsNullable:b,example:g,namespace:O,groupName:m}){return i==null||i==="double"?G8({nameOverride:e,generatedName:t,title:r,primitive:ap.double({default:n,minimum:a,maximum:u,exclusiveMinimum:l,exclusiveMaximum:d,multipleOf:s,example:g}),wrapAsNullable:b,description:o,availability:c,namespace:O,groupName:m}):i==="float"?G8({nameOverride:e,generatedName:t,title:r,primitive:ap.float({example:g}),wrapAsNullable:b,description:o,availability:c,namespace:O,groupName:m}):i==="int32"?G8({nameOverride:e,generatedName:t,title:r,primitive:ap.int({default:n,minimum:a,maximum:u,exclusiveMinimum:l,exclusiveMaximum:d,multipleOf:s,example:g}),wrapAsNullable:b,description:o,availability:c,namespace:O,groupName:m}):i==="int64"?G8({nameOverride:e,generatedName:t,title:r,primitive:ap.int64({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,namespace:O,groupName:m}):i==="uint32"?G8({nameOverride:e,generatedName:t,title:r,primitive:ap.uint({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,namespace:O,groupName:m}):i==="uint64"?G8({nameOverride:e,generatedName:t,title:r,primitive:ap.uint64({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,namespace:O,groupName:m}):i==="time-delta"?G8({nameOverride:e,generatedName:t,title:r,primitive:ap.float({example:g}),wrapAsNullable:b,description:o,availability:c,namespace:O,groupName:m}):G8({nameOverride:e,generatedName:t,title:r,primitive:ap.float({example:g}),wrapAsNullable:b,description:o,availability:c,namespace:O,groupName:m})}var VNE={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="schemas",applyStrategy:e=>{let t=[e[3]??""];return{refUnderProcessing:e.slice(4),newBreadcrumbs:t}}},WNE={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="responses",applyStrategy:e=>{let t=[e[3]??""];return e=e.slice(4),{refUnderProcessing:e.slice(4),newBreadcrumbs:t}}},HNE={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="parameters",applyStrategy:e=>{let t=[e[3]??""];return e=e.slice(4),e[0]==="schema"&&(e=e.slice(1)),{refUnderProcessing:e,newBreadcrumbs:t}}},$NE={isApplicable:e=>e[0]==="properties",applyStrategy:e=>{let t=[e[1]??""];return{refUnderProcessing:e.slice(2),newBreadcrumbs:t}}},GNE={isApplicable:e=>e[0]==="items",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},QNE={isApplicable:e=>e[0]==="allOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},JNE={isApplicable:e=>e[0]==="anyOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},KNE={isApplicable:e=>e[0]==="oneOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})};function Bau(e){let t=e.split("/").map(a=>a.replace(/~1/g,"/")),r=[],i=[VNE,WNE,HNE,$NE,GNE,QNE,JNE,KNE],n;do{n=t;for(let a of i)if(a.isApplicable(t)){let{refUnderProcessing:u,newBreadcrumbs:l}=a.applyStrategy(t);t=u,r=[...r,...l]}}while(t.join("")!==n.join(""));return r}function Q8(e,t){let i=e.map(n=>/^[^a-zA-Z0-9]+$/.test(n)?n:qB(S_(n))).join("");return/^\d/.test(i)?U5a(i)??i:i}function _Sc(e){let t=e.join("_");return S_(t)}function iA(e){switch(e.type){case"object":return cv.object({allOf:e.allOf,properties:e.properties.map(t=>XNE(t)),allOfPropertyConflicts:e.allOfPropertyConflicts,description:e.description,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName,additionalProperties:e.additionalProperties,availability:e.availability,source:e.source,inline:e.inline});case"array":return cv.array({description:e.description,availability:e.availability,value:iA(e.value),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName,inline:e.inline});case"enum":return cv.enum({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,values:e.values,default:e.default,namespace:e.namespace,groupName:e.groupName,source:e.source,inline:e.inline});case"literal":return cv.literal({description:e.description,availability:e.availability,value:e.value,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName});case"nullable":return cv.nullable({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:iA(e.value),namespace:e.namespace,groupName:e.groupName,inline:e.inline});case"optional":return cv.optional({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:iA(e.value),namespace:e.namespace,groupName:e.groupName,inline:e.inline});case"primitive":return cv.primitive({description:e.description,availability:e.availability,schema:x1_(e.schema),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName});case"map":return cv.map({description:e.description,availability:e.availability,key:cv.primitive({description:e.key.description,availability:e.key.availability,schema:x1_(e.key.schema),generatedName:e.key.generatedName,title:e.key.title,nameOverride:e.key.nameOverride,namespace:e.namespace,groupName:e.groupName}),value:iA(e.value),generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,inline:e.inline});case"reference":return cv.reference({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schema:e.schema,namespace:e.namespace,groupName:e.groupName,source:e.source});case"oneOf":return cv.oneOf(YNE(e.value));case"unknown":return cv.unknown({nameOverride:e.nameOverride,generatedName:e.generatedName});default:So(e)}}function YNE(e){switch(e.type){case"discriminated":return Xmi.discriminated({commonProperties:e.commonProperties.map(t=>({key:t.key,schema:iA(t.schema)})),description:e.description,availability:e.availability,discriminantProperty:e.discriminantProperty,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schemas:Object.fromEntries(Object.entries(e.schemas).map(([t,r])=>[t,iA(r)])),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:e.inline});case"undiscriminated":return Xmi.undiscriminated({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schemas:e.schemas.map(t=>iA(t)),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:e.inline});default:So(e)}}function x1_(e){switch(e.type){case"string":return jw.string(e);case"base64":return jw.base64();case"boolean":return jw.boolean(e);case"date":return jw.date();case"datetime":return jw.datetime();case"double":return jw.double(e);case"float":return jw.float();case"int":return jw.int(e);case"int64":return jw.int64(e);case"uint":return jw.uint();case"uint64":return jw.uint64();default:So(e)}}function XNE(e){return{conflict:e.conflict,generatedName:e.generatedName,key:e.key,schema:iA(e.schema),audiences:e.audiences,nameOverride:e.nameOverride,availability:e.availability,readonly:e.readonly,writeonly:e.writeonly}}function Iau(e,t){return fue(iA(e),iA(t))}function N1_({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,properties:n,description:a,required:u,wrapAsNullable:l,allOf:d,context:s,propertiesToExclude:o,namespace:c,groupName:b,fullExamples:g,additionalProperties:O,availability:m,source:w}){let E=[...u??[]],q={...n},M=[],D=[];for(let I of d)if(Kd(I)){let L=s.resolveSchemaReference(I);if(L.discriminator!=null&&L.discriminator.mapping!=null)continue;if(L.oneOf!=null||L.anyOf!=null){let Y=L.oneOf??L.anyOf;if(Y!=null){for(let K of Y){let X=Kd(K)?s.resolveSchemaReference(K):K,oe=j0(X,!1,s.DUMMY,i,w,c);oe.type==="object"&&M.push(...oe.properties.map(pe=>pe.schema.type!=="optional"&&pe.schema.type!=="nullable"?{...pe,schema:Al.optional({nameOverride:void 0,generatedName:"",title:void 0,value:pe.schema,description:void 0,availability:pe.availability,namespace:void 0,groupName:void 0,inline:void 0})}:pe))}continue}}let V=YNi(I);if(V==null)continue;D.push({schemaId:V,convertedSchema:hSc(I,[V],w,s.options.preserveSchemaIds),properties:F1_({schema:I,context:s,breadcrumbs:i,source:w,namespace:c})}),s.markSchemaAsReferencedByNonRequest(V)}else{let L=j0(I,!1,s,i,w,c);L.type==="object"&&M.push(...L.properties)}let C={};for(let I of D)for(let[L,V]of Object.entries(I.properties)){let Y=C[L];Y!=null?(Y.schemaIds.push(I.schemaId),Y.schemas.some(X=>Iau(X,V))||Y.schemas.push(V)):C[L]={schemaIds:[I.schemaId],schemas:[V]}}let R=[];for(let[I,L]of Object.entries(C))L.schemaIds.length>1&&R.push({propertyKey:I,allOfSchemaIds:L.schemaIds,conflictingTypeSignatures:L.schemas.length>1});let G=Object.entries(q).map(([I,L])=>{let V=of(L,Kf.AUDIENCES)??[],Y=sK(L),K=Kd(L)?!1:L.readOnly,X=Kd(L)?!1:L.writeOnly,oe=E.includes(I)&&!K,pe=of(L,Kf.FERN_PROPERTY_NAME),de=[...i,I],Oe=_Sc(de),Ue=oe?j0(L,!1,s,de,w,c):Al.optional({nameOverride:e,generatedName:Oe,title:r,description:void 0,availability:Y,value:j0(L,!1,s,de,w,c),namespace:c,groupName:b,inline:void 0}),bt={};for(let De of D){let Te=De.properties[I];Te!=null&&!Iau(Ue,Te)?bt[De.schemaId]={differentSchema:!0}:Te!=null&&(bt[De.schemaId]={differentSchema:!1})}return{key:I,schema:Ue,nameOverride:pe,audiences:V,conflict:bt,generatedName:_Sc([...i,I]),availability:Y,readonly:K,writeonly:X}});return G.push(...M.map(I=>{let L=I.conflict;for(let V of D){let Y=V.properties[I.key];Y!=null&&!Iau(I.schema,Y)?L[V.schemaId]={differentSchema:!0}:Y!=null&&(L[V.schemaId]={differentSchema:!1})}return{...I,conflict:L}})),ZNE({nameOverride:e,generatedName:t,title:r,wrapAsNullable:l,properties:G.filter(I=>!o.has(I.key)),description:a,allOf:D.map(I=>I.convertedSchema),allOfPropertyConflicts:R,namespace:c,groupName:b,fullExamples:g,additionalProperties:O,availability:m,source:w,context:s})}function ZNE({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,properties:n,description:a,allOf:u,allOfPropertyConflicts:l,namespace:d,groupName:s,fullExamples:o,additionalProperties:c,availability:b,source:g,context:O}){return i?Al.nullable({nameOverride:e,generatedName:t,title:r,value:Al.object({description:a,properties:n,nameOverride:e,generatedName:t,title:r,allOf:u,allOfPropertyConflicts:l,namespace:d,groupName:s,fullExamples:o,additionalProperties:MKn(c,O.options),availability:void 0,source:g,inline:void 0}),description:a,availability:b,namespace:d,groupName:s,inline:void 0}):Al.object({description:a,properties:n,nameOverride:e,generatedName:t,title:r,allOf:u,allOfPropertyConflicts:l,namespace:d,groupName:s,fullExamples:o,additionalProperties:MKn(c,O.options),availability:b,source:g,inline:void 0})}function F1_({schema:e,context:t,breadcrumbs:r,source:i,namespace:n}){let a={},[u,l]=Kd(e)?[t.resolveSchemaReference(e),Bau(e.$ref)]:[e,r];for(let d of u.allOf??[])a={...a,...F1_({schema:d,context:t,breadcrumbs:l,source:i,namespace:n})};for(let[d,s]of Object.entries(u.properties??{})){let o=j0(s,!1,t,[...l,d],i,n);a[d]=o}return a}function XNi({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,description:n,availability:a,wrapAsNullable:u,context:l,subtypes:d,namespace:s,groupName:o,encoding:c,source:b,subtypePrefixOverrides:g}){let O=tFE({schemas:d}),m=d.flatMap((E,q)=>{if(!Kd(E)&&E.enum!=null&&l.options.coerceEnumsToLiterals&&E.type==="string")return E.enum.map(D=>Al.literal({nameOverride:void 0,generatedName:Q8([t,D],l.options.preserveSchemaIds),title:void 0,value:Kz.string(String(D)),namespace:s,groupName:void 0,description:void 0,availability:D.availability}));let M=O[q];if(g!=null){let D=g[q];D!=null&&"name"in D&&(M=D.name)}return[j0(E,!1,l,[...i,M??`${q}`],b,s)]}),w=kNE(m);return eFE({uniqueSubtypes:w,nameOverride:e,generatedName:t,title:r,wrapAsNullable:u,description:n,availability:a,namespace:s,groupName:o,context:l,encoding:c,source:b})}function kNE(e){let t=[];for(let r=0;r<e.length;++r){let i=e[r],n=!1;for(let a=r+1;a<e.length;++a){let u=e[a];if(i!=null&&u!=null&&fue(i,u)){n=!0;break}}i!=null&&!n&&t.push(i)}return t}function eFE({uniqueSubtypes:e,nameOverride:t,generatedName:r,title:i,wrapAsNullable:n,description:a,availability:u,namespace:l,groupName:d,context:s,encoding:o,source:c}){if(Object.entries(e).every(([g,O])=>O.type==="literal")){let g={},O=[];return Object.entries(e).forEach(([m,w])=>{w.type==="literal"&&w.value.type==="string"&&(O.push(w.value.value),w.description!=null&&(g[w.value.value]={description:w.description}))}),KNi({nameOverride:t,generatedName:r,title:i,wrapAsNullable:n,description:a,availability:u,fernEnum:g,enumVarNames:void 0,enumValues:O,_default:void 0,namespace:l,groupName:d,context:s,source:c,inline:void 0})}return e.length===1&&e[0]!=null&&!s.options.preserveSingleSchemaOneOf?e[0]:L1_({nameOverride:t,generatedName:r,title:i,wrapAsNullable:n,description:a,availability:u,subtypes:e,namespace:l,groupName:d,encoding:o,source:c})}function ySc({nameOverride:e,generatedName:t,title:r,description:i,availability:n,wrapAsNullable:a,context:u,namespace:l,groupName:d,discriminator:s,encoding:o,source:c}){let b=Object.entries(s.mapping??{}).map(([m,w],E)=>{let q={$ref:w},M=tPi(q,!1,u,[w],o,c,l);return u.markSchemaWithDiscriminantValue(q,s.propertyName,m),M.type==="object"&&(M.properties={[s.propertyName]:Al.literal({nameOverride:void 0,generatedName:Q8([t,m],u.options.preserveSchemaIds),title:void 0,value:Kz.string(m),namespace:void 0,groupName:void 0,description:void 0,availability:void 0}),...M.properties.filter(D=>D.key!==s.propertyName)}),M}),g=[];for(let m=0;m<b.length;++m){let w=b[m],E=!1;for(let q=m+1;q<b.length;++q){let M=b[q];if(w!=null&&M!=null&&fue(w,M)){E=!0;break}}w!=null&&!E&&g.push(w)}if(Object.entries(g).every(([m,w])=>w.type==="literal")){let m={},w=[];return Object.entries(g).forEach(([E,q])=>{q.type==="literal"&&q.value.type==="string"&&(w.push(q.value.value),q.description!=null&&(m[q.value.value]={description:q.description}))}),KNi({nameOverride:e,generatedName:t,title:r,wrapAsNullable:a,description:i,availability:n,fernEnum:m,enumVarNames:void 0,enumValues:w,_default:void 0,namespace:l,groupName:d,context:u,source:c,inline:void 0})}return g.length===1&&g[0]!=null&&!u.options.preserveSingleSchemaOneOf?g[0]:L1_({nameOverride:e,generatedName:t,title:r,wrapAsNullable:a,description:i,availability:n,subtypes:g,namespace:l,groupName:d,encoding:o,source:c})}function tFE({schemas:e}){let t={},r=0;for(let a of e){if(!Kd(a)){if(a.properties!=null&&Object.entries(a.properties).length>0){let u=Object.keys(a.properties),l={},d=u;for(let[s,o]of Object.entries(t)){let c=RAo(o,u);d=RAo(d,o),l[s]=c}l[r]=d,t=l}}r++}let i=[],n=0;for(let a of e){let u=t[n];if(u!=null&&u.length>0){let l=u.sort();if(l[0]!=null){i.push(l[0]),++n;continue}}Kd(a)?i.push($Ni(n)??`${n}`):a.type==="array"||a.type==="boolean"||a.type==="integer"||a.type==="number"||a.type==="string"?i.push(""):i.push($Ni(n)??`${n}`),++n}return i}function L1_({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,description:n,availability:a,subtypes:u,namespace:l,groupName:d,encoding:s,source:o}){return i?Al.nullable({nameOverride:e,generatedName:t,title:r,value:Al.oneOf(aee.undiscriminated({description:n,availability:a,nameOverride:e,generatedName:t,title:r,schemas:u,namespace:l,groupName:d,encoding:s,source:o,inline:void 0})),description:n,availability:a,namespace:l,groupName:d,inline:void 0}):Al.oneOf(aee.undiscriminated({description:n,availability:a,nameOverride:e,generatedName:t,title:r,schemas:u,namespace:l,groupName:d,encoding:s,source:o,inline:void 0}))}function qKn(e){if(e.default!=null&&typeof e.default=="string")return e.default}function zau({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="number")return e.example;let i=ran(e);for(let n of i??[])if(typeof n=="number")return n;if(r&&typeof r=="number")return r}function U1_({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="boolean")return e.example;let i=ran(e);for(let n of i??[])if(typeof n=="boolean")return n;if(r&&typeof r=="boolean")return r}function Sor({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="string")return e.example;let i=ran(e);for(let n of i??[])if(typeof n=="string")return n;if(r&&typeof r=="string")return r}function V1_({schema:e,logger:t,fallback:r}){if(e.example!=null&&Array.isArray(e.example))return e.example;let i=ran(e);for(let n of i??[])if(Array.isArray(n))return n;if(r&&Array.isArray(r))return r}var nan="#/components/schemas/";function j0(e,t,r,i,n,a,u=!1,l=new Set,d){let s=M1_(e)??n,o=cFE({schema:e,logger:r.logger});if(Kd(e)){let c=YNi(e);return c!=null?(u?r.markSchemaAsReferencedByRequest(c):r.markSchemaAsReferencedByNonRequest(c),tPi(e,t,r,i,o,s,a)):AKn(r.resolveSchemaReference(e),t,r,Bau(e.$ref),o,s,a,l,u,d)}return AKn(e,t,r,i,o,s,a,l,u,d)}function tPi(e,t,r,i,n,a,u){let l=e.$ref.includes("properties")?AKn(r.resolveSchemaReference(e),t,r,i,n,a,u,new Set):Al.reference(hSc(e,i,a,r.options.preserveSchemaIds));return t?Al.nullable({title:void 0,nameOverride:void 0,generatedName:Q8(i,r.options.preserveSchemaIds),value:l,description:void 0,availability:void 0,namespace:void 0,groupName:void 0,inline:void 0}):l}function rFE(e){if(e!=null&&!e.includes(" ")&&/^[a-zA-Z]+$/.test(e))return e}function AKn(e,t,r,i,n,a,u,l=new Set,d=!1,s){typeof e=="string"&&(e={type:e});let o=of(e,Kf.TYPE_NAME)??(r.options.useTitlesAsName?rFE(e.title):void 0),c=of(e,Kf.SDK_GROUP_NAME)??of(e,JH.TAGS)?.[0],b=(typeof c=="string"?[c]:c)??[];b=r.resolveGroupName(b);let g=Q8(i,r.options.preserveSchemaIds),O=e.title,m=e.description,w=sK(e),E=[];e.example!=null&&E.push({name:void 0,value:e.example,description:void 0});let q=of(e,JH.EXAMPLES);q!=null&&Object.keys(q).length>0&&E.push(...Object.entries(q).map(([C,R])=>({name:R?.summary??C,value:R.value,description:R.description})));let M=ran(e);M!=null&&Object.keys(M).length>0&&E.push(...M.map(C=>({name:void 0,value:C,description:void 0})));let D=E1_({schema:e,description:m,title:O,nameOverride:o,generatedName:g,availability:w});if(D!=null)return D;if(Array.isArray(e.type)){let C=e.type.indexOf("null"),R=C!==-1;if(e.type.length===1)e.type=e.type[0];else if(e.type.length===2&&R)e.type.splice(C,1),e.type=e.type[0],e.nullable=!0;else if(R&&(e.type.splice(C,1),e.nullable=!0),e.oneOf==null)e.oneOf=[...new Set(e.type)];else{let G=new Set([...e.oneOf,...e.type]);e.oneOf=[...G]}}if(!t&&e.nullable===!0)return AKn(e,!0,r,i,n,a,u,l,d,s);if(e.enum!=null&&(e.type==="string"||e.type==null||e.type==="enum")){if(!Nau(e.enum))return G8({nameOverride:o,generatedName:g,title:O,primitive:ap.string({default:qKn(e),minLength:e.minLength,maxLength:e.maxLength,pattern:e.pattern,format:e.format,example:Sor({schema:e,logger:r.logger,fallback:s})}),namespace:u,groupName:b,wrapAsNullable:t,description:m,availability:w});let C=D1_(e);return e.enum.length===1&&e.enum[0]!=null&&C==null?R1_({nameOverride:o,generatedName:g,title:O,wrapAsNullable:t,value:e.enum[0],description:m,availability:w,namespace:u,groupName:b}):KNi({nameOverride:o,generatedName:g,title:O,fernEnum:C,enumVarNames:of(e,[JH.ENUM_VAR_NAMES]),enumValues:e.enum,_default:e.default,description:m,availability:w,wrapAsNullable:t,namespace:u,groupName:b,context:r,source:a,inline:void 0})}if(Nau(e.type)&&e.type.length>1){let C=e.type.includes("null"),R=e.type.filter(G=>G!=="null").map(G=>({type:G,nullable:C}));return XNi({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,wrapAsNullable:t,context:r,subtypes:R,namespace:u,groupName:b,encoding:n,source:a})}if(e.type==="boolean"){let C=of(e,Kf.BOOLEAN_LITERAL);return C!=null?W1_({nameOverride:o,generatedName:g,title:O,literal:Kz.boolean(C),wrapAsNullable:t,description:m,availability:w,namespace:u,groupName:b}):G8({nameOverride:o,generatedName:g,title:O,primitive:ap.boolean({default:iFE(e.default),example:U1_({schema:e,logger:r.logger,fallback:s})}),wrapAsNullable:t,description:m,availability:w,namespace:u,groupName:b})}if(e.type==="number")return pSc({nameOverride:o,generatedName:g,title:O,format:e.format,_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:ian(e.exclusiveMinimum),exclusiveMaximum:ian(e.exclusiveMaximum),multipleOf:e.multipleOf,description:m,availability:w,wrapAsNullable:t,example:zau({schema:e,logger:r.logger,fallback:s}),namespace:u,groupName:b});if(e.type==="integer")return I1_({nameOverride:o,generatedName:g,title:O,format:e.format,_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:ian(e.exclusiveMinimum),exclusiveMaximum:ian(e.exclusiveMaximum),multipleOf:e.multipleOf,description:m,availability:w,wrapAsNullable:t,example:zau({schema:e,logger:r.logger,fallback:s}),namespace:u,groupName:b});if(e.type==="float")return pSc({nameOverride:o,generatedName:g,title:O,format:"float",_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:ian(e.exclusiveMinimum),exclusiveMaximum:ian(e.exclusiveMaximum),multipleOf:e.multipleOf,description:m,availability:w,wrapAsNullable:t,example:zau({schema:e,logger:r.logger,fallback:s}),namespace:u,groupName:b});if(e.type==="string"){if(e.format==="date-time")return G8({nameOverride:o,generatedName:g,title:O,primitive:ap.datetime({example:Sor({schema:e,logger:r.logger,fallback:s})}),wrapAsNullable:t,description:m,availability:w,namespace:u,groupName:b});if(e.format==="date"&&r.options.typeDatesAsStrings===!1)return G8({nameOverride:o,generatedName:g,title:O,primitive:ap.date({example:Sor({schema:e,logger:r.logger,fallback:s})}),wrapAsNullable:t,description:m,availability:w,namespace:u,groupName:b});if(e.format==="json-string")return Al.unknown({nameOverride:o,generatedName:g,title:O,description:m,availability:w,namespace:u,groupName:b,example:void 0});let C=G1_(e,"const");return C!=null?W1_({nameOverride:o,generatedName:g,title:O,literal:Kz.string(C),wrapAsNullable:t,description:m,availability:w,namespace:u,groupName:b}):G8({nameOverride:o,generatedName:g,title:O,primitive:ap.string({default:qKn(e),pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:Sor({schema:e,logger:r.logger,fallback:s})}),namespace:u,groupName:b,wrapAsNullable:t,description:m,availability:w})}if(e.type==="array")return T1_({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,item:e.items,description:m,availability:w,wrapAsNullable:t,context:r,namespace:u,groupName:b,example:V1_({schema:e,logger:r.logger,fallback:s}),source:a});if(e.additionalProperties!=null&&e.additionalProperties!==!1&&Rau(e))return A1_({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,additionalProperties:e.additionalProperties,description:m,availability:w,wrapAsNullable:t,context:r,namespace:u,groupName:b,encoding:n,example:e.example,source:a});if(e.oneOf!=null&&e.oneOf.length>0&&of(e,Kf.IS_DISCRIMINATED)===!1)return XNi({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,wrapAsNullable:t,context:r,subtypes:e.oneOf,namespace:u,groupName:b,encoding:n,source:a});if(e.type==="object"&&e.discriminator!=null&&e.discriminator.mapping!=null)return r.options.discriminatedUnionV2?ySc({nameOverride:o,generatedName:g,title:O,description:m,availability:w,wrapAsNullable:t,context:r,namespace:u,groupName:b,discriminator:e.discriminator,encoding:n,source:a}):fSc({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,discriminator:e.discriminator,properties:e.properties??{},required:e.required,wrapAsNullable:t,context:r,namespace:u,groupName:b,encoding:n,source:a});if(e.oneOf!=null&&e.oneOf.length>0){let C=of(e,Kf.IS_UNDISCRIMINATED);if(e.discriminator!=null&&e.discriminator.mapping!=null&&Object.keys(e.discriminator.mapping).length>0)return r.options.discriminatedUnionV2||C?ySc({nameOverride:o,generatedName:g,title:O,description:m,availability:w,wrapAsNullable:t,context:r,namespace:u,groupName:b,discriminator:e.discriminator,encoding:n,source:a}):fSc({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,discriminator:e.discriminator,properties:e.properties??{},required:e.required,wrapAsNullable:t,context:r,namespace:u,groupName:b,encoding:n,source:a});if(e.oneOf.length===1&&e.oneOf[0]!=null){if(r.options.preserveSingleSchemaOneOf)return XNi({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,wrapAsNullable:t,context:r,subtypes:e.oneOf.filter(G=>Kd(G)||G.type!=="null"),encoding:n,namespace:u,groupName:b,source:a});let R=j0(e.oneOf[0],t,r,i,a,u,d);return TKn(R,m,u,b)}else if(e.oneOf.length>1){if(e.oneOf.length===2&&e.oneOf[0]!=null&&e.oneOf[1]!=null){let L=e.oneOf[0],V=e.oneOf[1];if(!Kd(L)&&L.type==="null")return j0(V,!0,r,i,a,u);if(!Kd(V)&&V.type==="null")return j0(L,!0,r,i,a,u)}let R=oFE({schemas:e.oneOf});if(R!=null)return KNi({nameOverride:o,generatedName:g,title:O,fernEnum:void 0,enumVarNames:void 0,enumValues:R,_default:e.default,description:m,availability:w,wrapAsNullable:t,namespace:u,groupName:b,context:r,source:a,inline:void 0});let G=H1_({schemas:e.oneOf,context:r});if(G!=null&&!r.options.discriminatedUnionV2&&!C)return dSc({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,properties:e.properties??{},required:e.required,description:m,availability:w,wrapAsNullable:t,discriminant:G.discriminant,variants:G.schemas,context:r,namespace:u,groupName:b,encoding:n,source:a});let I=e.oneOf.filter(L=>!Kd(L)&&L.type==="null").length>0;return XNi({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,wrapAsNullable:t||I,context:r,subtypes:e.oneOf.filter(L=>Kd(L)||L.type!=="null"),encoding:n,namespace:u,groupName:b,source:a})}}if(e.anyOf!=null&&e.anyOf.length>0){if(e.anyOf.length===1&&e.anyOf[0]!=null){let G=j0(e.anyOf[0],t,r,i,a,u,d);return TKn(G,m,u,b)}if(e.anyOf.length===2){let[G,I]=e.anyOf;if(G!=null&&I!=null){if(!Kd(G)&&G.type==="null"){let L=j0(I,!0,r,i,a,u);return TKn(L,m,u,b)}else if(!Kd(I)&&I.type==="null"){let L=j0(G,!0,r,i,a,u);return TKn(L,m,u,b)}}}let C=H1_({schemas:e.anyOf,context:r});if(C!=null&&!r.options.discriminatedUnionV2)return dSc({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,properties:e.properties??{},required:e.required,description:m,availability:w,wrapAsNullable:t,discriminant:C.discriminant,variants:C.schemas,context:r,namespace:u,groupName:b,encoding:n,source:a});let R=e.anyOf.filter(G=>!Kd(G)&&G.type==="null").length>0;return XNi({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,wrapAsNullable:t||R,context:r,subtypes:e.anyOf.filter(G=>Kd(G)||G.type!=="null"),encoding:n,namespace:u,groupName:b,source:a})}if(e.allOf!=null||e.properties!=null){let C=[];for(let G of e.allOf??[])(Kd(G)||Object.keys(G).length>0)&&C.push(G);if((e.properties==null||Rau(e))&&C.length===1&&C[0]!=null){let G=j0(C[0],t,r,i,a,u,d);return TKn(G,m,u,b)}let R=C.filter(G=>{let I=xau(G);return I||r.logger.warn(`Skipping non-object allOf element: ${JSON.stringify(G)}`),I});if((e.properties==null||Rau(e))&&R.length===1&&R[0]!=null){let G=j0(R[0],t,r,i,a,u,d);return TKn(G,m,u,b)}return N1_({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,properties:e.properties??{},description:m,required:e.required,wrapAsNullable:t,allOf:R,context:r,propertiesToExclude:l,namespace:u,groupName:b,fullExamples:E,additionalProperties:e.additionalProperties,availability:w,encoding:n,source:a})}if(e.type==="object"&&nFE(e)&&aFE(e)&&Rau(e))return Cau({nameOverride:o,generatedName:g,title:O,description:m,availability:w,wrapAsNullable:t,keySchema:{nameOverride:void 0,generatedName:`${g}Key`,title:void 0,description:void 0,availability:void 0,schema:ap.string({default:qKn(e),pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:Sor({schema:e,logger:r.logger,fallback:s})}),namespace:u,groupName:b},valueSchema:Al.unknown({nameOverride:void 0,generatedName:`${g}Value`,title:void 0,description:void 0,availability:void 0,example:void 0,namespace:u,groupName:b}),namespace:u,groupName:b,encoding:n,example:e.example});if(e.type==null){let C=e.example??e.default;return Al.unknown({nameOverride:o,generatedName:g,title:O,description:m,availability:w,namespace:u,groupName:b,example:C})}throw new Error(`Failed to convert schema breadcrumbs=${JSON.stringify(i)} value=${JSON.stringify(e)}`)}function iFE(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 YNi(e){if(e.$ref.startsWith(nan))return e.$ref.replace(nan,"")}function hSc(e,t,r,i){let n=of(e,Kf.TYPE_NAME),a=Q8(t,i),u=e.description,l=sK(e),d=YNi(e);if(d==null)throw new Error(`Invalid schema reference ${JSON.stringify(e)}`);return cv.reference({generatedName:a,nameOverride:n,title:void 0,schema:d,description:u??void 0,availability:l,namespace:void 0,groupName:void 0,source:r})}function nFE(e){return e.oneOf==null||e.oneOf.length===0}function aFE(e){return e.allOf==null||e.allOf.length===0}function Rau(e){return e.properties==null||yq(e.properties)===0}function Nau(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function TKn(e,t,r,i){return e.type==="reference"?Al.reference({...e,description:t,availability:e.availability,namespace:r,groupName:i}):e.type==="optional"?Al.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:t,availability:e.availability,namespace:r,groupName:i,inline:void 0}):e.type==="nullable"?Al.nullable({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:t,availability:e.availability,namespace:r,groupName:i,inline:void 0}):e}function xau(e){return Kd(e)||e.type==="object"||e.properties!=null?!0:e.allOf!=null?e.allOf.every(t=>xau(t)):e.oneOf!=null?e.oneOf.every(t=>xau(t)):e.anyOf!=null?e.anyOf.every(t=>xau(t)):!1}function W1_({literal:e,wrapAsNullable:t,namespace:r,groupName:i,description:n,availability:a,nameOverride:u,generatedName:l,title:d}){return t?Al.nullable({nameOverride:u,generatedName:l,title:d,value:Al.literal({nameOverride:u,generatedName:l,title:d,value:e,description:n,availability:a,namespace:r,groupName:i}),namespace:r,groupName:i,description:n,availability:a,inline:void 0}):Al.literal({nameOverride:u,generatedName:l,title:d,value:e,namespace:r,groupName:i,description:n,availability:a})}function G8({primitive:e,wrapAsNullable:t,namespace:r,groupName:i,description:n,availability:a,generatedName:u,nameOverride:l,title:d}){return i=typeof i=="string"?[i]:i,t?Al.nullable({nameOverride:l,generatedName:u,title:d,value:Al.primitive({nameOverride:l,generatedName:u,title:d,schema:e,description:n,availability:a,namespace:r,groupName:i}),namespace:r,groupName:i,description:n,availability:a,inline:void 0}):Al.primitive({nameOverride:l,generatedName:u,title:d,schema:e,description:n,availability:a,namespace:r,groupName:i})}function oFE({schemas:e}){let t=new Set;for(let r of e){if(Kd(r))return;if(r.enum!=null&&Nau(r.enum))r.enum.forEach(i=>t.add(i));else return}return Array.from(t)}function H1_({schemas:e,context:t}){let r={};for(let i of e){let n=$1_({schema:i,context:t});for(let[a,u]of Object.entries(n)){let l=r[a];l!=null?l[u]=i:r[a]={[u]:i}}}for(let[i,n]of Object.entries(r))if(Object.keys(n).length===e.length)return{discriminant:i,schemas:n}}function $1_({schema:e,context:t}){let r=Kd(e)?t.resolveSchemaReference(e):e;return uFE({schema:r,context:t})}function uFE({schema:e,context:t}){let r={};if(e.anyOf!=null){for(let i of e.anyOf){let n=$1_({schema:i,context:t});for(let[a,u]of Object.entries(n??{}))r[a]=u}return r}for(let[i,n]of Object.entries(e.properties??{})){let a=Kd(n)?t.resolveSchemaReference(n):n;a.type==="string"&&a.enum!=null&&Nau(a.enum)&&sFE(a.enum).length===1&&a.enum[0]!=null&&(r[i]=a.enum[0]);let u=G1_(a,"const");a.type==="string"&&u!=null&&(r[i]=u),i==="type"&&a.example!=null&&(r[i]=a.example)}return r}function sFE(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 G1_(e,t){let r=e[t];if(r!=null)return r}function cFE({schema:e,logger:t}){let r=S1_({schema:e,logger:t});if(r!=null)return B1_(r)}var CKn=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(nan))throw new Error(`Failed to resolve schema reference: ${t.$ref}`);let i=t.$ref.substring(nan.length).split("/"),n=this.document.components;if(n==null||n.schemas==null)throw new Error("Document does not have components.schemas.");let[a,u,l]=i;if(a==null||a==="")throw new Error(`${t.$ref} cannot be resolved. No schema key provided.`);let d=n.schemas[a];if(d==null)throw new Error(`Schema "${a}" is undefined in document.components.schemas.`);if(Kd(d)&&(d=this.resolveSchemaReference(d)),u==="properties"&&l!=null){let s=d.properties?.[l];if(s==null)throw new Error(`Property "${l}" not found on "${a}". Full ref: ${t.$ref}`);Kd(s)?d=this.resolveSchemaReference(s):d=s}return d}referenceExists(t){let r=t.substring(2).split("/").map(n=>n.replace(/~1/g,"/")),i=this.document;for(let n of r){if(typeof i!="object"||i==null)return!1;i=i[n]}return!0}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}markReferencedByDiscriminatedUnion(t,r,i){}markSchemaWithDiscriminantValue(t,r,i){}};var Fau=class extends CKn{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 BKn(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 u=a.namespace;i[u]??={},i[u][n]=a;continue}case"oneOf":case"unknown":r[n]=a;continue;default:So(a)}return{rootSchemas:r,namespacedSchemas:i}}function ZNi(e){if(typeof e=="string")return xg.primitive(h_.string(e));if(typeof e=="number")return Number.isInteger(e)?xg.primitive(h_.int(e)):xg.primitive(h_.double(e));if(typeof e=="boolean")return xg.primitive(h_.boolean(e));if(Array.isArray(e)){let t=e.map(r=>ZNi(r));return t.length===0?void 0:xg.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=ZNi(i);n!=null&&t.push({key:h_.string(r),value:n})}return xg.map(t)}}function Y5a(e){if(e!=null&&typeof e=="object"&&Object.keys(e).every(t=>typeof t=="string"))return e}function Q1_(e){if(e!=null&&Array.isArray(e))return e}var kNi=class{schemas;nonRequestReferencedSchemas;context;constructor(t,r,i){this.schemas=t,this.nonRequestReferencedSchemas=r,this.context=i}buildExample({schema:t,exampleId:r,example:i,options:n,skipReadonly:a}){return this.buildExampleHelper({schema:t,visitedSchemaIds:new Set,exampleId:r,example:i,options:{...n,maxCheckerDepth:n.maxCheckerDepth??5},depth:0,skipReadonly:a??!1})}buildExampleHelper({exampleId:t,example:r,schema:i,depth:n,visitedSchemaIds:a,options:u,skipReadonly:l}){switch(i.type){case"enum":return typeof r=="string"&&J1_({schema:i,value:r})?xg.enum(r):i.values[0]!=null?xg.enum(i.values[0]?.value):void 0;case"literal":return xg.literal(i.value);case"nullable":{if(r==null&&!this.hasExample(i.value,0,a,u)&&(u.ignoreOptionals||this.exceedsMaxDepth(n,u)))return;let d=this.buildExampleHelper({schema:i.value,visitedSchemaIds:a,exampleId:t,example:r,depth:n,options:u,skipReadonly:l});return d!=null&&d.type==="array"&&d.value.length===0||d!=null&&d.type==="map"&&d.value.length===0||d!=null&&d.type==="object"&&Object.keys(d.properties).length===0?void 0:d}case"optional":{if(r==null&&!this.hasExample(i.value,0,a,u)&&(u.ignoreOptionals||this.exceedsMaxDepth(n,u))||Object.is(r,null))return;let d=this.buildExampleHelper({schema:i.value,visitedSchemaIds:a,exampleId:t,example:r,depth:n,options:u,skipReadonly:l});return d!=null&&d.type==="array"&&d.value.length===0||d!=null&&d.type==="map"&&d.value.length===0||d!=null&&d.type==="object"&&Object.keys(d.properties).length===0?void 0:d}case"primitive":{let d=this.buildExampleFromPrimitive({schema:i.schema,example:r,options:u});return xg.primitive(d)}case"reference":{let d=this.schemas[i.schema];if(d!=null&&!a.has(i.schema)){a.add(i.schema);let s=d?.type==="object"&&!this.nonRequestReferencedSchemas.has(i.schema),o=this.buildExampleHelper({example:r,schema:d,exampleId:t,visitedSchemaIds:a,depth:n,options:u,skipReadonly:s||this.context.options.respectReadonlySchemas?l:!1});return a.delete(i.schema),o}return}case"oneOf":switch(i.value.type){case"discriminated":{let d={},s={},o={},c=Y5a(r),b=c?.[i.value.discriminantProperty],g=i.value.schemas[b],O=[],m=this.getDiscriminatedUnionVariantSchema(i.value,c);m!=null&&O.push(m),O.push(...Object.entries(i.value.schemas));for(let w of O)if(b!=null&&g!=null&&g.type==="object"){s=this.getAllProperties(g),o=this.getAllRequiredProperties(g),d[i.value.discriminantProperty]=xg.primitive(h_.string(b));break}else{let E=this.buildExampleHelper({exampleId:t,schema:w[1],example:void 0,visitedSchemaIds:a,depth:n,options:u,skipReadonly:l});if(E!=null){this.mergeExampleWith(E,d),d[i.value.discriminantProperty]=xg.primitive(h_.string(w[0]));break}}for(let w of i.value.commonProperties){s[w.key]={schema:w.schema,readonly:!1};let E=this.getResolvedSchema(w.schema);E.type!=="optional"&&E.type!=="nullable"&&(o[w.key]=w.schema)}for(let[w,E]of Object.entries(s)){let q=w in o;if(q&&c?.[w]!=null){let M=this.buildExampleHelper({schema:E.schema,exampleId:t,example:c[w],visitedSchemaIds:a,depth:n+1,options:u,skipReadonly:l});if(M!=null)d[w]=M;else return}else{let M=this.buildExampleHelper({exampleId:t,schema:E.schema,example:c?.[w],visitedSchemaIds:a,depth:n+1,options:u,skipReadonly:l});if(M!=null)d[w]=M;else if(q)return}}return xg.oneOf(RNi.discriminated(d))}case"undiscriminated":{let d=this.getUnDiscriminatedUnionVariantSchema(i.value,r);if(d!=null)return this.buildExampleHelper({exampleId:t,example:r,schema:d,visitedSchemaIds:a,depth:n,options:u,skipReadonly:l});break}}return;case"unknown":if(r!=null){let d=ZNi(r);if(d!=null)return xg.unknown(d)}return u.ignoreOptionals||this.exceedsMaxDepth(n,u)?void 0:u.isParameter?xg.primitive(h_.string(u.name??"string")):xg.map([{key:h_.string("key"),value:xg.primitive(h_.string("value"))}]);case"array":{let d=Q1_(r),s=[];if(d!=null&&d.length>0)for(let o of d){let c=this.buildExampleHelper({exampleId:t,example:o,schema:i.value,depth:n+1,visitedSchemaIds:a,options:u,skipReadonly:l});c!=null&&s.push(c)}else if(i.example!=null&&i.example.length>0)for(let o of i.example){let c=this.buildExampleHelper({exampleId:t,example:o,schema:i.value,depth:n+1,visitedSchemaIds:a,options:u,skipReadonly:l});c!=null&&s.push(c)}else{let o=this.buildExampleHelper({exampleId:t,example:void 0,schema:i.value,depth:n+1,visitedSchemaIds:a,options:u,skipReadonly:l});o!=null&&s.push(o)}return xg.array(s)}case"map":{let d=Y5a(r??i.example);if(d!=null&&Object.entries(d).length>0){let c=[];for(let[b,g]of Object.entries(d)){let O=this.buildExampleFromPrimitive({schema:i.key.schema,example:b,options:u}),m=this.buildExampleHelper({exampleId:t,example:g,schema:i.value,visitedSchemaIds:a,depth:n+1,options:u,skipReadonly:l});m!=null&&c.push({key:O,value:m})}return xg.map(c)}if(i.key.schema.type==="string"&&i.value.type==="unknown")return xg.map([{key:h_.string("key"),value:xg.unknown(xg.primitive(h_.string("value")))}]);let s=this.buildExampleFromPrimitive({schema:i.key.schema,example:void 0,options:{...u,name:"key"}}),o=this.buildExampleHelper({exampleId:t,example:void 0,schema:i.value,visitedSchemaIds:a,depth:n+1,options:{...u,name:"value"},skipReadonly:l});return o!=null?xg.map([{key:s,value:o}]):xg.map([])}case"object":{let d={},s=i.fullExamples?.find(g=>g.name===t)??i.fullExamples?.find(g=>g.name==null)??i.fullExamples?.[0],o=Y5a(r)??(s!=null?Y5a(s.value):{})??{},c=this.getAllProperties(i),b=this.getAllRequiredProperties(i);for(let[g,O]of Object.entries(c)){if(l&&O.readonly||O.schema._visit({optional:q=>typeof q.availability=="string"&&q.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 m=g in b,w=Object.keys(o).includes(g),E=this.buildExampleHelper({schema:O.schema,exampleId:t,example:o[g],visitedSchemaIds:a,depth:n+1,options:{...u,name:g},skipReadonly:l});if(m&&E!=null)d[g]=E;else{if(m)return;(w&&E!=null||!u.ignoreOptionals&&E!=null)&&(d[g]=E)}}if(i.additionalProperties){for(let[g,O]of Object.entries(o))if(!(g in d)){let m=this.buildExampleHelper({schema:Al.unknown({example:O,title:void 0,availability:void 0,description:void 0,generatedName:"",nameOverride:void 0,namespace:void 0,groupName:void 0}),exampleId:t,example:O,visitedSchemaIds:a,depth:n+1,options:{...u,name:g},skipReadonly:l});m!=null&&(d[g]=m)}}return xg.object({properties:d})}default:So(i)}}mergeExampleWith(t,r){t._visit({array:$o,enum:$o,literal:$o,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:$o,unknown:$o,_other:$o})}getObjectSchema(t){if(t.type==="object")return t;if(t.type==="reference"){let r=this.schemas[t.schema];if(r!=null)return this.getObjectSchema(r)}}getDiscriminatedUnionVariantSchema(t,r){let i=r?.[t.discriminantProperty];if(i==null||typeof i!="string")return Object.entries(t.schemas)[0];let n=t.schemas[i];return n==null?Object.entries(t.schemas)[0]:[i,n]}getUnDiscriminatedUnionVariantSchema(t,r){return r==null?t.schemas[0]:t.schemas.map(a=>({schema:a,heuristic:this.calcExampleHeuristic(a,r)})).sort((a,u)=>u.heuristic-a.heuristic)[0]?.schema}calcExampleHeuristic(t,r){switch(t.type){case"literal":return t.value.value===r?5:0;case"enum":return J1_({schema:t,value:r})?5:0;case"object":{if(!vw(r))return 0;let i=this.getAllProperties(t),n=0;for(let[a,u]of Object.entries(i))r[a]!=null?(n++,n+=this.calcExampleHeuristic(u.schema,r[a])):n--;return n}case"array":{if(!Array.isArray(r))return 0;let i=0;for(let n of r)i+=this.calcExampleHeuristic(t.value,n);return i}case"map":{if(!vw(r))return 0;let i=0;for(let[,n]of Object.entries(r))i+=this.calcExampleHeuristic(t.value,n);return i}case"nullable":case"optional":return this.calcExampleHeuristic(t.value,r);case"reference":{let i=this.getResolvedSchema(t);return i==null?0:this.calcExampleHeuristic(i,r)}case"oneOf":return Object.values(t.value.schemas).map(n=>this.calcExampleHeuristic(n,r)).sort((n,a)=>a-n)[0]??0;case"primitive":return r==null?0:t.schema._visit({int:()=>typeof r=="number",int64:()=>typeof r=="number",uint:()=>typeof r=="number",uint64:()=>typeof r=="number",float:()=>typeof r=="number",double:()=>typeof r=="number",string:()=>typeof r=="string",datetime:()=>typeof r=="string",date:()=>typeof r=="string",base64:()=>typeof r=="string",boolean:()=>typeof r=="boolean",_other:()=>!0})?1:-1;default:return 0}}hasExample(t,r,i=new Set,n){if(this.exceedsMaxCheckerDepth(r,n))return!1;switch(t.type){case"array":return this.hasExample(t.value,r+1,i,n);case"enum":return t.example!=null;case"literal":return!1;case"map":return t.example!=null||t.key.schema.example!=null&&this.hasExample(t.value,r+1,i,n);case"object":{if(t.fullExamples!=null&&t.fullExamples.length>0)return!0;for(let u of t.properties)if(this.hasExample(u.schema,r+1,i,n))return!0;return!1}case"primitive":return t.schema.example!=null;case"reference":{let a=this.schemas[t.schema];if(a!=null&&!i.has(t.schema)){i.add(t.schema);let u=this.hasExample(a,r,i,n);return i.delete(t.schema),u}return!1}case"unknown":return t.example!=null;case"oneOf":return Object.values(t.value.schemas).some(a=>this.hasExample(a,r,i,n));default:return!1}}exceedsMaxCheckerDepth(t,r){return t>(r.maxCheckerDepth??0)}exceedsMaxDepth(t,r){return t>(r.maxDepth??0)}getAllProperties(t){let r={};for(let i of t.properties)r[i.key]={schema:i.schema,readonly:i.readonly??!1};for(let i of t.allOf){let n=this.schemas[i.schema];if(n==null)continue;let a=this.getResolvedSchema(n);a.type==="object"&&(r={...this.getAllProperties(a),...r})}return r}getAllRequiredProperties(t){let r={};for(let i of t.properties){let n=this.getResolvedSchema(i.schema);n.type!=="optional"&&n.type!=="nullable"&&(r[i.key]=i.schema)}for(let i of t.allOf){let n=this.schemas[i.schema];if(n==null)continue;let a=this.getResolvedSchema(n);a.type==="object"&&(r={...this.getAllRequiredProperties(a),...r})}return r}getResolvedSchema(t){for(;t.type==="reference";){let r=this.schemas[t.schema];if(r==null)throw new Error(`Unexpected error: Failed to resolve schema reference: ${t.schema}`);t=r}return t}buildExampleFromPrimitive({example:t,schema:r,options:i}){switch(r.type){case"string":return t!=null&&typeof t=="string"?h_.string(t):r.example!=null?h_.string(r.example):h_.string(i.name??Ch.STRING);case"base64":return t!=null&&typeof t=="string"?h_.base64(t):r.example!=null?h_.base64(r.example):h_.base64(Ch.BASE64);case"boolean":return t!=null&&typeof t=="boolean"?h_.boolean(t):r.example!=null?h_.boolean(r.example):h_.boolean(Ch.BOOLEAN);case"date":return t!=null&&typeof t=="string"?h_.date(t):r.example!=null?h_.date(r.example):h_.date(Ch.DATE);case"datetime":return t!=null&&typeof t=="string"?h_.datetime(t):r.example!=null?h_.datetime(r.example):h_.datetime(Ch.DATE_TIME);case"double":return t!=null&&typeof t=="number"?h_.double(t):r.example!=null?h_.double(r.example):h_.double(Ch.DOUBLE);case"float":return t!=null&&typeof t=="number"?h_.float(t):r.example!=null?h_.float(r.example):h_.float(Ch.FLOAT);case"int":return t!=null&&typeof t=="number"?h_.int(t):r.example!=null?h_.int(r.example):h_.int(Ch.INT);case"int64":return t!=null&&typeof t=="number"?h_.int64(t):r.example!=null?h_.int64(r.example):h_.int64(Ch.INT64);case"uint":return t!=null&&typeof t=="number"?h_.uint(t):r.example!=null?h_.uint(r.example):h_.uint(Ch.UINT);case"uint64":return t!=null&&typeof t=="number"?h_.uint64(t):r.example!=null?h_.uint64(r.example):h_.uint64(Ch.UINT64);default:So(r)}}};function J1_({schema:e,value:t}){return e.values.map(r=>r.value).includes(t)}function OQt(e){switch(e.type){case"object":return Al.object({allOf:e.allOf,properties:e.properties.map(t=>fFE(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});case"array":return Al.array({description:e.description,availability:e.availability,value:OQt(e.value),generatedName:e.generatedName,title:e.title,namespace:e.namespace,nameOverride:e.nameOverride,groupName:e.groupName,example:void 0,inline:void 0});case"enum":return Al.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 Al.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 Al.nullable({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:OQt(e.value),namespace:e.namespace,groupName:e.groupName,inline:void 0});case"optional":return Al.optional({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:OQt(e.value),namespace:e.namespace,groupName:e.groupName,inline:void 0});case"primitive":return Al.primitive({description:e.description,availability:e.availability,schema:K1_(e.schema),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName});case"map":return Al.map({description:e.description,availability:e.availability,key:Al.primitive({description:e.key.description,availability:e.key.availability,schema:K1_(e.key.schema),generatedName:e.key.generatedName,nameOverride:e.key.nameOverride,title:e.key.title,namespace:e.namespace,groupName:e.groupName}),value:OQt(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});case"reference":return Al.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 Al.oneOf(lFE(e.value));case"unknown":return Al.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:So(e)}}function lFE(e){switch(e.type){case"discriminated":return aee.discriminated({commonProperties:e.commonProperties.map(t=>({key:t.key,schema:OQt(t.schema)})),description:e.description,availability:e.availability,discriminantProperty:e.discriminantProperty,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schemas:Object.fromEntries(Object.entries(e.schemas).map(([t,r])=>[t,OQt(r)])),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:void 0});case"undiscriminated":return aee.undiscriminated({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schemas:e.schemas.map(t=>OQt(t)),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:void 0});default:So(e)}}function K1_(e){switch(e.type){case"string":return ap.string({default:e.default,pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:void 0});case"base64":return ap.base64({example:void 0});case"boolean":return ap.boolean({default:e.default,example:void 0});case"date":return ap.date({example:void 0});case"datetime":return ap.datetime({example:void 0});case"double":return ap.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 ap.float({example:void 0});case"int":return ap.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 ap.int64({default:e.default,example:void 0});case"uint":return ap.uint({default:void 0,example:void 0});case"uint64":return ap.uint64({default:void 0,example:void 0});default:So(e)}}function fFE(e){return{conflict:e.conflict,generatedName:e.generatedName,key:e.key,schema:OQt(e.schema),audiences:e.audiences,nameOverride:e.nameOverride,availability:e.availability,readonly:e.readonly,writeonly:e.writeonly}}function Lau(e){return e.type!=="optional"&&e.type!=="nullable"}function vSc(e){return e==="POST"||e==="PUT"||e==="PATCH"}function X5a(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 Uau=class{schemas;context;globalHeaders;exampleTypeFactory;logger;constructor(t,r,i){this.schemas=t,this.context=r,this.globalHeaders=i,this.schemas=t,this.exampleTypeFactory=new kNi(t,r.nonRequestReferencedSchemas,r),this.logger=r.logger}buildEndpointExample(t){this.logger.debug(`Building endpoint example for ${t.method.toUpperCase()} ${t.path}`);let r=pFE(t.request),i=_FE(t.response);if(r?.type==="unsupported"||i?.type==="unsupported")return[];let n=[];if(r!=null&&r.type==="present"){let c=this.isSchemaRequired(r.schema);if(r.examples.length===0){let b=this.exampleTypeFactory.buildExample({skipReadonly:vSc(t.method),schema:r.schema,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});b!=null&&n.push([void 0,b])}else for(let{name:b,value:g}of r.examples){let O=this.exampleTypeFactory.buildExample({skipReadonly:vSc(t.method),schema:r.schema,exampleId:b,example:g,options:{isParameter:!1,ignoreOptionals:!0}});O!=null&&n.push([b,O])}if(c&&n.length===0)return this.logger.trace(`Failed to generate required request example for ${t.method.toUpperCase()} ${t.path}`),[]}let a=[];if(i!=null&&i.type==="present"){let c=this.isSchemaRequired(i.schema);if(i.examples.length===0){let b=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:i.schema,exampleId:void 0,example:void 0,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});b!=null&&(t.response?.type==="json"?a.push([void 0,vQt.withoutStreaming(b)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&a.push([void 0,vQt.withStreaming({sse:t.response?.type==="streamingSse",events:[b]})]))}else for(let{name:b,value:g}of i.examples){let O=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:i.schema,exampleId:b,example:g,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});O!=null&&(t.response?.type==="json"?a.push([b,vQt.withoutStreaming(O)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&a.push([void 0,vQt.withStreaming({sse:t.response?.type==="streamingSse",events:[O]})]))}if(c&&a.length===0)return this.logger.trace(`Failed to generate required response example for ${t.method.toUpperCase()} ${t.path}`),[]}let u=[];for(let c of t.pathParameters){let b=this.isSchemaRequired(c.schema),g=this.exampleTypeFactory.buildExample({schema:c.schema,exampleId:void 0,example:void 0,options:{name:c.name,isParameter:!0,ignoreOptionals:!0}});if(g!=null&&!mQt(g)&&(this.logger.warn(`Expected a primitive example but got ${g.type} for path parameter ${c.name} for ${t.method.toUpperCase()} ${t.path}`),g=void 0),b&&g==null)return[];g!=null&&u.push({name:c.name,parameterNameOverride:c.parameterNameOverride,value:g})}let l=[];for(let c of t.queryParameters){let b=this.isSchemaRequired(c.schema),g=this.exampleTypeFactory.buildExample({schema:c.schema,exampleId:void 0,example:void 0,options:{name:c.name,isParameter:!0,ignoreOptionals:!0}});if(g!=null&&!mQt(g)&&(this.logger.warn(`Expected a primitive example but got ${g.type} for query parameter ${c.name} for ${t.method.toUpperCase()} ${t.path}`),g=void 0),b&&g==null)return[];g!=null&&l.push({name:c.name,value:g})}let d=[];for(let c of t.headers){let b=this.isSchemaRequired(c.schema),g=this.exampleTypeFactory.buildExample({schema:c.schema,exampleId:void 0,example:void 0,options:{name:c.name,isParameter:!0,ignoreOptionals:!0}});if(g!=null&&!mQt(g)&&(this.logger.warn(`Expected a primitive example but got ${g.type} for header ${c.name} for ${t.method.toUpperCase()} ${t.path}`),g=void 0),b&&g==null)return[];g!=null&&d.push({name:c.name,value:g})}for(let c of this.globalHeaders){let b=c.schema!=null?OQt(c.schema):Al.primitive({nameOverride:void 0,generatedName:"",title:void 0,description:void 0,availability:void 0,namespace:void 0,groupName:void 0,schema:ap.string({default:void 0,pattern:void 0,maxLength:void 0,minLength:void 0,example:void 0,format:void 0})}),g=this.exampleTypeFactory.buildExample({schema:b,exampleId:void 0,example:void 0,options:{name:c.header,isParameter:!0,ignoreOptionals:!0}});if(g!=null&&!mQt(g)&&(this.logger.warn(`Expected a primitive example but got ${g.type} for global header ${c.header} for ${t.method.toUpperCase()} ${t.path}`),g=void 0),g==null)return[];g!=null&&d.push({name:c.header,value:g})}let s=[];t.request!=null&&t.response!=null?s=dFE(n,a):t.request!=null?s=n.map(([c,b])=>({id:c,request:b,response:void 0})):t.response!=null&&(s=a.map(([c,b])=>({id:c,request:void 0,response:b})));let o=t.examples.filter(c=>X5a(c)).flatMap(c=>{if(c.type==="unknown"){if(c.value!=null){let b=c.value["code-samples"];if(b!=null)return this.convertCodeSamples(b)}return}else return c.codeSamples}).filter(c=>iv(c));return s.length===0?[yQt.full({name:void 0,description:void 0,pathParameters:u,queryParameters:l,headers:d,request:void 0,response:void 0,codeSamples:o})]:s.map(({id:c,request:b,response:g})=>yQt.full({name:c,description:void 0,pathParameters:u,queryParameters:l,headers:d,request:b,response:g,codeSamples:o}))}convertCodeSamples(t){return t.map(r=>"language"in r?Kmi.language({name:r.name??void 0,description:r.docs??void 0,language:r.language,code:r.code,install:r.install??void 0}):Kmi.sdk({name:r.name??void 0,description:r.docs??void 0,sdk:r.sdk==="c#"?GH.Csharp:r.sdk,code:r.code})).filter(iv)}isSchemaRequired(t){return Lau(this.getResolvedSchema(t))}getResolvedSchema(t){return t}};function dFE(e,t){let r=[];if(e.length<=1){let[n,a]=e[0]??[];if(t.length===0)return r.push({id:n,request:a,response:void 0}),r;for(let[u,l]of t)r.push({id:u??n,request:a,response:l});return r}if(t.length<=1){let[n,a]=t[0]??[];if(t.length===0)return r.push({id:n,request:void 0,response:a}),r;for(let[u,l]of e)r.push({id:u??n,request:l,response:a});return r}let i=new Set;for(let[n,a]of e){let u=t.find(([d])=>d==null)?.[1]??t[0]?.[1];if(n==null){if(u==null)continue;r.push({id:void 0,request:a,response:u});continue}let l=!1;for(let d=0;d<t.length;d++){let[s,o]=t[d];s==null||i.has(d)||n===s&&(r.push({id:n,request:a,response:o}),s!=null&&i.add(d),l=!0)}!l&&u!=null&&r.push({id:n,request:a,response:u})}for(let n=0;n<t.length;n++){if(i.has(n))continue;let[a,u]=t[n],l=e.find(([d])=>d==null)?.[1]??e[0]?.[1];l!=null&&r.push({id:a,request:l,response:u})}return r}function pFE(e){if(e!=null)return e.type==="multipart"?{type:"present",schema:hFE(e),examples:[]}:e.type==="json"||e.type==="formUrlEncoded"?{type:"present",schema:e.schema,examples:e.fullExamples??[]}:{type:"unsupported"}}function _FE(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 mQt(e){switch(e.type){case"primitive":case"enum":case"literal":return!0;case"unknown":return mQt(e);case"array":case"object":case"map":return!1;case"oneOf":switch(e.value.type){case"discriminated":return!1;case"undiscriminated":return mQt(e.value.value);default:return!1}default:So(e)}}function hFE(e){return Al.object({properties:e.properties.map(t=>t.schema.type==="file"?null:{key:t.key,schema:OQt(t.schema.value),audiences:[],conflict:{},generatedName:t.key,nameOverride:void 0,availability:void 0,readonly:void 0,writeonly:void 0,inline:void 0}).filter(iv),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})}var IKn=class{exampleTypeFactory;schemas;constructor(t,r){this.exampleTypeFactory=new kNi(t,new Set,r),this.schemas=t}buildWebsocketSessionExamplesForExtension({context:t,extensionExamples:r,handshake:i,source:n,namespace:a}){let u=[];for(let l of r){let d=[];for(let c of i.queryParameters){let b=this.isSchemaRequired(c.schema),g=this.exampleTypeFactory.buildExample({schema:c.schema,exampleId:void 0,example:l.queryParameters?.[c.name],options:{name:c.name,isParameter:!0,ignoreOptionals:!0}});g!=null&&!mQt(g)&&(g=void 0),!(b&&g==null)&&g!=null&&d.push({name:c.name,value:g})}let s=[];for(let c of i.headers){let b=this.isSchemaRequired(c.schema),g=this.exampleTypeFactory.buildExample({schema:c.schema,exampleId:void 0,example:l.headers?.[c.name],options:{name:c.name,isParameter:!0,ignoreOptionals:!0}});g!=null&&!mQt(g)&&(g=void 0),!(b&&g==null)&&g!=null&&s.push({name:c.name,value:g})}let o=[];for(let c of l.messages){let b=t.getExampleMessageReference(c),g=t.resolveMessageReference({$ref:b}),O=Kd(g.payload)?t.resolveSchemaReference(g.payload):g.payload,m=this.exampleTypeFactory.buildExample({schema:j0(O,!1,t,[c.messageId],n,a),exampleId:void 0,example:c.value,options:{isParameter:!1,ignoreOptionals:!0}});m!=null&&o.push({messageType:c.type,payload:m,description:void 0})}u.push({name:l.summary,queryParameters:d,headers:s,description:l.description,messages:o})}return u}buildWebsocketSessionExample({handshake:t,messages:r}){let i={name:void 0,queryParameters:[],headers:[],description:void 0,messages:[]},n=[];for(let u of t.queryParameters){let l=this.isSchemaRequired(u.schema),d=this.exampleTypeFactory.buildExample({schema:u.schema,exampleId:void 0,example:void 0,options:{name:u.name,isParameter:!0,ignoreOptionals:!0}});if(d!=null&&!mQt(d)&&(d=void 0),l&&d==null)return;d!=null&&n.push({name:u.name,value:d})}let a=[];for(let u of t.headers){let l=this.isSchemaRequired(u.schema),d=this.exampleTypeFactory.buildExample({schema:u.schema,exampleId:void 0,example:void 0,options:{name:u.name,isParameter:!0,ignoreOptionals:!0}});if(d!=null&&!mQt(d)&&(d=void 0),l&&d==null)return;d!=null&&a.push({name:u.name,value:d})}for(let u of r){let l=this.exampleTypeFactory.buildExample({schema:u.payload,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});l!=null&&i.messages.push({messageType:u.type,payload:l,description:void 0})}return i}isSchemaRequired(t){return Lau(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 see={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_EXAMPLES:"x-fern-examples",BASE_PATH:"x-fern-base-path",FERN_ENUM:"x-fern-enum",IGNORE:"x-fern-ignore"};function Vau(e){return of(e,see.FERN_EXAMPLES)??[]}function Wau(e,t){return t.includes("://")?t:`${e}://${t}`}function Hau(e){return e.startsWith("/")?e:"/"+e}function Z1_({context:e,breadcrumbs:t,source:r,asyncApiOptions:i,document:n}){let a={},u={};for(let[s,o]of Object.entries(n.components?.schemas??{})){let c=j0(o,!1,e,[s],r,e.namespace);a[s]=c}let l=new IKn(a,e),d={};for(let[s,o]of Object.entries(n.servers??{}))d[s]={name:s,url:Wau(o.protocol,o.url)};for(let[s,o]of Object.entries(n.channels??{})){let c=of(o,see.IGNORE);if(c!=null&&c){e.logger.debug(`Channel ${s} is marked with x-fern-ignore. Skipping.`);continue}let b=[];if(o.parameters!=null)for(let[E,q]of Object.entries(o.parameters??{}))b.push({name:E,description:q.description,parameterNameOverride:void 0,schema:q.schema!=null?j0(q.schema,!1,e,t,r,e.namespace):Al.primitive({schema:ap.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:sK(q),source:r});let g=[],O=[];if(o.bindings?.ws!=null){if(o.bindings.ws.headers!=null){let E=o.bindings.ws.headers.required??[];for(let[q,M]of Object.entries(o.bindings.ws.headers.properties??{})){if(Kd(M)){let D=e.resolveSchemaReference(M);g.push({name:q,schema:tPi(M,!1,e,t,void 0,r,e.namespace),description:D.description,parameterNameOverride:void 0,env:void 0,availability:sK(D),source:r});continue}g.push({name:q,schema:j0(M,!E.includes(q),e,[...t,q],r,e.namespace),description:M.description,parameterNameOverride:void 0,env:void 0,availability:sK(M),source:r})}}if(o.bindings.ws.query!=null){let E=o.bindings.ws.query.required??[];for(let[q,M]of Object.entries(o.bindings.ws.query.properties??{})){if(Kd(M)){let D=e.resolveSchemaReference(M);O.push({name:q,schema:tPi(M,!1,e,t,void 0,r,e.namespace),description:D.description,parameterNameOverride:void 0,availability:sK(D),source:r});continue}O.push({name:q,schema:j0(M,!E.includes(q),e,[...t,q],r,e.namespace),description:M.description,parameterNameOverride:void 0,availability:sK(M),source:r})}}}let m;o.publish!=null&&("oneOf"in o.publish.message?m=Y1_({generatedName:o.publish.operationId??"PublishEvent",event:o.publish,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:i}):m=X1_({action:"Publish",channelPath:s,message:o.publish.message,context:e,source:r}));let w;if(o.subscribe!=null&&("oneOf"in o.subscribe.message?w=Y1_({generatedName:o.subscribe.operationId??"SubscribeEvent",event:o.subscribe,breadcrumbs:t,context:e,source:r,options:e.options,asyncApiOptions:i}):w=X1_({action:"Subscribe",channelPath:s,message:o.subscribe.message,context:e,source:r})),g.length>0||O.length>0||m!=null||w!=null){let E=Vau(o),q=[];if(E.length>0)q=l.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:E,handshake:{headers:g,queryParameters:O},source:r,namespace:e.namespace});else{let R=[];m!=null&&R.push({type:"publish",payload:m}),w!=null&&R.push({type:"subscribe",payload:w});let G=l.buildWebsocketSessionExample({handshake:{headers:g,queryParameters:O},messages:R});G!=null&&q.push(G)}let M=of(o,see.FERN_CHANNEL_ADDRESS),D=M??Hau(s),C=[];m!=null&&C.push({origin:"client",name:"publish",body:iA(m)}),w!=null&&C.push({origin:"server",name:"subscribe",body:iA(w)}),u[s]={audiences:of(o,Kf.AUDIENCES)??[],handshake:{headers:g.map(R=>({...R,schema:iA(R.schema),env:R.env})),queryParameters:O.map(R=>({...R,schema:iA(R.schema)})),pathParameters:b.map(R=>({...R,parameterNameOverride:void 0,schema:iA(R.schema)}))},groupName:e.resolveGroupName([of(o,see.FERN_SDK_GROUP_NAME)??s]),messages:C,servers:(o.servers?.map(R=>d[R])??Object.values(d)).filter(R=>R!=null),summary:of(o,see.FERN_DISPLAY_NAME),path:D,description:o.description,examples:q,source:r}}}return{groupedSchemas:BKn(e.namespace,a),channels:u??void 0,servers:Object.values(d),basePath:of(n,see.BASE_PATH)}}function Y1_({generatedName:e,event:t,context:r,breadcrumbs:i,source:n,options:a,asyncApiOptions:u}){if("oneOf"in t.message&&t.message.oneOf!=null){let l=[],d=[];for(let s of t.message.oneOf){let o,c={type:"notFound"};if(Kd(s)){let b=r.resolveMessageReference(s);!Kd(b.payload)&&u.naming==="v2"?(c=b.name?{type:"name",name:b.name}:c,o={...b.payload,title:b.name??b.payload.title,description:b.name??b.payload.description}):o=b.payload}else o=s;d.push(c),l.push(o)}return XNi({description:t.description??t.message.description,availability:sK(t.message),subtypes:l,nameOverride:t.operationId,generatedName:e,title:t.message.title,groupName:void 0,wrapAsNullable:!1,breadcrumbs:i,context:r,encoding:void 0,source:n,namespace:r.namespace,subtypePrefixOverrides:u.naming==="v2"?d:[]})}}function X1_({action:e,channelPath:t,message:r,context:i,source:n}){if(r.payload!=null){let a=r.payload;return Kd(r.payload)&&(a=i.resolveSchemaReference(r.payload)),j0(a,!1,i,[t,e],n,i.namespace)}}var $au=class extends CKn{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){let r="#/channels/",i="#/components/messages/";if(t.$ref.startsWith(r)){let l=t.$ref.split("/"),d=l[2],s=l[4];if(d==null||s==null||!this.document.channels?.[d])throw new Error(`Failed to resolve message reference ${t.$ref} in channel ${d}`);let c=this.document.channels[d].messages?.[s];if(c==null)throw new Error(`${t.$ref} is undefined`);return"$ref"in c?this.resolveMessageReference(c):{name:s,...c}}let n=this.document.components;if(!t.$ref.startsWith(i)||!n?.messages)throw new Error(`Failed to resolve message reference: ${t.$ref} in v3 components`);let a=t.$ref.substring(i.length),u=n.messages[a];if(u==null)throw new Error(`${t.$ref} is undefined`);return{name:a,...u}}isMessageWithPayload(t){return t!=null&&typeof t=="object"&&"payload"in t}isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}};var k1_="#/channels/",eS_="#/servers/",bSc="$message.";function rS_({context:e,breadcrumbs:t,source:r,asyncApiOptions:i,document:n}){let a={},u={},l={},d=[],s={};for(let[O,m]of Object.entries(n.components?.schemas??{}))a[O]=j0(m,!1,e,[O],r,e.namespace);for(let[O,m]of Object.entries(n.channels??{}))if(u[O]||(u[O]={}),m.messages){for(let[w,E]of Object.entries(m.messages))if(e.isReferenceObject(E)||e.isMessageWithPayload(E))if(l[w]||(l[w]=[]),e.isReferenceObject(E)){let q=e.resolveMessageReference(E);l[w].push({channelId:O,payload:q.payload})}else l[w].push({channelId:O,payload:E.payload})}for(let[O,m]of Object.entries(l))if(m.length===1){let w=m[0],E=w.channelId;u[E]=u[E]||{},u[E][O]=j0(w.payload,!1,e,[O],r,e.namespace)}else{d.push(O);for(let{channelId:w,payload:E}of m){let q=`${w}_${O}`;u[w]||(u[w]={}),u[w][q]=j0(E,!1,e,[q],r,e.namespace)}}let o=Object.values(u).reduce((O,m)=>({...O,...m}),{}),c=new IKn(o,e),b={};for(let[O,m]of Object.entries(n.servers??{}))b[O]={name:O,url:Wau(m.protocol,m.host)};let g={};for(let[O,m]of Object.entries(n.operations??{})){if(of(m,see.IGNORE))continue;let w=yFE(m);if(g[w]||(g[w]={subscribe:[],publish:[],__parsedMessages:[]}),m.action==="receive")g[w].subscribe.push(...m.messages);else if(m.action==="send")g[w].publish.push(...m.messages);else throw new Error(`Operation ${O} has an invalid action: ${m.action}`)}for(let[O,m]of Object.entries(g)){let w=[];w.push(...tS_({messages:m.subscribe,channelPath:O,origin:"server",messageSchemas:u[O]??{},duplicatedMessageIds:d,context:e})),w.push(...tS_({messages:m.publish,channelPath:O,origin:"client",messageSchemas:u[O]??{},duplicatedMessageIds:d,context:e})),g[O]!=null&&(g[O].__parsedMessages=w)}for(let[O,m]of Object.entries(n.channels??{})){if(of(m,see.IGNORE))continue;let w=[],E=[],q=[];if(m.parameters!=null)for(let[M,D]of Object.entries(m.parameters)){let C=e.isReferenceObject(D)?e.resolveParameterReference(D):D,{type:R,parameterKey:G}=C.location!=null?vFE(C.location):{type:m.address?.includes(`={${M}}`)?"query":"path",parameterKey:M},I=of(C,see.FERN_PARAMETER_OPTIONAL),L=qB(S_(O))+qB(S_(M)),V={...C,type:"string",title:L,example:C.examples?.[0],default:C.default,enum:C.enum,required:void 0},Y=j0(V,!1,e,[G],r,e.namespace);I&&(Y=Al.optional({value:Y,description:void 0,availability:void 0,generatedName:"",title:L,namespace:void 0,groupName:void 0,nameOverride:void 0,inline:void 0}));let K={name:G,description:C.description,parameterNameOverride:void 0,schema:Y,variableReference:void 0,availability:sK(D),source:r};R==="header"?w.push({...K,env:void 0}):R==="path"?E.push(K):(R==="payload"||R==="query")&&q.push(K)}if(w.length>0||q.length>0||g[O]!=null&&(g[O].publish!=null||g[O].subscribe!=null)){let M=Vau(m),D=g[O]?.__parsedMessages??[],C=[];if(M.length>0)C=c.buildWebsocketSessionExamplesForExtension({context:e,extensionExamples:M,handshake:{headers:w,queryParameters:q},source:r,namespace:e.namespace});else{let R=[],{examplePublishMessage:G,exampleSubscribeMessage:I}=gFE({messages:D,messageSchemas:u[O]??{}});G!=null&&R.push(G),I!=null&&R.push(I);let L=c.buildWebsocketSessionExample({handshake:{headers:w,queryParameters:q},messages:R});L!=null&&C.push(L)}s[O]={audiences:of(m,Kf.AUDIENCES)??[],handshake:{headers:w.map(R=>({...R,schema:iA(R.schema),env:R.env})),queryParameters:q.map(R=>({...R,schema:iA(R.schema)})),pathParameters:E.map(R=>({...R,parameterNameOverride:void 0,schema:iA(R.schema)}))},groupName:e.resolveGroupName([of(m,see.FERN_SDK_GROUP_NAME)??O]),messages:D,summary:of(m,see.FERN_DISPLAY_NAME),servers:m.servers?.map(R=>bFE(b,R))??Object.values(b),path:m.address?.split("?")[0]??Hau(O),description:m.description,examples:C,source:r}}}return{groupedSchemas:BKn(e.namespace,a),channels:s,servers:Object.values(b),basePath:of(n,see.BASE_PATH)}}function yFE(e){if(!e.channel.$ref.startsWith(k1_))throw new Error(`Failed to resolve channel path from operation ${e.channel.$ref}`);return e.channel.$ref.substring(k1_.length)}function vFE(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(bSc))throw new Error(`Invalid location format: ${e}; expected ${bSc} prefix`);let i=t.substring(bSc.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 bFE(e,t){if(!t.$ref.startsWith(eS_))throw new Error(`Failed to resolve server name from server ref ${t.$ref}`);let r=t.$ref.substring(eS_.length),i=e[r];if(i==null)throw new Error(`Failed to find server with name ${r}`);return i}function tS_({messages:e,channelPath:t,origin:r,messageSchemas:i,duplicatedMessageIds:n,context:a}){let u=[];return e.forEach((l,d)=>{let o=a.resolveMessageReference(l).name;n.includes(o)&&(o=`${t}_${o}`);let c=i[o];c!=null&&u.push({origin:r,name:o??`${r}Message${d+1}`,body:iA(c)})}),u}function gFE({messages:e,messageSchemas:t}){let r=e.find(u=>u.origin==="client")?.name,i=e.find(u=>u.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 iS_({document:e,taskContext:t,options:r,source:i,asyncApiOptions:n,namespace:a}){let u=[];if(a!=null&&u.push(a),parseFloat(e.asyncapi)<3){let l=e;l.tags?.[0]!=null?u.push(l.tags[0].name):n.naming!=="v2"&&u.push("websocket");let d=new Fau({document:l,taskContext:t,options:r,namespace:a});return Z1_({context:d,breadcrumbs:u,source:i,asyncApiOptions:n,document:l})}else{let l=e,d=new $au({document:l,taskContext:t,options:r,namespace:a});return rS_({context:d,breadcrumbs:u,source:i,asyncApiOptions:n,document:l})}}function nS_(e){return of(e,Kf.ASYNC_CONFIG)}var aS_="$request.";function oS_(e){let t=of(e,Kf.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:OFE(t["stream-condition"]),responseStream:t["response-stream"],response:t.response}}function OFE(e){return e.startsWith(aS_)?e.slice(aS_.length):e}function uS_(e){let t=e;if(t.cursor!=null)return t7e.cursor({cursor:t.cursor,nextCursor:t.next_cursor,results:t.results});if("offset"in e){let r=e;return t7e.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 t7e.custom({results:r.results})}throw new Error("Invalid pagination extension")}function sS_(e,t){let r=of(t,Kf.PAGINATION);if(r!=null){if(typeof r=="boolean"){let i=of(e,Kf.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:uS_(i)}return uS_(r)}}function cS_(e){let t=mFE(e),r={};return gSc({obj:t,occurrences:r,breadcrumbs:[]}),r}function gSc({obj:e,occurrences:t,breadcrumbs:r}){if(e!=null){if(Array.isArray(e)){for(let i of e)gSc({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)gSc({obj:e[i],occurrences:t,breadcrumbs:[...r,i]})}}}function mFE(e){return{...e,paths:Object.fromEntries(Object.entries(e.paths??{}).map(([t,r])=>[t,{...r,get:r?.get!=null?Z5a(r.get):void 0,put:r?.put!=null?Z5a(r.put):void 0,post:r?.post!=null?Z5a(r.post):void 0,patch:r?.patch!=null?Z5a(r.patch):void 0,delete:r?.delete!=null?Z5a(r.delete):void 0}]))}}function Z5a(e){return{...e,requestBody:e.requestBody!=null?Kd(e.requestBody)?e.requestBody:PFE(e.requestBody):void 0}}function PFE(e){let t,r;for(let i in e.content){let n=hq.parse(i);n!=null&&(n.isJSON()?t=e.content[i]:n.isMultipart()&&(r=e.content[i]))}return r!=null&&t!=null?{...e,content:{[hq.MULTIPART_FORM_DATA]:r}}:e}var Gau=class{endpoints;parser=new Aen;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 lS_="#/components/parameters/",fS_="#/components/responses/",dS_="#/components/examples/",pS_="#/components/requestBodies/",zKn=class{logger;document;taskContext;authHeaders;refOccurrences;DUMMY;options;source;filter;namespace;constructor({document:t,taskContext:r,authHeaders:i,options:n,source:a,namespace:u}){this.document=t,this.logger=r.logger,this.taskContext=r,this.authHeaders=i,this.refOccurrences=cS_(t),this.options=n,this.source=a,this.filter=new Gau({context:r,options:n}),this.DUMMY=this.getDummy(),this.namespace=u}getNumberOfOccurrencesForRef(t){return this.refOccurrences[t.$ref]??0}resolveTagsToTagIds(t){let r=[];return this.namespace!=null&&r.push(this.namespace),r.concat(t??[])}resolveTags(t){let r=[];if(this.namespace!=null){let i={type:"namespace",name:this.namespace};r.push(i)}return r.concat(t??[])}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveSchemaReference(t){let r=t.$ref.substring(2).split("/").map(n=>n.replace(/~1/g,"/")),i=this.document;for(let n of r){if(typeof i!="object"||i==null)return{"x-fern-type":"unknown"};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.warn(`Encountered undefined reference: ${t.$ref}`),{"x-fern-type":"unknown"}):(Kd(i)&&(i=this.resolveSchemaReference(i)),i)}resolveParameterReference(t){if(this.document.components==null||this.document.components.parameters==null||!t.$ref.startsWith(lS_))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(lS_.length),i=this.document.components.parameters[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return Kd(i)?this.resolveParameterReference(i):i}resolveRequestBodyReference(t){if(this.document.components==null||this.document.components.requestBodies==null||!t.$ref.startsWith(pS_))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(pS_.length),i=this.document.components.requestBodies[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return Kd(i)?this.resolveRequestBodyReference(i):i}resolveResponseReference(t){if(this.document.components==null||this.document.components.responses==null||!t.$ref.startsWith(fS_))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(fS_.length),i=this.document.components.responses[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return Kd(i)?this.resolveResponseReference(i):i}resolveExampleReference(t){if(this.document.components==null||this.document.components.examples==null||!t.$ref.startsWith(dS_))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(dS_.length),i=this.document.components.examples[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return Kd(i)?this.resolveExampleReference(i):i}referenceExists(t){let r=t.substring(2).split("/").map(n=>n.replace(/~1/g,"/")),i=this.document;for(let n of r){if(typeof i!="object"||i==null)return!1;i=i[n]}return!0}};var aan=class extends zKn{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 jFE=Su.object({lang:Su.string(),label:Su.optional(Su.string()),source:Su.string()}),OSc=Su.array(jFE);var _S_={README_EXT:"x-readme"};function wFE(e){if(!Array.isArray(e))return!1;for(let t of e)if(!vw(t)||typeof t.language!="string"||typeof t.code!="string")return!1;return!0}function hS_(e){let t=of(e,_S_.README_EXT);if(!vw(t))return[];let r=t["code-samples"];if(!wFE(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 yS_(e,t,r){let n=(of(t,Kf.EXAMPLES)??[]).filter(s=>{let o=MF.serialization.ExampleEndpointCallSchema.parse(s);return o.ok||r.logger.error(`Failed to parse x-fern-example in ${e.path}/${e.method}`),o.ok}),a=J5a(t,JH.REDOCLY_CODE_SAMPLES_KEBAB,OSc,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],l=[...J5a(t,JH.REDOCLY_CODE_SAMPLES_CAMEL,OSc,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],...a];l.length>0&&n.push({"code-samples":l.map(s=>({name:s.label??s.lang,language:s.lang,code:s.source,install:void 0,docs:void 0}))});let d=hS_(t);return d.length>0&&n.push({"code-samples":d}),n.map(yQt.unknown)}function vS_(e){let t=of(e,Kf.AVAILABILITY);if(t==="ga"||t==="generally-available")return $H.GenerallyAvailable;if(t==="beta"||t==="pre-release")return $H.Beta;if(t==="deprecated")return $H.Deprecated;if(e.deprecated)return $H.Deprecated}function Qau(e){return{url:SFE({url:e.url,variables:e.variables??{}}),description:e.description,name:DFE(e),audiences:of(e,Kf.AUDIENCES)}}function SFE({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 DFE(e){let t=of(e,[Kf.SERVER_NAME_V1,Kf.SERVER_NAME_V2]);if(t!=null)return t;if(e.description?.toLowerCase()==="production")return"Production";if(e.description?.toLowerCase()==="sandbox")return"Sandbox"}function bS_(e){return of(e,Kf.PARAMETER_NAME)}function gS_(e){return of(e,Kf.SDK_VARIABLE)}function Jau({path:e,httpMethod:t,parameters:r,context:i,requestBreadcrumbs:n,source:a}){let u={pathParameters:[],queryParameters:[],headers:[]};for(let l of r){let d=of(l,Kf.IGNORE);if(d!=null&&d){i.logger.debug(`${t.toUpperCase()} ${e} has a parameter marked with x-fern-ignore. Skipping.`);continue}let s=Kd(l)?i.resolveParameterReference(l):l,o=s.required??!1,c=sK(s),b=[...n,s.name],g=Q8(b,i.options.preserveSchemaIds),O=s.schema!=null?j0(s.schema,!o,i,b,a,i.namespace,!1,new Set,Sor({schema:s,logger:i.logger})):o?Al.primitive({nameOverride:void 0,generatedName:g,title:void 0,schema:ap.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:Sor({schema:s,logger:i.logger})}),description:void 0,availability:c,namespace:void 0,groupName:void 0}):Al.optional({nameOverride:void 0,generatedName:g,title:void 0,value:Al.primitive({nameOverride:void 0,generatedName:g,title:void 0,schema:ap.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:Sor({schema:s,logger:i.logger})}),description:void 0,availability:void 0,namespace:void 0,groupName:void 0}),description:void 0,availability:c,namespace:void 0,groupName:void 0,inline:void 0});if(s.in==="header"&&s.schema!=null&&!Kd(s.schema)&&s.schema.default!=null){let w=s.schema.default;typeof w=="string"&&w.length>0&&(O=Al.literal({nameOverride:void 0,generatedName:g,title:void 0,value:Kz.string(w),description:void 0,availability:c,namespace:void 0,groupName:void 0}))}let m={name:s.name,schema:O,description:s.description,parameterNameOverride:bS_(s),availability:c,source:a};s.in==="query"?u.queryParameters.push(m):s.in==="path"?u.pathParameters.push({...m,variableReference:gS_(s)}):s.in==="header"?!EFE.has(s.name.toLowerCase())&&!i.authHeaders.has(s.name)?u.headers.push({...m,env:void 0}):i.logger.debug(`Ignoring ${s.name} header, in ${t.toUpperCase()} ${e}`):i.logger.warn(`Skipping ${s.in} parameter, ${s.name}, in ${t.toUpperCase()} ${e}`)}return u}var EFE=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]);function OS_(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:k5a(i,t)}}}function MFE(e){return e.includes("json")||e==="*/*"}function mSc({content:e,context:t}){for(let[r,i]of Object.entries(e))if(Kau({mediaType:r,mediaTypeObject:i,context:t})!=null)return[r,i]}function Kau({mediaType:e,mediaTypeObject:t,context:r}){if(!MFE(e))return;let i=t.schema;return{contentType:e.includes("*")?void 0:e,schema:i??{},examples:k5a(t,r)}}function Yau({content:e,context:t}){let r=mSc({content:e,context:t});if(!r)return;let[i,n]=r;return Kau({mediaType:i,mediaTypeObject:n,context:t})}function mS_(e,t){for(let r of Object.keys(e)){let i=e[r];if(i==null)continue;return{schema:i.schema??{},examples:k5a(i,t)}}}function k5a(e,t){let r=[];e.example!=null&&r.push({name:void 0,value:e.example,description:void 0});let i=of(e,JH.EXAMPLES);return i!=null&&Object.keys(i).length>0&&r.push(...Object.entries(i).map(([n,a])=>({name:a.summary??n,value:a.value,description:a.description}))),e.examples!=null&&Object.keys(e.examples).length>0&&r.push(...Object.entries(e.examples).map(([n,a])=>{let u=Kd(a)?t.resolveExampleReference(a):a;return{name:u.summary??n,value:u.value,description:u.description}})),r}function AFE({content:e,context:t}){for(let[r,i]of Object.entries(e))if(jS_({mediaType:r,mediaTypeObject:i,context:t}))return[r,i]}function jS_({mediaType:e,mediaTypeObject:t,context:r}){if(hq.parse(e)?.isURLEncoded())return{schema:t.schema,contentType:e,examples:k5a(t,r)}}function qFE({content:e}){for(let[t,r]of Object.entries(e))if(wS_({mediaType:t,mediaTypeObject:r}))return[t,r]}function wS_({mediaType:e,mediaTypeObject:t}){if(hq.parse(e)?.isMultipart())return{schema:t.schema,encoding:t.encoding}}function SS_({mediaType:e}){return hq.parse(e)?.isBinary()??!1}function TFE({content:e}){for(let[t,r]of Object.entries(e))if(SS_({mediaType:t}))return[t,r]}function CFE(e,t){let r=Kd(e)?PSc(e,t):{id:void 0,schema:e};return Object.entries(r.schema.properties??{}).find(([i,n])=>!Kd(n)&&n.type==="string"&&n.format==="binary")!=null}function Zau({content:e,description:t,document:r,context:i,requestBreadcrumbs:n,source:a,namespace:u}){let l=TFE({content:e});if(l){let[b,g]=l;return Dor({mediaType:b,mediaTypeObject:g,description:t,document:r,context:i,requestBreadcrumbs:n,source:a,namespace:u})}let d=qFE({content:e}),s=mSc({content:e,context:i}),o=BFE({json:s,multipart:d,document:r,visitor:{json:([b,g])=>Dor({mediaType:b,mediaTypeObject:g,description:t,document:r,context:i,requestBreadcrumbs:n,source:a,namespace:u}),multipart:([b,g])=>Dor({mediaType:b,mediaTypeObject:g,description:t,document:r,context:i,requestBreadcrumbs:n,source:a,namespace:u}),neither:()=>{}}});if(o)return o;let c=AFE({content:e,context:i});if(c){let[b,g]=c;return Dor({mediaType:b,mediaTypeObject:g,description:t,document:r,context:i,requestBreadcrumbs:n,source:a,namespace:u})}}function BFE({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&&CFE(n.schema,r)?i.multipart(t):i.json(e):n?.schema?i.json(e):a?.schema?i.multipart(t):i.neither()}function Dor({mediaType:e,mediaTypeObject:t,description:r,document:i,context:n,requestBreadcrumbs:a,source:u,namespace:l}){let d=IFE({mediaTypeObject:t});if(SS_({mediaType:e}))return nee.octetStream({description:r,source:u,sdkMethodName:d,contentType:e});let s=wS_({mediaType:e,mediaTypeObject:t}),o=s?.schema,c=s?.encoding;if(o){let O=Kd(o)?PSc(o,i):{id:void 0,schema:o},m=j0(O.schema,!1,n,a,u,l,!1),w=[];if(m.type==="object")for(let E of m.properties){let{isFile:q,isOptional:M,isArray:D,description:C}=Xau({schema:E.schema});if(q){let R=PS_(E.key,c);w.push({key:E.key,schema:Ymi.file({isOptional:M,isArray:D,description:C}),description:C,contentType:R,exploded:!1,encoding:R==null?n.options.defaultFormParameterEncoding:void 0})}else{let R=PS_(E.key,c);w.push({key:E.key,schema:Ymi.json(E.schema),description:void 0,contentType:R,exploded:c?.[E.key]?.explode,encoding:R==null?n.options.defaultFormParameterEncoding:RFE(R)})}}return nee.multipart({name:Kd(o)&&n.getNumberOfOccurrencesForRef(o)===1?O.id:void 0,description:O.schema.description,properties:w,source:u,sdkMethodName:d})}let b=Kau({mediaType:e,mediaTypeObject:t,context:n});if(b){let O=j0(b.schema,!1,n,a,u,l,!0);return nee.json({description:void 0,schema:O,contentType:b.contentType,fullExamples:b.examples,additionalProperties:!Kd(b.schema)&&MKn(b.schema.additionalProperties,n.options),source:u,sdkMethodName:d})}let g=jS_({mediaType:e,mediaTypeObject:t,context:n});if(g!=null&&g.schema!=null){let O=j0(g.schema,!1,n,a,u,l,!1);return nee.formUrlEncoded({schema:O,description:r,contentType:g.contentType,source:u,fullExamples:g.examples,additionalProperties:!1,sdkMethodName:d})}}function IFE({mediaTypeObject:e}){return of(e,Kf.SDK_METHOD_NAME)}var zFE={"application/json":"json"};function RFE(e){return e?zFE[e]:void 0}function PSc(e,t){if(!e.$ref.startsWith(nan))throw new Error(`Failed to resolve schema reference because of unsupported prefix: ${e.$ref}`);let r=YNi(e);if(r==null)throw new Error(`Failed to resolve schema reference because missing schema id: ${e.$ref}`);let i=t.components?.schemas?.[r];if(i==null)throw new Error(`Failed to resolve schema reference because missing: ${e.$ref}`);return Kd(i)?PSc(i,t):{id:r,schema:i}}function Xau({schema:e,isOptional:t,isArray:r,description:i}){return NFE(e)?Xau({schema:e.value,isOptional:!0,isArray:r,description:e.description}):FFE(e)?Xau({schema:e.value,isOptional:t,isArray:r,description:e.description}):LFE(e)?Xau({schema:e.value,isOptional:t,isArray:!0,description:e.description}):xFE(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 xFE(e){return e.type==="primitive"&&e.schema.type==="string"&&e.schema.format==="binary"}function NFE(e){return e.type==="optional"}function FFE(e){return e.type==="nullable"}function LFE(e){return e.type==="array"}function PS_(e,t){return t?.[e]?.contentType}var jSc={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"},DS_=new Set(Object.values(jSc));var UFE=["200","201","202","204"];function MS_({operationContext:e,responses:t,context:r,responseBreadcrumbs:i,responseStatusCode:n,streamFormat:a,source:u}){if(t==null)return{value:void 0,errors:{}};let l=VFE({responses:t,context:r,source:u,namespace:r.namespace}),d=!1,s;for(let o of n!=null?[n]:UFE){let c=t[o];c!=null&&(d=!0,s==null&&(s=ES_({operationContext:e,response:c,context:r,responseBreadcrumbs:i,streamFormat:a,source:u,namespace:r.namespace,statusCode:typeof o=="string"?parseInt(o):o})))}if(s==null&&!d&&t.default!=null&&(s=ES_({operationContext:e,response:t.default,context:r,responseBreadcrumbs:i,streamFormat:a,source:u,namespace:r.namespace})),s!=null)switch(s.type){case"json":return{value:s,errors:l};case"streamingJson":case"streamingSse":return{value:s,errors:l};case"bytes":case"file":case"text":case"streamingText":return{value:s,errors:l};default:So(s)}return{value:void 0,errors:l}}function ES_({operationContext:e,streamFormat:t,response:r,context:i,responseBreadcrumbs:n,source:a,namespace:u,statusCode:l}){let d=Kd(r)?i.resolveResponseReference(r):r;if(d.content!=null&&Object.entries(d.content).find(([b,g])=>{if(g.schema==null)return!1;let O=Kd(g.schema)?i.resolveSchemaReference(g.schema):g.schema;return O.type==="string"&&O.format==="binary"}))return i.options.useBytesForBinaryResponse&&t==null?iB.bytes({description:d.description,source:a,statusCode:l}):iB.file({description:d.description,source:a,statusCode:l});let s=OS_(d.content??{},i);if(s!=null&&t!=null)switch(t){case"json":return iB.streamingJson({statusCode:l,description:d.description,responseProperty:of(e.operation,Kf.RESPONSE_PROPERTY),fullExamples:s.examples,schema:j0(s.schema,!1,i,n,a,u),source:a});case"sse":return iB.streamingSse({description:d.description,responseProperty:void 0,fullExamples:s.examples,schema:j0(s.schema,!1,i,n,a,u),source:a,statusCode:l})}let o=Yau({context:i,content:d.content??{}});if(o){if(t!=null)switch(t){case"json":return iB.streamingJson({description:d.description,responseProperty:void 0,fullExamples:o.examples,schema:j0(o.schema,!1,i,n,a,u),source:a,statusCode:l});case"sse":return iB.streamingSse({description:d.description,responseProperty:void 0,fullExamples:o.examples,schema:j0(o.schema,!1,i,n,a,u),source:a,statusCode:l})}return iB.json({description:d.description,schema:j0(o.schema,!1,i,n,a,u),responseProperty:of(e.operation,Kf.RESPONSE_PROPERTY),fullExamples:o.examples,source:a,statusCode:l})}for(let[c,b]of Object.entries(d.content??{})){let g=hq.parse(c);if(g!=null){if(g.isOctetStream()||g.isPDF()||g.isAudio()||g.isImage()||g.isVideo()||g.isMultiPartMixed())return iB.file({description:d.description,source:a,statusCode:l});if(g.isPlainText()){let O=b.schema;if(O==null)return iB.text({description:d.description,source:a,statusCode:l});let m=Kd(O)?i.resolveSchemaReference(O):O;return m.type==="string"&&m.format==="byte"?iB.file({description:d.description,source:a,statusCode:l}):iB.text({description:d.description,source:a,statusCode:l})}}}}function VFE({responses:e,context:t,source:r,namespace:i}){let n={};for(let[a,u]of Object.entries(e)){if(a==="default")continue;let l=parseInt(a);if(l<400||l>600)continue;let d=Kd(u)?t.resolveResponseReference(u):u,s=mS_(d.content??{},t),o=jSc[l];if(o==null){t.logger.warn(`No error name found for status code ${a}`);continue}n[l]={statusCode:l,nameOverride:void 0,generatedName:o,description:d.description,schema:j0(s?.schema??{},!1,t,[o,"Body"],r,i),fullExamples:s?.examples,source:r}}return n}function rPi({operationContext:e,context:t,responseStatusCode:r,suffix:i,streamFormat:n,source:a}){let{document:u,operation:l,path:d,method:s,baseBreadcrumbs:o}=e,c=of(l,Kf.IDEMPOTENT),b=of(l,[Kf.REQUEST_NAME_V1,Kf.REQUEST_NAME_V2]),g=[...o,"Request"],O=Jau({parameters:[...e.pathItemParameters,...e.operationParameters],context:t,requestBreadcrumbs:g,path:d,httpMethod:s,source:a}),m=/{([^}]+)}/g,E=[...d.matchAll(m)].map(I=>I[1]).filter(I=>!O.pathParameters.some(L=>L.name===I));if(E.length>0)for(let I of E)O.pathParameters.push({name:I??"",variableReference:void 0,parameterNameOverride:void 0,availability:void 0,source:a,schema:Al.primitive({schema:ap.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});let q=(()=>{if(e.method==="GET")return[void 0];if(!l.requestBody)return[void 0];let I=Kd(l.requestBody)?t.resolveRequestBodyReference(l.requestBody):l.requestBody,L=Object.values(I.content).every(Y=>WFE({mediaTypeObject:Y})!=null),V=[];if(L)return V.push(...Object.entries(I.content).map(([Y,K])=>{let X=Dor({mediaType:Y,mediaTypeObject:K,description:I.description,document:u,context:new aan({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:g,source:a,namespace:t.namespace});return AS_({context:t,convertedParameters:O})&&X!=null&&(X.type==="json"||X.type==="formUrlEncoded")&&X.schema.type!=="object"&&l.requestBody!=null?X=Dor({mediaType:Y,mediaTypeObject:K,description:I.description,document:u,context:t,requestBreadcrumbs:[...g,"Body"],source:a,namespace:t.namespace}):l.requestBody!=null&&(X=Dor({mediaType:Y,mediaTypeObject:K,description:I.description,document:u,context:t,requestBreadcrumbs:[...g],source:a,namespace:t.namespace})),X}).filter(Y=>Y!=null)),V.length===0?[void 0]:V;{let Y=Zau({content:I.content,description:I.description,document:u,context:new aan({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:g,source:a,namespace:t.namespace});return AS_({context:t,convertedParameters:O})&&Y!=null&&(Y.type==="json"||Y.type==="formUrlEncoded")&&Y.schema.type!=="object"&&l.requestBody!=null?Y=Zau({content:I.content,description:I.description,document:u,context:t,requestBreadcrumbs:[...g,"Body"],source:a,namespace:t.namespace}):l.requestBody!=null&&(Y=Zau({content:I.content,description:I.description,document:u,context:t,requestBreadcrumbs:[...g],source:a,namespace:t.namespace})),[Y]}})(),M=[...o,"Response"],D=MS_({operationContext:e,streamFormat:n,responses:l.responses,context:t,responseBreadcrumbs:M,responseStatusCode:r,source:a}),C=vS_(l),R=yS_(e,l,t),G=of(l,Kf.SERVER_NAME_V2);return q.map(I=>({summary:l.summary,internal:of(l,JH.INTERNAL),idempotent:c,audiences:of(l,Kf.AUDIENCES)??[],operationId:l.operationId!=null&&i!=null?l.operationId+"_"+i:l.operationId,tags:t.resolveTagsToTagIds(l.tags),namespace:t.namespace,sdkName:HFE({operationContext:e,request:I}),pathParameters:O.pathParameters,queryParameters:O.queryParameters,headers:O.headers,requestNameOverride:b??void 0,generatedRequestName:Q8(g,t.options.preserveSchemaIds),request:I,response:D.value,errors:D.errors,servers:G!=null?[{name:G,url:void 0,audiences:void 0}]:(l.servers??[]).map(L=>Qau(L)),description:l.description,authed:$FE(l,u),availability:C,method:s,path:d,examples:R,pagination:e.pagination,source:a}))}function WFE({mediaTypeObject:e}){return of(e,Kf.SDK_METHOD_NAME)}function HFE({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 $FE(e,t){return e.security!=null?Object.keys(e.security).length>0:t.security!=null?Object.keys(t.security).length>0:!1}function AS_({context:e,convertedParameters:t}){return e.options.inlinePathParameters&&t.pathParameters.length>0||t.queryParameters.length>0||t.headers.length>0}function TS_({operationContext:e,context:t,asyncExtension:r,source:i}){let{operation:n,pathItemParameters:a,operationParameters:u}=e,l=r.discriminant.name,d=r.discriminant.value,s=r["response-status-code"],o=qS_({context:t,headerToIgnore:l,parameters:a}),c=qS_({context:t,headerToIgnore:l,parameters:u}),b=rPi({operationContext:{...e,pathItemParameters:o,operationParameters:c,operation:{...n,responses:Object.fromEntries(Object.entries(n.responses).filter(([O])=>parseInt(O)!==s))}},context:t,streamFormat:void 0,source:i}),g=rPi({operationContext:{...e,pathItemParameters:o,operationParameters:c,baseBreadcrumbs:[...e.baseBreadcrumbs,"async"]},context:t,suffix:"async",responseStatusCode:s,streamFormat:void 0,source:i});return g.forEach(O=>{O.headers.push({name:l,schema:Al.literal({nameOverride:void 0,generatedName:Q8([l],t.options.preserveSchemaIds),title:void 0,description:void 0,availability:void 0,value:Kz.string(d),namespace:void 0,groupName:void 0}),description:void 0,parameterNameOverride:void 0,env:void 0,availability:void 0,source:i})}),{sync:b,async:g}}function qS_({context:e,headerToIgnore:t,parameters:r}){return r.filter(i=>{let n=Kd(i)?e.resolveParameterReference(i):i;return!(n.in==="header"&&n.name===t)})}var wSc="stream";function zS_({operationContext:e,context:t,streamingExtension:r}){switch(r.type){case"stream":return{streaming:rPi({operationContext:e,context:t,streamFormat:r.format,source:t.source}),nonStreaming:[]};case"streamCondition":{let i=CS_({context:t,operation:e.operation,streamingExtension:r,isStreaming:!0});if(i?.schemaReference!=null){let s=YNi(i.schemaReference);s!=null&&t.excludeSchema(s)}let n=BS_({operation:e.operation,response:r.responseStream}),a=rPi({operationContext:{...e,sdkMethodName:e.sdkMethodName!=null?{groupName:e.sdkMethodName.groupName,methodName:e.sdkMethodName.methodName+"_"+wSc}:void 0,operation:{...e.operation,description:r.streamDescription??e.operation.description,requestBody:i?.requestBody,responses:n},baseBreadcrumbs:[...e.baseBreadcrumbs,wSc]},context:t,streamFormat:r.format,suffix:wSc,source:t.source});a.forEach(s=>{s.examples=s.examples.filter(o=>IS_(o,t)!==!1)});let u=CS_({context:t,operation:e.operation,streamingExtension:r,isStreaming:!1}),l=BS_({operation:e.operation,response:r.response}),d=rPi({streamFormat:void 0,operationContext:{...e,operation:{...e.operation,requestBody:u?.requestBody,responses:l}},context:t,source:t.source});return d.forEach(s=>{s.examples=s.examples.filter(o=>IS_(o,t)!==!0)}),{streaming:a,nonStreaming:d}}default:So(r)}}function CS_({context:e,operation:t,streamingExtension:r,isStreaming:i}){if(t.requestBody==null)return;let n=Kd(t.requestBody)?e.resolveRequestBodyReference(t.requestBody):t.requestBody,a=Yau({content:n.content,context:e});if(a==null)return;let u=Kd(a.schema)?e.resolveSchemaReference(a.schema):a.schema;if(u.allOf==null&&u.properties==null)return;let l=u.properties?.[r.streamConditionProperty];l!=null&&Kd(l)&&(l=void 0);let d={...u,properties:{...u.properties,[r.streamConditionProperty]:{type:"boolean","x-fern-boolean-literal":i,...l??{}}},title:void 0,required:[...u.required??[],r.streamConditionProperty]};return{requestBody:{content:{[hq.APPLICATION_JSON]:{schema:d}}},schemaReference:Kd(a.schema)?a.schema:void 0}}function BS_({operation:e,response:t}){return{...e.responses,200:{description:"",content:{[hq.APPLICATION_JSON]:{schema:t}}}}}function IS_(e,t){return e._visit({unknown:r=>{let i=MF.serialization.ExampleEndpointCallSchema.parse(r);if(i.ok&&i.value.response!=null)return i.value.response.stream!=null},full:()=>{},_other:()=>{}})}function RS_({context:e,operationContext:t,source:r}){let{document:i,operation:n,path:a,method:u,baseBreadcrumbs:l,sdkMethodName:d}=t,s=[...l,"Payload"],o=Jau({parameters:[...t.pathItemParameters,...t.operationParameters],context:e,requestBreadcrumbs:s,path:a,httpMethod:u,source:r});if(n.requestBody==null)return e.logger.error(`Skipping webhook ${u.toUpperCase()} ${a}: Missing a request body`),[];let c=n.operationId;if(c==null)return e.logger.error(`Skipping webhook ${a} because no operation id present`),[];if(u!=="POST"&&u!=="GET")return e.logger.error(`Skipping webhook ${u.toUpperCase()} ${a}: Not POST or GET`),[];let b=Kd(n.requestBody)?e.resolveRequestBodyReference(n.requestBody):n.requestBody;return Object.entries(b.content).map(([g,O])=>Dor({mediaType:g,mediaTypeObject:O,description:b.description,document:i,context:e,requestBreadcrumbs:[...l,"Payload"],source:r,namespace:e.namespace})).filter(g=>g!=null).map(g=>{if(g==null||g.type!=="json"&&g.type!=="formUrlEncoded"){e.logger.error(`Skipping webhook ${a} because non-json and non-formUrlEncoded request body`);return}return{summary:n.summary,audiences:of(n,Kf.AUDIENCES)??[],sdkName:d,namespace:e.namespace,method:u,operationId:c,tags:e.resolveTagsToTagIds(n.tags),headers:o.headers,generatedPayloadName:Q8(s,e.options.preserveSchemaIds),payload:g.schema,description:n.description,examples:GFE(g.fullExamples),source:r}}).filter(g=>g!=null)}function GFE(e){if(e==null)return[];let t=[];for(let r of e){let i=ZNi(r.value);i!=null&&t.push({description:r.description,name:r.name,payload:i})}return t}function SSc({context:e,pathItemContext:t,operation:r,convertToWebhook:i}){let n=of(r,Kf.IGNORE);if(n!=null&&n){e.logger.debug(`${t.method.toUpperCase()} ${t.path} is marked with x-fern-ignore. Skipping.`);return}let a=QFE(r,e),u=sS_(e.document,r),l={...t,sdkMethodName:a,baseBreadcrumbs:JFE({operation:r,sdkMethodName:a,httpMethod:t.method,path:t.path,shouldUseIdiomaticRequestNames:e.options.shouldUseIdiomaticRequestNames}),operation:r,operationParameters:r.parameters??[],pagination:u};if(i)return{type:"webhook",value:RS_({context:e,operationContext:l,source:e.source})};let d=oS_(r);if(d!=null){let c=zS_({context:e,operationContext:l,streamingExtension:d});return c!=null?{type:"streaming",streaming:c.streaming,nonStreaming:c.nonStreaming}:void 0}let s=nS_(r);if(s!=null){let c=TS_({context:e,operationContext:l,asyncExtension:s,source:e.source});return{type:"async",async:c.async,sync:c.sync}}return{type:"http",value:rPi({context:e,operationContext:l,streamFormat:void 0,source:e.source})}}function QFE(e,t){let r=of(e,Kf.SDK_METHOD_NAME),i=of(e,Kf.SDK_GROUP_NAME)??[];if(r!=null){let n=typeof i=="string"?[i]:i;return n=t.resolveGroupName(n),{groupName:n,methodName:r}}}function JFE({sdkMethodName:e,operation:t,httpMethod:r,path:i,shouldUseIdiomaticRequestNames:n}){let a=[];if(e!=null){if(n&&a.push(e.methodName),e.groupName.length>0){let u=e.groupName[e.groupName.length-1];u!=null&&a.push(typeof u=="string"?u:u.name)}n||a.push(e.methodName)}else t.operationId!=null?a.push(t.operationId):a.push(S_(`${r}_${i.split("/").join("_")}`));return a}function xS_(e,t,r,i){let n=[],a=FS_(t),u={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let l of a){if(i.filter.skipEndpoint({method:l.method,path:e})){i.logger.debug(`Skipping endpoint "${l.method} ${e}"`);continue}let d=KFE({operation:l.operation}),s=SSc({context:i,pathItemContext:{...u,method:l.method},operation:l.operation,convertToWebhook:d});s&&n.push(s)}return n}function NS_(e,t,r,i){let n=[],a=FS_(t),u={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let l of a){if(i.filter.skipEndpoint({method:l.method,path:e})){i.logger.debug(`Skipping endpoint "${l.method} ${e}"`);continue}let d=SSc({context:i,pathItemContext:{...u,method:l.method},operation:l.operation,convertToWebhook:!0});d&&n.push(d)}return n}function FS_(e){let t=[];return e.get!=null&&t.push({method:QH.Get,operation:e.get}),e.post!=null&&t.push({method:QH.Post,operation:e.post}),e.put!=null&&t.push({method:QH.Put,operation:e.put}),e.delete!=null&&t.push({method:QH.Delete,operation:e.delete}),e.patch!=null&&t.push({method:QH.Patch,operation:e.patch}),e.head!=null&&t.push({method:QH.Head,operation:e.head}),t}function KFE({operation:e}){return of(e,[Kf.WEBHOOK])??!1}function LS_(e){let t=of(e,Kf.BASIC_AUTH_USERNAME_VARIABLE_NAME),r=of(e,Kf.BASIC_AUTH_PASSWORD_VARIABLE_NAME);return{usernameVariable:t,passwordVariable:r}}function US_(e){return of(e,Kf.FERN_BASIC_AUTH)}function DSc(e,t){if(Kd(e))throw new Error(`Converting referenced security schemes is unsupported: ${JSON.stringify(e)}`);return YFE(e,t)}function YFE(e,t){if(e.type==="apiKey"&&e.in==="header"){let r=of(e,JH.BEARER_FORMAT),i=of(e,Kf.FERN_HEADER_AUTH);return JL.header({headerName:e.name,prefix:r!=null?"Bearer":i?.prefix,headerVariableName:i?.name??of(e,Kf.HEADER_VARIABLE_NAME),headerEnvVar:i?.env})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="bearer"){let r=of(e,Kf.FERN_BEARER_TOKEN);return JL.bearer({tokenVariableName:r?.name??of(e,Kf.BEARER_TOKEN_VARIABLE_NAME),tokenEnvVar:r?.env})}else if(e.type==="http"&&e.scheme?.toLowerCase()==="basic"){let r=US_(e),i=LS_(e);return JL.basic({usernameVariableName:r?.username?.name??i.usernameVariable,usernameEnvVar:r?.username?.env,passwordVariableName:r?.password?.name??i.passwordVariable,passwordEnvVar:r?.password?.env})}else{if(e.type==="openIdConnect")return JL.bearer({tokenVariableName:void 0,tokenEnvVar:void 0});if(e.type==="oauth2")return JL.oauth({scopesEnum:XFE(e,t)})}}function XFE(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=KNi({nameOverride:void 0,generatedName:"OauthScope",title:void 0,enumValues:Object.keys(r),fernEnum:Object.fromEntries(Object.entries(r).map(([a,u])=>[a,{description:u}])),_default:void 0,description:void 0,availability:void 0,enumVarNames:void 0,wrapAsNullable:!1,namespace:void 0,groupName:void 0,context:void 0,source:t,inline:void 0}),n=iA(i);if(n.type==="enum")return n}}function VS_(e){return of(e,Kf.BASE_PATH)}var ZFE=Su.record(Su.string(),Su.object({summary:Su.string().optional(),description:Su.string().optional()}));function WS_({document:e,context:t}){return J5a(e,Kf.GROUPS,ZFE,t.logger)}function HS_({context:e,document:t}){return of(t,Kf.FERN_VERSION)??void 0}function $S_(e){let t=of(e,Kf.FERN_GLOBAL_HEADERS),r=[];for(let i of t??[])r.push({...i,schema:i.type!=null?K5a({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 GS_(e){let t=of(e,Kf.FERN_IDEMPOTENCY_HEADERS),r=[];for(let i of t??[])r.push({...i,schema:i.type!=null?K5a({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 QS_(e,t){let r=of(e,Kf.SDK_VARIABLES);return r==null?{}:Object.fromEntries(Object.entries(r).map(([i,n])=>{if(n.type==="string")return[i,{nameOverride:void 0,generatedName:Q8([i],t),title:n.title,schema:jw.string({default:qKn(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 kFE="webhooks";function JS_(e){return of(e,kFE)??{}}var kau=class extends zKn{nonRequestReferencedSchemas=new Set;twoOrMoreRequestsReferencedSchemas=new Set;singleRequestReferencedSchemas=new Set;discriminatedUnionReferences={};discriminatedUnionMetadata={};schemasToExclude=new Set;constructor({document:t,taskContext:r,authHeaders:i,options:n,source:a,namespace:u}){super({document:t,taskContext:r,authHeaders:i,options:n,source:a,namespace:u})}getDummy(){return new aan({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 KS_(e){return of(e,Kf.RESOLUTIONS)}function YS_({openapi:e}){let t=KS_(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=e3E({openapi:e,schemaReference:a,schemaName:i.name}),e=XS_({openapi:e,replaceReference:a,schemaReference:n,replacedReferences:r}),r={...r,...Object.fromEntries(i.resolutions.map(u=>[n,u]))}}return e}function e3E({openapi:e,schemaReference:t,schemaName:r}){let i=t.replace("#/","").split("/").map(a=>a.replaceAll("~1","/")),n=e;for(let a of i){let u=n[a];if(u==null)return e;n=u}return e.components==null&&(e.components={}),e.components.schemas==null&&(e.components.schemas={}),e.components.schemas[r]=n,e}function XS_({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 XS_({openapi:e,replaceReference:t,schemaReference:s,replacedReferences:{}})}}let a=t.replace("#/","").split("/").map(d=>d.replaceAll("~1","/")),u=e;for(let d of a.slice(0,-1)){let s=u[d];if(s==null)return e;u=s}let l=a[a.length-1];return l==null||(u[l]={$ref:r}),e}function kS_({openApi:e,taskContext:t,options:r,source:i,namespace:n}){e=YS_({openapi:e});let a=Object.fromEntries(Object.entries(e.components?.securitySchemes??{}).map(([I,L])=>DSc(L,i)==null?[]:[I,DSc(L,i)])),u=new Set(...Object.entries(a).map(([I,L])=>L.type==="basic"||L.type==="bearer"?"Authorization":L.type==="header"?L.headerName:null)),l=QS_(e,r.preserveSchemaIds),d=$S_(e),s=GS_(e),o=r.audiences??[],c=[],b=[],g=new kau({document:e,taskContext:t,authHeaders:u,options:r,source:i,namespace:n});g.filter.hasEndpoints()&&t.logger.debug("Endpoint filter applied..."),Object.entries(e.paths??{}).forEach(([I,L])=>{if(L==null)return;t.logger.debug(`Converting path ${I}`);let V=xS_(I,L,e,g);for(let Y of V){let K=ZS_({operation:Y});if(!(o.length>0&&!o.some(X=>K.includes(X))))switch(Y.type){case"async":c.push(...Y.sync),c.push(...Y.async);break;case"http":c.push(...Y.value);break;case"streaming":c.push(...Y.streaming),Y.nonStreaming&&c.push(...Y.nonStreaming);break;case"webhook":b.push(...Y.value);break;default:So(Y)}}}),Object.entries(JS_(e)).forEach(([I,L])=>{if(L==null)return;t.logger.debug(`Converting path ${I}`);let V=NS_(I,L,e,g);for(let Y of V){let K=ZS_({operation:Y});o.length>0&&!o.some(X=>K.includes(X))||b.push(...Y.value)}});let O=Object.fromEntries(Object.entries(e.components?.schemas??{}).map(([I,L])=>{let V=of(L,Kf.SDK_NAMESPACE);if(!Kd(L)){let Y=of(L,Kf.IGNORE);if(Y!=null&&Y)return[];if(DS_.has(I))return[I,j0({...L,"x-fern-type-name":`${I}Body`},!1,g,[I],i,V??n)]}return[I,j0(L,!1,g,[I],i,V??n)]}).filter(I=>I.length>0)),m=t3E(O,g,i),w=r3E(m,g),E={};for(let[I,L]of Object.entries(w)){let V=iA(L);g.isSchemaExcluded(I)||(E[I]=V,t.logger.debug(`Converted schema ${I}`))}let q=new kNi(w,g.nonRequestReferencedSchemas,g),M=b.map(I=>{let V=I.examples;if(!r.disableExamples&&V.length===0){let Y=q.buildExample({schema:I.payload,exampleId:void 0,example:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});Y!=null&&(V=[{name:void 0,description:void 0,payload:Y}])}return{...I,payload:iA(I.payload),examples:V}}),D=new Uau(w,g,d),C=c.map(I=>{let L=I.examples,V=L;if(!r.disableExamples&&(L.length===0||L.every(X5a))){let X=D.buildEndpointExample(I);X.length>0&&(V=[...X,...L.filter(oe=>!X5a(oe))])}let Y=I.request,K=I.response;return{...I,request:Y?.type==="json"||Y?.type==="formUrlEncoded"?{...Y,schema:iA(Y.schema)}:Y,response:K?.type==="json"?{...K,schema:iA(K.schema)}:K,queryParameters:I.queryParameters.map(X=>({description:X.description,name:X.name,schema:iA(X.schema),parameterNameOverride:X.parameterNameOverride,availability:X.availability,source:X.source})),pathParameters:I.pathParameters.map(X=>({description:X.description,name:X.name,schema:iA(X.schema),parameterNameOverride:X.parameterNameOverride,variableReference:X.variableReference,availability:X.availability,source:X.source})),headers:I.headers.map(X=>({description:X.description,name:X.name,schema:iA(X.schema),parameterNameOverride:X.parameterNameOverride,env:X.env,availability:X.availability,source:X.source})),examples:V,errors:_d(I.errors,X=>{let oe=X.fullExamples?.map(pe=>{let de=ZNi(pe.value);if(de!=null)return{name:pe.name,description:pe.description,example:de}}).filter(iv);if(oe?.length===0){let pe=q.buildExample({schema:X.schema,example:void 0,exampleId:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});pe!=null&&oe.push({name:void 0,description:void 0,example:pe})}return{generatedName:X.generatedName,nameOverride:X.nameOverride,schema:iA(X.schema),description:X.description,source:X.source,examples:oe}})}}),R=WS_({document:e,context:g});return{apiVersion:HS_({context:g,document:e}),basePath:VS_(e),title:e.info.title??"",description:e.info.description,groups:Object.fromEntries(Object.entries(R??{}).map(([I,L])=>[I,{summary:L.summary??void 0,description:L.description??void 0}])),servers:(e.servers??[]).map(I=>Qau(I)),websocketServers:[],tags:{tagsById:Object.fromEntries((e.tags??[]).map(I=>[I.name,{id:I.name,description:I.description}])),orderedTagIds:e.tags?.map(I=>I.name)},endpoints:C,webhooks:M,channels:{},groupedSchemas:BKn(n,E),securitySchemes:a,hasEndpointsMarkedInternal:C.some(I=>I.internal),nonRequestReferencedSchemas:g.getReferencedSchemas(),variables:l,globalHeaders:d,idempotencyHeaders:s}}function t3E(e,t,r){let i={};for(let[n,a]of Object.entries(e)){if(a.type!=="object"){i[n]=a;continue}let u={$ref:`#/components/schemas/${n}`},l=t.getReferencesFromDiscriminatedUnion(u);if(l==null){i[n]=a;continue}let d={...a,type:"object",properties:a.properties.filter(o=>!l.discriminants.has(o.key)),allOfPropertyConflicts:a.allOfPropertyConflicts.filter(o=>!l.discriminants.has(o.propertyKey)),source:r};i[n]=d;let s=eD_({schema:a,schemas:e});for(let o of[...new Set(s)]){let c=i[o]??e[o];c==null||c.type!=="object"||(i[o]={...c,type:"object",properties:c.properties.filter(b=>!l.discriminants.has(b.key)),allOfPropertyConflicts:c.allOfPropertyConflicts.filter(b=>!l.discriminants.has(b.propertyKey))})}}return i}function r3E(e,t){let r={};for(let[i,n]of Object.entries(e)){if(n.type!=="object"){r[i]=n;continue}let a={$ref:`#/components/schemas/${i}`},u=t.getDiscriminatedUnionMetadata(a);if(u==null){r[i]=n;continue}let l=[];for(let s of n.properties)if(u.discriminants.has(s.key)){let o=u.discriminants.get(s.key);o!=null&&l.push({...s,schema:Al.literal({nameOverride:void 0,generatedName:Q8([n.generatedName,o],t.options.preserveSchemaIds),title:void 0,value:Kz.string(o),namespace:void 0,groupName:void 0,description:void 0,availability:n.availability})})}else l.push(s);let d={...n,type:"object",properties:l};r[i]=d}return r}function eD_({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(...eD_({schema:n,schemas:t}))}return r}function eou(e){return[...new Set(e)]}function ZS_({operation:e}){let t=[];switch(e.type){case"async":t=eou(e.async.flatMap(r=>r.audiences));break;case"http":t=eou(e.value.flatMap(r=>r.audiences));break;case"streaming":t=eou(e.streaming.flatMap(r=>r.audiences));break;case"webhook":t=eou(e.value.flatMap(r=>r.audiences));break;default:So(e)}return t}function oan({context:e,documents:t,options:r}){let i={apiVersion:void 0,title:void 0,description:void 0,basePath:void 0,servers:[],websocketServers:[],tags:{tagsById:{},orderedTagIds:void 0},hasEndpointsMarkedInternal:!1,endpoints:[],webhooks:[],channels:{},groupedSchemas:{rootSchemas:{},namespacedSchemas:{}},variables:{},nonRequestReferencedSchemas:new Set,securitySchemes:{},globalHeaders:[],idempotencyHeaders:[],groups:{}};for(let n of t){let a=n.source!=null?n.source:nK.openapi({file:"<memory>"});switch(n.type){case"openapi":{let u=kS_({taskContext:e,openApi:n.value,options:gQt({options:n.settings,overrides:r}),source:a,namespace:n.namespace});i=n3E(i,u);break}case"asyncapi":{let u=iS_({document:n.value,taskContext:e,options:gQt({options:n.settings,overrides:r}),source:a,asyncApiOptions:i3E({options:n.settings}),namespace:n.namespace});u.servers!=null&&(i.websocketServers=[...i.websocketServers,...u.servers.map(l=>({...l,audiences:void 0,description:void 0}))]),u.channels!=null&&(i.channels={...i.channels,...u.channels}),u.groupedSchemas!=null&&(i.groupedSchemas=tD_(i.groupedSchemas,u.groupedSchemas)),u.basePath!=null&&(i.basePath=u.basePath);break}default:So(n)}}return i}function i3E({options:e,overrides:t}){return{naming:t?.naming??e?.asyncApiNaming??w1_.naming}}function n3E(e,t){return{apiVersion:e.apiVersion??t.apiVersion,title:e.title??t.title,description:e.description??t.description,basePath:e.basePath??t.basePath,servers:[...e.servers,...t.servers],websocketServers:[...e.websocketServers,...t.websocketServers],tags:{tagsById:{...e.tags.tagsById,...t.tags.tagsById},orderedTagIds:e.tags.orderedTagIds==null&&t.tags.orderedTagIds==null?void 0:[...e.tags.orderedTagIds??[],...t.tags.orderedTagIds??[]]},hasEndpointsMarkedInternal:e.hasEndpointsMarkedInternal||t.hasEndpointsMarkedInternal,endpoints:[...e.endpoints,...t.endpoints],webhooks:[...e.webhooks,...t.webhooks],channels:{...e.channels,...t.channels},groupedSchemas:tD_(e.groupedSchemas,t.groupedSchemas),variables:{...e.variables,...t.variables},nonRequestReferencedSchemas:new Set([...e.nonRequestReferencedSchemas,...t.nonRequestReferencedSchemas]),securitySchemes:{...e.securitySchemes,...t.securitySchemes},globalHeaders:e.globalHeaders!=null?[...e.globalHeaders,...t.globalHeaders??[]]:void 0,idempotencyHeaders:e.idempotencyHeaders!=null?[...e.idempotencyHeaders,...t.idempotencyHeaders??[]]:void 0,groups:{...e.groups,...t.groups}}}function tD_(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 Dz_=ui(Ycu(),1),Xcu={config:new Dz_.Config({apis:{},styleguide:{plugins:[lSc],rules:{struct:"warn"}}},void 0),dereference:!1,removeUnusedComponents:!1,keepUrlRefs:!0};function CYn(e){if(e.settings==null&&e.raw?.api?.auth==null)return;let t={detectGlobalHeaders:!0};return e.settings?.unions==="v1"&&(t.discriminatedUnionV2=!0),e.raw?.api?.auth!=null&&(t.auth=e.raw?.api?.auth),t}function nLa(e){return e.swagger!=null}function Fqc(e){return e.openapi!=null}function aLa({options:e,overrides:t}={}){return{...gQt({options:e,overrides:t}),...R5a({options:e,overrides:t})}}function EFi(e,t={}){return{...Object.fromEntries(B3(e.namedDefinitionFiles).map(([r,i])=>[r,{...i,defaultUrl:t.defaultURL}])),...B3(e.importedDefinitions).reduce((r,[i,n])=>({...r,...Dza(EFi(n.definition,{defaultURL:n.url}),(a,u)=>PF(i,fy.of(u)))}),{})}}function oLa(e,t={}){return{...Object.fromEntries(B3(e.packageMarkers).map(([r,i])=>[r,{...i,defaultUrl:t.defaultURL}])),...B3(e.importedDefinitions).reduce((r,[i,n])=>({...r,...Dza(oLa(n.definition,{defaultURL:n.url}),(a,u)=>PF(i,fy.of(u)))}),{})}}function OPi(e){return{...oLa(e),...EFi(e)}}function gue(e,t){return OPi(e.definition)[t]?.contents}function m7(e,t){for(let[r,i]of B3(OPi(e.definition)))t(r,i.contents,{isPackageMarker:lki(r)===fS,defaultUrl:i.defaultUrl})}function Can(e,t){for(let[r,i]of B3(oLa(e.definition)))t(r,i.contents)}function p7e({breadcrumbs:e=[],title:t,subtitle:r}){let i=[];return e.length>0&&i.push(Ds.blue(e.join(" -> "))),i.push(t),r!=null&&i.push(Ds.dim(r)),i.join(`
1960
1960
  `)}var Ez_={None:"none",Header:"header"};var Olu={};Po(Olu,{ConjureAliasDeclaration:()=>nlu,ConjureArgument:()=>vlu,ConjureArgumentWithParamType:()=>ylu,ConjureAuthDefinition:()=>RYn,ConjureAuthDefinitionType:()=>_lu,ConjureDefinitions:()=>dlu,ConjureEndpointDefinition:()=>blu,ConjureEnumDeclaration:()=>llu,ConjureEnumVariant:()=>clu,ConjureEnumWithDocs:()=>slu,ConjureObjectDeclaration:()=>ulu,ConjureParamType:()=>hlu,ConjurePrimitive:()=>ilu,ConjureService:()=>glu,ConjureServiceName:()=>rlu,ConjureType:()=>qFi,ConjureTypeDeclaration:()=>flu,ConjureTypeReference:()=>TFi,ConjureTypeWithDocs:()=>alu,ConjureTypes:()=>plu,ConjureUnionDeclaration:()=>olu,DefinitionFile:()=>tR_,WithDocs:()=>Ror,commons:()=>Hqc,conjure:()=>$qc,services:()=>Gqc,types:()=>Qqc});var Hqc={};Po(Hqc,{WithDocs:()=>Ror});var lp={};Po(lp,{JsonError:()=>BYn,ParseError:()=>IYn,any:()=>Vz_,bigint:()=>Az_,boolean:()=>Wz_,booleanLiteral:()=>Uz_,date:()=>qz_,discriminant:()=>Zz_,enum_:()=>kcu,getObjectLikeUtils:()=>qQt,getObjectUtils:()=>Ban,getSchemaUtils:()=>jT,isProperty:()=>AFi,lazy:()=>Tz_,lazyObject:()=>Nz_,list:()=>tlu,number:()=>Hz_,object:()=>elu,objectWithoutOptionalProperties:()=>xz_,optional:()=>Lqc,property:()=>Bz_,record:()=>Jz_,set:()=>Kz_,string:()=>$z_,stringLiteral:()=>Lz_,transform:()=>Uqc,undiscriminatedUnion:()=>Xz_,union:()=>eR_,unknown:()=>Gz_,withParsedProperties:()=>Wqc});var ew={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 HA(e,t){return`Expected ${t}. Received ${drM(e)}.`}function drM(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 ZL(e){return{...e,json:Mz_(e.json),parse:Mz_(e.parse)}}function Mz_(e){return(t,r)=>{let i=e(t,r),{skipValidation:n=!1}=r??{};return!i.ok&&n?(console.warn(["Failed to validate.",...i.errors.map(a=>" - "+(a.path.length>0?`${a.path.join(".")}: ${a.message}`:a.message))].join(`
1961
1961
  `)),{ok:!0,value:t}):i}}function Zcu(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var BYn=class e extends Error{errors;constructor(t){super(t.map(Zcu).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var IYn=class e extends Error{errors;constructor(t){super(t.map(Zcu).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function jT(e){return{optional:()=>Lqc(e),transform:t=>Uqc(e,t),parseOrThrow:(t,r)=>{let i=e.parse(t,r);if(i.ok)return i.value;throw new IYn(i.errors)},jsonOrThrow:(t,r)=>{let i=e.json(t,r);if(i.ok)return i.value;throw new BYn(i.errors)}}}function Lqc(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:()=>ew.OPTIONAL};return{...t,...jT(t)}}function Uqc(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,...jT(r)}}function Az_(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:HA(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:HA(t,"bigint")}]},getType:()=>ew.BIGINT};return{...ZL(e),...jT(e)}}var prM=/^([+-]?\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 qz_(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:HA(t,"string")}]}:prM.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:HA(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:HA(t,"Date object")}]},getType:()=>ew.DATE};return{...ZL(e),...jT(e)}}function _K(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{...ZL(r),...jT(r)}}}function kcu(e){let t=new Set(e);return _K(ew.ENUM,(i,{allowUnrecognizedEnumValues:n,breadcrumbsPrefix:a=[]}={})=>typeof i!="string"?{ok:!1,errors:[{path:a,message:HA(i,"string")}]}:!t.has(i)&&!n?{ok:!1,errors:[{path:a,message:HA(i,"enum")}]}:{ok:!0,value:i})()}function Tz_(e){let t=Vqc(e);return{...t,...jT(t)}}function Vqc(e){return{parse:(t,r)=>zYn(e).parse(t,r),json:(t,r)=>zYn(e).json(t,r),getType:()=>zYn(e).getType()}}function zYn(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function uLa(e){return Object.entries(e)}function sLa(e,t){let r=new Set(t);return Object.entries(e).reduce((i,[n,a])=>(r.has(n)&&(i[n]=a),i),{})}function MFi(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 cLa(e){return Object.keys(e)}function Cz_(e,t){let r=[],i=[];for(let n of e)t(n)?r.push(n):i.push(n);return[r,i]}function qQt(e){return{withParsedProperties:t=>Wqc(e,t)}}function Wqc(e,t){let r={parse:(i,n)=>{let a=e.parse(i,n);if(!a.ok)return a;let u=Object.entries(t).reduce((l,[d,s])=>({...l,[d]:typeof s=="function"?s(a.value):s}),{});return{ok:!0,value:{...a.value,...u}}},json:(i,n)=>{if(!MFi(i))return{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:HA(i,"object")}]};let a=new Set(Object.keys(t)),u=sLa(i,Object.keys(i).filter(l=>!a.has(l)));return e.json(u,n)},getType:()=>e.getType()};return{...r,...jT(r),...qQt(r)}}function Bz_(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function AFi(e){return e.isProperty}function elu(e){let t={_getRawProperties:()=>Object.entries(e).map(([r,i])=>AFi(i)?i.rawKey:r),_getParsedProperties:()=>cLa(e),parse:(r,i)=>{let n={},a=[];for(let[u,l]of uLa(e)){let d=AFi(l)?l.rawKey:u,s=AFi(l)?l.valueSchema:l,o={rawKey:d,parsedKey:u,valueSchema:s};n[d]=o,Rz_(s)&&a.push(d)}return Iz_({value:r,requiredKeys:a,getProperty:u=>{let l=n[u];if(l!=null)return{transformedKey:l.parsedKey,transform:d=>l.valueSchema.parse(d,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],u]})}},unrecognizedObjectKeys:i?.unrecognizedObjectKeys,skipValidation:i?.skipValidation,breadcrumbsPrefix:i?.breadcrumbsPrefix,omitUndefined:i?.omitUndefined})},json:(r,i)=>{let n=[];for(let[a,u]of uLa(e)){let l=AFi(u)?u.valueSchema:u;Rz_(l)&&n.push(a)}return Iz_({value:r,requiredKeys:n,getProperty:a=>{let u=e[a];if(u!=null)return AFi(u)?{transformedKey:u.rawKey,transform:l=>u.valueSchema.json(l,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],a]})}:{transformedKey:a,transform:l=>u.json(l,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],a]})}},unrecognizedObjectKeys:i?.unrecognizedObjectKeys,skipValidation:i?.skipValidation,breadcrumbsPrefix:i?.breadcrumbsPrefix,omitUndefined:i?.omitUndefined})},getType:()=>ew.OBJECT};return{...ZL(t),...jT(t),...qQt(t),...Ban(t)}}function Iz_({value:e,requiredKeys:t,getProperty:r,unrecognizedObjectKeys:i="fail",skipValidation:n=!1,breadcrumbsPrefix:a=[]}){if(!MFi(e))return{ok:!1,errors:[{path:a,message:HA(e,"object")}]};let u=new Set(t),l=[],d={};for(let[s,o]of Object.entries(e)){let c=r(s);if(c!=null){u.delete(s);let b=c.transform(o);b.ok?d[c.transformedKey]=b.value:(d[s]=o,l.push(...b.errors))}else switch(i){case"fail":l.push({path:[...a,s],message:`Unexpected key "${s}"`});break;case"strip":break;case"passthrough":d[s]=o;break}}return l.push(...t.filter(s=>u.has(s)).map(s=>({path:a,message:`Missing required key "${s}"`}))),l.length===0||n?{ok:!0,value:d}:{ok:!1,errors:l}}function Ban(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(i,n)=>zz_({extensionKeys:t._getRawProperties(),value:i,transformBase:a=>e.parse(a,n),transformExtension:a=>t.parse(a,n)}),json:(i,n)=>zz_({extensionKeys:t._getParsedProperties(),value:i,transformBase:a=>e.json(a,n),transformExtension:a=>t.json(a,n)}),getType:()=>ew.OBJECT};return{...r,...jT(r),...qQt(r),...Ban(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:()=>ew.OBJECT};return{...t,...jT(t),...qQt(t),...Ban(t)}}}}function zz_({extensionKeys:e,value:t,transformBase:r,transformExtension:i}){let n=new Set(e),[a,u]=Cz_(cLa(t),s=>n.has(s)),l=r(sLa(t,u)),d=i(sLa(t,a));return l.ok&&d.ok?{ok:!0,value:{...l.value,...d.value}}:{ok:!1,errors:[...l.ok?[]:l.errors,...d.ok?[]:d.errors]}}function Rz_(e){return!_rM(e)}function _rM(e){switch(e.getType()){case ew.ANY:case ew.UNKNOWN:case ew.OPTIONAL:return!0;default:return!1}}function xz_(e){return elu(e)}function Nz_(e){let t={...Vqc(e),_getRawProperties:()=>zYn(e)._getRawProperties(),_getParsedProperties:()=>zYn(e)._getParsedProperties()};return{...t,...jT(t),...qQt(t),...Ban(t)}}function tlu(e){let t={parse:(r,i)=>Fz_(r,(n,a)=>e.parse(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),json:(r,i)=>Fz_(r,(n,a)=>e.json(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),getType:()=>ew.LIST};return{...ZL(t),...jT(t)}}function Fz_(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:HA(e,"list"),path:[]}]}}function Lz_(e){return _K(ew.STRING_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:HA(r,`"${e}"`)}]})()}function Uz_(e){return _K(ew.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:HA(r,`${e.toString()}`)}]})()}var Vz_=_K(ew.ANY,e=>({ok:!0,value:e}));var Wz_=_K(ew.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:HA(e,"boolean")}]});var Hz_=_K(ew.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:HA(e,"number")}]});var $z_=_K(ew.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:HA(e,"string")}]});var Gz_=_K(ew.UNKNOWN,e=>({ok:!0,value:e}));function Jz_(e,t){let r={parse:(i,n)=>Qz_({value:i,isKeyNumeric:e.getType()===ew.NUMBER,transformKey:a=>e.parse(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,u)=>t.parse(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${u}`]}),breadcrumbsPrefix:n?.breadcrumbsPrefix}),json:(i,n)=>Qz_({value:i,isKeyNumeric:e.getType()===ew.NUMBER,transformKey:a=>e.json(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,u)=>t.json(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${u}`]}),breadcrumbsPrefix:n?.breadcrumbsPrefix}),getType:()=>ew.RECORD};return{...ZL(r),...jT(r)}}function Qz_({value:e,isKeyNumeric:t,transformKey:r,transformValue:i,breadcrumbsPrefix:n=[]}){return MFi(e)?uLa(e).reduce((a,[u,l])=>{if(l==null)return a;let d=a,s=u;if(t){let g=u.length>0?Number(u):NaN;isNaN(g)||(s=g)}let o=r(s),c=i(l,s);if(d.ok&&o.ok&&c.ok)return{ok:!0,value:{...d.value,[o.value]:c.value}};let b=[];return d.ok||b.push(...d.errors),o.ok||b.push(...o.errors),c.ok||b.push(...c.errors),{ok:!1,errors:b}},{ok:!0,value:{}}):{ok:!1,errors:[{path:n,message:HA(e,"object")}]}}function Kz_(e){let t=tlu(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:HA(i,"Set")}]},getType:()=>ew.SET};return{...ZL(r),...jT(r)}}function Xz_(e){let t={parse:(r,i)=>Yz_((n,a)=>n.parse(r,a),e,i),json:(r,i)=>Yz_((n,a)=>n.json(r,a),e,i),getType:()=>ew.UNDISCRIMINATED_UNION};return{...ZL(t),...jT(t)}}function Yz_(e,t,r){let i=[];for(let[n,a]of t.entries()){let u=e(a,{...r,skipValidation:!1});if(u.ok)return u;for(let l of u.errors)i.push({path:l.path,message:`[Variant ${n}] ${l.message}`})}return{ok:!1,errors:i}}function Zz_(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}function eR_(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,i=typeof e=="string"?e:e.parsedDiscriminant,n=kcu(cLa(t)),a={parse:(u,l)=>kz_({value:u,discriminant:r,transformedDiscriminant:i,transformDiscriminantValue:d=>n.parse(d,{allowUnrecognizedEnumValues:l?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...l?.breadcrumbsPrefix??[],r]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:l?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,s)=>s.parse(d,l),breadcrumbsPrefix:l?.breadcrumbsPrefix}),json:(u,l)=>kz_({value:u,discriminant:i,transformedDiscriminant:r,transformDiscriminantValue:d=>n.json(d,{allowUnrecognizedEnumValues:l?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...l?.breadcrumbsPrefix??[],i]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:l?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,s)=>s.json(d,l),breadcrumbsPrefix:l?.breadcrumbsPrefix}),getType:()=>ew.UNION};return{...ZL(a),...jT(a),...qQt(a)}}function kz_({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:i,getAdditionalPropertiesSchema:n,allowUnrecognizedUnionMembers:a=!1,transformAdditionalProperties:u,breadcrumbsPrefix:l=[]}){if(!MFi(e))return{ok:!1,errors:[{path:l,message:HA(e,"object")}]};let{[t]:d,...s}=e;if(d==null)return{ok:!1,errors:[{path:l,message:`Missing discriminant ("${t}")`}]};let o=i(d);if(!o.ok)return{ok:!1,errors:o.errors};let c=n(o.value);if(c==null)return a?{ok:!0,value:{[r]:o.value,...s}}:{ok:!1,errors:[{path:[...l,t],message:"Unexpected discriminant value"}]};let b=u(s,c);return b.ok?{ok:!0,value:{[r]:d,...b.value}}:b}var Ror=lp.objectWithoutOptionalProperties({docs:lp.string().optional()});var $qc={};Po($qc,{ConjureServiceName:()=>rlu,DefinitionFile:()=>tR_});var rlu=lp.string();var ilu=lp.enum_(["rid","string","safelong","integer","double","boolean"]);var qFi=lp.undiscriminatedUnion([ilu,lp.string()]);var nlu=lp.objectWithoutOptionalProperties({alias:qFi,docs:lp.string().optional()});var alu=lp.objectWithoutOptionalProperties({type:qFi,docs:lp.string().optional()});var TFi=lp.undiscriminatedUnion([qFi,alu]);var olu=lp.objectWithoutOptionalProperties({union:lp.record(lp.string(),TFi)});var ulu=lp.objectWithoutOptionalProperties({fields:lp.record(lp.string(),TFi)});var slu=lp.objectWithoutOptionalProperties({value:lp.string()}).extend(Ror);var clu=lp.undiscriminatedUnion([lp.string(),slu]);var llu=lp.objectWithoutOptionalProperties({values:lp.list(clu)});var flu=lp.undiscriminatedUnion([nlu,olu,ulu,llu]);var dlu=lp.objectWithoutOptionalProperties({objects:lp.record(lp.string(),flu).optional()});var plu=lp.objectWithoutOptionalProperties({conjureImports:lp.property("conjure-imports",lp.record(lp.string(),lp.string()).optional()),definitions:dlu.optional()});var _lu=lp.enum_(["none","header"]);var RYn=lp.undiscriminatedUnion([_lu,lp.string()]);var hlu=lp.enum_(["path","query","body"]);var ylu=lp.objectWithoutOptionalProperties({paramType:lp.property("param-type",hlu),type:lp.string()}).extend(Ror);var vlu=lp.undiscriminatedUnion([lp.string(),ylu]);var blu=lp.objectWithoutOptionalProperties({http:lp.string(),auth:RYn.optional(),args:lp.record(lp.string(),vlu).optional(),returns:TFi.optional()}).extend(Ror);var glu=lp.objectWithoutOptionalProperties({name:lp.string().optional(),package:lp.string().optional(),basePath:lp.property("base-path",lp.string().optional()),defaultAuth:lp.property("default-auth",RYn.optional()),endpoints:lp.record(lp.string(),blu).optional()}).extend(Ror);var tR_=lp.objectWithoutOptionalProperties({types:plu.optional(),services:lp.record(rlu,glu).optional()});var Gqc={};Po(Gqc,{ConjureArgument:()=>vlu,ConjureArgumentWithParamType:()=>ylu,ConjureAuthDefinition:()=>RYn,ConjureAuthDefinitionType:()=>_lu,ConjureEndpointDefinition:()=>blu,ConjureParamType:()=>hlu,ConjureService:()=>glu});var Qqc={};Po(Qqc,{ConjureAliasDeclaration:()=>nlu,ConjureDefinitions:()=>dlu,ConjureEnumDeclaration:()=>llu,ConjureEnumVariant:()=>clu,ConjureEnumWithDocs:()=>slu,ConjureObjectDeclaration:()=>ulu,ConjurePrimitive:()=>ilu,ConjureType:()=>qFi,ConjureTypeDeclaration:()=>flu,ConjureTypeReference:()=>TFi,ConjureTypeWithDocs:()=>alu,ConjureTypes:()=>plu,ConjureUnionDeclaration:()=>olu});var rR_=require("fs/promises");async function iR_(e,t){let r=[];for(let i of await _ae(e,t))r.push(await hrM({relativeFilepath:yT(e,i),absoluteFilepath:i}));return r}async function hrM({relativeFilepath:e,absoluteFilepath:t}){let r=(await(0,rR_.readFile)(t)).toString().replaceAll(/: rid(?:$|\s)/g,`: string
1962
1962
  `).replaceAll("<rid>","<string>").replaceAll("rid>","string>").replaceAll(": safelong",": long").replaceAll("<safelong>","<long>").replaceAll("safelong>","long>").replaceAll(": any",": unknown").replaceAll("<any>","<unknown>").replaceAll("any>","unknown>");return{relativeFilepath:e,absoluteFilepath:t,fileContents:Olu.DefinitionFile.parseOrThrow(wd.load(r),{unrecognizedObjectKeys:"passthrough",allowUnrecognizedEnumValues:!0,allowUnrecognizedUnionMembers:!0})}}function nR_(e,t){if(yrM(e))return t.alias(e);if(vrM(e))return t.enum(e);if(brM(e))return t.object(e);if(grM(e))return t.union(e);So(e)}function yrM(e){return e?.alias!=null}function vrM(e){return e?.values!=null}function brM(e){return e?.fields!=null}function grM(e){return e?.union!=null}var lLa=class extends G5a{fernDefinitionBuilder=new tan(!1);conjureFilepathToFernFilepath={};async import({absolutePathToConjureFolder:t,authOverrides:r,environmentOverrides:i,globalHeaderOverrides:n}){if(r!=null){for(let[a,u]of Object.entries(r["auth-schemes"]??{}))this.fernDefinitionBuilder.addAuthScheme({name:a,schema:u});r.auth!=null&&this.fernDefinitionBuilder.setAuth(r.auth)}if(i!=null){for(let[a,u]of Object.entries(i.environments??{}))this.fernDefinitionBuilder.addEnvironment({name:a,schema:u});i["default-environment"]!=null&&this.fernDefinitionBuilder.setDefaultEnvironment(i["default-environment"]),i["default-url"]!=null&&this.fernDefinitionBuilder.setDefaultUrl(i["default-url"])}return await aR_(t,(a,u,l)=>{for(let[o,c]of Object.entries(l.services??{})){let b=xAo({value:o,suffix:"Service"});this.conjureFilepathToFernFilepath[u]=Ia.of(`${b}/__package__.yml`);return}let s=CGs(u)?.split(".")[0];s!=null&&(this.conjureFilepathToFernFilepath[u]=Ia.of(`${s}/__package__.yml`))}),await aR_(t,(a,u,l)=>{if(l.services==null||Object.keys(l.services??{}).length===0){let d=this.conjureFilepathToFernFilepath[u];if(d==null)throw new Error(`Failed to find corresponding fern filepath for conjure file ${u}`);for(let[s,o]of Object.entries(l.types?.conjureImports??{})){let c=this.getFernFileToImport({absoluteFilePathToConjureFile:a,absoluteFilePathToConjureFolder:t,importFilePath:Ia.of(o)});this.fernDefinitionBuilder.addImport({file:d,fileToImport:Ia.of(c),alias:s})}this.importAllTypes({conjureFile:l,fernFilePath:d});return}for(let[d,s]of Object.entries(l.services)){let o=xAo({value:d,suffix:"Service"}),c=Ia.of(`${o}/__package__.yml`),b={};s.basePath!=null&&(b["base-path"]=s.basePath),s.docs!=null&&(b.docs=s.docs),this.fernDefinitionBuilder.setServiceInfo(c,b),this.importAllTypes({conjureFile:l,fernFilePath:c});for(let[g,O]of Object.entries(l.types?.conjureImports??{})){let m=this.getFernFileToImport({absoluteFilePathToConjureFile:a,absoluteFilePathToConjureFolder:t,importFilePath:Ia.of(O)});this.fernDefinitionBuilder.addImport({file:c,fileToImport:Ia.of(m),alias:g})}for(let[g,O]of Object.entries(s.endpoints??{})){let m=eHs(O.http);if(m.type==="failure"){this.context?.logger.error(`Failed to parse ${O.http}. Skipping.`);continue}let E={auth:(O.auth??s.defaultAuth)!==Ez_.None,path:m.path,method:m.method,response:O.returns==="binary"?"file":O.returns};O.docs!=null&&(E.docs=O.docs);let q={};if(O.args!=null)for(let M of m.pathParameters){let D=O.args[M];if(D==null)throw new Error(`Failed to find path parameter ${M} in ${O.http}`);q[M]=typeof D=="string"?D:{type:D.type}}Object.entries(q).length>0&&(E["path-parameters"]=q);for(let[M,D]of Object.entries(O.args??{}))if(q[M]==null)if(typeof D=="string")E.request?typeof E.request=="string"&&(E.request={body:E.request}):E.request={},E.request.body=D==="binary"?"bytes":D;else switch(D.paramType){case"body":E.request={body:D.type==="binary"?"bytes":D.type};break;case"query":E.request==null?E.request={"query-parameters":{[M]:D.type}}:typeof E.request!="string"&&E.request?.["query-parameters"]==null?E.request["query-parameters"]={[M]:D.type}:typeof E.request!="string"&&E.request?.["query-parameters"]!=null&&(E.request["query-parameters"][M]=D.type)}E.request!=null&&typeof E.request!="string"&&E.request?.["query-parameters"]!=null&&(E.request.name=`${g}Request`),this.fernDefinitionBuilder.addEndpoint(c,{name:g,schema:E,source:void 0})}}}),this.fernDefinitionBuilder.build()}importAllTypes({conjureFile:t,fernFilePath:r}){for(let[i,n]of Object.entries(t.types?.definitions?.objects??{}))nR_(n,{alias:a=>{this.fernDefinitionBuilder.addType(r,{name:i,schema:{type:a.alias,docs:a.docs}})},object:a=>{this.fernDefinitionBuilder.addType(r,{name:i,schema:{properties:a.fields}})},enum:a=>{this.fernDefinitionBuilder.addType(r,{name:i,schema:{enum:a.values}})},union:a=>{this.fernDefinitionBuilder.addType(r,{name:i,schema:{union:Object.fromEntries(Object.entries(a.union).map(([u,l])=>[u,{type:typeof l=="string"?l:l.type,docs:typeof l=="string"?void 0:l.docs,key:u}]))}})}})}getFernFileToImport({absoluteFilePathToConjureFile:t,importFilePath:r,absoluteFilePathToConjureFolder:i}){let n=Eu(Rd(t),Ia.of(r)),a=hae(i,n),u=this.conjureFilepathToFernFilepath[a];if(u==null)throw new Error(`Failed to find corresponding fern filepath for conjure file ${a}`);return u}};async function aR_(e,t){for(let r of await iR_(e,"{yml,yaml}"))await t(r.absoluteFilepath,r.relativeFilepath,r.fileContents)}function oR_(e,t){return _d(e,t)}var mlu=class extends hQt{type="conjure";absolutePathToConjureFolder;constructor({relativePathToConjureDirectory:t,...r}){super(r),this.absolutePathToConjureFolder=Eu(r.absoluteFilePath,t)}async toFernWorkspace({context:t},r){let i=await this.getDefinition({context:t},r);return new ZAe({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 lLa(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:Fc.of("/DUMMY_PATH"),rootApiFile:{defaultUrl:n.rootApiFile["default-url"],contents:n.rootApiFile,rawContents:wd.dump(n.rootApiFile)},namedDefinitionFiles:{...oR_(n.definitionFiles,a=>({absoluteFilepath:Fc.of("/DUMMY_PATH"),rawContents:wd.dump(a),contents:a})),[Ia.of(fS)]:{absoluteFilepath:Fc.of("/DUMMY_PATH"),rawContents:wd.dump(n.packageMarkerFile),contents:n.packageMarkerFile}},packageMarkers:{},importedDefinitions:{}}}getAbsoluteFilePaths(){return[this.absolutePathToConjureFolder]}};var wF_=ui(dR_(),1);var ij;(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"})(ij||(ij={}));function Plu(e,t){for(let[r,i]of B3(e))mrM({relativeFilepath:r,failure:i,logger:t})}function mrM({relativeFilepath:e,failure:t,logger:r}){switch(t.type){case ij.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 ij.FILE_READ:r.error("Failed to open file: "+e);break;case ij.FILE_MISSING:r.error("Missing file: "+e);break;case ij.FILE_PARSE:t.error instanceof VRa?r.error(p7e({title:`Failed to parse ${e}: ${t.error.reason}`,subtitle:t.error.mark.snippet})):r.error("Failed to parse file: "+e);break;case ij.STRUCTURE_VALIDATION:for(let i of t.error.issues)for(let{title:n,subtitle:a}of PrM(i))r.error(p7e({title:n,subtitle:a,breadcrumbs:[e,...i.path]}));break;case ij.FAILED_TO_LOAD_DEPENDENCY:r.error("Failed to load dependency: "+t.dependencyName);break;case ij.DEPENDENCY_NOT_LISTED:r.error(`Dependency is not listed in ${mqo}: `+t.dependencyName);break;case ij.EXPORT_PACKAGE_HAS_DEFINITIONS:r.error("Exported package contains API definitions: "+t.pathToPackage);break;case ij.EXPORTING_PACKAGE_MARKER_OTHER_KEYS:r.error(`${t.pathOfPackageMarker} has an export so it cannot define other keys.`);break;case ij.JSONSCHEMA_VALIDATION:t.error.error!=null&&r.error(p7e({title:t.error.error.message??"Unknown error",breadcrumbs:[e,...t.error.error.instancePath.split("/").filter(i=>i!=="")]}));for(let i of t.error.allErrors)i!==t.error.error&&r.debug(p7e({title:i.message??"Unknown error",breadcrumbs:[e,...i.instancePath.split("/").filter(n=>n!=="")]}));break;default:So(t)}}function PrM(e){switch(e.code){case Bl.invalid_type:return[{title:"Incorrect type",subtitle:`Expected ${Ds.underline(e.expected)} but received ${Ds.underline(e.received)}`}];case Bl.unrecognized_keys:return e.keys.map(t=>({title:"Unexpected key",subtitle:`Encountered unexpected key ${Ds.underline(t)}`}));case Bl.invalid_enum_value:return[{title:"Unrecognized value",subtitle:`Allowed values: ${e.options.map(t=>Ds.underline(t)).join(", ")}`}];case Bl.invalid_union:case Bl.invalid_arguments:case Bl.invalid_return_type:case Bl.invalid_date:case Bl.invalid_string:case Bl.too_small:case Bl.too_big:case Bl.invalid_intersection_types:case Bl.not_multiple_of:case Bl.custom:default:return[{title:e.message}]}}var pR_=require("fs/promises");async function _R_(e,t){let r=[];for(let i of await _ae(e,t))r.push(await jrM({relativeFilepath:yT(e,i),absoluteFilepath:i}));return r}async function jrM({relativeFilepath:e,absoluteFilepath:t}){return{relativeFilepath:e,absoluteFilepath:t,fileContents:(await(0,pR_.readFile)(t)).toString()}}async function hR_(e){let t={},r={};function i(n){try{t[n.relativeFilepath]={defaultUrl:void 0,contents:wd.load(n.fileContents,{schema:wd.CORE_SCHEMA}),rawContents:n.fileContents}}catch(a){r[n.relativeFilepath]={type:ij.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 xCc=ui(Nzi(),1);var pF_=require("fs"),uXn=require("fs/promises");var _F_=require("os"),hF_=ui(require("path"),1),yF_=require("stream/promises"),vF_=ui(Afu(),1),bF_=ui(hk(),1);var knM=DOi();async function gF_({dependencyName:e,dependenciesConfiguration:t,context:r,rootApiFile:i,cliVersion:n,settings:a,loadAPIWorkspace:u}){let l,d={type:ij.FAILED_TO_LOAD_DEPENDENCY,dependencyName:e},s=t.dependencies[e];return s==null?d={type:ij.DEPENDENCY_NOT_LISTED,dependencyName:e}:await r.runInteractiveTask({name:`Download ${oaM(s)}`},async o=>{switch(s.type){case"version":l=await naM({context:o,dependency:s,cliVersion:n,settings:a,loadAPIWorkspace:u});return;case"local":l=await iaM({context:o,dependency:s,cliVersion:n,settings:a,loadAPIWorkspace:u});return;default:So(s)}}),l!=null?{didSucceed:!0,definition:l}:{didSucceed:!1,failure:d}}var OF_="dependencies";var eaM="metadata.json",taM=".fern";function raM(e){return Eu(Fc.of((0,_F_.homedir)()),Ia.of(taM),Ia.of(OF_),Ia.of(e.organization),Ia.of(e.apiName),Ia.of(e.version))}async function iaM({dependency:e,context:t,cliVersion:r,settings:i,loadAPIWorkspace:n}){if(n==null){t.failWithoutThrowing("Failed to load api definition");return}t.logger.info("Parsing...");let a=await n({absolutePathToWorkspace:e.absoluteFilepath,context:t,cliVersion:r,workspaceName:void 0});if(!a.didSucceed){t.failWithoutThrowing("Failed to load api definition",a.failures);return}t.logger.info("Modifying source filepath ...");let u=await a.workspace.getDefinition({context:t,relativePathToDependency:Ia.of(e.path)},i);return t.logger.info("Loaded..."),u}async function naM({dependency:e,context:t,cliVersion:r,settings:i,loadAPIWorkspace:n}){let a=raM(e),u=Eu(a,Ia.of(OF_)),l=Eu(a,Ia.of(eaM)),d;if(!await jf(u)||!await jf(l)){t.logger.info("Downloading manifest...");let c=await knM.definitionRegistry.get(xCc.FernFiddle.OrganizationId(e.organization),xCc.FernFiddle.ApiId(e.apiName),e.version);if(!c.ok){c.error._visit({orgDoesNotExistError:()=>{t.failWithoutThrowing("Organization does not exist")},apiDoesNotExistError:()=>{t.failWithoutThrowing("API does not exist")},versionDoesNotExistError:()=>{t.failWithoutThrowing("Version does not exist")},_other:m=>{t.failWithoutThrowing("Failed to download API manifest",m)}});return}let b=c.body.yamlSchemaVersion!=null?parseInt(c.body.yamlSchemaVersion):void 0,g=Lnn(r),O=Lnn(c.body.cliVersion);if(b!=null){if(b>1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a higher version of fern. Upgrade this workspace to ${c.body.cliVersion}`);return}else if(b<1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a lower version of fern. Upgrade it to ${r}`);return}}else if(g.major!==O.major||g.minor!==O.minor){t.failWithoutThrowing(`CLI version is ${c.body.cliVersion}. Expected ${g.major}.${g.minor}.x (to match current workspace).`);return}t.logger.info("Downloading..."),t.logger.debug("Remote URL: "+c.body.definitionS3DownloadUrl),await(0,uXn.mkdir)(u,{recursive:!0});try{await aaM({s3PreSignedReadUrl:c.body.definitionS3DownloadUrl,absolutePathToLocalOutput:u})}catch(m){t.failWithoutThrowing("Failed to download API",m);return}d=c.body,await(0,uXn.writeFile)(l,JSON.stringify(d))}else d=JSON.parse((await(0,uXn.readFile)(l)).toString());if(t.logger.info("Parsing..."),n==null){t.failWithoutThrowing("Failed to load API");return}let s=await n({absolutePathToWorkspace:u,context:t,cliVersion:d.cliVersion,workspaceName:void 0});if(!s.didSucceed){t.failWithoutThrowing("Failed to parse dependency after downloading",s.failures);return}if(s.workspace.type==="oss"){t.failWithoutThrowing("Dependency must be a fern workspace.");return}return await s.workspace.getDefinition({context:t},i)}async function aaM({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t}){let r=await xF.get(e,{responseType:"stream"}),i=await bF_.default.dir(),n=hF_.default.join(i.path,"api.tgz");await(0,yF_.pipeline)(r.data,(0,pF_.createWriteStream)(n)),await(0,vF_.extract)({file:n,cwd:t})}function oaM(e){switch(e.type){case"version":return`@${e.organization}/${e.apiName}`;case"local":return`${e.path}`;default:So(e)}}async function mF_({dependenciesConfiguration:e,structuralValidationResult:t,context:r,cliVersion:i,settings:n,loadAPIWorkspace:a}){let u={},l={},d={};return await Promise.all(B3(t.packageMarkers).map(async([s,o])=>{if(o.contents.export==null)u[s]=o;else{let{export:c,...b}=o.contents;if(yq(b)>0)d[s]={type:ij.EXPORTING_PACKAGE_MARKER_OTHER_KEYS,pathOfPackageMarker:s};else{let g=Rd(s);if(s$t(t.namedDefinitionFiles).some(m=>m!==s&&m.startsWith(g)))d[s]={type:ij.EXPORT_PACKAGE_HAS_DEFINITIONS,pathToPackage:g};else{let m=await gF_({dependencyName:typeof o.contents.export=="string"?o.contents.export:o.contents.export.dependency,dependenciesConfiguration:e,context:r,rootApiFile:t.rootApiFile.contents,cliVersion:i,settings:n,loadAPIWorkspace:a});m.didSucceed?l[Rd(s)]={definition:m.definition,url:typeof o.contents.export=="object"?o.contents.export.url:void 0}:d[s]=m.failure}}}})),yq(d)>0?{didSucceed:!1,failures:d}:{didSucceed:!0,packageMarkers:u,importedDefinitions:l}}var PF_=ui(require("path"),1);var NCc={};Po(NCc,{additionalProperties:()=>laM,default:()=>daM,definitions:()=>faM,properties:()=>saM,required:()=>caM,type:()=>uaM});var uaM="object",saM={docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},"default-url":{oneOf:[{type:"string"},{type:"null"}]},"default-environment":{oneOf:[{type:"string"},{type:"null"}]},environments:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/environments.EnvironmentSchema"}},{type:"null"}]},auth:{oneOf:[{$ref:"#/definitions/auth.ApiAuthSchema"},{type:"null"}]},"auth-schemes":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/auth.AuthSchemeDeclarationSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},name:{type:"string"},imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},"error-discrimination":{oneOf:[{$ref:"#/definitions/file.ErrorDiscriminationSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},errors:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"idempotency-headers":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},variables:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/variables.VariableDeclarationSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"null"}]},product:{oneOf:[{$ref:"#/definitions/products.ProductDeclarationSchema"},{type:"null"}]},version:{oneOf:[{$ref:"#/definitions/versioning.VersionDeclarationSchema"},{type:"null"}]}},caM=["name"],laM=!1,faM={"environments.SingleBaseUrlEnvironmentSchema":{type:"object",properties:{audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},url:{type:"string"}},required:["url"],additionalProperties:!1},"environments.MultipleBaseUrlsEnvironmentSchema":{type:"object",properties:{audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},urls:{type:"object",additionalProperties:{type:"string"}}},required:["urls"],additionalProperties:!1},"environments.EnvironmentSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/environments.SingleBaseUrlEnvironmentSchema"},{$ref:"#/definitions/environments.MultipleBaseUrlsEnvironmentSchema"}]},"auth.AuthSchemeReferenceSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{type:"string"}},required:["scheme"],additionalProperties:!1},"auth.AnyAuthItem":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.AuthSchemeReferenceSchema"}]},"auth.AnyAuthSchemesSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},any:{type:"array",items:{$ref:"#/definitions/auth.AnyAuthItem"}}},required:["any"],additionalProperties:!1},"auth.ApiAuthSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.AuthSchemeReferenceSchema"},{$ref:"#/definitions/auth.AnyAuthSchemesSchema"}]},"auth.OAuthAccessTokenRequestPropertiesSchema":{type:"object",properties:{"client-id":{oneOf:[{type:"string"},{type:"null"}]},"client-secret":{oneOf:[{type:"string"},{type:"null"}]},scopes:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthAccessTokenResponsePropertiesSchema":{type:"object",properties:{"access-token":{oneOf:[{type:"string"},{type:"null"}]},"expires-in":{oneOf:[{type:"string"},{type:"null"}]},"refresh-token":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthGetTokenEndpointSchema":{type:"object",properties:{endpoint:{type:"string"},"request-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthAccessTokenRequestPropertiesSchema"},{type:"null"}]},"response-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthAccessTokenResponsePropertiesSchema"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.OAuthRefreshTokenRequestPropertiesSchema":{type:"object",properties:{"refresh-token":{type:"string"}},required:["refresh-token"],additionalProperties:!1},"auth.OAuthRefreshTokenResponsePropertiesSchema":{type:"object",properties:{"access-token":{oneOf:[{type:"string"},{type:"null"}]},"expires-in":{oneOf:[{type:"string"},{type:"null"}]},"refresh-token":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthRefreshTokenEndpointSchema":{type:"object",properties:{endpoint:{type:"string"},"request-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenRequestPropertiesSchema"},{type:"null"}]},"response-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenResponsePropertiesSchema"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.OAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"oauth"},type:{const:"client-credentials"},scopes:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"client-id-env":{oneOf:[{type:"string"},{type:"null"}]},"client-secret-env":{oneOf:[{type:"string"},{type:"null"}]},"token-prefix":{oneOf:[{type:"string"},{type:"null"}]},"token-header":{oneOf:[{type:"string"},{type:"null"}]},"get-token":{$ref:"#/definitions/auth.OAuthGetTokenEndpointSchema"},"refresh-token":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenEndpointSchema"},{type:"null"}]}},required:["scheme","type","get-token"],additionalProperties:!1},"auth.HeaderAuthSchemeSchema":{type:"object",properties:{env:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},header:{type:"string"},type:{oneOf:[{type:"string"},{type:"null"}]},prefix:{oneOf:[{type:"string"},{type:"null"}]}},required:["header"],additionalProperties:!1},"auth.AuthVariable":{type:"object",properties:{env:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.BasicAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"basic"},username:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]},password:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]}},required:["scheme"],additionalProperties:!1},"auth.TokenBearerAuthSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"bearer"},token:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]}},required:["scheme"],additionalProperties:!1},"auth.InferredAuthenticatedRequestHeader":{type:"object",properties:{"response-property":{type:"string"},"header-name":{type:"string"},"value-prefix":{oneOf:[{type:"string"},{type:"null"}]}},required:["response-property","header-name"],additionalProperties:!1},"auth.InferredGetTokenEndpointSchemaObject":{type:"object",properties:{endpoint:{type:"string"},"expiry-response-property":{oneOf:[{type:"string"},{type:"null"}]},"authenticated-request-headers":{oneOf:[{type:"array",items:{$ref:"#/definitions/auth.InferredAuthenticatedRequestHeader"}},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.InferredGetTokenEndpointSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.InferredGetTokenEndpointSchemaObject"}]},"auth.InferredBearerAuthSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"bearer"},"get-token":{$ref:"#/definitions/auth.InferredGetTokenEndpointSchema"}},required:["scheme","get-token"],additionalProperties:!1},"auth.BearerAuthSchemeSchema":{anyOf:[{$ref:"#/definitions/auth.TokenBearerAuthSchema"},{$ref:"#/definitions/auth.InferredBearerAuthSchema"}]},"auth.AuthSchemeDeclarationSchema":{anyOf:[{$ref:"#/definitions/auth.OAuthSchemeSchema"},{$ref:"#/definitions/auth.HeaderAuthSchemeSchema"},{$ref:"#/definitions/auth.BasicAuthSchemeSchema"},{$ref:"#/definitions/auth.BearerAuthSchemeSchema"}]},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"file.PropertyBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"property"},"property-name":{type:"string"}},required:["strategy","property-name"],additionalProperties:!1},"file.StatusCodeBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"status-code"}},required:["strategy"],additionalProperties:!1},"file.ErrorDiscriminationSchema":{anyOf:[{$ref:"#/definitions/file.PropertyBasedErrorDiscrimination"},{$ref:"#/definitions/file.StatusCodeBasedErrorDiscrimination"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"variables.VariableDeclarationDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"variables.VariableDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/variables.VariableDeclarationDetailed"}]},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"}]},"versioning.VersionValueDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionValue":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionValueDetailed"}]},"versioning.VersionDeclarationHeaderObjectSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionDeclarationHeaderSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionDeclarationHeaderObjectSchema"}]},"versioning.VersionDeclarationSchema":{type:"object",properties:{default:{oneOf:[{type:"string"},{type:"null"}]},values:{type:"array",items:{$ref:"#/definitions/versioning.VersionValue"}},header:{$ref:"#/definitions/versioning.VersionDeclarationHeaderSchema"}},required:["values","header"],additionalProperties:!1},"products.ProductValueDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},versions:{oneOf:[{$ref:"#/definitions/versioning.VersionDeclarationSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"products.ProductValue":{anyOf:[{type:"string"},{$ref:"#/definitions/products.ProductValueDetailed"}]},"products.ProductDeclarationHeaderObjectSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"products.ProductDeclarationHeaderSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/products.ProductDeclarationHeaderObjectSchema"}]},"products.ProductDeclarationSchema":{type:"object",properties:{default:{oneOf:[{type:"string"},{type:"null"}]},values:{type:"array",items:{$ref:"#/definitions/products.ProductValue"}},header:{$ref:"#/definitions/products.ProductDeclarationHeaderSchema"}},required:["values","header"],additionalProperties:!1}},daM={type:uaM,properties:saM,required:caM,additionalProperties:laM,definitions:faM};var FCc={};Po(FCc,{additionalProperties:()=>haM,default:()=>vaM,definitions:()=>yaM,properties:()=>_aM,type:()=>paM});var paM="object",_aM={docs:{oneOf:[{type:"string"},{type:"null"}]},imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},types:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeDeclarationSchema"}},{type:"null"}]},service:{oneOf:[{$ref:"#/definitions/service.HttpServiceSchema"},{type:"null"}]},errors:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/errors.ErrorDeclarationSchema"}},{type:"null"}]},webhooks:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/webhooks.WebhookSchema"}},{type:"null"}]},channel:{oneOf:[{$ref:"#/definitions/websocket.WebSocketChannelSchema"},{type:"null"}]}},haM=!1,yaM={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"}]},"types.ObjectPropertyAccess":{type:"string",enum:["read-only","write-only"]},"types.ObjectPropertyWithAccessSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},access:{oneOf:[{$ref:"#/definitions/types.ObjectPropertyAccess"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.ObjectPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectPropertyWithAccessSchema"}]},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE","HEAD"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"service.QueryParameterTypeReferenceDetailed":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"allow-multiple":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpQueryParameterSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.QueryParameterTypeReferenceDetailed"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"service.HttpReferencedRequestBodySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"service.FormDataBodyEncodingStyle":{type:"string",enum:["json","exploded","form"]},"service.HttpInlineFileRequestBodyPropertySchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/service.FormDataBodyEncodingStyle"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpInlineRequestBodyPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpInlineFileRequestBodyPropertySchema"}]},"service.HttpInlineRequestBodySchema":{type:"object",properties:{extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpInlineRequestBodyPropertySchema"}},{type:"null"}]}},additionalProperties:!1},"service.HttpRequestBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpReferencedRequestBodySchema"},{$ref:"#/definitions/service.HttpInlineRequestBodySchema"}]},"service.HttpRequestSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/service.HttpRequestBodySchema"},{type:"null"}]}},additionalProperties:!1},"service.HttpRequest":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpRequestSchema"}]},"service.HttpResponseSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},property:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"service.HttpResponseSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseSchemaDetailed"}]},"service.StreamFormat":{type:"string",enum:["sse","json"]},"service.HttpResponseStreamSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"},format:{oneOf:[{$ref:"#/definitions/service.StreamFormat"},{type:"null"}]},terminator:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpResponseStreamSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseStreamSchemaDetailed"}]},"service.ResponseErrorWithDocsSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},error:{type:"string"}},required:["error"],additionalProperties:!1},"service.ResponseError":{anyOf:[{type:"string"},{$ref:"#/definitions/service.ResponseErrorWithDocsSchema"}]},"service.ResponseErrorsSchema":{type:"array",items:{$ref:"#/definitions/service.ResponseError"}},"examples.ExampleTypeReferenceSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleBodyResponseSchema":{type:"object",properties:{error:{oneOf:[{type:"string"},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},additionalProperties:!1},"examples.ExampleStreamResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleSseEventSchema":{type:"object",properties:{event:{type:"string"},data:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},required:["event"],additionalProperties:!1},"examples.ExampleSseResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleSseEventSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleResponseSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleBodyResponseSchema"},{$ref:"#/definitions/examples.ExampleStreamResponseSchema",description:"JSON Streams"},{$ref:"#/definitions/examples.ExampleSseResponseSchema",description:"Server-Sent Event streams"}]},"examples.SupportedSdkLanguageSchema":{type:"string",enum:["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm","c#"]},"examples.ExampleCodeSampleSchemaSdk":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},sdk:{$ref:"#/definitions/examples.SupportedSdkLanguageSchema"},code:{type:"string"}},required:["sdk","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchemaLanguage":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},language:{type:"string"},code:{type:"string"},install:{oneOf:[{type:"string"},{type:"null"}]}},required:["language","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleCodeSampleSchemaSdk"},{$ref:"#/definitions/examples.ExampleCodeSampleSchemaLanguage"}]},"examples.ExampleEndpointCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/examples.ExampleResponseSchema"},{type:"null"}]},"code-samples":{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleCodeSampleSchema"}},{type:"null"}]}},additionalProperties:!1},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"}]},"service.Pagination":{anyOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"boolean"}]},"service.HttpEndpointSchema":{type:"object",properties:{"display-name":{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},method:{oneOf:[{$ref:"#/definitions/service.HttpMethodSchema"},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},auth:{oneOf:[{type:"boolean"},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},"stream-condition":{oneOf:[{type:"string"},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/service.HttpRequest"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},errors:{oneOf:[{$ref:"#/definitions/service.ResponseErrorsSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleEndpointCallSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/service.Pagination"},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]}},required:["path"],additionalProperties:!1},"service.HttpServiceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},"base-path":{type:"string"},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},endpoints:{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpEndpointSchema"}}},required:["auth","base-path","endpoints"],additionalProperties:!1},"errors.ErrorDeclarationSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{type:"integer"},type:{oneOf:[{type:"string"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]}},required:["status-code"],additionalProperties:!1},"webhooks.WebhookMethodSchema":{type:"string",enum:["POST","GET"]},"webhooks.WebhookReferencedPayloadSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"webhooks.WebhookInlinedPayloadSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"webhooks.WebhookPayloadSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/webhooks.WebhookReferencedPayloadSchema"},{$ref:"#/definitions/webhooks.WebhookInlinedPayloadSchema"}]},"examples.ExampleWebhookCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},payload:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},required:["payload"],additionalProperties:!1},"webhooks.WebhookSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},method:{$ref:"#/definitions/webhooks.WebhookMethodSchema"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},payload:{$ref:"#/definitions/webhooks.WebhookPayloadSchema"},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebhookCallSchema"}},{type:"null"}]}},required:["method","payload"],additionalProperties:!1},"websocket.WebSocketOrigin":{type:"string",enum:["client","server"]},"websocket.WebSocketChannelReferencedMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"websocket.WebSocketChannelInlinedMessageSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"websocket.WebSocketChannelMessageBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/websocket.WebSocketChannelReferencedMessageSchema"},{$ref:"#/definitions/websocket.WebSocketChannelInlinedMessageSchema"}]},"websocket.WebSocketChannelMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},origin:{$ref:"#/definitions/websocket.WebSocketOrigin"},body:{$ref:"#/definitions/websocket.WebSocketChannelMessageBodySchema"}},required:["origin","body"],additionalProperties:!1},"examples.ExampleWebSocketMessage":{type:"object",properties:{type:{type:"string"},body:{type:["string","number","boolean","object","array","null"]}},required:["type","body"],additionalProperties:!1},"examples.ExampleWebSocketSession":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},messages:{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketMessage"}}},required:["messages"],additionalProperties:!1},"websocket.WebSocketChannelSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},messages:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/websocket.WebSocketChannelMessageSchema"}},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketSession"}},{type:"null"}]}},required:["auth","path"],additionalProperties:!1}},vaM={type:paM,properties:_aM,additionalProperties:haM,definitions:yaM};var LCc={};Po(LCc,{additionalProperties:()=>OaM,default:()=>PaM,definitions:()=>maM,properties:()=>gaM,type:()=>baM});var baM="object",gaM={imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},types:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeDeclarationSchema"}},{type:"null"}]},service:{oneOf:[{$ref:"#/definitions/service.HttpServiceSchema"},{type:"null"}]},errors:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/errors.ErrorDeclarationSchema"}},{type:"null"}]},webhooks:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/webhooks.WebhookSchema"}},{type:"null"}]},channel:{oneOf:[{$ref:"#/definitions/websocket.WebSocketChannelSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},navigation:{oneOf:[{$ref:"#/definitions/file.Navigation"},{type:"null"}]},export:{oneOf:[{$ref:"#/definitions/file.Export"},{type:"null"}]}},OaM=!1,maM={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"}]},"types.ObjectPropertyAccess":{type:"string",enum:["read-only","write-only"]},"types.ObjectPropertyWithAccessSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},access:{oneOf:[{$ref:"#/definitions/types.ObjectPropertyAccess"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.ObjectPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectPropertyWithAccessSchema"}]},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE","HEAD"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"service.QueryParameterTypeReferenceDetailed":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"allow-multiple":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpQueryParameterSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.QueryParameterTypeReferenceDetailed"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"service.HttpReferencedRequestBodySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"service.FormDataBodyEncodingStyle":{type:"string",enum:["json","exploded","form"]},"service.HttpInlineFileRequestBodyPropertySchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/service.FormDataBodyEncodingStyle"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpInlineRequestBodyPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpInlineFileRequestBodyPropertySchema"}]},"service.HttpInlineRequestBodySchema":{type:"object",properties:{extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpInlineRequestBodyPropertySchema"}},{type:"null"}]}},additionalProperties:!1},"service.HttpRequestBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpReferencedRequestBodySchema"},{$ref:"#/definitions/service.HttpInlineRequestBodySchema"}]},"service.HttpRequestSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/service.HttpRequestBodySchema"},{type:"null"}]}},additionalProperties:!1},"service.HttpRequest":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpRequestSchema"}]},"service.HttpResponseSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},property:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"service.HttpResponseSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseSchemaDetailed"}]},"service.StreamFormat":{type:"string",enum:["sse","json"]},"service.HttpResponseStreamSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"},format:{oneOf:[{$ref:"#/definitions/service.StreamFormat"},{type:"null"}]},terminator:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpResponseStreamSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseStreamSchemaDetailed"}]},"service.ResponseErrorWithDocsSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},error:{type:"string"}},required:["error"],additionalProperties:!1},"service.ResponseError":{anyOf:[{type:"string"},{$ref:"#/definitions/service.ResponseErrorWithDocsSchema"}]},"service.ResponseErrorsSchema":{type:"array",items:{$ref:"#/definitions/service.ResponseError"}},"examples.ExampleTypeReferenceSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleBodyResponseSchema":{type:"object",properties:{error:{oneOf:[{type:"string"},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},additionalProperties:!1},"examples.ExampleStreamResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleSseEventSchema":{type:"object",properties:{event:{type:"string"},data:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},required:["event"],additionalProperties:!1},"examples.ExampleSseResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleSseEventSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleResponseSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleBodyResponseSchema"},{$ref:"#/definitions/examples.ExampleStreamResponseSchema",description:"JSON Streams"},{$ref:"#/definitions/examples.ExampleSseResponseSchema",description:"Server-Sent Event streams"}]},"examples.SupportedSdkLanguageSchema":{type:"string",enum:["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm","c#"]},"examples.ExampleCodeSampleSchemaSdk":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},sdk:{$ref:"#/definitions/examples.SupportedSdkLanguageSchema"},code:{type:"string"}},required:["sdk","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchemaLanguage":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},language:{type:"string"},code:{type:"string"},install:{oneOf:[{type:"string"},{type:"null"}]}},required:["language","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleCodeSampleSchemaSdk"},{$ref:"#/definitions/examples.ExampleCodeSampleSchemaLanguage"}]},"examples.ExampleEndpointCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/examples.ExampleResponseSchema"},{type:"null"}]},"code-samples":{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleCodeSampleSchema"}},{type:"null"}]}},additionalProperties:!1},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"}]},"service.Pagination":{anyOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"boolean"}]},"service.HttpEndpointSchema":{type:"object",properties:{"display-name":{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},method:{oneOf:[{$ref:"#/definitions/service.HttpMethodSchema"},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},auth:{oneOf:[{type:"boolean"},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},"stream-condition":{oneOf:[{type:"string"},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/service.HttpRequest"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},errors:{oneOf:[{$ref:"#/definitions/service.ResponseErrorsSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleEndpointCallSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/service.Pagination"},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]}},required:["path"],additionalProperties:!1},"service.HttpServiceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},"base-path":{type:"string"},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},endpoints:{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpEndpointSchema"}}},required:["auth","base-path","endpoints"],additionalProperties:!1},"errors.ErrorDeclarationSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{type:"integer"},type:{oneOf:[{type:"string"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]}},required:["status-code"],additionalProperties:!1},"webhooks.WebhookMethodSchema":{type:"string",enum:["POST","GET"]},"webhooks.WebhookReferencedPayloadSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"webhooks.WebhookInlinedPayloadSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"webhooks.WebhookPayloadSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/webhooks.WebhookReferencedPayloadSchema"},{$ref:"#/definitions/webhooks.WebhookInlinedPayloadSchema"}]},"examples.ExampleWebhookCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},payload:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},required:["payload"],additionalProperties:!1},"webhooks.WebhookSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},method:{$ref:"#/definitions/webhooks.WebhookMethodSchema"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},payload:{$ref:"#/definitions/webhooks.WebhookPayloadSchema"},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebhookCallSchema"}},{type:"null"}]}},required:["method","payload"],additionalProperties:!1},"websocket.WebSocketOrigin":{type:"string",enum:["client","server"]},"websocket.WebSocketChannelReferencedMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"websocket.WebSocketChannelInlinedMessageSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"websocket.WebSocketChannelMessageBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/websocket.WebSocketChannelReferencedMessageSchema"},{$ref:"#/definitions/websocket.WebSocketChannelInlinedMessageSchema"}]},"websocket.WebSocketChannelMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},origin:{$ref:"#/definitions/websocket.WebSocketOrigin"},body:{$ref:"#/definitions/websocket.WebSocketChannelMessageBodySchema"}},required:["origin","body"],additionalProperties:!1},"examples.ExampleWebSocketMessage":{type:"object",properties:{type:{type:"string"},body:{type:["string","number","boolean","object","array","null"]}},required:["type","body"],additionalProperties:!1},"examples.ExampleWebSocketSession":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},messages:{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketMessage"}}},required:["messages"],additionalProperties:!1},"websocket.WebSocketChannelSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},messages:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/websocket.WebSocketChannelMessageSchema"}},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketSession"}},{type:"null"}]}},required:["auth","path"],additionalProperties:!1},"file.Navigation":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"file.ExportDetailed":{type:"object",properties:{dependency:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]}},required:["dependency"],additionalProperties:!1},"file.Export":{anyOf:[{type:"string"},{$ref:"#/definitions/file.ExportDetailed"}]}},PaM={type:baM,properties:gaM,additionalProperties:OaM,definitions:maM};function jF_({files:e,absolutePathToDefinition:t}){let r,i={},n={},a={};for(let[u,l]of B3(e)){let d=l.contents,s=o=>{a[u]={type:ij.JSONSCHEMA_VALIDATION,error:o}};if(u===z3){let o=p$t(d,NCc);if(o.success){let c=MF.serialization.RootApiFileSchema.parseOrThrow(d);r={defaultUrl:c["default-url"],contents:c,rawContents:l.rawContents}}else s(o)}else if(PF_.default.basename(u)===fS){let o=p$t(d,LCc);if(o.success){let c=MF.serialization.PackageMarkerFileSchema.parseOrThrow(d);n[u]={defaultUrl:typeof c.export=="object"?c.export.url:void 0,contents:c,rawContents:l.rawContents}}else s(o)}else{let o=p$t(d,FCc);if(o.success){let c=MF.serialization.DefinitionFileSchema.parseOrThrow(d);i[u]={defaultUrl:void 0,contents:c,rawContents:l.rawContents,absoluteFilePath:Eu(t,u)}}else s(o)}}return r==null?{didSucceed:!1,failures:{[Ia.of(z3)]:{type:ij.FILE_MISSING},...a}}:Object.keys(a).length>0?{didSucceed:!1,failures:a}:{didSucceed:!0,namedDefinitionFiles:i,rootApiFile:r,packageMarkers:n}}var Hor=class extends hQt{type="fern";context;fernWorkspaces={};loadAPIWorkspace;constructor({context:t,loadAPIWorkspace:r,...i}){super(i),this.context=t,this.loadAPIWorkspace=r}async getDefinition({context:t},r){return(await this.toFernWorkspace({context:t},r)).definition}async toFernWorkspace({context:t},r){let i=(0,wF_.default)(r??{}),n=this.fernWorkspaces[i];if(n==null){let a=t||this.context,u=Eu(this.absoluteFilePath,Ia.of(rL)),l=await qQs({absolutePathToWorkspace:this.absoluteFilePath,context:a}),d=await _R_(u,"{yml,yaml}"),s=await hR_(d);if(!s.didSucceed)return Plu(s.failures,a.logger),a.failAndThrow();let o=jF_({files:s.files,absolutePathToDefinition:u});if(!o.didSucceed)return Plu(o.failures,a.logger),a.failAndThrow();let c=await mF_({dependenciesConfiguration:l,structuralValidationResult:o,context:a,cliVersion:this.cliVersion,settings:r,loadAPIWorkspace:this.loadAPIWorkspace});if(!c.didSucceed)return Plu(c.failures,a.logger),a.failAndThrow();let b={absoluteFilePath:u,rootApiFile:o.rootApiFile,namedDefinitionFiles:o.namedDefinitionFiles,packageMarkers:c.packageMarkers,importedDefinitions:c.importedDefinitions};r?.auth!=null&&(b={...b,rootApiFile:{...b.rootApiFile,contents:{...b.rootApiFile.contents,auth:r?.auth}}}),n=new ZAe({absoluteFilePath:this.absoluteFilePath,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:l,workspaceName:this.workspaceName,definition:b,cliVersion:this.cliVersion,sources:[]}),this.fernWorkspaces[i]=n}return n}getAbsoluteFilePaths(){return[this.absoluteFilePath]}};var x4_=require("fs/promises");var B4_=ui(C4_(),1);async function SUa(e){return(await(0,B4_.convertObj)(e,{})).openapi}var z4_=require("fs/promises");var I4_=require("fs/promises");async function EXn({absoluteFilePathToOverrides:e,data:t,context:r,allowNullKeys:i}){let n=null;try{let a=(await(0,I4_.readFile)(e,"utf8")).toString();try{n=JSON.parse(a)}catch{n=wd.load(a,{json:!0})}}catch{return r.failAndThrow(`Failed to read overrides from file ${e}`)}return kWs({data:t,overrides:n,allowNullKeys:i})}async function WIc({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let i=(await(0,z4_.readFile)(t)).toString(),n=await wd.load(i);return r!=null?await EXn({absoluteFilePathToOverrides:r,context:e,data:n}):n}var EUa=ui(Ycu(),1);var R4_=ui(Ycu(),1),HIc=ui(require("path"),1),DUa=class extends R4_.BaseResolver{absolutePathToOpenAPIOverrides;constructor(t){super(),this.absolutePathToOpenAPIOverrides=t}resolveExternalRef(t,r){let i=super.resolveExternalRef(t,r);return Agi(Fc.of(i))?i:this.absolutePathToOpenAPIOverrides!=null?HIc.default.resolve(HIc.default.dirname(this.absolutePathToOpenAPIOverrides),r):i}};async function $Ic({absolutePathToOpenAPI:e,absolutePathToOpenAPIOverrides:t,parsed:r}){return(r!=null?await(0,EUa.bundle)({...Xcu,doc:{source:new EUa.Source(e,"<openapi>"),parsed:r},externalRefResolver:new DUa(t)}):await(0,EUa.bundle)({...Xcu,ref:e,externalRefResolver:new DUa(t)})).bundle.parsed}var IfM=["examples","example",Kf.EXAMPLES,JH.REDOCLY_CODE_SAMPLES_CAMEL,JH.REDOCLY_CODE_SAMPLES_KEBAB];async function MUa({context:e,absolutePathToOpenAPI:t,absolutePathToOpenAPIOverrides:r}){let i=await $Ic({absolutePathToOpenAPI:t}),n;if(r!=null?n=r:typeof i=="object"&&i[Kf.OPENAPI_OVERIDES_FILEPATH]!=null&&(n=Eu(Rd(t),Ia.of(i[Kf.OPENAPI_OVERIDES_FILEPATH]))),n!=null){let a=await EXn({absoluteFilePathToOverrides:n,context:e,data:i,allowNullKeys:IfM});return await $Ic({absolutePathToOpenAPI:t,absolutePathToOpenAPIOverrides:r,parsed:a})}return i}var zQt=class{absoluteFilePath;constructor(t){this.absoluteFilePath=t}async loadDocuments({context:t,specs:r}){let i=[];for(let n of r){let a=(await(0,x4_.readFile)(n.absoluteFilepath)).toString(),u=yT(this.absoluteFilePath,n.source.file);n.source.relativePathToDependency!=null&&(u=Eu(n.source.relativePathToDependency,u));let l=n.source.type==="protobuf"?nK.protobuf({file:u}):nK.openapi({file:u});if(a.includes("openapi")||a.includes("swagger")){let d=await MUa({absolutePathToOpenAPI:n.absoluteFilepath,context:t,absolutePathToOpenAPIOverrides:n.absoluteFilepathToOverrides});if(Fqc(d)){i.push({type:"openapi",value:d,source:l,namespace:n.namespace,settings:gQt({options:n.settings})});continue}else if(nLa(d)){(!d.schemes||d.schemes.length===0)&&(d.schemes=["https"]);let s=await SUa(d);i.push({type:"openapi",value:s,source:l,namespace:n.namespace,settings:gQt({options:n.settings})});continue}}if(a.includes("asyncapi")){let d=await WIc({context:t,absoluteFilePath:n.absoluteFilepath,absoluteFilePathToOverrides:n.absoluteFilepathToOverrides});i.push({type:"asyncapi",value:d,source:l,namespace:n.namespace,settings:gQt({options:n.settings})});continue}if(a.includes("openrpc")){let d=await WIc({context:t,absoluteFilePath:n.absoluteFilepath,absoluteFilePathToOverrides:n.absoluteFilepathToOverrides});i.push({type:"asyncapi",value:d,source:l,namespace:n.namespace,settings:gQt({options:n.settings})});continue}t.failAndThrow(`${n.absoluteFilepath} is not a valid OpenAPI or AsyncAPI file`)}return i}};var zfM=Su.object({type:Su.string(),channelId:Su.string().optional(),messageId:Su.string(),value:Su.any()}),RfM=Su.object({summary:Su.string().optional(),description:Su.string().optional(),"query-parameters":Su.record(Su.string()).optional(),headers:Su.record(Su.string()).optional(),messages:Su.array(zfM)}),N4_=Su.array(RfM);var xdu=class extends Yg{channel;key="x-fern-examples";constructor({breadcrumbs:t,channel:r,context:i}){super({breadcrumbs:t??[],context:i}),this.channel=r}convert(){let t=this.getExtensionValue(this.channel);if(t==null)return;let r=N4_.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-examples extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data.map(i=>({summary:i.summary,description:i.description,queryParameters:i["query-parameters"],headers:i.headers,messages:i.messages.map(n=>({type:n.type,channelId:n.channelId,messageId:n.messageId,value:n.value}))}))}};var MXn=class extends e_{channel;channelPath;inlinedTypes={};websocketGroup;constructor({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a}){super({context:t,breadcrumbs:r}),this.websocketGroup=i,this.channel=n,this.channelPath=a}convertExamples({fullPath:t,baseUrl:r,asyncApiVersion:i}){let a=new xdu({context:this.context,breadcrumbs:this.breadcrumbs,channel:this.channel}).convert();return a==null?{}:Object.fromEntries(a.map((u,l)=>[l.toString(),{channel:{method:"GET",path:t},baseUrl:t,environment:r,auth:void 0,pathParameters:{},queryParameters:u.queryParameters,headers:u.headers,messages:u.messages.map(d=>({type:i==="v2"?d.type:d.messageId,body:d.value}))}]))}transformToValidPath(t){return t.startsWith("/")?t:"/"+t}};var c3i=class extends tA.AbstractConverters.AbstractParameterConverter{parameterNamePrefix;constructor({context:t,breadcrumbs:r,parameter:i,parameterNamePrefix:n}){super({context:t,breadcrumbs:r,parameter:i}),this.parameterNamePrefix=n}convert(){let t,r={},n=new VH.FernOptionalExtension({breadcrumbs:this.breadcrumbs,parameter:this.parameter,context:this.context}).convert()??this.parameter.required===!1,a=this.parameter.schema??{...this.parameter,type:"string",enum:this.parameter.enum,default:this.parameter.default,example:this.parameter.example??this.parameter.name,examples:Object.values(this.parameter.examples??{}),deprecated:this.parameter.deprecated,required:void 0},l=new tA.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaIdOverride:this.parameterNamePrefix?`${this.parameterNamePrefix}_${this.parameter.name}`:this.parameter.name,schemaOrReference:a,wrapAsOptional:n}).convert();return l!=null&&(t=l.type,r=l.inlinedTypes??{}),this.convertToOutput({schema:a,typeReference:t,inlinedTypes:r})}};var Ndu=class extends Yg{channel;key="x-fern-address";constructor({breadcrumbs:t,channel:r,context:i}){super({breadcrumbs:t,context:i}),this.channel=r}convert(){let t=this.getExtensionValue(this.channel);if(!(t==null||typeof t!="string"))return t}};var AXn=class extends Yg{channel;key="x-fern-display-name";constructor({breadcrumbs:t,channel:r,context:i}){super({breadcrumbs:t,context:i}),this.channel=r}convert(){let t=this.getExtensionValue(this.channel);if(!(t==null||typeof t!="string"))return t}};var Fdu=class extends MXn{inlinedTypes={};constructor({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a}){super({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a})}convert(){let t=[],r=[],i=[],a=new AXn({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert()??this.websocketGroup?.join(".");this.channel.parameters&&this.convertPathParameters({context:this.context,pathParameters:t}),this.channel.bindings?.ws!=null&&(this.convertHeaders({context:this.context,headers:i}),this.convertBindingQueryParameters({context:this.context,queryParameters:r}));let u;this.channel.subscribe!=null&&(u=this.convertMessage({context:this.context,operation:this.channel.subscribe,origin:"server"}));let l;this.channel.publish!=null&&(l=this.convertMessage({context:this.context,operation:this.channel.publish,origin:"client"}));let d=[];u!=null&&d.push(u),l!=null&&d.push(l);let o=new Ndu({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert(),c=this.transformToValidPath(o??this.channelPath),b=this.channel.servers?.[0]??Object.keys(this.context.spec.servers??{})[0],g=WF(c),O=S_(this.channelPath),m=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[];return{channel:{name:this.context.casingsGenerator.generateName(O),displayName:a,baseUrl:b,path:g,auth:!1,headers:i,queryParameters:r,pathParameters:t,messages:d,availability:this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({fullPath:c,baseUrl:b,asyncApiVersion:"v2"})}},audiences:m,inlinedTypes:this.inlinedTypes}}convertMessage({context:t,operation:r,origin:i}){let n,a=i==="server"?"subscribe":"publish",u=[...this.breadcrumbs,a],l=t.resolveMaybeReference({schemaOrReference:r.message,breadcrumbs:u});l!=null&&(r.message=l);let d=CZi(S_(`${this.channelPath}_${a}`)).replace(/ /g,"");if("oneOf"in r.message){let o=new tA.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:u,schemaOrReference:r.message,schemaIdOverride:d}).convert();o!=null&&o.schema!=null&&(n=o.schema,this.inlinedTypes={...this.inlinedTypes,...o.inlinedTypes})}else if(t.isMessageWithPayload(r.message)){let s=t.resolveMaybeReference({schemaOrReference:r.message.payload,breadcrumbs:u});if(s!=null){let c=new tA.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:u,schemaOrReference:s,schemaIdOverride:d}).convert();c!=null&&c.schema!=null&&(n=c.schema,this.inlinedTypes={...this.inlinedTypes,...c.inlinedTypes})}}if(n!=null){let s=n,o=Xc.named({fernFilepath:t.createFernFilepath(),name:s.typeDeclaration.name.name,typeId:s.typeDeclaration.name.typeId,displayName:void 0,default:void 0,inline:!1}),c=wL.reference({bodyType:o,docs:r.description}),b=i==="server"?"subscribe":"publish";return{type:b,displayName:b,origin:i,body:c,availability:t.getAvailability({node:r,breadcrumbs:this.breadcrumbs}),docs:r.description}}}convertPathParameters({context:t,pathParameters:r}){for(let[i,n]of Object.entries(this.channel.parameters??{})){let a=t.resolveMaybeReference({schemaOrReference:n,breadcrumbs:this.breadcrumbs});if(a==null)continue;let l=new c3i({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...a,name:i,in:"path",description:a.description,required:a.required??!0}}).convert();l!=null&&(this.inlinedTypes={...this.inlinedTypes,...l.inlinedTypes},l.type==="path"&&r.push(l.parameter))}}convertHeaders({context:t,headers:r}){if(this.channel.bindings?.ws?.headers!=null){let i=this.channel.bindings.ws.headers.required??[];for(let[n,a]of Object.entries(this.channel.bindings.ws.headers.properties??{})){let u=t.resolveMaybeReference({schemaOrReference:a,breadcrumbs:[...this.breadcrumbs,n]});if(u==null)continue;let d=new c3i({context:this.context,breadcrumbs:[...this.breadcrumbs,n],parameter:{name:n,in:"header",required:i.includes(n),schema:u,description:"description"in u?u.description:void 0}}).convert();d!=null&&d.type==="header"&&(this.inlinedTypes={...this.inlinedTypes,...d.inlinedTypes},r.push(d.parameter))}}}convertBindingQueryParameters({context:t,queryParameters:r}){if(this.channel.bindings?.ws?.query!=null){let i=this.channel.bindings.ws.query.required??[];for(let[n,a]of Object.entries(this.channel.bindings.ws.query.properties??{})){let u=t.resolveMaybeReference({schemaOrReference:a,breadcrumbs:[...this.breadcrumbs,n]});if(u==null)continue;let d=new c3i({context:this.context,breadcrumbs:[...this.breadcrumbs,n],parameter:{name:n,in:"query",required:i.includes(n),schema:u,description:"description"in u?u.description:void 0,deprecated:u.deprecated??!1}}).convert();d!=null&&d.type==="query"&&(this.inlinedTypes={...this.inlinedTypes,...d.inlinedTypes},r.push(d.parameter))}}}};var qXn=class extends e_{servers;constructor({context:t,breadcrumbs:r,servers:i}){super({context:t,breadcrumbs:r}),this.servers=i}convert(){if(this.servers==null||Object.keys(this.servers).length===0)return;let t=[],r;for(let[i,n]of Object.entries(this.servers)){let a=this.buildSingleBaseUrlEnvironment(this.context,i,n);t.push(a),r==null&&(r=a.id)}return{defaultEnvironment:r,environments:$R.singleBaseUrl({environments:t})}}constructServerUrl(t,r){return r.includes("://")?r:`${t}://${r}`}};var Ldu=class extends qXn{constructor({context:t,breadcrumbs:r,servers:i}){super({context:t,breadcrumbs:r,servers:i})}buildSingleBaseUrlEnvironment(t,r,i){return{id:r,name:t.casingsGenerator.generateName(r),url:this.constructServerUrl(i.protocol,i.url),docs:void 0}}};var GIc="$message.",F4_="#/channels/",L4_="#/servers/",Udu=class extends MXn{operations;inlinedTypes={};constructor({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a,operations:u}){super({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a}),this.operations=u}convert(){let t=[],r=[],i=[],a=new AXn({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert()??this.websocketGroup?.join(".")??this.channelPath;this.channel.parameters&&this.convertChannelParameters({pathParameters:t,queryParameters:r,headers:i,channelPath:this.channelPath});let u=Object.entries(this.operations).reduce((b,[g,O])=>{try{this.getChannelPathFromOperation(O)===this.channelPath&&(b[g]=O)}catch{}return b},{}),l=[];for(let[b,g]of Object.entries(u))for(let O of g.messages){let m=this.context.convertReferenceToTypeReference({reference:O});if(m.ok){let w=wL.reference({bodyType:m.reference,docs:g.description});l.push({type:b,displayName:b,origin:g.action==="send"?"client":"server",body:w,availability:this.context.getAvailability({node:g,breadcrumbs:this.breadcrumbs}),docs:g.description})}}let d=this.resolveChannelServersFromReference(this.channel.servers??[])??Object.keys(this.context.spec.servers??{})[0],s=this.transformToValidPath(this.channel.address??this.channelPath),o=WF(s),c=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[];return{channel:{name:this.context.casingsGenerator.generateName(a),displayName:a,baseUrl:d,path:o,auth:!1,headers:i,queryParameters:r,pathParameters:t,messages:l,availability:this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({fullPath:s,baseUrl:d,asyncApiVersion:"v3"})}},audiences:c,inlinedTypes:this.inlinedTypes}}convertChannelParameters({pathParameters:t,queryParameters:r,headers:i,channelPath:n}){for(let a of Object.values(this.channel.parameters??{})){let u=this.context.resolveMaybeReference({schemaOrReference:a,breadcrumbs:[...this.breadcrumbs,"parameters"]});if(u==null)continue;let l=this.convertChannelParameterLocation(u.location);if(l==null)continue;let{type:d,parameterKey:s}=l,c=new c3i({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...u,name:s,in:d},parameterNamePrefix:this.channelPath}).convert();if(c!=null)switch(this.inlinedTypes={...this.inlinedTypes,...c.inlinedTypes},c.type){case"path":t.push(c.parameter);break;case"query":r.push(c.parameter);break;case"header":i.push(c.parameter);break}}}convertChannelParameterLocation(t){try{let[r,i]=t.split("#/");if(r==null||i==null){this.context.errorCollector.collect({message:`Invalid location format: ${t}; unable to parse message type and parameter key`,path:this.breadcrumbs});return}if(!r.startsWith(GIc)){this.context.errorCollector.collect({message:`Invalid location format: ${t}; expected ${GIc} prefix`,path:this.breadcrumbs});return}let n=r.substring(GIc.length);if(n!=="header"&&n!=="path"&&n!=="payload"){this.context.errorCollector.collect({message:`Invalid message type: ${n}. Must be one of: header, path, payload`,path:this.breadcrumbs});return}return n==="payload"?{type:"query",parameterKey:i}:{type:n,parameterKey:i}}catch{this.context.errorCollector.collect({message:`Invalid location format: ${t}; see here for more details: https://www.asyncapi.com/docs/reference/specification/v3.0.0#runtimeExpression`,path:this.breadcrumbs});return}}resolveChannelServersFromReference(t){if(t==null||t.length===0||t[0]==null)return;let r=t[0];if(!r.$ref.startsWith(L4_)){this.context.errorCollector.collect({message:`Failed to resolve server name from server ref ${r.$ref}`,path:this.breadcrumbs});return}let i=r.$ref.substring(L4_.length);if(i==null){this.context.errorCollector.collect({message:`Failed to find server with name ${i}`,path:this.breadcrumbs});return}return i}getChannelPathFromOperation(t){if(!t.channel.$ref.startsWith(F4_))throw new Error(`Failed to resolve channel path from operation ${t.channel.$ref}`);return t.channel.$ref.substring(F4_.length)}};var Vdu=class extends qXn{constructor({context:t,breadcrumbs:r,servers:i}){super({context:t,breadcrumbs:r,servers:i})}buildSingleBaseUrlEnvironment(t,r,i){return{id:r,name:t.casingsGenerator.generateName(r),url:this.constructServerUrl(i.protocol,i.host),docs:void 0}}};var AUa=class extends cQt{constructor({context:t,breadcrumbs:r,audiences:i}){super({context:t,breadcrumbs:r,audiences:i})}async convert(){return this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.context.spec=await this.resolveAllExternalRefs({spec:this.context.spec}),this.isAsyncAPIV3(this.context)?this.convertChannelMessages():this.convertComponentMessages(),this.convertSchemas(),this.convertServers(),this.convertChannels(),this.finalizeIr()}isAsyncAPIV3(t){return parseFloat(t.spec.asyncapi)>=3}convertChannelMessages(){let t=this.context.spec;for(let[r,i]of Object.entries(t.channels??{}))for(let[n,a]of Object.entries(i.messages??{})){if(!this.context.isMessageWithPayload(a)&&!this.context.isReferenceObject(a))continue;let u=["channels",r,"messages",n],l=this.context.resolveMaybeReference({schemaOrReference:a,breadcrumbs:u});if(!this.context.isMessageWithPayload(l))continue;let d=this.context.resolveMaybeReference({schemaOrReference:l.payload,breadcrumbs:u});if(d==null)continue;let s=`${r}_${n}`;this.convertSchema({id:s,breadcrumbs:u,schema:d})}}convertComponentMessages(){for(let[t,r]of Object.entries(this.context.spec.components?.messages??{})){if(r.payload==null)continue;let i=["components","messages",t],n=this.context.resolveMaybeReference({schemaOrReference:r.payload,breadcrumbs:i});n!=null&&this.convertSchema({id:t,breadcrumbs:i,schema:n})}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{}))this.convertSchema({id:t,breadcrumbs:["components","schemas",t],schema:r})}convertSchema({id:t,breadcrumbs:r,schema:i}){let a=new tA.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:r,schema:i}).convert();a!=null&&(this.addTypeToRootPackage(t),this.addTypesToIr({...a.inlinedTypes,[t]:a.convertedSchema}))}convertServers(){let t;if(this.isAsyncAPIV3(this.context)){let r=this.context.spec.servers;t=new Vdu({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}else{let r=this.context.spec.servers;t=new Ldu({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}this.addEnvironmentsToIr({environmentConfig:t})}convertChannels(){for(let[t,r]of Object.entries(this.context.spec.channels??{})){let n=new VH.SdkGroupNameExtension({breadcrumbs:["channels",t],operation:r,context:this.context}).convert()?.groups,a;if(this.isAsyncAPIV3(this.context)){let l=this.context.spec.operations??{};a=new Udu({context:this.context,breadcrumbs:["channels",t],websocketGroup:n,channel:r,channelPath:t,operations:l}).convert()}else a=new Fdu({context:this.context,breadcrumbs:["channels",t],websocketGroup:n,channel:r,channelPath:t}).convert();a!=null&&(this.addWebsocketChannelToIr({websocketChannel:a.channel,channelPath:t,audiences:a.audiences,websocketGroup:n}),this.addTypesToIr(a.inlinedTypes))}}};var qUa=class extends d7{isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}isMessageWithPayload(t){return t!=null&&typeof t=="object"&&"payload"in t}getTypeIdFromMessageReference(t){let r=t.$ref.match(/\/messages\/(.+)$/);if(!(!r||!r[1]))return r[1]}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n}){let a,u=t.$ref.match(/^.*\/schemas\/(.+)$/),l=t.$ref.match(/^.*\/channels\/([^/]+)\/messages\/(.+)$/),d=t.$ref.match(/^.*\/messages\/(.+)$/);if(u&&u[1])return a=u[1],this.convertSchemaReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a});if(l&&l[2]){let s=l[1],o=l[2];return a=`${s}_${o}`,this.convertV3MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a})}else return d&&d[1]?(a=d[1],this.convertV2MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a})):{ok:!1}}convertSchemaReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a}){let u=this.resolveReference({reference:t,breadcrumbs:r});if(!u.resolved)return{ok:!1};let l;return n==="reference_identifier"?l=i??u.value.title:(n==="discriminator_key"||n==="schema_identifier")&&(l=u.value.title??i),{ok:!0,reference:Xc.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(a),typeId:a,displayName:l,default:void 0,inline:!1})}}convertV3MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a}){let u=this.resolveReference({reference:t,breadcrumbs:r});if(!u.resolved)return{ok:!1};let l;return n==="reference_identifier"?l=i??u.value.name:(n==="discriminator_key"||n==="schema_identifier")&&(l=u.value.name??i),{ok:!0,reference:Xc.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(a),typeId:a,displayName:l,default:void 0,inline:!1})}}convertV2MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a}){let u=this.resolveReference({reference:t,breadcrumbs:r});if(!u.resolved)return{ok:!1};let l;return n==="reference_identifier"?l=i??u.value.messageId??u.value.name:(n==="discriminator_key"||n==="schema_identifier")&&(l=u.value.messageId??u.value.name??i),{ok:!0,reference:Xc.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(a),typeId:a,displayName:l,default:void 0,inline:!1})}}};var $4_=ui(Wdu(),1);var Hdu=class extends Yg{document;key="x-fern-global-headers";constructor({breadcrumbs:t,document:r,context:i}){super({breadcrumbs:t,context:i}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(!Array.isArray(t)){this.context.errorCollector.collect({message:"Received unexpected non-array value for x-fern-global-headers",path:this.breadcrumbs});return}return t}}};function U4_({globalHeaders:e,context:t}){return e.map(r=>({name:t.casingsGenerator.generateNameAndWireValue({name:r.name??"",wireValue:r.header}),valueType:r.optional?e_.OPTIONAL_STRING:e_.STRING,env:r.env,v2Examples:r.optional?void 0:FfM({header:r,context:t}),availability:void 0,docs:void 0}))}function FfM({header:e,context:t}){let r=new G3e({breadcrumbs:[],context:t,schema:{type:"string"},example:e.header}),{validExample:i}=r.convert();return{userSpecifiedExamples:{},autogeneratedExamples:{globalHeaderExample:i}}}var $du=class extends tA.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r,parameter:i})}convert(){let t,r={};if(this.parameter.schema!=null){let i=this.context.convertBreadcrumbsToName([...this.breadcrumbs,this.parameter.name]),a=new tA.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,this.parameter.name,"schema"],schemaOrReference:this.parameter.schema,wrapAsOptional:this.parameter.required==null||!this.parameter.required,schemaIdOverride:i}).convert();a!=null&&(t=a.type,r=a.inlinedTypes??{})}return this.convertToOutput({schema:this.parameter.schema??{type:"string"},typeReference:t,inlinedTypes:r})}};var Gdu=class extends tA.AbstractConverters.AbstractMediaTypeObjectConverter{contentType;mediaType;description;required;schemaId;streamingExtension;constructor({context:t,breadcrumbs:r,contentType:i,mediaType:n,description:a,required:u,group:l,method:d,streamingExtension:s}){super({context:t,breadcrumbs:r,group:l,method:d}),this.contentType=i,this.mediaType=n,this.description=a,this.required=u,this.schemaId=[...this.group,this.method,"Request"].join("_"),this.streamingExtension=s}convert(){return this.streamingExtension?.type=="streamCondition"?this.convertStreamConditionRequestBody():this.convertNonStreamConditionRequestBody()}convertStreamConditionRequestBody(){if(this.isOrderedJsonOrFormContentType())return this.handleStreamConditionJsonOrFormContent({contentType:this.contentType})}convertNonStreamConditionRequestBody(){if(this.isOrderedJsonOrFormContentType())return this.handleJsonOrFormContent({contentType:this.contentType});if(hq.parse(this.contentType)?.isMultipart())return this.handleMultipartContent({contentType:this.contentType});if(this.isBinaryContentType())return this.handleBinaryContent({contentType:this.contentType})}isOrderedJsonOrFormContentType(){let t=hq.parse(this.contentType);return t?t.isJSON()||t.isURLEncoded()||t.isPlainText()||t.isCSV()||t.isHTML()||t.isXML()||t.isDNS()||t.isApplicationText():!1}isBinaryContentType(){let t=hq.parse(this.contentType);return t?t.isBinary():!1}handleJsonOrFormContent({contentType:t}){let r=this.mediaType;if(r==null)return;let i=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,contentType:t});if(i==null)return;let n=i.schema?.typeDeclaration.shape;return n?.type==="object"?{requestBody:IA.inlinedRequestBody({contentType:t,docs:this.description,name:this.context.casingsGenerator.generateName(this.schemaId),extendedProperties:n.extendedProperties,extends:n.extends,properties:n.properties,extraProperties:n.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:i.inlinedTypes})}:{requestBody:IA.reference({contentType:t,docs:this.description,requestBodyType:i.type,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:i.inlinedTypes??{}}}handleMultipartContent({contentType:t}){let r=this.mediaType;if(r==null||r.schema==null)return;let i=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,resolveSchema:!0,contentType:t});if(i==null)return;let n=i.schema?.typeDeclaration.shape;if(n?.type==="object")return{requestBody:IA.fileUpload({contentType:t,docs:this.description,name:this.context.casingsGenerator.generateName(this.schemaId),properties:n.properties.map(a=>{let u=r.encoding?.[a.name.wireValue];return this.convertRequestBodyProperty({property:a,contentType:t,encoding:u})}),v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:i.inlinedTypes}),examples:i.examples}}handleBinaryContent({contentType:t}){let r=this.mediaType;if(r==null)return;let i=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,contentType:t});return{requestBody:IA.bytes({contentType:t,isOptional:this.required===!1,docs:this.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:i?.inlinedTypes??{}}}convertRequestBodyProperty({property:t,contentType:r,encoding:i}){let{isFile:n,isOptional:a,isArray:u}=this.recursivelyCheckTypeReferenceIsFile({typeReference:t.valueType});return n?u?P4.file(roe.fileArray({key:t.name,isOptional:a,contentType:r,docs:t.docs})):P4.file(roe.file({key:t.name,isOptional:a,contentType:r,docs:t.docs})):P4.bodyProperty({...t,contentType:i?.contentType??r,style:UfM({encoding:i}),name:t.name})}handleStreamConditionJsonOrFormContent({contentType:t}){if(this.streamingExtension?.type!=="streamCondition")return;let r=this.mediaType;if(r==null||r.schema==null)return;let i=this.context.resolveMaybeReference({schemaOrReference:r.schema,breadcrumbs:[...this.breadcrumbs,"content",t,"schema"]});if(i==null)return;let n=i.properties?.[this.streamingExtension.streamConditionProperty];if(n==null||this.context.isReferenceObject(n))return;let a=this.buildStreamConditionInlinedRequestBody({streamConditionProperty:n,resolvedMediaTypeSchema:i,isStreaming:!0,contentType:t,mediaTypeObject:r}),u=this.buildStreamConditionInlinedRequestBody({streamConditionProperty:n,resolvedMediaTypeSchema:i,isStreaming:!1,contentType:t,mediaTypeObject:r});if(!(a==null||u==null))return{requestBody:u.requestBody,streamRequestBody:a.requestBody,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:{...a.inlinedTypes,...u.inlinedTypes}})}}buildStreamConditionInlinedRequestBody({streamConditionProperty:t,resolvedMediaTypeSchema:r,isStreaming:i,contentType:n,mediaTypeObject:a}){if(this.streamingExtension==null||this.streamingExtension.type!=="streamCondition")return;let u={...r,properties:{...r.properties,[this.streamingExtension.streamConditionProperty]:{type:"boolean",const:i,...t}},required:[...r.required??[],this.streamingExtension.streamConditionProperty]},l={...a,schema:u},d=this.parseMediaTypeObject({mediaTypeObject:l,schemaId:this.schemaId,contentType:n});if(d==null)return;let s=d.schema?.typeDeclaration.shape;if(s?.type==="object")return{requestBody:IA.inlinedRequestBody({contentType:n,docs:void 0,name:this.context.casingsGenerator.generateName(i?`${this.schemaId}_streaming`:this.schemaId),extendedProperties:s.extendedProperties,extends:s.extends,properties:s.properties,extraProperties:s.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:l,exampleGenerationStrategy:"request"})}),inlinedTypes:d.inlinedTypes}}recursivelyCheckTypeReferenceIsFile({typeReference:t,isOptional:r,isArray:i}){return this.context.isList(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.list,isOptional:r,isArray:!0}):this.context.isOptional(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.optional,isOptional:!0,isArray:i}):this.context.isNullable(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.nullable,isOptional:r,isArray:i}):{isFile:this.context.isFile(t),isOptional:r??!1,isArray:i??!1}}},LfM={"application/json":"json"};function UfM({encoding:e}){if(e){if(e.explode)return"exploded";if(e.style==="form")return"form";if(e.contentType)return LfM[e.contentType]}}var VfM=/{([^}]+)}/g,WfM=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]),TXn=class extends e_{operation;method;path;inlinedTypes={};constructor({context:t,breadcrumbs:r,operation:i,method:n,path:a}){super({context:t,breadcrumbs:r}),this.operation=i,this.method=n,this.path=a}convertHttpMethod(){switch(this.method){case"get":return xB.Get;case"post":return xB.Post;case"put":return xB.Put;case"delete":return xB.Delete;case"patch":return xB.Patch;case"head":return xB.Head;default:return}}convertParameters({breadcrumbs:t}){let r=[],i=[],n=[];if(!this.operation.parameters)return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:i,headers:n};for(let a of this.operation.parameters){let u=this.context.resolveMaybeReference({schemaOrReference:a,breadcrumbs:t});if(u==null)continue;let d=new $du({context:this.context,breadcrumbs:t,parameter:u}).convert();if(d!=null)switch(this.inlinedTypes={...this.inlinedTypes,...d.inlinedTypes},d.type){case"path":r.push(d.parameter);break;case"query":i.push(d.parameter);break;case"header":{let s=d.parameter.name.name.originalName,o=d.parameter.name.wireValue,c=!1,b=this.context.authOverrides?.["auth-schemes"];if(b!=null){for(let O of Object.values(b))if(QfM(O)&&O.header.toLowerCase()===o.toLowerCase()){c=!0;break}}let g=this.context.globalHeaderNames;if(g!=null){for(let O of g)if(O.toLowerCase()===o.toLowerCase()){c=!0;break}}!WfM.has(s.toLowerCase())&&!c&&n.push(d.parameter);break}}}return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:i,headers:n}}checkMissingPathParameters(t){let i=[...this.path.matchAll(VfM)].map(n=>n[1]).filter(n=>!t.some(a=>a.name.originalName===n));for(let n of i){if(n==null)continue;let a=`${n}_example`;t.push({name:this.context.casingsGenerator.generateName(n),valueType:e_.STRING,docs:void 0,location:"ENDPOINT",variable:void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{[a]:this.generateStringParameterExample({example:n})}}})}}convertRequestBody({breadcrumbs:t,group:r,method:i,streamingExtension:n}){if(this.operation.requestBody==null)return;let a=this.context.resolveMaybeReference({schemaOrReference:this.operation.requestBody,breadcrumbs:t});if(a==null)return null;let u=[];for(let[l,d]of Object.entries(a.content)){let o=new Gdu({context:this.context,breadcrumbs:t,contentType:l,mediaType:d,description:a.description,required:a.required,group:r??[],method:i,streamingExtension:n}).convert();o!=null&&(this.inlinedTypes={...this.inlinedTypes,...o.inlinedTypes},u.push({requestBody:o.requestBody,streamRequestBody:o.streamRequestBody,examples:o.examples}))}return u}computeGroupNameAndLocationFromExtensions(){let r=new VH.SdkMethodNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.methodName,n=new VH.SdkGroupNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.groups??[];if(r!=null)return{group:n,method:r}}evaluateMethodNameFromOperation(){let t=this.operation.operationId;return t??(this.operation.summary!=null?S_(this.operation.summary):S_(`${this.method}_${this.path.split("/").join("_")}`))}computeGroupNameFromTagAndOperationId(){let t=this.operation.tags?.[0],r=this.evaluateMethodNameFromOperation();if(t==null)return{method:r};let i=V4_(t),n=V4_(r);return g8(i,n)?{method:t}:this.computeGroupAndMethodFromTokens({tag:t,tagTokens:i,methodName:r,methodNameTokens:n})}computeGroupAndMethodFromTokens({tag:t,tagTokens:r,methodName:i,methodNameTokens:n}){if(r.some((l,d)=>l!==n[d]))return{group:[t],method:i};let u=n.slice(r.length);return{group:[t],method:S_(u.join("_"))}}generateStringParameterExample({example:t}){let r=new tA.ExampleConverter({breadcrumbs:this.breadcrumbs,context:this.context,schema:{type:"string"},example:t}),{validExample:i}=r.convert();return i}};function V4_(e){let t=HfM(e)?$fM(e):GfM(e);return t=t.map(r=>r.toLowerCase()),t=Gxe(t),t}function HfM(e){return/^[a-z]+(?:[A-Z][a-z]+)*$/.test(e)}function $fM(e){return e.split(/(?=[A-Z])/)}function GfM(e){return e.split(/[^a-zA-Z0-9]+/)}function QfM(e){return e?.header!=null}var CXn=class extends TXn{constructor({context:t,breadcrumbs:r,operation:i,method:n,path:a}){super({context:t,breadcrumbs:r,operation:i,method:n,path:a})}convert(){if(this.operation.requestBody==null){this.context.errorCollector.collect({message:"Skipping webhook because no request body present",path:this.breadcrumbs});return}let t=this.convertHttpMethod();if(t==null)return;if(t!=="POST"&&t!=="GET"){this.context.errorCollector.collect({message:"Skipping webhook because non-POST or GET method",path:this.breadcrumbs});return}let{group:r,method:i}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),n=[...this.breadcrumbs,"Payload"],{headers:a}=this.convertParameters({breadcrumbs:n}),u=this.convertRequestBody({breadcrumbs:n,group:r,method:i,streamingExtension:void 0});if(u==null)return;let l=u[0]?.requestBody;if(l==null)return;let d;if(l.type==="inlinedRequestBody")d=yH.inlinedPayload({name:l.name,extends:l.extends,properties:l.properties});else if(l.type==="reference")d=yH.reference({payloadType:l.requestBodyType,docs:l.docs});else return;return{audiences:this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],group:r,webhook:{id:`${r?.join(".")??""}.${i}`,name:this.context.casingsGenerator.generateName(i),displayName:this.operation.summary,method:t,headers:a,payload:d,examples:[],availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),docs:this.operation.description,v2Examples:{autogeneratedExamples:this.getWebhookV2ExamplesFromRequestBodyV2Examples(l.v2Examples?.autogeneratedExamples??{}),userSpecifiedExamples:this.getWebhookV2ExamplesFromRequestBodyV2Examples(l.v2Examples?.userSpecifiedExamples??{})}},inlinedTypes:this.inlinedTypes}}getWebhookV2ExamplesFromRequestBodyV2Examples(t){return Object.fromEntries(Object.entries(t).map(([r,i])=>[r,{name:r,payload:i}]))}};var KIc=ui(Wdu(),1);var W4_=["get","post","put","delete","patch","head"];var Qdu=class extends Yg{operation;key="x-fern-idempotent";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-idempotent",path:this.breadcrumbs});return}return t}}};var JfM=Su.object({cursor:Su.string(),next_cursor:Su.string(),results:Su.string()}),KfM=Su.object({offset:Su.string(),results:Su.string(),step:Su.string().optional(),"has-next-page":Su.string().optional()}),QIc=Su.union([Su.boolean(),JfM,KfM]);var JIc="$request.",Jdu="$response.",Kdu=class extends Yg{operation;document;key="x-fern-pagination";constructor({breadcrumbs:t,operation:r,document:i,context:n}){super({breadcrumbs:t,context:n}),this.operation=r,this.document=i}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=QIc.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-pagination extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean"){let i=this.getExtensionValue(this.document);if(i==null)return;if(typeof i=="boolean"){this.context.errorCollector.collect({message:"Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.",path:this.breadcrumbs});return}let n=QIc.safeParse(i);if(!n.success){this.context.errorCollector.collect({message:`Invalid x-fern-pagination extension: ${n.error.message}`,path:this.breadcrumbs});return}if(typeof n.data=="boolean"){this.context.errorCollector.collect({message:"Global pagination extension is a boolean, expected an object.",path:this.breadcrumbs});return}return this.convertPaginationConfig({config:n.data})}if(typeof r.data=="boolean"){this.context.errorCollector.collect({message:"Pagination extension is a boolean with no global configuration.",path:this.breadcrumbs});return}return this.convertPaginationConfig({config:r.data})}convertPaginationConfig({config:t}){let r=t;if("cursor"in r)return{type:"cursor",cursor:d7.maybeTrimPrefix(r.cursor,JIc),nextCursor:d7.maybeTrimPrefix(r.next_cursor,Jdu),results:d7.maybeTrimPrefix(r.results,Jdu)};let i=t;return{type:"offset",offset:d7.maybeTrimPrefix(i.offset,JIc),results:d7.maybeTrimPrefix(i.results,Jdu),step:i.step!=null?d7.maybeTrimPrefix(i.step,JIc):void 0,hasNextPage:i["has-next-page"]!=null?d7.maybeTrimPrefix(i["has-next-page"],Jdu):void 0}}};var YfM="$request.",XfM=Su.object({"stream-condition":Su.string().optional(),format:Su.enum(["sse","json"]).optional(),"stream-description":Su.string().optional(),"response-stream":Su.any(),response:Su.any()}),ZfM=Su.union([Su.boolean(),XfM]),Ydu=class extends Yg{operation;key="x-fern-streaming";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=ZfM.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-streaming extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean")return r.data?{type:"stream",format:"json"}:void 0;if(r.data["stream-condition"]==null&&r.data.format!=null)return{type:"stream",format:r.data.format};if(r.data["stream-condition"]==null){this.context.errorCollector.collect({message:"Missing stream-condition property without specified format.",path:this.breadcrumbs});return}return{type:"streamCondition",format:r.data.format??"json",streamDescription:r.data["stream-description"],streamConditionProperty:d7.maybeTrimPrefix(r.data["stream-condition"],YfM),responseStream:r.data["response-stream"],response:r.data.response}}};var Xdu=class extends Yg{operation;key="x-fern-webhook";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-webhook",path:this.breadcrumbs});return}return t}}};var Zdu=class extends Yg{operation;key="x-fern-examples";constructor({context:t,breadcrumbs:r,operation:i}){super({breadcrumbs:r,context:t}),this.operation=i}convert(){let t=this.getExtensionValue(this.operation);return t==null?void 0:(Array.isArray(t)?t:[]).filter(n=>{let a=MF.serialization.ExampleEndpointCallSchema.parse(n);return a.ok||this.context.errorCollector.collect({message:`Failed to parse x-fern-example in ${this.breadcrumbs.join(".")}`,path:this.breadcrumbs}),a.ok})}};var kdu=class extends tA.AbstractConverters.AbstractMediaTypeObjectConverter{responseBody;statusCode;streamingExtension;constructor({context:t,breadcrumbs:r,responseBody:i,group:n,method:a,statusCode:u,streamingExtension:l}){super({context:t,breadcrumbs:r,group:n,method:a}),this.responseBody=i,this.statusCode=u,this.streamingExtension=l}convert(){return this.shouldConvertAsStreaming()?this.convertStreamingResponseBody():this.convertNonStreamingResponseBody()}convertStreamingResponseBody(){if(this.streamingExtension!=null){if(this.streamingExtension.type=="streamCondition"){let t=this.streamingExtension.responseStream,r=this.streamingExtension.response,i=[...this.group,this.method,"Response",this.statusCode].join("_"),n=`${i}_streaming`,a=this.parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:n}),u=this.parseMediaTypeSchemaOrReference({schemaOrReference:r,schemaId:i});return this.convertStreamConditionResponse({convertedStreamingSchema:a,convertedNonStreamingSchema:u})}if(this.streamingExtension.type==="stream"){let t=[...this.group,this.method,"Response",this.statusCode].join("_"),r=Object.keys(this.responseBody.content??{});for(let i of r){let n=this.responseBody.content?.[i];if(n==null)continue;let a=this.parseMediaTypeObject({mediaTypeObject:n,schemaId:t,contentType:this.streamingExtension.format});if(a!=null)return this.convertStreamingResponse({mediaTypeObject:n,convertedSchema:a})}}}}convertNonStreamingResponseBody(){let t=[...this.group,this.method,"Response",this.statusCode].join("_"),r=Object.keys(this.responseBody.content??{}).filter(a=>a.includes("json"));for(let a of r){let u=this.responseBody.content?.[a];if(u==null)continue;let l=this.parseMediaTypeObject({mediaTypeObject:u,schemaId:t,contentType:a});if(l!=null&&this.shouldReturnJsonResponse(a))return this.returnJsonResponse({mediaTypeObject:u,convertedSchema:l})}let i=Object.keys(this.responseBody.content??{}).filter(a=>!a.includes("json"));for(let a of i){let u=this.responseBody.content?.[a];if(u==null)continue;let l=this.parseMediaTypeObject({mediaTypeObject:u,schemaId:t,contentType:a});if(l!=null){if(this.isBinarySchema(l))return this.shouldReturnBytesResponse()?this.returnBytesResponse({mediaTypeObject:u}):this.returnFileDownloadResponse({mediaTypeObject:u});if(this.shouldReturnTextResponse(a))return this.returnTextResponse({mediaTypeObject:u})}}let n=parseInt(this.statusCode);if(!isNaN(n)&&n>=200&&n<300){let a={schema:{type:"object",description:"Empty response body"}},u=this.parseMediaTypeObject({mediaTypeObject:a,schemaId:t,contentType:"application/json",resolveSchema:!0});if(u!=null)return this.returnJsonResponse({mediaTypeObject:a,convertedSchema:u})}}convertStreamConditionResponse({convertedStreamingSchema:t,convertedNonStreamingSchema:r}){if(!(t==null||r==null))return{responseBody:c1.json(OL.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:r.schema?.typeDeclaration.v2Examples})),streamResponseBody:c1.streaming(mL.json({docs:this.responseBody.description,payload:t.type,terminator:void 0,v2Examples:t.schema?.typeDeclaration.v2Examples})),inlinedTypes:{...t.inlinedTypes,...r.inlinedTypes}}}convertStreamingResponse({mediaTypeObject:t,convertedSchema:r}){if(this.streamingExtension==null)return;switch(this.streamingExtension.format){case"json":return{responseBody:c1.streaming(mL.json({docs:this.responseBody.description,payload:r.type,terminator:void 0,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples};case"sse":return{responseBody:c1.streaming(mL.sse({docs:this.responseBody.description,payload:r.type,terminator:void 0,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples};default:return}}returnJsonResponse({mediaTypeObject:t,convertedSchema:r}){return{responseBody:c1.json(OL.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples}}returnBytesResponse({mediaTypeObject:t}){return{responseBody:c1.bytes({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{}}}returnFileDownloadResponse({mediaTypeObject:t}){return{responseBody:c1.fileDownload({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{}}}returnTextResponse({mediaTypeObject:t}){return{responseBody:c1.text({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{}}}isBinarySchema(t){let r=t.type;switch(r.type){case"container":case"named":case"unknown":return!1;case"primitive":return r.primitive.v2==null?!1:r.primitive.v2.type==="string"&&r.primitive.v2.validation?.format==="binary";default:return!1}}shouldConvertAsStreaming(){return this.streamingExtension!=null}shouldReturnJsonResponse(t){return t.includes("json")}shouldReturnBytesResponse(){return this.context.settings.useBytesForBinaryResponse&&this.streamingExtension==null}shouldReturnTextResponse(t){return hq.parse(t)?.isText()??!1}};var epu=class extends tA.AbstractConverters.AbstractMediaTypeObjectConverter{responseError;statusCode;methodName;constructor({context:t,breadcrumbs:r,responseError:i,group:n,method:a,methodName:u,statusCode:l}){super({context:t,breadcrumbs:r,group:n,method:a}),this.responseError=i,this.statusCode=l,this.methodName=u}convert(){if(!this.responseError.content){let i=o5a[this.statusCode];if(i==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}let n=this.getErrorIdFromErrorName(i);return{error:{error:{name:this.context.casingsGenerator.generateName(n),fernFilepath:{allParts:[],packagePath:[],file:void 0},errorId:n},docs:this.responseError.description},errorType:Xc.unknown(),displayName:i,statusCode:this.statusCode,inlinedTypes:{},examples:{}}}let t=Object.keys(this.responseError.content).filter(i=>i.includes("json")),r=o5a[this.statusCode];if(r==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}for(let i of[...t]){let n=this.responseError.content?.[i];if(n==null)continue;let a=this.parseMediaTypeObject({mediaTypeObject:n,schemaId:H4_(`${this.methodName}Request${r}`),contentType:i});if(a==null)continue;let u=this.getErrorIdFromErrorName(r);if(a.schema!=null)return this.constructErrorConverterOutput({errorName:r,errorId:u,fernFilepath:a.schema.typeDeclaration.name.fernFilepath,convertedSchema:a});if(a.type.type==="named")return this.constructErrorConverterOutput({errorName:r,errorId:u,fernFilepath:a.type.fernFilepath,convertedSchema:a})}}constructErrorConverterOutput({errorName:t,errorId:r,fernFilepath:i,convertedSchema:n}){return{error:{error:{name:this.context.casingsGenerator.generateName(r),fernFilepath:i,errorId:r},docs:this.responseError.description},errorType:n.type,displayName:t,statusCode:this.statusCode,inlinedTypes:n.inlinedTypes,examples:n.examples}}getErrorIdFromErrorName(t){return this.context.enableUniqueErrorsPerEndpoint?H4_(`${this.methodName}Request${t}`):t}};function H4_(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1)}var tpu=class e extends TXn{idempotent;idToAuthScheme;topLevelServers;streamingExtension;static AUTHORIZATION_HEADER="Authorization";constructor({context:t,breadcrumbs:r,operation:i,method:n,path:a,idempotent:u,idToAuthScheme:l,topLevelServers:d,streamingExtension:s}){super({context:t,breadcrumbs:r,operation:i,method:n,path:a}),this.idempotent=u,this.idToAuthScheme=l,this.topLevelServers=d,this.streamingExtension=s}convert(){let t=this.convertHttpMethod();if(t==null)return;let{group:r,method:i}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),n=this.getGroupDisplayName(r),{headers:a,pathParameters:u,queryParameters:l}=this.convertParameters({breadcrumbs:[...this.breadcrumbs,"parameters"]}),d=this.convertRequestBody({breadcrumbs:[...this.breadcrumbs,"requestBody"],group:r,method:i,streamingExtension:this.streamingExtension}),s=d?.[0]?.requestBody,o=d?.[0]?.streamRequestBody,c={requestBodies:d?.map(K=>K.requestBody)},b=this.convertResponseBody({breadcrumbs:[...this.breadcrumbs,"responses"],group:r,method:i,streamingExtension:this.streamingExtension}),g=b?.response,O=b?.streamResponse,m=b!=null?b.errors:[],w={},E=m.map(K=>K.error),q=WF(this.path),M=this.getEndpointBaseUrl(),D=this.getEndpointBaseUrls(),C=this.convertExamples({httpPath:q,httpMethod:t,baseUrl:M}),R=new Set(this.operation.security?.flatMap(K=>Object.keys(K))??[]),G=this.authSchemeToHeaders(Array.from(R));G.length>0&&a.push(...G);for(let K of m){let X=K.error,oe=K.errorType,pe=X.error.errorId,de=K.examples;w[pe]={name:X.error,displayName:K.displayName,discriminantValue:{name:X.error.name,wireValue:pe},type:oe,statusCode:K.statusCode,docs:X.docs,examples:[],v2Examples:{userSpecifiedExamples:de??{},autogeneratedExamples:{}}}}let I=this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],L={displayName:this.operation.summary,method:t,baseUrl:M,v2BaseUrls:D,path:q,pathParameters:u,queryParameters:l,headers:a.filter((K,X,oe)=>X===oe.findIndex(pe=>pe.name.wireValue===K.name.wireValue)),sdkRequest:void 0,errors:E,auth:this.operation.security!=null||this.context.spec.security!=null,availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),userSpecifiedExamples:[],autogeneratedExamples:[],idempotent:this.idempotent??!1,basePath:void 0,fullPath:q,allPathParameters:u,pagination:void 0,transport:void 0,source:DJ.openapi(),audiences:I},V=this.context.namespace!=null?[this.context.namespace]:[],Y=r?.map(K=>S_(K));return V.push(...Y??[]),{audiences:I,group:r,groupDisplayName:n,errors:w,endpoint:{...L,id:`endpoint_${V.join("/")}.${i}`,name:this.context.casingsGenerator.generateName(i),requestBody:s,v2RequestBodies:c,response:g,docs:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:C.examples},v2Responses:{responses:b?.v2Responses}},streamEndpoint:O!=null&&O.body!=null?{...L,id:`endpoint_${V.join("/")}.${i}_stream`,name:this.context.casingsGenerator.generateName(`${i}_stream`),requestBody:o,v2RequestBodies:void 0,response:O,docs:this.streamingExtension?.type==="streamCondition"?this.streamingExtension.streamDescription??this.operation.description:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:C.streamExamples},v2Responses:{responses:b?.v2Responses}}:void 0,inlinedTypes:this.inlinedTypes,servers:this.filterOutTopLevelServers(this.operation.servers??[])}}convertResponseBody({breadcrumbs:t,group:r,method:i,streamingExtension:n}){if(this.operation.responses==null)return;let a,u=!1;for(let[l,d]of Object.entries(this.operation.responses)){let s=parseInt(l);if(!(isNaN(s)||s<200||s>=300&&s<400)){if(a==null&&(a={response:void 0,v2Responses:void 0,streamResponse:void 0,errors:[],examples:{}}),s>=200&&s<300){let o=this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:[...t,l]});if(o==null)continue;let b=new kdu({context:this.context,breadcrumbs:[...t,l],responseBody:o,group:r??[],method:i,statusCode:l,streamingExtension:n}).convert();b!=null&&(this.inlinedTypes={...this.inlinedTypes,...b.inlinedTypes},u||(u=!0,a.response={statusCode:s,body:b.responseBody},a.streamResponse={statusCode:s,body:b.streamResponseBody}),a.v2Responses=[...a.v2Responses??[],{statusCode:s,body:b.responseBody}])}if(s>=400&&s<600){let o=this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:[...t,l]});if(o==null)continue;let b=new epu({context:this.context,breadcrumbs:[...t,l],responseError:o,group:r??[],method:i,methodName:this.evaluateMethodNameFromOperation(),statusCode:s}).convert();b!=null&&(this.inlinedTypes={...this.inlinedTypes,...b.inlinedTypes},a.errors.push(b))}}}return a}authSchemeToHeaders(t){let r=[];for(let i of t){let n=this.idToAuthScheme?.[i];if(n==null)continue;let a={valueType:e_.STRING,availability:void 0,docs:void 0,env:void 0,v2Examples:void 0};switch(n.type){case"bearer":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},...a});break;case"basic":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},...a});break;case"header":r.push({name:n.name,...a});break}}return r}convertExamples({httpPath:t,httpMethod:r,baseUrl:i}){let a=new Zdu({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation}).convert();return a==null?{examples:{},streamExamples:{}}:this.streamingExtension?.type==="streamCondition"?this.convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:a}):{examples:this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:a}),streamExamples:{}}}convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:n}){let a=n.filter(s=>!(s.response!=null&&"stream"in s.response)),u=n.filter(s=>s.response!=null&&"stream"in s.response),l=this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:a}),d=this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:u});return{examples:l,streamExamples:d}}convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:n}){return Object.fromEntries(n.map((a,u)=>[this.getExampleName({example:a,exampleIndex:u}),{displayName:void 0,request:a.request!=null?{docs:void 0,endpoint:{method:r,path:this.buildExamplePath(t,a["path-parameters"]??{})},baseUrl:void 0,environment:i,auth:void 0,pathParameters:a["path-parameters"]??{},queryParameters:a["query-parameters"]??{},headers:a.headers??{},requestBody:a.request}:void 0,response:a.response!=null?{docs:void 0,statusCode:void 0,body:this.getExampleResponseBody({example:a})}:void 0,codeSamples:a["code-samples"]?.map(l=>{let d=("language"in l?l.language:l.sdk)??void 0;return{name:l.name,docs:void 0,language:d,code:l.code}})}]))}getExampleName({example:t,exampleIndex:r}){return t.name??t["code-samples"]?.[0]?.name??`Example_${r}`}getExampleResponseBody({example:t}){if(t.response!=null){if("stream"in t.response)return Vs.V2HttpEndpointResponseBody.stream(t.response.stream);if("body"in t.response)return Vs.V2HttpEndpointResponseBody.json(t.response.body)}}getEndpointBaseUrl(){let t=this.operation.servers?.[0];if(t==null)return;let i=this.topLevelServers?.find(n=>n.url===t.url)??t;return QAe.getServerName({server:i,context:this.context})}getEndpointBaseUrls(){let t=this.operation.servers;return t?.map(i=>{let a=this.topLevelServers?.find(u=>u.url===i.url)??i;return QAe.getServerName({server:a,context:this.context})})}buildExamplePath(t,r){return t.head+t.parts.map(i=>`${r[i.pathParameter]?.toString()??i.pathParameter}${i.tail}`).join("")}filterOutTopLevelServers(t){return t.filter(r=>!this.topLevelServers?.some(i=>i.url===r.url))}getGroupDisplayName(t){let r=this.operation.tags?.[0];r!=null&&(r=this.context.getDisplayNameForTag(r));let i=t?.[t.length-1];if(i!=null&&r!=null)return r.toLowerCase().replaceAll(" ","")===i?r:void 0}};var rpu=class extends e_{pathItem;path;idToAuthScheme;topLevelServers;constructor({context:t,breadcrumbs:r,pathItem:i,path:n,idToAuthScheme:a,topLevelServers:u}){super({context:t,breadcrumbs:r}),this.pathItem=i,this.path=n,this.idToAuthScheme=a,this.topLevelServers=u}convert(){let t=[],r=[],i={};for(let n of W4_){let a=this.pathItem[n];if(a==null)continue;let u=[...this.breadcrumbs,n],l=this.tryParseAsWebhook({operationBreadcrumbs:u,operation:a,method:n,context:this.context});if(l!=null){r.push(l),Object.assign(i,l.inlinedTypes);continue}let s=new Ydu({breadcrumbs:u,operation:a,context:this.context}).convert(),o=this.tryParseAsHttpEndpoint({operationBreadcrumbs:u,operation:a,method:n,streamingExtension:s});o!=null&&(t.push(o),Object.assign(i,o.inlinedTypes))}return{endpoints:t,webhooks:r,inlinedTypes:i}}tryParseAsWebhook({operation:t,method:r,operationBreadcrumbs:i,context:n}){return new Xdu({breadcrumbs:i,operation:t,context:n}).convert()?new CXn({context:this.context,breadcrumbs:i,operation:t,method:KIc.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path}).convert():void 0}tryParseAsHttpEndpoint({operation:t,method:r,operationBreadcrumbs:i,streamingExtension:n}){new Kdu({breadcrumbs:i,operation:t,document:this.context.spec,context:this.context}).convert()!=null;let d=new Qdu({breadcrumbs:i,operation:t,context:this.context}).convert();return new tpu({context:this.context,breadcrumbs:i,operation:t,method:KIc.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path,idempotent:d,idToAuthScheme:this.idToAuthScheme,topLevelServers:this.topLevelServers,streamingExtension:n}).convert()}};var ipu=class extends e_{securityScheme;constructor({context:t,breadcrumbs:r,securityScheme:i}){super({context:t,breadcrumbs:r}),this.securityScheme=i}convert(){switch(this.securityScheme.type){case"http":{if(this.securityScheme.scheme==="bearer")return BA.bearer({token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,docs:this.securityScheme.description});if(this.securityScheme.scheme==="basic")return BA.basic({username:this.context.casingsGenerator.generateName("username"),password:this.context.casingsGenerator.generateName("password"),usernameEnvVar:void 0,passwordEnvVar:void 0,docs:this.securityScheme.description});break}case"apiKey":{if(this.securityScheme.in==="header")return BA.header({name:{name:this.context.casingsGenerator.generateName("apiKey"),wireValue:this.securityScheme.name},valueType:e_.OPTIONAL_STRING,prefix:void 0,headerEnvVar:void 0,docs:this.securityScheme.description});break}case"oauth2":return BA.bearer({token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,docs:this.securityScheme.description})}}};var TUa=class extends cQt{constructor({breadcrumbs:t,context:r,audiences:i}){super({breadcrumbs:t,context:r,audiences:i})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.context.spec=await this.resolveAllExternalRefs({spec:this.context.spec});let t=this.convertSecuritySchemes();this.convertGlobalHeaders(),this.convertSchemas(),this.convertWebhooks();let{endpointLevelServers:r,errors:i}=this.convertPaths({idToAuthScheme:t});this.addErrorsToIr(i);let{defaultUrl:n}=this.convertServers({endpointLevelServers:r});return this.updateEndpointsWithDefaultUrl(n),this.finalizeIr()}convertGlobalHeaders(){this.context.globalHeaderOverrides;let r=new Hdu({breadcrumbs:["x-fern-global-headers"],document:this.context.spec,context:this.context}).convert();if(r!=null){let i=U4_({globalHeaders:r,context:this.context});this.addGlobalHeadersToIr(i),this.context.setGlobalHeaders(i)}}convertSecuritySchemes(){if(this.context.authOverrides)return this.addAuthToIR(Yjc({rawApiFileSchema:this.context.authOverrides,casingsGenerator:this.context.casingsGenerator})),{};let t={},r=[];for(let[i,n]of Object.entries(this.context.spec.components?.securitySchemes??{})){let a=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:["components","securitySchemes",i]});if(a==null)continue;let l=new ipu({context:this.context,breadcrumbs:["components","securitySchemes",i],securityScheme:a}).convert();l!=null&&(this.shouldAddAuthSchemeToIr({authScheme:l,schemeId:i,currentSecuritySchemes:r})?r.push(l):t[i]=l)}return r.length>0&&this.addAuthToIR({requirement:r.length===1?"ALL":"ANY",schemes:r,docs:void 0}),t}convertServers({endpointLevelServers:t}){if(this.context.environmentOverrides){let n=Y8a({rawApiFileSchema:this.context.environmentOverrides,casingsGenerator:this.context.casingsGenerator});return n!=null&&this.addEnvironmentsToIr({environmentConfig:n.environmentsConfig,audiences:n.audiences}),{defaultUrl:this.context.environmentOverrides["default-url"]}}let i=new QAe({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t}).convert();return this.addEnvironmentsToIr({environmentConfig:i?.value}),{defaultUrl:i?.defaultUrl}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{})){let n=new tA.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:["components","schemas",t],schema:r}).convert();n!=null&&(this.addTypeToPackage(t),this.addTypesToIr({...n.inlinedTypes,[t]:n.convertedSchema}))}}convertWebhooks(){for(let[,t]of Object.entries(this.context.spec.webhooks??{})){if(t==null){this.context.errorCollector.collect({message:"Skipping empty webhook",path:this.breadcrumbs});continue}if(!("post"in t)){this.context.errorCollector.collect({message:"Skipping webhook as it is not a POST method",path:this.breadcrumbs});continue}if(t.post?.operationId==null){this.context.errorCollector.collect({message:"Skipping webhook as no operationId is present",path:this.breadcrumbs});continue}let r=t.post.operationId,n=new CXn({context:this.context,breadcrumbs:["webhooks",r],operation:t.post,method:$4_.OpenAPIV3.HttpMethods.POST,path:r}).convert();n!=null&&(this.addWebhookToIr({webhook:n.webhook,operationId:r,audiences:n.audiences,group:n.group}),this.addTypesToIr(n.inlinedTypes))}}convertPaths({idToAuthScheme:t}){let r=[],i={};for(let[n,a]of Object.entries(this.context.spec.paths??{})){if(a==null)continue;let l=new rpu({context:this.context,breadcrumbs:["paths",n],topLevelServers:this.context.spec.servers,pathItem:a,path:n}).convert();if(l!=null){for(let d of l.endpoints){if(d.streamEndpoint!=null&&this.addEndpointToIr({endpoint:d.streamEndpoint,audiences:d.audiences,endpointGroup:d.group,endpointGroupDisplayName:d.groupDisplayName}),this.addEndpointToIr({endpoint:d.endpoint,audiences:d.audiences,endpointGroup:d.group,endpointGroupDisplayName:d.groupDisplayName}),d.servers)for(let s of d.servers)this.shouldAddServerToCollectedServers({server:s,currentServers:r})&&r.push(s);if(d.errors)for(let[s,o]of Object.entries(d.errors))i[s]=o}for(let d of l.webhooks){let s=this.context.getGroup({groupParts:d.group,namespace:this.context.namespace});this.addWebhookToIr({webhook:d.webhook,operationId:s.join("."),group:s,audiences:d.audiences})}this.addTypesToIr(l.inlinedTypes)}}return{endpointLevelServers:r,errors:i}}shouldAddAuthSchemeToIr({authScheme:t,schemeId:r,currentSecuritySchemes:i}){let n=i.some(u=>u.type===t.type&&u.type==="bearer"&&t.type==="bearer"?u.token===t.token:!1),a=new Set(this.context.spec.security?.flatMap(u=>Object.keys(u))??[]);return(a.size===0||a.has(r))&&!n}};var npu=class extends Yg{tag;key="x-displayName";constructor({breadcrumbs:t,tag:r,context:i}){super({breadcrumbs:t,context:i}),this.tag=r}convert(){if(typeof this.tag!="object"||this.tag==null)return;let t=this.tag[this.key];if(t!=null){if(typeof t!="string"){this.context.errorCollector.collect({message:"x-displayName extension must be a string",path:this.breadcrumbs});return}if(t.trim().length!==0)return{displayName:t}}}};var CUa=class extends d7{globalHeaderNames;tagToDisplayName={};isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n}){let a=this.getTypeIdFromSchemaReference(t);if(a==null)return{ok:!1};let u=this.resolveReference({reference:t,breadcrumbs:r});if(!u.resolved)return{ok:!1};let l;n==="reference_identifier"?l=i??u.value.title:(n==="discriminator_key"||n==="schema_identifier")&&(l=u.value.title??i);let d;if(a.includes("/")){let o=new tA.SchemaConverters.SchemaConverter({context:this,breadcrumbs:r??[],schema:u.value,id:a}).convert();o!=null&&(d={[a]:o.convertedSchema})}return{ok:!0,reference:Xc.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(a),typeId:a,default:void 0,inline:!1,displayName:l}),inlinedTypes:d}}setGlobalHeaders(t){this.globalHeaderNames=t.map(r=>r.name.wireValue)}getDisplayNameForTag(t){if(Object.keys(this.tagToDisplayName).length===0)for(let r of this.spec.tags??[]){let n=new npu({breadcrumbs:["tags",r.name],tag:r,context:this}).convert()?.displayName??r.name;this.tagToDisplayName[r.name]=n}return this.tagToDisplayName[t]??t}};var kfM=Su.object({description:Su.string().optional(),required:Su.boolean().optional(),deprecated:Su.boolean().optional(),allowEmptyValue:Su.boolean().optional(),style:Su.string().optional(),explode:Su.boolean().optional(),allowReserved:Su.boolean().optional(),schema:Su.any().optional(),example:Su.any().optional(),examples:Su.record(Su.string(),Su.any()).optional(),content:Su.record(Su.string(),Su.any()).optional()}),edM=kfM.extend({name:Su.string(),in:Su.string()}),tdM=Su.array(edM),apu=class extends Yg{operation;key="x-fern-parameters";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null)try{return tdM.parse(t)}catch(r){this.context.errorCollector.collect({message:`Failed to parse x-fern-parameters extension: ${r instanceof Error?r.message:String(r)}`,path:this.breadcrumbs});return}}};var opu=class extends e_{method;pathParameters;queryParameters;headers;topLevelServers;constructor({context:t,breadcrumbs:r,method:i,pathParameters:n=[],queryParameters:a=[],headers:u=[],topLevelServers:l=[]}){super({context:t,breadcrumbs:r}),this.method=i,this.pathParameters=n,this.queryParameters=a,this.headers=u,this.topLevelServers=l}convert(){let t={},r="";for(let s of this.pathParameters)r+=`/{${s.name.originalName}}`;let i=WF(r),n=[];for(let[s,o]of this.method.params.entries()){let c;if(this.context.isReferenceObject(o)){let m=this.context.resolveReference({reference:o});if(m.resolved)c=m.value;else continue}else c=o;let b=[this.method.name,"Param",c.name].join("_"),O=new tA.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"Param",c.name],schemaIdOverride:b,context:this.context,schemaOrReference:c.schema,wrapAsOptional:!c.required}).convert();O!=null&&(n.push({docs:c.description,availability:this.context.getAvailability({node:o,breadcrumbs:[...this.breadcrumbs,"parameters"]}),name:this.context.casingsGenerator.generateNameAndWireValue({name:c.name,wireValue:c.name}),valueType:O.type,v2Examples:O.schema?.typeDeclaration.v2Examples,propertyAccess:void 0}),t={...O.inlinedTypes,...t,...O.schema!=null?{[b]:O.schema}:{}})}let a;if(this.method.result!=null){let s=this.context.resolveMaybeReference({schemaOrReference:this.method.result,breadcrumbs:[...this.breadcrumbs,"result"]});if(s!=null){let o=new tA.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"result"],context:this.context,schemaOrReference:s.schema}),c=[this.method.name,"Result"].join("_"),b=o.convert();b!=null&&(a={docs:s.description,v2Examples:b.schema?.typeDeclaration.v2Examples,responseBodyType:b.type},t={...b.inlinedTypes,...t,...b.schema!=null?{[c]:b.schema}:{}})}}let u=this.getEndpointBaseUrls(),l=this.context.getAudiences({operation:this.method,breadcrumbs:this.breadcrumbs})??[];return{endpoint:{baseUrl:void 0,v2BaseUrls:u,basePath:void 0,auth:!1,method:"POST",id:this.method.name,docs:this.method.description,name:this.context.casingsGenerator.generateName(this.method.name),headers:this.headers,displayName:this.method.name,pathParameters:this.pathParameters,queryParameters:this.queryParameters,allPathParameters:this.pathParameters,path:i,fullPath:i,requestBody:n.length>0?IA.inlinedRequestBody({name:this.context.casingsGenerator.generateName([this.method.name,"Request"].join("_")),docs:void 0,properties:n,extends:[],extendedProperties:[],contentType:"application/json",extraProperties:!1,v2Examples:void 0}):void 0,v2RequestBodies:void 0,sdkRequest:void 0,response:a!=null?{body:c1.json(OL.response(a)),statusCode:void 0}:void 0,v2Responses:void 0,errors:[],idempotent:!1,pagination:void 0,userSpecifiedExamples:[],autogeneratedExamples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples()},transport:void 0,availability:void 0,source:DJ.openrpc(),audiences:l},audiences:l,inlinedTypes:t,servers:this.filterOutTopLevelServers(this.method.servers??[])}}filterOutTopLevelServers(t){return t.filter(r=>!this.topLevelServers.some(i=>i.url===r.url))}getEndpointBaseUrls(){let t=this.method.servers;return t?.map(i=>{if(this.topLevelServers.find(l=>l.name===i.name&&l.url!==i.url)!=null)return i.url;let u=this.topLevelServers.find(l=>l.url===i.url)??i;return QAe.getServerName({server:u,context:this.context})})}convertExamples(){let t={},r=0;if(this.method.examples&&this.method.examples.length>0){for(let i of this.method.examples??[]){let n;if(this.context.isReferenceObject(i)){let d=this.context.resolveReference({reference:i});if(d.resolved)n=d.value;else continue}else n=i;let a;if(n.result)if(this.context.isReferenceObject(n.result)){let d=this.context.resolveReference({reference:n.result});d.resolved&&(a=d.value)}else a=n.result;let u=n.name??`Example ${r+1}`,l=[];if(n.params&&Array.isArray(n.params)){l=[];for(let d of n.params)if(this.context.isReferenceObject(d)){let s=this.context.resolveReference({reference:d});if(s.resolved)l.push(s.value);else continue}else l.push(d)}t[u]={displayName:void 0,request:{docs:void 0,endpoint:{method:"POST",path:"/{apiKey}"},baseUrl:void 0,environment:void 0,auth:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:l.map(d=>d.value)??void 0},response:{docs:void 0,statusCode:void 0,body:a?.value?Vs.V2HttpEndpointResponseBody.json({jsonrpc:"2.0",id:n.examplePairedRequest?.id||"1",result:a.value}):void 0},codeSamples:[]}}++r}return t}};var upu=class extends tA.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r,parameter:i})}convert(){let t,r={};if(this.parameter.schema!=null){let n=new tA.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaOrReference:this.parameter.schema,wrapAsOptional:this.parameter.required==null||!this.parameter.required}).convert();n!=null&&(t=n.type,r=n.inlinedTypes??{})}return this.convertToOutput({schema:this.parameter.schema??{type:"string"},typeReference:t,inlinedTypes:r})}};var BUa=class extends cQt{constructor({context:t,breadcrumbs:r,audiences:i}){super({context:t,breadcrumbs:r,audiences:i})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.convertSchemas();let{endpointLevelServers:t}=this.convertMethods(),{defaultUrl:r}=this.convertServers({endpointLevelServers:t});return this.updateEndpointsWithDefaultUrl(r),this.finalizeIr()}convertServers({endpointLevelServers:t}){let i=new QAe({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t}).convert();return this.addEnvironmentsToIr({environmentConfig:i?.value}),{defaultUrl:i?.defaultUrl}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{})){let n=new tA.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:["components","schemas",t],schema:r}).convert();n!=null&&(this.addTypeToPackage(t),this.addTypesToIr({...n.inlinedTypes,[t]:n.convertedSchema}))}}convertMethods(){let t=[],i=new apu({context:this.context,breadcrumbs:["methods"],operation:this.context.spec}).convert(),n=[],a=[],u=[];if(i&&i.length>0)for(let[d,s]of i.entries()){let c=new upu({context:this.context,breadcrumbs:[...this.breadcrumbs,`x-fern-parameters[${d}]`],parameter:s}).convert();if(c!=null)switch(c.type){case"path":{n.push(c.parameter);break}case"query":{a.push(c.parameter);break}case"header":{u.push(c.parameter);break}}}let l=this.context.getGroup({groupParts:[],namespace:this.context.namespace});for(let d of this.context.spec.methods??[]){let s=this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:["methods"]});if(s==null)continue;let c=new opu({context:this.context,breadcrumbs:["methods"],method:s,pathParameters:n,queryParameters:a,headers:u,topLevelServers:this.context.spec.servers}).convert();if(c!=null&&(this.addEndpointToIr({endpoint:c.endpoint,audiences:c.audiences,endpointGroup:l,serviceName:"service_root"}),this.addTypesToIr(c.inlinedTypes),c.servers))for(let b of c.servers)this.shouldAddServerToCollectedServers({server:b,currentServers:t,specType:"openrpc"})&&t.push(this.maybeDeduplicateServerName(b))}return{endpointLevelServers:t}}maybeDeduplicateServerName(t){return this.context.spec.servers?.find(i=>i.name===t.name&&i.url!==t.url)?{...t,name:t.url}:t}};var IUa=class extends d7{isReferenceObject(t){return t!=null&&"$ref"in t}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n}){let a=this.getTypeIdFromSchemaReference(t);if(a==null)return{ok:!1};let u=this.resolveReference({reference:t,breadcrumbs:r});if(!u.resolved)return{ok:!1};let l;return n==="reference_identifier"?l=i??u.value.title:(n==="discriminator_key"||n==="schema_identifier")&&(l=u.value.title??i),{ok:!0,reference:Xc.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(a),typeId:a,displayName:l,default:void 0,inline:!1})}}};var I8_=require("fs/promises");var G4_={[Bh.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,qB(e)])),[Bh.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"]),[Bh.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"]),[Bh.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"]),[Bh.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"]),[Bh.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"]),[Bh.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"]),[Bh.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"]),[Bh.GenerationLanguage.SWIFT]:new Set([])};var rdM=["go","ruby"];function lpu({generationLanguage:e,keywords:t,smartCasing:r}){let i={generateName:(n,a)=>{let u=c=>({unsafeName:c,safeName:idM({name:c,keywords:ndM({generationLanguage:e,keywords:t})})}),l=S_(n),d=qB(l),s=TZi(n),o=EZi(l);return r&&(!udM(o)&&(e==null||rdM.includes(e))&&(l=o.map((c,b)=>{if(b>0){let g=spu(c);if(g!=null)return g;if(cpu(c))return c.toUpperCase()}return c}).join(""),d=qB(o.map((c,b)=>{let g=spu(c);return g??(cpu(c)?c.toUpperCase():b===0?qB(c):c)}).join(""))),s=n.split(" ").map(c=>c.split(/(\d+)/).map(TZi).join("")).join("_")),{originalName:n,camelCase:u(a?.casingOverrides?.camel??l),snakeCase:u(a?.casingOverrides?.snake??s),screamingSnakeCase:u(a?.casingOverrides?.["screaming-snake"]??s.toUpperCase()),pascalCase:u(a?.casingOverrides?.pascal??d)}},generateNameAndWireValue:({name:n,wireValue:a,opts:u})=>({name:i.generateName(n,u),wireValue:a})};return i}function idM({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":odM(e)?"_"+e:e}function ndM({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return G4_[e]}var adM=/^[0-9]/;function odM(e){return adM.test(e)}function udM(e){return e.some((t,r)=>{if(r===0)return!1;let i=e[r-1];if(i==null)return!1;let n=spu(i)!=null||cpu(i),a=spu(t)!=null||cpu(t);return n&&a})}function spu(e){return cdM.get(e.toUpperCase())}function cpu(e){return sdM.has(e.toUpperCase())}var sdM=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"]),cdM=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]);var Q4_=require("fs/promises");async function YIc({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let i=(await(0,Q4_.readFile)(t)).toString(),n;try{n=JSON.parse(i)}catch{n=wd.load(i)}return r!=null?await EXn({absoluteFilePathToOverrides:r,context:e,data:n}):n}var m8_=ui(O8_(),1);function f3i(e,t,r=[],{doNotPipeOutput:i=!1,secrets:n=[],substitutions:a={},...u}={}){let l=n.reduce((s,o)=>({...s,[o]:"<redacted>"}),a),d=[t,...r].join(" ");for(let[s,o]of Object.entries(l))d=d.replaceAll(s,o);return e?.debug(`+ ${d}`),(0,m8_.default)(t,r,u)}async function Xz(e,t,r=[],{doNotPipeOutput:i=!1,secrets:n=[],substitutions:a={},...u}={}){let l=f3i(e,t,r,{doNotPipeOutput:i,secrets:n,substitutions:a,...u});i||(l.stdout?.pipe(process.stdout),l.stderr?.pipe(process.stderr));let d=await l;return d.stdout==null&&(d.stdout=""),d.stderr==null&&(d.stderr=""),d}function d3i(e,{logger:t,...r}={}){return(i,n)=>Xz(t,e,i,{...r,...n})}var lqe=require("fs/promises"),q8_=ui(require("path"),1),pzc=ui(hk(),1);var P8_="buf.gen.yaml",r_M="output",j8_=`${r_M}/ir.json`,w8_="protoc-gen-fern",S8_=`version: v1