fern-api 0.65.17 → 0.65.18

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 +3 -3
  2. package/package.json +1 -1
package/cli.cjs CHANGED
@@ -1712,7 +1712,7 @@ ${RAp.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&eJs(th
1712
1712
  `+xHi.default.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?xHi.default.cyan(GAp(t,this.opt.mask)):xHi.default.italic(xHi.default.dim("[hidden]")):this.opt.mask?GAp(t,this.opt.mask):xHi.default.italic(xHi.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 KFo=ui(F2(),1),vTp=ui(GJs(),1),bTp=ui(LEe(),1);var eEa=class extends L2{_run(t){this.done=t,this.editorResult=new bTp.Subject;let r=DW(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"?KFo.default.dim("Received"):KFo.default.dim("Press <enter> to launch your preferred editor."),t&&(r=KFo.default.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),(0,vTp.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 jTp=require("stream");var mTp=ui(require("readline"),1),PTp=ui(OTp(),1),HHi=class{constructor(t){this.rl||=mTp.default.createInterface(__D(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 __D(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 PTp.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var tEa=class extends HHi{constructor(t={}){super(t),this.log=new jTp.Writable({write:(r,i,n)=>{this.writeLog(r),n()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return xDa(this.rl,this.bottomBar.split(`
1713
1713
  `).length),this}updateBottomBar(t){return xDa(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+`
1714
1714
  `}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&&jFo(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var UE=ui(LEe(),1),DTp=ui(nDa(),1);var YFo=ui(LEe(),1),wTp=ui(nDa(),1),XFo=function(e,t,r){return typeof e[t]!="function"?(0,YFo.of)(e):(0,YFo.from)((0,wTp.default)(e[t])(r).then(i=>(e[t]=i,e)))};var STp={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}},pFn=class extends HHi{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,UE.from)(t):(0,UE.isObservable)(t)?i=t:Object.values(t).every(n=>typeof n=="object"&&!Array.isArray(n)&&n!=null)?i=(0,UE.from)(Object.entries(t).map(([n,a])=>({name:n,...a}))):i=(0,UE.from)([t]),this.process=i.pipe((0,UE.concatMap)(this.processQuestion.bind(this)),(0,UE.publish)()),this.process.connect(),this.process.pipe((0,UE.reduce)((n,a)=>(STp.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,UE.defer)(()=>(0,UE.of)(t).pipe((0,UE.concatMap)(this.setDefaultType.bind(this)),(0,UE.concatMap)(this.filterIfRunnable.bind(this)),(0,UE.concatMap)(()=>XFo(t,"message",this.answers)),(0,UE.concatMap)(()=>XFo(t,"default",this.answers)),(0,UE.concatMap)(()=>XFo(t,"choices",this.answers)),(0,UE.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,UE.defer)(()=>(0,UE.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,UE.defer)(()=>(0,UE.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&STp.get(this.answers,t.name)!==void 0)return UE.EMPTY;if(t.when===!1)return UE.EMPTY;if(typeof t.when!="function")return(0,UE.of)(t);let{answers:r}=this;return(0,UE.defer)(()=>(0,UE.from)((0,DTp.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,UE.filter)(i=>i!=null)))}};function ETp(e){let t=function(r,i){let n;try{n=new pFn(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",NDa),this.registerPrompt("input",zHi),this.registerPrompt("number",FDa),this.registerPrompt("confirm",LDa),this.registerPrompt("rawlist",UDa),this.registerPrompt("expand",VDa),this.registerPrompt("checkbox",WDa),this.registerPrompt("password",HDa),this.registerPrompt("editor",eEa)},t.restoreDefaultPrompts(),t}var JJs=ETp();function y_D(e,t){JJs.registerPrompt(e,t)}function v_D(){JJs.restoreDefaultPrompts()}var b_D={prompt:JJs,ui:{BottomBar:tEa,Prompt:pFn},createPromptModule:ETp,registerPrompt:y_D,restoreDefaultPrompts:v_D,Separator:sae},ZFo=b_D;var SFn=require("path"),uBp=require("fs"),sBp=require("readline"),CCp="posthog-node";function kyD(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[O3o.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 O3o=class{constructor(t,r,i,n){this.name=CCp,this.name=CCp,this.setupOnce=function(a,u){let l=u()?.getClient()?.getDsn()?.projectId;a(kyD(t,{organization:r,projectId:l,prefix:i,severityAllowList:n}))}}};O3o.POSTHOG_ID_TAG="posthog_distinct_id";var h3o="0123456789abcdef",m3o=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+=h3o.charAt(this.bytes[r]>>>4),t+=h3o.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+=h3o.charAt(this.bytes[r]>>>4),t+=h3o.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}},RKs=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??evD()}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 m3o.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,m3o.ofInner(t)}},evD=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),BCp,NKs=()=>tvD().toString(),tvD=()=>(BCp||(BCp=new RKs)).generate();function rvD(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 ivD(e,t){global.process.on("uncaughtException",rvD(e,t))}function nvD(e){global.process.on("unhandledRejection",t=>{e(t,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var y3o,ICp,v3o;function avD(e){let t=globalThis._posthogChunkIds;if(!t)return console.error("No chunk id map found"),{};let r=Object.keys(t);return v3o&&r.length===ICp||(ICp=r.length,v3o=r.reduce((i,n)=>{y3o||(y3o={});let a=y3o[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,y3o[n]=[s,o];break}}}return i},{})),v3o}function ovD(e){return typeof Event<"u"&&cBp(e,Event)}function uvD(e){return lBp(e,"Object")}function GKs(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return cBp(e,Error)}}function cBp(e,t){try{return e instanceof t}catch{return!1}}function svD(e){return lBp(e,"ErrorEvent")}function lBp(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}async function cvD(e,t,r,i){let a=i&&i.mechanism||{handled:!0,type:"generic"},u=fBp(a,r,i);return{$exception_list:await Promise.all(u.map(async s=>{let o=await yvD(e,t,s);return o.value=o.value||"",o.type=o.type||"Error",o.mechanism=a,o}))}}function fBp(e,t,r){let i=lvD(e,t,r);return i.cause?[i,...fBp(e,i.cause,r)]:[i]}function lvD(e,t,r){if(GKs(t))return t;if(e.synthetic=!0,uvD(t)){let n=fvD(t);if(n)return n;let a=dvD(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 fvD(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(GKs(r))return r}}function dvD(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=_vD(e);if(svD(e))return`Event \`ErrorEvent\` captured as exception with message \`${e.message}\``;let r=pvD(e);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${t}`}function pvD(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{}}function _vD(e,t=40){let r=Object.keys(hvD(e));r.sort();let i=r[0];if(!i)return"[object has no keys]";if(i.length>=t)return zCp(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:zCp(a,t)}return""}function zCp(e,t=0){return typeof e!="string"||t===0||e.length<=t?e:`${e.slice(0,t)}...`}function hvD(e){return GKs(e)?{message:e.message,name:e.name,stack:e.stack,...xCp(e)}:ovD(e)?{type:e.type,target:RCp(e.target),currentTarget:RCp(e.currentTarget),...xCp(e)}:e}function xCp(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 RCp(e){try{return Object.prototype.toString.call(e)}catch{return"<unknown>"}}async function yvD(e,t,r){let i={type:r.name||r.constructor.name,value:r.message},n=vvD(e,r);for(let a of t)n=await a(n);return n.length&&(i.stacktrace={frames:n,type:"raw"}),i}function vvD(e,t){return bvD(e(t.stack||"",1),e)}function bvD(e,t){let r=avD(t);return e.forEach(i=>{i.filename&&(i.chunk_id=r[i.filename])}),e}var gvD=2e3,PFn=class e{static async captureException(t,r,i,n,a){let u={...a};n||(u.$process_person_profile=!1);let l=await cvD(this.stackParser,this.frameModifiers,r,i);t.capture({event:"$exception",distinctId:n||NKs(),properties:{...l,...u}})}constructor(t,r){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this.startAutocaptureIfEnabled()}startAutocaptureIfEnabled(){this.isEnabled()&&(ivD(this.onException.bind(this),this.onFatalError.bind(this)),nvD(this.onException.bind(this)))}onException(t,r){e.captureException(this.client,t,r)}async onFatalError(){await this.client.shutdown(gvD)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}};function OvD(e=process.argv[1]?(0,SFn.dirname)(process.argv[1]):process.cwd(),t=SFn.sep==="\\"){let r=t?NCp(e):e;return i=>{if(!i)return;let n=t?NCp(i):i,{dir:a,base:u,ext:l}=SFn.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 NCp(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var P3o=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)}}},g3o=new P3o(25),dBp=new P3o(20),QKs=7,mvD=1e3,PvD=1e4;async function jvD(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"||EvD(u)||MvD(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(dBp.get(n))continue;let a=t[n];if(!a)continue;a.sort((d,s)=>d-s);let u=qvD(a);if(u.every(d=>AvD(n,d)))continue;let l=TvD(g3o,n,{});i.push(wvD(n,u,l))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&SvD(e,g3o),g3o.reduce(),e}function wvD(e,t,r){return new Promise(i=>{let n=(0,uBp.createReadStream)(e),a=(0,sBp.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(){dBp.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]=CvD(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 SvD(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;DvD(r.lineno,r,i)}}function DvD(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=pBp(e);n<e;n++){let a=r[n];if(a===void 0){FCp(t);return}t.pre_context.push(a)}if(r[e]===void 0){FCp(t);return}t.context_line=r[e];let i=_Bp(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 FCp(e){delete e.pre_context,delete e.context_line,delete e.post_context}function EvD(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function MvD(e){return e.lineno!==void 0&&e.lineno>PvD||e.colno!==void 0&&e.colno>mvD}function AvD(e,t){let r=g3o.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 qvD(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=LCp(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+QKs:(n.push(i),i=LCp(a)),t++}return n}function LCp(e){return[pBp(e),_Bp(e)]}function pBp(e){return Math.max(1,e-QKs)}function _Bp(e){return e+QKs}function TvD(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function CvD(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 BvD="4.18.0",_ae;(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"})(_ae||(_ae={}));var UCp;(function(e){e.Left="left",e.Right="right",e.Center="center"})(UCp||(UCp={}));var VCp;(function(e){e.Button="button",e.Tab="tab",e.Selector="selector"})(VCp||(VCp={}));var WCp;(function(e){e.Popover="popover",e.API="api",e.Widget="widget"})(WCp||(WCp={}));var HCp;(function(e){e.Html="html",e.Text="text"})(HCp||(HCp={}));var $Cp;(function(e){e.Number="number",e.Emoji="emoji"})($Cp||($Cp={}));var GCp;(function(e){e.Open="open",e.MultipleChoice="multiple_choice",e.SingleChoice="single_choice",e.Rating="rating",e.Link="link"})(GCp||(GCp={}));var QCp;(function(e){e.NextQuestion="next_question",e.End="end",e.ResponseBased="response_based",e.SpecificQuestion="specific_question"})(QCp||(QCp={}));var JCp;(function(e){e.Regex="regex",e.NotRegex="not_regex",e.Exact="exact",e.IsNot="is_not",e.Icontains="icontains",e.NotIcontains="not_icontains"})(JCp||(JCp={}));var KCp;(function(e){e.Contains="contains",e.Exact="exact",e.Regex="regex"})(KCp||(KCp={}));var IvD=e=>{if("flags"in e){let t=xvD(e.flags),r=RvD(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}else{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([n,a])=>[n,hBp(a)])),i=Object.fromEntries(Object.entries(t).map(([n,a])=>[n,zvD(n,a,r[n])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}};function zvD(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 xvD=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,JKs(r)]).filter(([,t])=>t!==void 0)),RvD=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?hBp(i):void 0]}))},JKs=e=>e===void 0?void 0:e.variant??e.enabled,hBp=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}},NvD=1,FvD=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"]),LvD="utf8";function UvD(e,t){if(!e||typeof e!="string"||VvD(e))throw new Error(t)}function VvD(e){return e.trim().length===0}function WvD(e){return e?.replace(/\/+$/,"")}async function HvD(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 YCp(){return new Date().getTime()}function zKs(){return new Date().toISOString()}function j3o(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}function $vD(){return typeof fetch<"u"?fetch:typeof globalThis.fetch<"u"?globalThis.fetch:void 0}function GvD(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 QvD(e,t=0,r){let i=GvD(e);return r?.has(i)?!1:parseInt(i,16)/4294967295<t}function XCp(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var fEa=String.fromCharCode,ZCp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",b3o={};function JvD(e,t){if(!b3o[e]){b3o[e]={};for(let r=0;r<e.length;r++)b3o[e][e.charAt(r)]=r}return b3o[e][t]}var OFn={compressToBase64:function(e){if(e==null)return"";let t=OFn._compress(e,6,function(r){return ZCp.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:OFn._decompress(e.length,32,function(t){return JvD(ZCp,e.charAt(t))})},compress:function(e){return OFn._compress(e,16,function(t){return fEa(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:OFn._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=fEa(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=fEa(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++]=fEa(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++]=fEa(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++)}}},FKs=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)}},jFn=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()}},dEa=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function kCp(e){if(e instanceof jFn){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 xKs(e){return typeof e=="object"&&(e instanceof jFn||e instanceof dEa)}function eBp(e){return typeof e=="object"&&e instanceof jFn&&e.status===413}var LKs;(function(e){e.FeatureFlags="feature_flags",e.Recordings="recordings"})(LKs||(LKs={}));var UKs=class{constructor(t,r){this.flushPromise=null,this.shutdownPromise=null,this.pendingPromises={},this._events=new FKs,this._isInitialized=!1,UvD(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=WvD(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:xKs},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(_ae.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(_ae.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(_ae.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=NKs();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=QvD(this.apiKey,NvD,FvD)?`${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=>IvD(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=JKs(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(LKs.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(_ae.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(_ae.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(_ae.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(_ae.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(_ae.Queue,a),this._events.emit(t,n),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=j3o(()=>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:zKs()};this.historicalMigration&&(n.historical_migration=!0);let a=JSON.stringify(n),u=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${YCp()}&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(OFn.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:zKs(),uuid:i?.uuid?i.uuid:NKs()};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 kCp(t)})}async flush(){let t=XCp([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),XCp([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(_ae.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(_ae.Queue)||[]).slice(n.length);this.setPersistedProperty(_ae.Queue,g),t=g},l={api_key:this.apiKey,batch:a,sent_at:zKs()};this.historicalMigration&&(l.historical_migration=!0);let d=JSON.stringify(l),s=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${YCp()}&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(OFn.compressToBase64(d))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:d},c={retryCheck:b=>eBp(b)?!1:xKs(b)};try{await this.fetchWithRetry(s,o,c)}catch(b){if(eBp(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 dEa||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,LvD)}catch{l=new TextEncoder().encode(u).length}return await HvD(async()=>{let d=null;try{d=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(o){throw new dEa(o)}if(!(r.mode==="no-cors")&&(d.status<200||d.status>=400))throw new jFn(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(_ae.Queue)||[]).length===0||(await this.flush(),r)););}catch(n){if(!xKs(n))throw n;await kCp(n)}};return Promise.race([new Promise((n,a)=>{j3o(()=>{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}},VKs=$vD();if(!VKs){let e=TCp();VKs=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 yBp=VKs,w3o=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()}},vBp=new w3o(async()=>{try{return await import("crypto")}catch{return}});async function KvD(){return await vBp.getValue()}var YvD=new w3o(async()=>{if(typeof globalThis.crypto?.subtle<"u")return globalThis.crypto.subtle;try{let e=await vBp.getValue();if(e?.webcrypto?.subtle)return e.webcrypto.subtle}catch{}});async function XvD(){return await YvD.getValue()}async function ZvD(e){let t=await KvD();if(t)return t.createHash("sha1").update(e).digest("hex");let r=await XvD();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 kvD=60*1e3,ebD=1152921504606847e3,tbD=["is_not"],mFn=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},U2=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},WKs=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||yBp,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 U2?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 U2||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 U2("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 U2("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 U2)u=!0;else throw o}if(l!==void 0)return l;if(u)throw new U2("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=gBp(l,n,this.cohorts,this.debugMode):s=bBp(l,n,u),!s)return!1}if(a==null)return!0}return!(a!=null&&await tBp(t.key,r)>a/100)}async getMatchingVariant(t,r){let i=await tBp(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(kvD,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 mFn(`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 mFn(`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 mFn(`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 mFn&&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=j3o(()=>{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=j3o(()=>{a.abort()},this.timeout),i.signal=a.signal}try{return this.fetch(r,i)}finally{clearTimeout(n)}}};async function tBp(e,t,r=""){let i=await ZvD(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/ebD}function bBp(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 U2("Operator is_not_set is not supported")}else throw new U2(`Property ${i} not found in propertyValues`);let u=t[i];if(u==null&&!tbD.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 rBp(String(n))&&String(u).match(String(n))!==null;case"not_regex":return rBp(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=rbD(String(n));if(s==null&&(s=iBp(n)),s==null)throw new U2(`Invalid date: ${n}`);let o=iBp(u);return["is_date_before"].includes(a)?o<s:o>s}default:throw new U2(`Unknown operator: ${a}`)}}function gBp(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new U2("can't match cohort without a given cohort property value");let a=r[n];return OBp(a,t,r,i)}function OBp(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=OBp(l,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof U2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new U2("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=gBp(l,t,r,i):d=bBp(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 U2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new U2("can't match cohort without a given cohort property value");return n==="AND"}}function rBp(e){try{return new RegExp(e),!0}catch{return!1}}function iBp(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 U2(`${e} is in an invalid date format`)}else throw new U2(`The date provided ${e} must be a string, number, or date object`)}function rbD(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 HKs=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},ibD=100,nBp=30*1e3,nbD=50*1e3,$Ks=class extends UKs{constructor(t,r={}){if(super(t,r),this._memoryStorage=new HKs,this.options=r,this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,ibD):nBp,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 WKs({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 PFn(this,r),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||nbD}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):yBp(t,r)}getLibraryVersion(){return BvD}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=nBp){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=JKs(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");PFn.captureException(this,t,{syntheticException:n},r,i)}},aBp=/\(error: (.*)\)/,mBp=50,PBp="?";function abD(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||PBp,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:oBp(n[3]),colno:oBp(n[4]),in_app:obD(o||"",c),platform:"node:javascript"}}if(i.match(t))return{filename:i,platform:"node:javascript"}}}function obD(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 oBp(e){return parseInt(e||"",10)||void 0}function ubD(e){return[90,abD(e)]}function sbD(e){let r=[ubD(e)].sort((i,n)=>i[0]-n[0]).map(i=>i[1]);return(i,n=0)=>{let a=[],u=i.split(`
1715
- `);for(let l=n;l<u.length;l++){let d=u[l];if(d.length>1024)continue;let s=aBp.test(d)?d.replace(aBp,"$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>=mBp)break}}return cbD(a)}}function cbD(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,mBp).map(r=>({...r,filename:r.filename||lbD(t).filename,function:r.function||PBp}))}function lbD(e){return e[e.length-1]||{}}PFn.stackParser=sbD(OvD());PFn.frameModifiers=[jvD];var wFn=class extends $Ks{getLibraryId(){return"posthog-node"}};var S3o=class{posthog;constructor({posthogApiKey:t}){this.posthog=new wFn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.65.17",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var pEa=class{async sendEvent(){}async identify(){}async flush(){}};var DFn=require("fs/promises"),DBp=require("os"),EBp=require("path");var jBp=ui(require("crypto")),E3o=new Uint8Array(256),D3o=E3o.length;function KKs(){return D3o>E3o.length-16&&(jBp.default.randomFillSync(E3o),D3o=0),E3o.slice(D3o,D3o+=16)}var AW=[];for(let e=0;e<256;++e)AW.push((e+256).toString(16).slice(1));function wBp(e,t=0){return AW[e[t+0]]+AW[e[t+1]]+AW[e[t+2]]+AW[e[t+3]]+"-"+AW[e[t+4]]+AW[e[t+5]]+"-"+AW[e[t+6]]+AW[e[t+7]]+"-"+AW[e[t+8]]+AW[e[t+9]]+"-"+AW[e[t+10]]+AW[e[t+11]]+AW[e[t+12]]+AW[e[t+13]]+AW[e[t+14]]+AW[e[t+15]]}var SBp=ui(require("crypto")),YKs={randomUUID:SBp.default.randomUUID};function fbD(e,t,r){if(YKs.randomUUID&&!t&&!e)return YKs.randomUUID();e=e||{};let i=e.random||(e.rng||KKs)();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 wBp(i)}var hae=fbD;var dbD="id",pbD=".fern",_Ea=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new wFn(r),this.userId=t==null?void 0:LVs(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.65.17",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Ru(ul.of((0,DBp.homedir)()),Na.of(pbD),Na.of(dbD));await mf(t)||(await(0,DFn.mkdir)((0,EBp.dirname)(t),{recursive:!0}),await(0,DFn.writeFile)(t,hae())),this.persistedDistinctId=(await(0,DFn.readFile)(t)).toString()}return this.persistedDistinctId}};var XKs;async function EFn(){return XKs==null&&(XKs=await _bD()),XKs}async function _bD(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new pEa;let r=await GBo();return r!=null?new _Ea({token:r,posthogApiKey:e}):await DRn()!=null?new S3o({posthogApiKey:e}):new _Ea({token:void 0,posthogApiKey:e})}catch{return new pEa}}function hEa(e,t){return function(){return e.apply(t,arguments)}}var{toString:hbD}=Object.prototype,{getPrototypeOf:kKs}=Object,{iterator:A3o,toStringTag:ABp}=Symbol,q3o=(e=>t=>{let r=hbD.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),cWt=e=>(e=e.toLowerCase(),t=>q3o(t)===e),T3o=e=>t=>typeof t===e,{isArray:MFn}=Array,yEa=T3o("undefined");function ybD(e){return e!==null&&!yEa(e)&&e.constructor!==null&&!yEa(e.constructor)&&yae(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var qBp=cWt("ArrayBuffer");function vbD(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&qBp(e.buffer),t}var bbD=T3o("string"),yae=T3o("function"),TBp=T3o("number"),C3o=e=>e!==null&&typeof e=="object",gbD=e=>e===!0||e===!1,M3o=e=>{if(q3o(e)!=="object")return!1;let t=kKs(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(ABp in e)&&!(A3o in e)},ObD=cWt("Date"),mbD=cWt("File"),PbD=cWt("Blob"),jbD=cWt("FileList"),wbD=e=>C3o(e)&&yae(e.pipe),SbD=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||yae(e.append)&&((t=q3o(e))==="formdata"||t==="object"&&yae(e.toString)&&e.toString()==="[object FormData]"))},DbD=cWt("URLSearchParams"),[EbD,MbD,AbD,qbD]=["ReadableStream","Request","Response","Headers"].map(cWt),TbD=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function vEa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),MFn(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 CBp(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 YHi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,BBp=e=>!yEa(e)&&e!==YHi;function ZKs(){let{caseless:e}=BBp(this)&&this||{},t={},r=(i,n)=>{let a=e&&CBp(t,n)||n;M3o(t[a])&&M3o(i)?t[a]=ZKs(t[a],i):M3o(i)?t[a]=ZKs({},i):MFn(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&vEa(arguments[i],r);return t}var CbD=(e,t,r,{allOwnKeys:i}={})=>(vEa(t,(n,a)=>{r&&yae(n)?e[a]=hEa(n,r):e[a]=n},{allOwnKeys:i}),e),BbD=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),IbD=(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)},zbD=(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&&kKs(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},xbD=(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},RbD=e=>{if(!e)return null;if(MFn(e))return e;let t=e.length;if(!TBp(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},NbD=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&kKs(Uint8Array)),FbD=(e,t)=>{let i=(e&&e[A3o]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},LbD=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},UbD=cWt("HTMLFormElement"),VbD=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),MBp=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),WbD=cWt("RegExp"),IBp=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};vEa(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},HbD=e=>{IBp(e,(t,r)=>{if(yae(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(yae(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+"'")})}})},$bD=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return MFn(e)?i(e):i(String(e).split(t)),r},GbD=()=>{},QbD=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function JbD(e){return!!(e&&yae(e.append)&&e[ABp]==="FormData"&&e[A3o])}var KbD=e=>{let t=new Array(10),r=(i,n)=>{if(C3o(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=MFn(i)?[]:{};return vEa(i,(u,l)=>{let d=r(u,n+1);!yEa(d)&&(a[l]=d)}),t[n]=void 0,a}}return i};return r(e,0)},YbD=cWt("AsyncFunction"),XbD=e=>e&&(C3o(e)||yae(e))&&yae(e.then)&&yae(e.catch),zBp=((e,t)=>e?setImmediate:t?((r,i)=>(YHi.addEventListener("message",({source:n,data:a})=>{n===YHi&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),YHi.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",yae(YHi.postMessage)),ZbD=typeof queueMicrotask<"u"?queueMicrotask.bind(YHi):typeof process<"u"&&process.nextTick||zBp,kbD=e=>e!=null&&yae(e[A3o]),os={isArray:MFn,isArrayBuffer:qBp,isBuffer:ybD,isFormData:SbD,isArrayBufferView:vbD,isString:bbD,isNumber:TBp,isBoolean:gbD,isObject:C3o,isPlainObject:M3o,isReadableStream:EbD,isRequest:MbD,isResponse:AbD,isHeaders:qbD,isUndefined:yEa,isDate:ObD,isFile:mbD,isBlob:PbD,isRegExp:WbD,isFunction:yae,isStream:wbD,isURLSearchParams:DbD,isTypedArray:NbD,isFileList:jbD,forEach:vEa,merge:ZKs,extend:CbD,trim:TbD,stripBOM:BbD,inherits:IbD,toFlatObject:zbD,kindOf:q3o,kindOfTest:cWt,endsWith:xbD,toArray:RbD,forEachEntry:FbD,matchAll:LbD,isHTMLForm:UbD,hasOwnProperty:MBp,hasOwnProp:MBp,reduceDescriptors:IBp,freezeMethods:HbD,toObjectSet:$bD,toCamelCase:VbD,noop:GbD,toFiniteNumber:QbD,findKey:CBp,global:YHi,isContextDefined:BBp,isSpecCompliantForm:JbD,toJSONObject:KbD,isAsyncFn:YbD,isThenable:XbD,setImmediate:zBp,asap:ZbD,isIterable:kbD};function AFn(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)}os.inherits(AFn,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:os.toJSONObject(this.config),code:this.code,status:this.status}}});var xBp=AFn.prototype,RBp={};["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=>{RBp[e]={value:e}});Object.defineProperties(AFn,RBp);Object.defineProperty(xBp,"isAxiosError",{value:!0});AFn.from=(e,t,r,i,n,a)=>{let u=Object.create(xBp);return os.toFlatObject(e,u,function(d){return d!==Error.prototype},l=>l!=="isAxiosError"),AFn.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var Fp=AFn;var NBp=ui(kFo(),1),B3o=NBp.default;function eYs(e){return os.isPlainObject(e)||os.isArray(e)}function LBp(e){return os.endsWith(e,"[]")?e.slice(0,-2):e}function FBp(e,t,r){return e?e.concat(t).map(function(n,a){return n=LBp(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function e0D(e){return os.isArray(e)&&!e.some(eYs)}var t0D=os.toFlatObject(os,{},null,function(t){return/^is[A-Z]/.test(t)});function r0D(e,t,r){if(!os.isObject(e))throw new TypeError("target must be an object");t=t||new(B3o||FormData),r=os.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,w){return!os.isUndefined(w[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&os.isSpecCompliantForm(t);if(!os.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(os.isDate(O))return O.toISOString();if(os.isBoolean(O))return O.toString();if(!d&&os.isBlob(O))throw new Fp("Blob is not supported. Use a Buffer instead.");return os.isArrayBuffer(O)||os.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(os.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(os.isArray(O)&&e0D(O)||(os.isFileList(O)||os.endsWith(m,"[]"))&&(E=os.toArray(O)))return m=LBp(m),E.forEach(function(A,D){!(os.isUndefined(A)||A===null)&&t.append(u===!0?FBp([m],D,a):u===null?m:m+"[]",s(A))}),!1}return eYs(O)?!0:(t.append(FBp(w,m,a),s(O)),!1)}let c=[],b=Object.assign(t0D,{defaultVisitor:o,convertValue:s,isVisitable:eYs});function g(O,m){if(!os.isUndefined(O)){if(c.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));c.push(O),os.forEach(O,function(E,q){(!(os.isUndefined(E)||E===null)&&n.call(t,E,os.isString(q)?q.trim():q,m,b))===!0&&g(E,m?m.concat(q):[q])}),c.pop()}}if(!os.isObject(e))throw new TypeError("data must be an object");return g(e),t}var ZSi=r0D;function UBp(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function VBp(e,t){this._pairs=[],e&&ZSi(e,this,t)}var WBp=VBp.prototype;WBp.append=function(t,r){this._pairs.push([t,r])};WBp.toString=function(t){let r=t?function(i){return t.call(this,i,UBp)}:UBp;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var HBp=VBp;function i0D(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function XHi(e,t,r){if(!t)return e;let i=r&&r.encode||i0D;os.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=os.isURLSearchParams(t)?t.toString():new HBp(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var tYs=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){os.forEach(this.handlers,function(i){i!==null&&t(i)})}},rYs=tYs;var qFn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var JBp=ui(require("crypto"),1);var $Bp=ui(require("url"),1),GBp=$Bp.default.URLSearchParams;var iYs="abcdefghijklmnopqrstuvwxyz",QBp="0123456789",KBp={DIGIT:QBp,ALPHA:iYs,ALPHA_DIGIT:iYs+iYs.toUpperCase()+QBp},n0D=(e=16,t=KBp.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);JBp.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},YBp={isNode:!0,classes:{URLSearchParams:GBp,FormData:B3o,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:KBp,generateString:n0D,protocols:["http","https","file","data"]};var oYs={};Po(oYs,{hasBrowserEnv:()=>aYs,hasStandardBrowserEnv:()=>a0D,hasStandardBrowserWebWorkerEnv:()=>o0D,navigator:()=>nYs,origin:()=>u0D});var aYs=typeof window<"u"&&typeof document<"u",nYs=typeof navigator=="object"&&navigator||void 0,a0D=aYs&&(!nYs||["ReactNative","NativeScript","NS"].indexOf(nYs.product)<0),o0D=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",u0D=aYs&&window.location.href||"http://localhost";var oA={...oYs,...YBp};function uYs(e,t){return ZSi(e,new oA.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return oA.isNode&&os.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function s0D(e){return os.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function c0D(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 l0D(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&&os.isArray(n)?n.length:u,d?(os.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!l):((!n[u]||!os.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&os.isArray(n[u])&&(n[u]=c0D(n[u])),!l)}if(os.isFormData(e)&&os.isFunction(e.entries)){let r={};return os.forEachEntry(e,(i,n)=>{t(s0D(i),n,r,0)}),r}return null}var I3o=l0D;function f0D(e,t,r){if(os.isString(e))try{return(t||JSON.parse)(e),os.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var sYs={transitional:qFn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=os.isObject(t);if(a&&os.isHTMLForm(t)&&(t=new FormData(t)),os.isFormData(t))return n?JSON.stringify(I3o(t)):t;if(os.isArrayBuffer(t)||os.isBuffer(t)||os.isStream(t)||os.isFile(t)||os.isBlob(t)||os.isReadableStream(t))return t;if(os.isArrayBufferView(t))return t.buffer;if(os.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 uYs(t,this.formSerializer).toString();if((l=os.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return ZSi(l?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),f0D(t)):t}],transformResponse:[function(t){let r=this.transitional||sYs.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(os.isResponse(t)||os.isReadableStream(t))return t;if(t&&os.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"?Fp.from(l,Fp.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:oA.classes.FormData,Blob:oA.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};os.forEach(["delete","get","head","post","put","patch"],e=>{sYs.headers[e]={}});var TFn=sYs;var d0D=os.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"]),XBp=e=>{let t={},r,i,n;return e&&e.split(`
1715
+ `);for(let l=n;l<u.length;l++){let d=u[l];if(d.length>1024)continue;let s=aBp.test(d)?d.replace(aBp,"$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>=mBp)break}}return cbD(a)}}function cbD(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,mBp).map(r=>({...r,filename:r.filename||lbD(t).filename,function:r.function||PBp}))}function lbD(e){return e[e.length-1]||{}}PFn.stackParser=sbD(OvD());PFn.frameModifiers=[jvD];var wFn=class extends $Ks{getLibraryId(){return"posthog-node"}};var S3o=class{posthog;constructor({posthogApiKey:t}){this.posthog=new wFn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.65.18",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var pEa=class{async sendEvent(){}async identify(){}async flush(){}};var DFn=require("fs/promises"),DBp=require("os"),EBp=require("path");var jBp=ui(require("crypto")),E3o=new Uint8Array(256),D3o=E3o.length;function KKs(){return D3o>E3o.length-16&&(jBp.default.randomFillSync(E3o),D3o=0),E3o.slice(D3o,D3o+=16)}var AW=[];for(let e=0;e<256;++e)AW.push((e+256).toString(16).slice(1));function wBp(e,t=0){return AW[e[t+0]]+AW[e[t+1]]+AW[e[t+2]]+AW[e[t+3]]+"-"+AW[e[t+4]]+AW[e[t+5]]+"-"+AW[e[t+6]]+AW[e[t+7]]+"-"+AW[e[t+8]]+AW[e[t+9]]+"-"+AW[e[t+10]]+AW[e[t+11]]+AW[e[t+12]]+AW[e[t+13]]+AW[e[t+14]]+AW[e[t+15]]}var SBp=ui(require("crypto")),YKs={randomUUID:SBp.default.randomUUID};function fbD(e,t,r){if(YKs.randomUUID&&!t&&!e)return YKs.randomUUID();e=e||{};let i=e.random||(e.rng||KKs)();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 wBp(i)}var hae=fbD;var dbD="id",pbD=".fern",_Ea=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new wFn(r),this.userId=t==null?void 0:LVs(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.65.18",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Ru(ul.of((0,DBp.homedir)()),Na.of(pbD),Na.of(dbD));await mf(t)||(await(0,DFn.mkdir)((0,EBp.dirname)(t),{recursive:!0}),await(0,DFn.writeFile)(t,hae())),this.persistedDistinctId=(await(0,DFn.readFile)(t)).toString()}return this.persistedDistinctId}};var XKs;async function EFn(){return XKs==null&&(XKs=await _bD()),XKs}async function _bD(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new pEa;let r=await GBo();return r!=null?new _Ea({token:r,posthogApiKey:e}):await DRn()!=null?new S3o({posthogApiKey:e}):new _Ea({token:void 0,posthogApiKey:e})}catch{return new pEa}}function hEa(e,t){return function(){return e.apply(t,arguments)}}var{toString:hbD}=Object.prototype,{getPrototypeOf:kKs}=Object,{iterator:A3o,toStringTag:ABp}=Symbol,q3o=(e=>t=>{let r=hbD.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),cWt=e=>(e=e.toLowerCase(),t=>q3o(t)===e),T3o=e=>t=>typeof t===e,{isArray:MFn}=Array,yEa=T3o("undefined");function ybD(e){return e!==null&&!yEa(e)&&e.constructor!==null&&!yEa(e.constructor)&&yae(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var qBp=cWt("ArrayBuffer");function vbD(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&qBp(e.buffer),t}var bbD=T3o("string"),yae=T3o("function"),TBp=T3o("number"),C3o=e=>e!==null&&typeof e=="object",gbD=e=>e===!0||e===!1,M3o=e=>{if(q3o(e)!=="object")return!1;let t=kKs(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(ABp in e)&&!(A3o in e)},ObD=cWt("Date"),mbD=cWt("File"),PbD=cWt("Blob"),jbD=cWt("FileList"),wbD=e=>C3o(e)&&yae(e.pipe),SbD=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||yae(e.append)&&((t=q3o(e))==="formdata"||t==="object"&&yae(e.toString)&&e.toString()==="[object FormData]"))},DbD=cWt("URLSearchParams"),[EbD,MbD,AbD,qbD]=["ReadableStream","Request","Response","Headers"].map(cWt),TbD=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function vEa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),MFn(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 CBp(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 YHi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,BBp=e=>!yEa(e)&&e!==YHi;function ZKs(){let{caseless:e}=BBp(this)&&this||{},t={},r=(i,n)=>{let a=e&&CBp(t,n)||n;M3o(t[a])&&M3o(i)?t[a]=ZKs(t[a],i):M3o(i)?t[a]=ZKs({},i):MFn(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&vEa(arguments[i],r);return t}var CbD=(e,t,r,{allOwnKeys:i}={})=>(vEa(t,(n,a)=>{r&&yae(n)?e[a]=hEa(n,r):e[a]=n},{allOwnKeys:i}),e),BbD=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),IbD=(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)},zbD=(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&&kKs(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},xbD=(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},RbD=e=>{if(!e)return null;if(MFn(e))return e;let t=e.length;if(!TBp(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},NbD=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&kKs(Uint8Array)),FbD=(e,t)=>{let i=(e&&e[A3o]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},LbD=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},UbD=cWt("HTMLFormElement"),VbD=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),MBp=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),WbD=cWt("RegExp"),IBp=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};vEa(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},HbD=e=>{IBp(e,(t,r)=>{if(yae(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(yae(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+"'")})}})},$bD=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return MFn(e)?i(e):i(String(e).split(t)),r},GbD=()=>{},QbD=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function JbD(e){return!!(e&&yae(e.append)&&e[ABp]==="FormData"&&e[A3o])}var KbD=e=>{let t=new Array(10),r=(i,n)=>{if(C3o(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=MFn(i)?[]:{};return vEa(i,(u,l)=>{let d=r(u,n+1);!yEa(d)&&(a[l]=d)}),t[n]=void 0,a}}return i};return r(e,0)},YbD=cWt("AsyncFunction"),XbD=e=>e&&(C3o(e)||yae(e))&&yae(e.then)&&yae(e.catch),zBp=((e,t)=>e?setImmediate:t?((r,i)=>(YHi.addEventListener("message",({source:n,data:a})=>{n===YHi&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),YHi.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",yae(YHi.postMessage)),ZbD=typeof queueMicrotask<"u"?queueMicrotask.bind(YHi):typeof process<"u"&&process.nextTick||zBp,kbD=e=>e!=null&&yae(e[A3o]),os={isArray:MFn,isArrayBuffer:qBp,isBuffer:ybD,isFormData:SbD,isArrayBufferView:vbD,isString:bbD,isNumber:TBp,isBoolean:gbD,isObject:C3o,isPlainObject:M3o,isReadableStream:EbD,isRequest:MbD,isResponse:AbD,isHeaders:qbD,isUndefined:yEa,isDate:ObD,isFile:mbD,isBlob:PbD,isRegExp:WbD,isFunction:yae,isStream:wbD,isURLSearchParams:DbD,isTypedArray:NbD,isFileList:jbD,forEach:vEa,merge:ZKs,extend:CbD,trim:TbD,stripBOM:BbD,inherits:IbD,toFlatObject:zbD,kindOf:q3o,kindOfTest:cWt,endsWith:xbD,toArray:RbD,forEachEntry:FbD,matchAll:LbD,isHTMLForm:UbD,hasOwnProperty:MBp,hasOwnProp:MBp,reduceDescriptors:IBp,freezeMethods:HbD,toObjectSet:$bD,toCamelCase:VbD,noop:GbD,toFiniteNumber:QbD,findKey:CBp,global:YHi,isContextDefined:BBp,isSpecCompliantForm:JbD,toJSONObject:KbD,isAsyncFn:YbD,isThenable:XbD,setImmediate:zBp,asap:ZbD,isIterable:kbD};function AFn(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)}os.inherits(AFn,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:os.toJSONObject(this.config),code:this.code,status:this.status}}});var xBp=AFn.prototype,RBp={};["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=>{RBp[e]={value:e}});Object.defineProperties(AFn,RBp);Object.defineProperty(xBp,"isAxiosError",{value:!0});AFn.from=(e,t,r,i,n,a)=>{let u=Object.create(xBp);return os.toFlatObject(e,u,function(d){return d!==Error.prototype},l=>l!=="isAxiosError"),AFn.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var Fp=AFn;var NBp=ui(kFo(),1),B3o=NBp.default;function eYs(e){return os.isPlainObject(e)||os.isArray(e)}function LBp(e){return os.endsWith(e,"[]")?e.slice(0,-2):e}function FBp(e,t,r){return e?e.concat(t).map(function(n,a){return n=LBp(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function e0D(e){return os.isArray(e)&&!e.some(eYs)}var t0D=os.toFlatObject(os,{},null,function(t){return/^is[A-Z]/.test(t)});function r0D(e,t,r){if(!os.isObject(e))throw new TypeError("target must be an object");t=t||new(B3o||FormData),r=os.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,w){return!os.isUndefined(w[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&os.isSpecCompliantForm(t);if(!os.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(os.isDate(O))return O.toISOString();if(os.isBoolean(O))return O.toString();if(!d&&os.isBlob(O))throw new Fp("Blob is not supported. Use a Buffer instead.");return os.isArrayBuffer(O)||os.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(os.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(os.isArray(O)&&e0D(O)||(os.isFileList(O)||os.endsWith(m,"[]"))&&(E=os.toArray(O)))return m=LBp(m),E.forEach(function(A,D){!(os.isUndefined(A)||A===null)&&t.append(u===!0?FBp([m],D,a):u===null?m:m+"[]",s(A))}),!1}return eYs(O)?!0:(t.append(FBp(w,m,a),s(O)),!1)}let c=[],b=Object.assign(t0D,{defaultVisitor:o,convertValue:s,isVisitable:eYs});function g(O,m){if(!os.isUndefined(O)){if(c.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));c.push(O),os.forEach(O,function(E,q){(!(os.isUndefined(E)||E===null)&&n.call(t,E,os.isString(q)?q.trim():q,m,b))===!0&&g(E,m?m.concat(q):[q])}),c.pop()}}if(!os.isObject(e))throw new TypeError("data must be an object");return g(e),t}var ZSi=r0D;function UBp(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function VBp(e,t){this._pairs=[],e&&ZSi(e,this,t)}var WBp=VBp.prototype;WBp.append=function(t,r){this._pairs.push([t,r])};WBp.toString=function(t){let r=t?function(i){return t.call(this,i,UBp)}:UBp;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var HBp=VBp;function i0D(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function XHi(e,t,r){if(!t)return e;let i=r&&r.encode||i0D;os.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=os.isURLSearchParams(t)?t.toString():new HBp(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var tYs=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){os.forEach(this.handlers,function(i){i!==null&&t(i)})}},rYs=tYs;var qFn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var JBp=ui(require("crypto"),1);var $Bp=ui(require("url"),1),GBp=$Bp.default.URLSearchParams;var iYs="abcdefghijklmnopqrstuvwxyz",QBp="0123456789",KBp={DIGIT:QBp,ALPHA:iYs,ALPHA_DIGIT:iYs+iYs.toUpperCase()+QBp},n0D=(e=16,t=KBp.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);JBp.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},YBp={isNode:!0,classes:{URLSearchParams:GBp,FormData:B3o,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:KBp,generateString:n0D,protocols:["http","https","file","data"]};var oYs={};Po(oYs,{hasBrowserEnv:()=>aYs,hasStandardBrowserEnv:()=>a0D,hasStandardBrowserWebWorkerEnv:()=>o0D,navigator:()=>nYs,origin:()=>u0D});var aYs=typeof window<"u"&&typeof document<"u",nYs=typeof navigator=="object"&&navigator||void 0,a0D=aYs&&(!nYs||["ReactNative","NativeScript","NS"].indexOf(nYs.product)<0),o0D=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",u0D=aYs&&window.location.href||"http://localhost";var oA={...oYs,...YBp};function uYs(e,t){return ZSi(e,new oA.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return oA.isNode&&os.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function s0D(e){return os.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function c0D(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 l0D(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&&os.isArray(n)?n.length:u,d?(os.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!l):((!n[u]||!os.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&os.isArray(n[u])&&(n[u]=c0D(n[u])),!l)}if(os.isFormData(e)&&os.isFunction(e.entries)){let r={};return os.forEachEntry(e,(i,n)=>{t(s0D(i),n,r,0)}),r}return null}var I3o=l0D;function f0D(e,t,r){if(os.isString(e))try{return(t||JSON.parse)(e),os.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var sYs={transitional:qFn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=os.isObject(t);if(a&&os.isHTMLForm(t)&&(t=new FormData(t)),os.isFormData(t))return n?JSON.stringify(I3o(t)):t;if(os.isArrayBuffer(t)||os.isBuffer(t)||os.isStream(t)||os.isFile(t)||os.isBlob(t)||os.isReadableStream(t))return t;if(os.isArrayBufferView(t))return t.buffer;if(os.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 uYs(t,this.formSerializer).toString();if((l=os.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return ZSi(l?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),f0D(t)):t}],transformResponse:[function(t){let r=this.transitional||sYs.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(os.isResponse(t)||os.isReadableStream(t))return t;if(t&&os.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"?Fp.from(l,Fp.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:oA.classes.FormData,Blob:oA.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};os.forEach(["delete","get","head","post","put","patch"],e=>{sYs.headers[e]={}});var TFn=sYs;var d0D=os.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"]),XBp=e=>{let t={},r,i,n;return e&&e.split(`
1716
1716
  `).forEach(function(u){n=u.indexOf(":"),r=u.substring(0,n).trim().toLowerCase(),i=u.substring(n+1).trim(),!(!r||t[r]&&d0D[r])&&(r==="set-cookie"?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t};var ZBp=Symbol("internals");function bEa(e){return e&&String(e).trim().toLowerCase()}function z3o(e){return e===!1||e==null?e:os.isArray(e)?e.map(z3o):String(e)}function p0D(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 _0D=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function cYs(e,t,r,i,n){if(os.isFunction(i))return i.call(this,t,r);if(n&&(t=r),!!os.isString(t)){if(os.isString(i))return t.indexOf(i)!==-1;if(os.isRegExp(i))return i.test(t)}}function h0D(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,i)=>r.toUpperCase()+i)}function y0D(e,t){let r=os.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 CFn=class{constructor(t){t&&this.set(t)}set(t,r,i){let n=this;function a(l,d,s){let o=bEa(d);if(!o)throw new Error("header name must be a non-empty string");let c=os.findKey(n,o);(!c||n[c]===void 0||s===!0||s===void 0&&n[c]!==!1)&&(n[c||d]=z3o(l))}let u=(l,d)=>os.forEach(l,(s,o)=>a(s,o,d));if(os.isPlainObject(t)||t instanceof this.constructor)u(t,r);else if(os.isString(t)&&(t=t.trim())&&!_0D(t))u(XBp(t),r);else if(os.isObject(t)&&os.isIterable(t)){let l={},d,s;for(let o of t){if(!os.isArray(o))throw TypeError("Object iterator must return a key-value pair");l[s=o[0]]=(d=l[s])?os.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=bEa(t),t){let i=os.findKey(this,t);if(i){let n=this[i];if(!r)return n;if(r===!0)return p0D(n);if(os.isFunction(r))return r.call(this,n,i);if(os.isRegExp(r))return r.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=bEa(t),t){let i=os.findKey(this,t);return!!(i&&this[i]!==void 0&&(!r||cYs(this,this[i],i,r)))}return!1}delete(t,r){let i=this,n=!1;function a(u){if(u=bEa(u),u){let l=os.findKey(i,u);l&&(!r||cYs(i,i[l],l,r))&&(delete i[l],n=!0)}}return os.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||cYs(this,this[a],a,t,!0))&&(delete this[a],n=!0)}return n}normalize(t){let r=this,i={};return os.forEach(this,(n,a)=>{let u=os.findKey(i,a);if(u){r[u]=z3o(n),delete r[a];return}let l=t?h0D(a):String(a).trim();l!==a&&delete r[a],r[l]=z3o(n),i[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return os.forEach(this,(i,n)=>{i!=null&&i!==!1&&(r[n]=t&&os.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(`
1717
1717
  `)}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[ZBp]=this[ZBp]={accessors:{}}).accessors,n=this.prototype;function a(u){let l=bEa(u);i[l]||(y0D(n,u),i[l]=!0)}return os.isArray(t)?t.forEach(a):a(t),this}};CFn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);os.reduceDescriptors(CFn.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(i){this[r]=i}}});os.freezeMethods(CFn);var aR=CFn;function gEa(e,t){let r=this||TFn,i=t||r,n=aR.from(i.headers),a=i.data;return os.forEach(e,function(l){a=l.call(r,a,n.normalize(),t?t.status:void 0)}),n.normalize(),a}function OEa(e){return!!(e&&e.__CANCEL__)}function kBp(e,t,r){Fp.call(this,e??"canceled",Fp.ERR_CANCELED,t,r),this.name="CanceledError"}os.inherits(kBp,Fp,{__CANCEL__:!0});var VEe=kBp;function Ktr(e,t,r){let i=r.config.validateStatus;!r.status||!i||i(r.status)?e(r):t(new Fp("Request failed with status code "+r.status,[Fp.ERR_BAD_REQUEST,Fp.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function lYs(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function fYs(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function ZHi(e,t,r){let i=!lYs(t);return e&&(i||r==!1)?fYs(e,t):t}var hIp=ui(rEa(),1),yIp=ui(require("http"),1),vIp=ui(require("https"),1),bIp=ui(require("util"),1),gIp=ui(fKs(),1),_fi=ui(require("zlib"),1);var kHi="1.10.0";function mEa(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var v0D=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function dYs(e,t,r){let i=r&&r.Blob||oA.classes.Blob,n=mEa(e);if(t===void 0&&i&&(t=!0),n==="data"){e=n.length?e.slice(n.length+1):e;let a=v0D.exec(e);if(!a)throw new Fp("Invalid URL",Fp.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 Fp("Blob is not supported",Fp.ERR_NOT_SUPPORT);return new i([s],{type:u})}return s}throw new Fp("Unsupported protocol "+n,Fp.ERR_NOT_SUPPORT)}var t$i=ui(require("stream"),1);var eIp=ui(require("stream"),1);var pYs=Symbol("internals"),_Ys=class extends eIp.default.Transform{constructor(t){t=os.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(i,n)=>!os.isUndefined(n[i])),super({readableHighWaterMark:t.chunkSize});let r=this[pYs]={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[pYs];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,i){let n=this[pYs],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,A=0;if(a){let D=Date.now();(!n.ts||(A=D-n.ts)>=l)&&(n.ts=D,q=s-n.bytes,n.bytes=q<0?-q:0,A=0),q=s-n.bytes}if(a){if(q<=0)return setTimeout(()=>{O(null,g)},l-A);q<E&&(E=q)}E&&m>E&&m-E>o&&(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)})}},hYs=_Ys;var OIp=require("events");var rIp=ui(require("util"),1),iIp=require("stream");var{asyncIterator:tIp}=Symbol,b0D=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[tIp]?yield*e[tIp]():yield e},x3o=b0D;var g0D=oA.ALPHABET.ALPHA_DIGIT+"-_",PEa=typeof TextEncoder=="function"?new TextEncoder:new rIp.default.TextEncoder,e$i=`\r
1718
1718
  `,O0D=PEa.encode(e$i),m0D=2,yYs=class{constructor(t,r){let{escapeName:i}=this.constructor,n=os.isString(r),a=`Content-Disposition: form-data; name="${i(t)}"${!n&&r.name?`; filename="${i(r.name)}"`:""}${e$i}`;n?r=PEa.encode(String(r).replace(/\r?\n|\r\n?/g,e$i)):a+=`Content-Type: ${r.type||"application/octet-stream"}${e$i}`,this.headers=PEa.encode(a+e$i),this.contentLength=n?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+m0D,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;os.isTypedArray(t)?yield t:yield*x3o(t),yield O0D}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},P0D=(e,t,r)=>{let{tag:i="form-data-boundary",size:n=25,boundary:a=i+"-"+oA.generateString(n,g0D)}=r||{};if(!os.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=PEa.encode("--"+a+e$i),l=PEa.encode("--"+a+"--"+e$i),d=l.byteLength,s=Array.from(e.entries()).map(([c,b])=>{let g=new yYs(c,b);return d+=g.size,g});d+=u.byteLength*s.length,d=os.toFiniteNumber(d);let o={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(d)&&(o["Content-Length"]=d),t&&t(o),iIp.Readable.from(async function*(){for(let c of s)yield u,yield*c.encode();yield l}())},nIp=P0D;var aIp=ui(require("stream"),1),vYs=class extends aIp.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)}},oIp=vYs;var j0D=(e,t)=>os.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,uIp=j0D;function w0D(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 sIp=w0D;function S0D(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 cIp=S0D;var pfi=(e,t,r=3)=>{let i=0,n=sIp(50,250);return cIp(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)},BFn=(e,t)=>{let r=e!=null;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},IFn=e=>(...t)=>os.asap(()=>e(...t));var lIp={flush:_fi.default.constants.Z_SYNC_FLUSH,finishFlush:_fi.default.constants.Z_SYNC_FLUSH},D0D={flush:_fi.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:_fi.default.constants.BROTLI_OPERATION_FLUSH},fIp=os.isFunction(_fi.default.createBrotliDecompress),{http:E0D,https:M0D}=gIp.default,A0D=/https:?/,dIp=oA.protocols.map(e=>e+":"),pIp=(e,[t,r])=>(e.on("end",r).on("error",r),t);function q0D(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function mIp(e,t,r){let i=t;if(!i&&i!==!1){let n=hIp.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){mIp(a,t,a.href)}}var T0D=typeof process<"u"&&os.kindOf(process)==="process",C0D=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)}),B0D=({address:e,family:t})=>{if(!os.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},_Ip=(e,t)=>B0D(os.isObject(e)?e:{address:e,family:t}),PIp=T0D&&function(t){return C0D(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=uIp(l,Ue=>os.isArray(Ue)?Ue:[Ue]);l=(Ue,wt,De)=>{Oe(Ue,wt,(Te,xt,Pe)=>{if(Te)return De(Te);let ot=os.isArray(xt)?xt.map(at=>_Ip(at)):[_Ip(xt,Pe)];wt.all?De(Te,ot):De(Te,ot[0].address,ot[0].family)})}}let m=new OIp.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 VEe(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=ZHi(t.baseURL,t.url,t.allowAbsoluteUrls),A=new URL(q,oA.hasBrowserEnv?oA.origin:void 0),D=A.protocol||dIp[0];if(D==="data:"){let Oe;if(c!=="GET")return Ktr(i,n,{status:405,statusText:"method not allowed",headers:{},config:t});try{Oe=dYs(t.url,s==="blob",{Blob:t.env&&t.env.Blob})}catch(Ue){throw Fp.from(Ue,Fp.ERR_BAD_REQUEST,t)}return s==="text"?(Oe=Oe.toString(o),(!o||o==="utf8")&&(Oe=os.stripBOM(Oe))):s==="stream"&&(Oe=t$i.default.Readable.from(Oe)),Ktr(i,n,{data:Oe,status:200,statusText:"OK",headers:new aR,config:t})}if(dIp.indexOf(D)===-1)return n(new Fp("Unsupported protocol "+D,Fp.ERR_BAD_REQUEST,t));let C=aR.from(t.headers).normalize();C.set("User-Agent","axios/"+kHi,!1);let{onUploadProgress:x,onDownloadProgress:$}=t,I=t.maxRate,F,V;if(os.isSpecCompliantForm(u)){let Oe=C.getContentType(/boundary=([-_\w\d]{10,70})/i);u=nIp(u,Ue=>{C.set(Ue)},{tag:`axios-${kHi}-boundary`,boundary:Oe&&Oe[1]||void 0})}else if(os.isFormData(u)&&os.isFunction(u.getHeaders)){if(C.set(u.getHeaders()),!C.hasContentLength())try{let Oe=await bIp.default.promisify(u.getLength).call(u);Number.isFinite(Oe)&&Oe>=0&&C.setContentLength(Oe)}catch{}}else if(os.isBlob(u)||os.isFile(u))u.size&&C.setContentType(u.type||"application/octet-stream"),C.setContentLength(u.size||0),u=t$i.default.Readable.from(x3o(u));else if(u&&!os.isStream(u)){if(!Buffer.isBuffer(u))if(os.isArrayBuffer(u))u=Buffer.from(new Uint8Array(u));else if(os.isString(u))u=Buffer.from(u,"utf-8");else return n(new Fp("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",Fp.ERR_BAD_REQUEST,t));if(C.setContentLength(u.length,!1),t.maxBodyLength>-1&&u.length>t.maxBodyLength)return n(new Fp("Request body larger than maxBodyLength limit",Fp.ERR_BAD_REQUEST,t))}let K=os.toFiniteNumber(C.getContentLength());os.isArray(I)?(F=I[0],V=I[1]):F=V=I,u&&(x||F)&&(os.isStream(u)||(u=t$i.default.Readable.from(u,{objectMode:!1})),u=t$i.default.pipeline([u,new hYs({maxRate:os.toFiniteNumber(F)})],os.noop),x&&u.on("progress",pIp(u,BFn(K,pfi(IFn(x),!1,3)))));let Y;if(t.auth){let Oe=t.auth.username||"",Ue=t.auth.password||"";Y=Oe+":"+Ue}if(!Y&&A.username){let Oe=A.username,Ue=A.password;Y=Oe+":"+Ue}Y&&C.delete("authorization");let Z;try{Z=XHi(A.pathname+A.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"+(fIp?", br":""),!1);let oe={path:Z,method:c,headers:C.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:Y,protocol:D,family:d,beforeRedirect:q0D,beforeRedirects:{}};!os.isUndefined(l)&&(oe.lookup=l),t.socketPath?oe.socketPath=t.socketPath:(oe.hostname=A.hostname.startsWith("[")?A.hostname.slice(1,-1):A.hostname,oe.port=A.port,mIp(oe,t.proxy,D+"//"+A.hostname+(A.port?":"+A.port:"")+oe.path));let pe,de=A0D.test(oe.protocol);if(oe.agent=de?t.httpsAgent:t.httpAgent,t.transport?pe=t.transport:t.maxRedirects===0?pe=de?vIp.default:yIp.default:(t.maxRedirects&&(oe.maxRedirects=t.maxRedirects),t.beforeRedirect&&(oe.beforeRedirects.config=t.beforeRedirect),pe=de?M0D:E0D),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 wt=[Ue],De=+Ue.headers["content-length"];if($||V){let at=new hYs({maxRate:os.toFiniteNumber(V)});$&&at.on("progress",pIp(at,BFn(De,pfi(IFn($),!0,3)))),wt.push(at)}let Te=Ue,xt=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":wt.push(_fi.default.createUnzip(lIp)),delete Ue.headers["content-encoding"];break;case"deflate":wt.push(new oIp),wt.push(_fi.default.createUnzip(lIp)),delete Ue.headers["content-encoding"];break;case"br":fIp&&(wt.push(_fi.default.createBrotliDecompress(D0D)),delete Ue.headers["content-encoding"])}Te=wt.length>1?t$i.default.pipeline(wt,os.noop):wt[0];let Pe=t$i.default.finished(Te,()=>{Pe(),w()}),ot={status:Ue.statusCode,statusText:Ue.statusMessage,headers:new aR(Ue.headers),config:t,request:xt};if(s==="stream")ot.data=Te,Ktr(i,n,ot);else{let at=[],me=0;Te.on("data",function(jt){at.push(jt),me+=jt.length,t.maxContentLength>-1&&me>t.maxContentLength&&(g=!0,Te.destroy(),n(new Fp("maxContentLength size of "+t.maxContentLength+" exceeded",Fp.ERR_BAD_RESPONSE,t,xt)))}),Te.on("aborted",function(){if(g)return;let jt=new Fp("stream has been aborted",Fp.ERR_BAD_RESPONSE,t,xt);Te.destroy(jt),n(jt)}),Te.on("error",function(jt){O.destroyed||n(Fp.from(jt,null,t,xt))}),Te.on("end",function(){try{let jt=at.length===1?at[0]:Buffer.concat(at);s!=="arraybuffer"&&(jt=jt.toString(o),(!o||o==="utf8")&&(jt=os.stripBOM(jt))),ot.data=jt}catch(jt){return n(Fp.from(jt,null,t,ot.request,ot))}Ktr(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(Fp.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 Fp("error trying to parse `config.timeout` to int",Fp.ERR_BAD_OPTION_VALUE,t,O));return}O.setTimeout(Oe,function(){if(b)return;let wt=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",De=t.transitional||qFn;t.timeoutErrorMessage&&(wt=t.timeoutErrorMessage),n(new Fp(wt,De.clarifyTimeoutError?Fp.ETIMEDOUT:Fp.ECONNABORTED,t,O)),E()})}if(os.isStream(u)){let Oe=!1,Ue=!1;u.on("end",()=>{Oe=!0}),u.once("error",wt=>{Ue=!0,O.destroy(wt)}),u.on("close",()=>{!Oe&&!Ue&&E(new VEe("Request stream has been aborted",t,O))}),u.pipe(O)}else O.end(u)})};var jIp=oA.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,oA.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(oA.origin),oA.navigator&&/(msie|trident)/i.test(oA.navigator.userAgent)):()=>!0;var wIp=oA.hasStandardBrowserEnv?{write(e,t,r,i,n,a){let u=[e+"="+encodeURIComponent(t)];os.isNumber(r)&&u.push("expires="+new Date(r).toGMTString()),os.isString(i)&&u.push("path="+i),os.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 SIp=e=>e instanceof aR?{...e}:e;function lWt(e,t){t=t||{};let r={};function i(s,o,c,b){return os.isPlainObject(s)&&os.isPlainObject(o)?os.merge.call({caseless:b},s,o):os.isPlainObject(o)?os.merge({},o):os.isArray(o)?o.slice():o}function n(s,o,c,b){if(os.isUndefined(o)){if(!os.isUndefined(s))return i(void 0,s,c,b)}else return i(s,o,c,b)}function a(s,o){if(!os.isUndefined(o))return i(void 0,o)}function u(s,o){if(os.isUndefined(o)){if(!os.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(SIp(s),SIp(o),c,!0)};return os.forEach(Object.keys(Object.assign({},e,t)),function(o){let c=d[o]||n,b=c(e[o],t[o],o);os.isUndefined(b)&&c!==l||(r[o]=b)}),r}var R3o=e=>{let t=lWt({},e),{data:r,withXSRFToken:i,xsrfHeaderName:n,xsrfCookieName:a,headers:u,auth:l}=t;t.headers=u=aR.from(u),t.url=XHi(ZHi(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(os.isFormData(r)){if(oA.hasStandardBrowserEnv||oA.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(oA.hasStandardBrowserEnv&&(i&&os.isFunction(i)&&(i=i(t)),i||i!==!1&&jIp(t.url))){let s=n&&a&&wIp.read(a);s&&u.set(n,s)}return t};var I0D=typeof XMLHttpRequest<"u",DIp=I0D&&function(e){return new Promise(function(r,i){let n=R3o(e),a=n.data,u=aR.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 A=aR.from("getAllResponseHeaders"in w&&w.getAllResponseHeaders()),C={data:!l||l==="text"||l==="json"?w.responseText:w.response,status:w.status,statusText:w.statusText,headers:A,config:e,request:w};Ktr(function($){r($),m()},function($){i($),m()},C),w=null}"onloadend"in w?w.onloadend=E:w.onreadystatechange=function(){!w||w.readyState!==4||w.status===0&&!(w.responseURL&&w.responseURL.indexOf("file:")===0)||setTimeout(E)},w.onabort=function(){w&&(i(new Fp("Request aborted",Fp.ECONNABORTED,e,w)),w=null)},w.onerror=function(){i(new Fp("Network Error",Fp.ERR_NETWORK,e,w)),w=null},w.ontimeout=function(){let D=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded",C=n.transitional||qFn;n.timeoutErrorMessage&&(D=n.timeoutErrorMessage),i(new Fp(D,C.clarifyTimeoutError?Fp.ETIMEDOUT:Fp.ECONNABORTED,e,w)),w=null},a===void 0&&u.setContentType(null),"setRequestHeader"in w&&os.forEach(u.toJSON(),function(D,C){w.setRequestHeader(C,D)}),os.isUndefined(n.withCredentials)||(w.withCredentials=!!n.withCredentials),l&&l!=="json"&&(w.responseType=n.responseType),s&&([b,O]=pfi(s,!0),w.addEventListener("progress",b)),d&&w.upload&&([c,g]=pfi(d),w.upload.addEventListener("progress",c),w.upload.addEventListener("loadend",g)),(n.cancelToken||n.signal)&&(o=A=>{w&&(i(!A||A.type?new VEe(null,e,w):A),w.abort(),w=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));let q=mEa(n.url);if(q&&oA.protocols.indexOf(q)===-1){i(new Fp("Unsupported protocol "+q+":",Fp.ERR_BAD_REQUEST,e));return}w.send(a||null)})};var z0D=(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 Fp?o:new VEe(o instanceof Error?o.message:o))}},u=t&&setTimeout(()=>{u=null,a(new Fp(`timeout ${t} of ms exceeded`,Fp.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=()=>os.asap(l),d}},EIp=z0D;var x0D=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},R0D=async function*(e,t){for await(let r of N0D(e))yield*x0D(r,t)},N0D=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()}},bYs=(e,t,r,i)=>{let n=R0D(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 F3o=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",AIp=F3o&&typeof ReadableStream=="function",F0D=F3o&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),qIp=(e,...t)=>{try{return!!e(...t)}catch{return!1}},L0D=AIp&&qIp(()=>{let e=!1,t=new Request(oA.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),MIp=64*1024,gYs=AIp&&qIp(()=>os.isReadableStream(new Response("").body)),N3o={stream:gYs&&(e=>e.body)};F3o&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!N3o[t]&&(N3o[t]=os.isFunction(e[t])?r=>r[t]():(r,i)=>{throw new Fp(`Response type '${t}' is not supported`,Fp.ERR_NOT_SUPPORT,i)})})})(new Response);var U0D=async e=>{if(e==null)return 0;if(os.isBlob(e))return e.size;if(os.isSpecCompliantForm(e))return(await new Request(oA.origin,{method:"POST",body:e}).arrayBuffer()).byteLength;if(os.isArrayBufferView(e)||os.isArrayBuffer(e))return e.byteLength;if(os.isURLSearchParams(e)&&(e=e+""),os.isString(e))return(await F0D(e)).byteLength},V0D=async(e,t)=>{let r=os.toFiniteNumber(e.getContentLength());return r??U0D(t)},TIp=F3o&&(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}=R3o(e);s=s?(s+"").toLowerCase():"text";let g=EIp([n,a&&a.toAbortSignal()],u),O,m=g&&g.unsubscribe&&(()=>{g.unsubscribe()}),w;try{if(d&&L0D&&r!=="get"&&r!=="head"&&(w=await V0D(o,i))!==0){let C=new Request(t,{method:"POST",body:i,duplex:"half"}),x;if(os.isFormData(i)&&(x=C.headers.get("content-type"))&&o.setContentType(x),C.body){let[$,I]=BFn(w,pfi(IFn(d)));i=bYs(C.body,MIp,$,I)}}os.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),A=gYs&&(s==="stream"||s==="response");if(gYs&&(l||A&&m)){let C={};["status","statusText","headers"].forEach(F=>{C[F]=q[F]});let x=os.toFiniteNumber(q.headers.get("content-length")),[$,I]=l&&BFn(x,pfi(IFn(l),!0))||[];q=new Response(bYs(q.body,MIp,$,()=>{I&&I(),m&&m()}),C)}s=s||"text";let D=await N3o[os.findKey(N3o,s)||"text"](q,e);return!A&&m&&m(),await new Promise((C,x)=>{Ktr(C,x,{data:D,headers:aR.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 Fp("Network Error",Fp.ERR_NETWORK,e,O),{cause:E.cause||E}):Fp.from(E,E&&E.code,e,O)}});var OYs={http:PIp,xhr:DIp,fetch:TIp};os.forEach(OYs,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var CIp=e=>`- ${e}`,W0D=e=>os.isFunction(e)||e===null||e===!1,L3o={getAdapter:e=>{e=os.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,!W0D(r)&&(i=OYs[(u=String(r)).toLowerCase()],i===void 0))throw new Fp(`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 :
@@ -1912,7 +1912,7 @@ For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides
1912
1912
  2. your cache path is incorrectly configured (which is: ${this.puppeteer.configuration.cacheDirectory}).
1913
1913
  For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides/configuration.`)}}return n.executablePath}};qTa=new WeakMap;var rLo=class extends X6n{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
1914
1914
  `].join(`
1915
- `)),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?(Yc(!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,E$p.mkdtemp)(this.getProfilePath())}`),o=d.length-1);let c=d[o].split("=",2)[1];Yc(typeof c=="string","`--user-data-dir` is malformed");let b=l;return b||(Yc(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 P6n(t)}catch(i){throw B0(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=${M$p.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?a9o({browser:$A.CHROME,channel:C2D(t)}):this.resolveExecutablePath()}};function C2D(e){switch(e){case"chrome":return b3.STABLE;case"chrome-dev":return b3.DEV;case"chrome-beta":return b3.BETA;case"chrome-canary":return b3.CANARY}}var Bac=ui(require("fs"),1),FGi=require("fs/promises"),A$p=ui(require("os"),1),iLo=ui(require("path"),1);yC();uA();var nLo=class extends X6n{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&&Yc(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||!Bac.default.existsSync(s))throw new Error(`Firefox profile not found at '${s}'`);o=!1}else s=await(0,FGi.mkdtemp)(this.getProfilePath()),d.push("--profile"),d.push(s);await anc($A.FIREFOX,{path:s,preferences:u});let b;return this.puppeteer._isPuppeteerCore||n?(Yc(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 P6n(t)}catch(i){throw B0(i),i}else try{await(0,FGi.unlink)(iLo.default.join(t,"user.js"));let i=iLo.default.join(t,"prefs.js.puppeteer");if(Bac.default.existsSync(i)){let n=iLo.default.join(t,"prefs.js");await(0,FGi.unlink)(n),await(0,FGi.rename)(i,n)}}catch(i){B0(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(A$p.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 q$p=require("path");var CTa=Object.freeze({chromium:"1108766",firefox:"latest"});var Iac=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},FWt=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)},Z6n,kfi,ITa,BTa,k6n=class extends Tqa{constructor(t){let{configuration:r,...i}=t;switch(super(i),Z6n.add(this),kfi.set(this,void 0),ITa.set(this,void 0),this.configuration={},r&&(this.configuration=r),this.configuration.defaultProduct){case"firefox":this.defaultBrowserRevision=CTa.firefox;break;default:this.configuration.defaultProduct="chrome",this.defaultBrowserRevision=CTa.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 Iac(this,ITa,r,"f"),FWt(this,Z6n,"a",BTa).launch(t)}executablePath(t){return FWt(this,Z6n,"a",BTa).executablePath(t)}get browserRevision(){var t,r,i;return(i=(r=(t=FWt(this,kfi,"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,q$p.join)(this.configuration.cacheDirectory,this.product)}get lastLaunchedProduct(){var t;return(t=FWt(this,ITa,"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 FWt(this,Z6n,"a",BTa).product}defaultArgs(t={}){return FWt(this,Z6n,"a",BTa).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 J5o(t)}};kfi=new WeakMap,ITa=new WeakMap,Z6n=new WeakSet,BTa=function(){if(FWt(this,kfi,"f")&&FWt(this,kfi,"f").product===this.lastLaunchedProduct)return FWt(this,kfi,"f");switch(this.lastLaunchedProduct){case"chrome":this.defaultBrowserRevision=CTa.chromium,Iac(this,kfi,new rLo(this),"f");break;case"firefox":this.defaultBrowserRevision=CTa.firefox,Iac(this,kfi,new nLo(this),"f");break;default:throw new Error(`Unknown product: ${FWt(this,ITa,"f")}`)}return FWt(this,kfi,"f")};Itc();JMa();var B2D=new k6n({isPuppeteerCore:!0}),{connect:Yp8,createBrowserFetcher:Xp8,defaultArgs:Zp8,executablePath:kp8,launch:e_8}=B2D;var aJp=require("os"),oJp=require("path"),uJp=ui(nJp(),1);function aLD(e){switch(e){case"chrome":case"firefox":return!0;default:return!1}}var sJp=()=>{var e,t,r,i,n,a,u,l,d,s,o,c,b,g,O,m,w,E,q,A,D,C,x,$,I,F,V,K,Y,Z,oe,pe,de,Oe,Ue,wt,De;let Te=(0,uJp.cosmiconfigSync)("puppeteer").search(),xt=Te?Te.config:{};if(xt.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:xt.defaultProduct)!==null&&i!==void 0?i:"chrome",xt.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:xt.executablePath,xt.executablePath&&(xt.skipDownload=!0),xt.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:xt.skipDownload),xt.skipDownload||(xt.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:xt.browserRevision,xt.downloadHost=(A=(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&&A!==void 0?A:xt.downloadHost,xt.downloadPath=(x=(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&&x!==void 0?x:xt.downloadPath),xt.cacheDirectory=(V=(F=(I=($=process.env.PUPPETEER_CACHE_DIR)!==null&&$!==void 0?$:process.env.npm_config_puppeteer_cache_dir)!==null&&I!==void 0?I:process.env.npm_package_config_puppeteer_cache_dir)!==null&&F!==void 0?F:xt.cacheDirectory)!==null&&V!==void 0?V:(0,oJp.join)((0,aJp.homedir)(),".cache","puppeteer"),xt.temporaryDirectory=(Z=(Y=(K=process.env.PUPPETEER_TMP_DIR)!==null&&K!==void 0?K:process.env.npm_config_puppeteer_tmp_dir)!==null&&Y!==void 0?Y:process.env.npm_package_config_puppeteer_tmp_dir)!==null&&Z!==void 0?Z:xt.temporaryDirectory,(oe=xt.experiments)!==null&&oe!==void 0||(xt.experiments={}),xt.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:xt.experiments.macArmChromiumEnabled),xt.logLevel=(De=(wt=(Ue=process.env.PUPPETEER_LOGLEVEL)!==null&&Ue!==void 0?Ue:process.env.npm_config_LOGLEVEL)!==null&&wt!==void 0?wt:process.env.npm_package_config_LOGLEVEL)!==null&&De!==void 0?De:xt.logLevel,!aLD(xt.defaultProduct))throw new Error(`Unsupported product ${xt.defaultProduct}`);return xt};var oLD=sJp(),uLD=new k6n({isPuppeteerCore:!1,configuration:oLD}),{connect:ch8,createBrowserFetcher:lh8,defaultArgs:fh8,executablePath:dh8,launch:cJp}=uLD;var sLD="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",cLD={"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 KTa(e,t=3,r=1e3,i=2){try{return await e()}catch(n){if(t>0)return await new Promise(a=>setTimeout(a,r)),KTa(e,t-1,r*i,i);throw n}}async function lJp(){try{return await cJp({headless:"new",ignoreHTTPSErrors:!0})}catch{throw new Error("Could not create a Puppeteer instance")}}async function lLD(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(cLD),await r.setUserAgent(sLD),await r.setJavaScriptEnabled(!0),await KTa(()=>r.goto(t.toString(),{waitUntil:"networkidle2",timeout:3e4}));let i=await KTa(()=>r.content());return await r.close(),i}catch{throw new Error("Failed to download page from Puppeteer")}}async function fLD(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 Uoc({url:e,browser:t}){try{let r;if(t?r=await lLD(t,e):r=await KTa(()=>fLD(e)),r)return r;throw new Error("An unknown error occurred.")}catch{throw new Error(`Error retrieving HTML for ${e.toString()}`)}}async function fJp(e){try{let t=await KTa(()=>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 dLD=["png","jpeg","jpg","webp","avif","svg","ico","jfif","pjpeg","pjp","svgz","bmp"];async function dJp(e){if(!e)return{success:!1,data:void 0};if(e.startsWith("data:image/"))return{success:!0,data:[e,e]};let t=(0,u4n.join)(process.cwd(),"fern");try{let r=await pLD(e,(0,u4n.join)(t,"images"));return r=r.replace(t,""),{success:!0,data:[e,r]}}catch{return{success:!1,data:void 0}}}async function pLD(e,t){let r=hLD(e),i=(0,u4n.join)(t,r);if(!_LD(r))throw new Error(`${r} - file extension not supported`);if((0,ELo.existsSync)(i))return i;try{(0,ELo.mkdirSync)((0,u4n.dirname)(i),{recursive:!0})}catch{throw new Error(`${i} - failed to create directory`)}try{let n=await fJp(e);return h8p(i,n),i}catch{throw new Error(`${i}: failed to download file from source`)}}function _LD(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&&!dLD.includes(i))}function hLD(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 yLD(e){let t=[];return Ff(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 pJp(e,t){let r=A3n(e),i=yLD(r);if(i!=null){let n=await Promise.all(i.map(async a=>{let u=await dJp(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 _Jp=28;async function hJp(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 pJp(a,r)))}let i=[...new Set(r).values()];if(i.length!==0){if(i.length===1&&i[0]!=null){let n=Na.of(YG(i[0]));return{light:n,dark:n,height:_Jp}}if(i[0]!=null&&i[1]!=null){let n=Na.of(YG(i[0])),a=Na.of(YG(i[1]));return{light:n,dark:a,height:_Jp}}}}var MLo=class extends s$i{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:UEa});let i=await this.getHastForUrl(this.url),n=S5p(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=Ru(this.absolutePathToFernDirectory,Na.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 lJp(),u=await hJp(this.url,a);u!=null&&r.setLogo({logo:u});let l=await K3p(i);r.setTitle({title:l});let d=await $3p(i);if(d!=null){let o=await this.getAndCreateAssetsDirectory(),c=await fetch(d);if(c.ok){let b=Buffer.from(await c.arrayBuffer()),g=Ru(o,Na.of("favicon"));await(0,vEi.writeFile)(g,new Uint8Array(b)),r.setFavicon({favicon:Rie(this.absolutePathToFernDirectory,g)})}}let s=await E5p(i);r.setColors({colors:s}),a&&await a.close(),r.build({outputDirectory:this.absolutePathToFernDirectory})}async getAndCreateAssetsDirectory(){let t=Ru(this.absolutePathToFernDirectory,Na.of("assets"));return await(0,vEi.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=P5p(n);if(!a){this.logger.debug(`No sidebar element found for tab: ${t} (${r})`);return}let u=j5p(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 Uoc({url:t});return A3n(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,vEi.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 Uoc({url:u}),d=await m5p({logger:this.logger,html:l,url:u});if(d.success&&d.data){let s=this.getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:n,page:a.slug});await(0,vEi.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=Ru(n,Na.of(c)),m=Cd(O);await(0,vEi.mkdir)(m,{recursive:!0}),await(0,vEi.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:Rie(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 Ru(t,Na.of(`${this.kebabCaseWithoutEmojis(r.split("/").pop()||r)}.mdx`))}getAbsolutePathToOutputDirectoryForSection({absolutePathToOutputDirectory:t,section:r}){return Ru(t,Na.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 yJp=require("fs/promises");async function Voc({readmeUrl:e,outputPath:t,taskContext:r,versionOfCli:i,organization:n}){let a=new c$i;a.setInstance({companyName:n}),await new MLo({url:e,context:r,builder:a,absolutePathToFernDirectory:Ru(ul.of(process.cwd()),Na.of("fern"))}).import({args:{},builder:a}),await a.build({outputDirectory:t}),await(0,yJp.writeFile)(Ru(ul.of(t),Na.of(GV),Na.of(Bie)),JSON.stringify({version:i,organization:n},void 0,4))}var Woc=async({readmeUrl:e,organization:t,taskContext:r,versionOfCli:i})=>{if(!e||!ZUi(e)){r.failAndThrow("Provide a URL to a readme-generated site");return}let n=ul.of(kz());await Voc({readmeUrl:e,outputPath:n,taskContext:r,versionOfCli:i,organization:t})};var vJp="0.0.0";var bJp={[Oy.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,GC(e)])),[Oy.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"]),[Oy.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"]),[Oy.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"]),[Oy.GenerationLanguage.GO]:new Set(["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var","any","bool","byte","complex64","complex128","error","float32","float64","int","int8","int16","int32","int64","make","new","rune","string","uint","uint8","uint16","uint32","uint64","uintptr"]),[Oy.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"]),[Oy.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"]),[Oy.GenerationLanguage.SWIFT]:new Set([])};var bLD=["go","ruby"];function RZ({generationLanguage:e,keywords:t,smartCasing:r}){let i={generateName:(n,a)=>{let u=c=>({unsafeName:c,safeName:gLD({name:c,keywords:OLD({generationLanguage:e,keywords:t})})}),l=p_(n),d=GC(l),s=yUi(n),o=dUi(l);return r&&(!jLD(o)&&(e==null||bLD.includes(e))&&(l=o.map((c,b)=>{if(b>0){let g=ALo(c);if(g!=null)return g;if(qLo(c))return c.toUpperCase()}return c}).join(""),d=GC(o.map((c,b)=>{let g=ALo(c);return g??(qLo(c)?c.toUpperCase():b===0?GC(c):c)}).join(""))),s=n.split(" ").map(c=>c.split(/(\d+)/).map(yUi).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 gLD({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":PLD(e)?"_"+e:e}function OLD({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return bJp[e]}var mLD=/^[0-9]/;function PLD(e){return mLD.test(e)}function jLD(e){return e.some((t,r)=>{if(r===0)return!1;let i=e[r-1];if(i==null)return!1;let n=ALo(i)!=null||qLo(i),a=ALo(t)!=null||qLo(t);return n&&a})}function ALo(e){return SLD.get(e.toUpperCase())}function qLo(e){return wLD.has(e.toUpperCase())}var wLD=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"]),SLD=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]);function ZN(e){let t=ELD(e),{value:r,done:i}=Hoc(t,"{");return i?{head:r,parts:[]}:{head:r,parts:[...DLD(t)]}}function*DLD(e){let t;do{let{value:r}=Hoc(e,"}"),i=Hoc(e,"{");t=i.done,yield{pathParameter:r,tail:i.value}}while(!t)}function*ELD(e){for(let t of e)yield t}function Hoc(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 YTa(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 zrr({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 gJp({fieldName:e,containerType:t,maxDepth:r,currentDepth:i,typeDeclarations:n,skipOptionalProperties:a}){if(i>=r)return xrr({containerType:t});switch(t.type){case"list":{let u=Fq({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?xrr({containerType:t}):{type:"success",example:Pm.list({list:[u.example,u.example],itemType:t.list}),jsonExample:[u.jsonExample,u.jsonExample]}}case"literal":return{type:"success",example:Pm.literal({literal:t.literal._visit({boolean:u=>Fd.boolean(u),string:u=>Fd.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 xrr({containerType:t});let u=Fq({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?xrr({containerType:t}):{type:"success",example:Pm.optional({optional:u.example,valueType:t.optional}),jsonExample:u.jsonExample}}case"nullable":{if(a)return xrr({containerType:t});let u=Fq({fieldName:e,typeReference:t.nullable,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?xrr({containerType:t}):{type:"success",example:Pm.nullable({nullable:u.example,valueType:t.nullable}),jsonExample:u.jsonExample}}case"set":{let u=Fq({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?xrr({containerType:t}):{type:"success",example:Pm.set({set:[u.example],itemType:t.set}),jsonExample:[u.jsonExample]}}case"map":{let u=Fq({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a}),l=Fq({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"||l.type==="failure"?xrr({containerType:t}):{type:"success",example:Pm.map({map:[{key:u.example,value:l.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[u.jsonExample]:l.jsonExample}}}default:wo(t)}}function xrr({containerType:e}){switch(e.type){case"list":return{type:"success",example:Pm.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:Pm.literal({literal:e.literal._visit({boolean:t=>Fd.boolean(t),string:t=>Fd.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:Pm.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"nullable":return{type:"success",example:Pm.nullable({nullable:void 0,valueType:e.nullable}),jsonExample:void 0};case"set":return{type:"success",example:Pm.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:Pm.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:wo(e)}}function mJp({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":return CLD({fieldName:e,default_:MLD(t.v2),validation:ALD(t.v2)});case"BASE_64":return{type:"success",example:Fd.base64(bh.BASE64),jsonExample:bh.BASE64};case"BOOLEAN":return{type:"success",example:Fd.boolean(bh.BOOLEAN),jsonExample:bh.BOOLEAN};case"DATE":return{type:"success",example:Fd.date(bh.DATE),jsonExample:bh.DATE};case"DATE_TIME":return{type:"success",example:Fd.datetime({datetime:new Date(bh.DATE_TIME),raw:bh.DATE_TIME}),jsonExample:bh.DATE_TIME};case"DOUBLE":return BLD({fieldName:e,validation:qLD(t.v2)});case"FLOAT":return{type:"success",example:Fd.float(bh.FLOAT),jsonExample:bh.FLOAT};case"INTEGER":return ILD({fieldName:e,validation:TLD(t.v2)});case"UINT_64":return{type:"success",example:Fd.uint64(bh.INT64),jsonExample:bh.INT64};case"UINT":return{type:"success",example:Fd.uint(bh.UINT),jsonExample:bh.UINT};case"BIG_INTEGER":return{type:"success",example:Fd.bigInteger(bh.INT64.toString()),jsonExample:`${bh.INT64}`};case"LONG":return{type:"success",example:Fd.long(bh.INT64),jsonExample:bh.INT64};case"UUID":return{type:"success",example:Fd.uuid(bh.UUID),jsonExample:bh.UUID};default:wo(t.v1)}}function MLD(e){if(e?.type==="string")return e.default}function ALD(e){if(e?.type==="string")return e.validation}function qLD(e){if(e?.type==="double")return e.validation}function TLD(e){if(e?.type==="integer")return e.validation}function OJp(e){if(e<=bh.SAMPLE_STRINGS.length){let t=bh.SAMPLE_STRINGS[e-1];if(t)return t;throw new Error(`Unexpected undefined value in SAMPLE_STRINGS at index ${e-1}`)}return bh.SAMPLE_STRINGS[bh.SAMPLE_STRINGS.length-1]+".".repeat(e-bh.SAMPLE_STRINGS.length)}function CLD({fieldName:e,default_:t,validation:r}){if(t!=null)return{type:"success",example:Fd.string({original:t}),jsonExample:t};if(r){let n=r.minLength,a=r.maxLength;if(n){let u=OJp(n);return{type:"success",example:Fd.string({original:u}),jsonExample:u}}else if(a){let u=OJp(a);return{type:"success",example:Fd.string({original:u}),jsonExample:u}}}let i=e??bh.STRING;return{type:"success",example:Fd.string({original:i}),jsonExample:i}}function BLD({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:Fd.double(r),jsonExample:r};if(i)return{type:"success",example:Fd.double(i),jsonExample:i}}return{type:"success",example:Fd.double(bh.DOUBLE),jsonExample:bh.DOUBLE}}function ILD({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:Fd.integer(r),jsonExample:r};if(i)return{type:"success",example:Fd.integer(i),jsonExample:i}}return{type:"success",example:Fd.integer(bh.INT),jsonExample:bh.INT}}function s4n({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let u=Fq({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:Nw.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:Nw.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=s4n({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=zLD({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:Nw.object({properties:[...l,...s.properties]}),jsonExample:Object.assign({},u,o)}}case"undiscriminatedUnion":{let u=0;for(let l of r.shape.members){let d=Fq({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:Nw.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=Fq({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:Nw.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:n3.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=s4n({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:Nw.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:n3.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=Fq({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:Nw.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:n3.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 zLD({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=Fq({fieldName:s.name.wireValue,typeReference:s.valueType,typeDeclarations:i,currentDepth:a+1,maxDepth:n,skipOptionalProperties:u});if(o.type==="failure"&&!zrr({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:Nw.object({properties:d}),jsonExample:l}}function Fq({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=s4n({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:Wh.named({shape:d,typeName:u.name})},jsonExample:s}}case"container":{let u=gJp({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure"){let{example:s,jsonExample:o}=xrr({containerType:t.container});return{type:"success",example:{jsonExample:o,shape:Wh.container(s)},jsonExample:o}}let{example:l,jsonExample:d}=u;return{type:"success",example:{jsonExample:d,shape:Wh.container(l)},jsonExample:d}}case"primitive":{let{jsonExample:u,example:l}=mJp({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:u,shape:Wh.primitive(l)},jsonExample:u}}case"unknown":{let u={key:"value"};return{type:"success",example:{jsonExample:u,shape:Wh.unknown(u)},jsonExample:u}}}}function GGi(e,t){let r=[];for(let i of e){let n=Fq({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 c4n(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&zrr({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=Fq({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 TLo(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&zrr({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=Fq({fieldName:i.name.name.originalName,currentDepth:0,maxDepth:t.maxDepth??10,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,shape:i.allowMultiple?B2.exploded():B2.single(),value:n.example})}return{type:"success",example:r,jsonExample:void 0}}var $oc=Kc.primitive({v1:Vh.String,v2:Ed.string({default:void 0,validation:void 0})});function XTa({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:RT.ok(kC.body(void 0)),docs:void 0},l=GGi(t.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(l.type==="failure")return l;u.endpointPathParameters=l.example;let d=GGi(r.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(d.type==="failure")return d;u.servicePathParameters=d.example;let s=GGi(e.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(s.type==="failure")return s;u.rootPathParameters=s.example;let o=TLo(t.queryParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:10});if(o.type==="failure")return o;u.queryParameters=o.example;let c=c4n(t.headers,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(c.type==="failure")return c;u.endpointHeaders=c.example;let b=c4n(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=s4n({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=Fq({fieldName:m.name.wireValue,typeReference:m.valueType,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});if(w.type==="failure"&&!zrr({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=OQ.inlinedRequestBody({jsonExample:g,properties:O});break}case"reference":{let g=Fq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:n});if(g.type==="failure")return g;let{example:O}=g;u.request=OQ.reference(O);break}default:wo(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=Fq({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=RT.ok(kC.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=Fq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.nonStreamResponse.value.responseBodyType,skipOptionalProperties:!1});break;case"text":g=Fq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:$oc,skipOptionalProperties:!1});break;default:wo(t.response.body.nonStreamResponse)}if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RT.ok(kC.body({...O,jsonExample:m}));break}case"streaming":{let g;switch(t.response.body.value.type){case"sse":{if(g=Fq({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=RT.ok(kC.sse([{data:{...O,jsonExample:m},event:""}]));break}case"json":{if(g=Fq({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=RT.ok(kC.stream([{...O,jsonExample:m}]));break}case"text":{if(g=Fq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:$oc,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RT.ok(kC.stream([{...O,jsonExample:m}]));break}default:wo(t.response.body.value)}break}case"text":{let g=Fq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:$oc,skipOptionalProperties:!1});if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RT.ok(kC.body({...O,jsonExample:m}));break}case"bytes":return{type:"failure",message:"Bytes unsupported"};default:wo(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)u.response=RT.error({body:void 0,error:a.declaration.name});else{let g=Fq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:a.declaration.type,skipOptionalProperties:n});if(g.type==="failure")return g;let{example:O}=g;u.response=RT.error({body:O,error:a.declaration.name})}try{return{type:"success",example:{id:YTa(u),url:xLD(t,u),...u},jsonExample:void 0}}catch(g){return{type:"failure",message:`Parse failure with exceptions ${g}`}}}function xLD(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 Goc({ir:e,channel:t,typeDeclarations:r,skipOptionalRequestProperties:i}){let n={name:void 0,pathParameters:[],headers:[],queryParameters:[],messages:[],docs:void 0},a=GGi(t.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(a.type==="failure")return a;n.pathParameters.push(...a.example);let u=GGi(e.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(u.type==="failure")return u;n.pathParameters.push(...u.example);let l=TLo(t.queryParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:10});if(l.type==="failure")return l;n.queryParameters=l.example;let d=c4n(t.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(d.type==="failure")return d;n.headers.push(...d.example);let s=c4n(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=PJp({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=PJp({message:g,typeDeclarations:r,skipOptionalRequestProperties:i});O!=null&&n.messages.push({type:g.type,body:O})}return{type:"success",example:{...n,url:RLD(t,n)},jsonExample:void 0}}function PJp({message:e,typeDeclarations:t,skipOptionalRequestProperties:r}){if(e.body.type==="inlinedBody")return;let i=Fq({currentDepth:0,maxDepth:10,typeDeclarations:t,typeReference:e.body.bodyType,skipOptionalProperties:r});if(i.type==="success")return TEe.reference(i.example)}function RLD(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 l4n(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{},i=Object.values(t)[0],n=Object.values(r)[0];return{userExample:i,autoExample:n}}function bEi(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{};return{userExamples:t,autoExamples:r}}function jJp({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}=l4n(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}=l4n(u.v2Examples);if(l!==void 0)n.queryParameters[u.name.name.originalName]=l;else if(d!==void 0){if(r&&zrr({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}=l4n(u.v2Examples);if(l!==void 0)n.headers[u.name.wireValue]=l;else if(d!==void 0){if(r&&zrr({typeReference:u.valueType,typeDeclarations:i}))continue;n.headers[u.name.wireValue]=d}}return n}function wJp({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let{pathParameters:i,queryParameters:n,headers:a}=jJp({endpoint:e,ir:t,skipOptionalRequestProperties:r}),u={},l={},d={endpoint:{method:e.method,path:NLD(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}=bEi(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}=bEi(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}=bEi(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:wo(e.requestBody)}return{userRequestExamples:u,autoRequestExamples:l,baseExample:d}}function NLD(e){let t={};[...e.pathParameters,...e.allPathParameters].forEach(i=>{let{userExample:n,autoExample:a}=l4n(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 SJp({endpoint:e}){let t={},r={},i={statusCode:e.response?.statusCode,body:void 0,docs:void 0};if(e.response==null)return{userResponseExamples:{},autoResponseExamples:{},baseExample:i};if(e.response.body==null)return e.source?.type==="openrpc"?{userResponseExamples:{},autoResponseExamples:{},baseExample:{...i,body:RN.json(ZTa(null))}}:{userResponseExamples:{},autoResponseExamples:{},baseExample:i};switch(e.response.body.type){case"bytes":break;case"fileDownload":break;case"text":{let n=e.response.body,{userExamples:a,autoExamples:u}=bEi(n.v2Examples);for(let[l,d]of Object.entries(a)){let s=e.source?.type==="openrpc"?ZTa(d):d;t[l]={...i,body:RN.json(s)}}for(let[l,d]of Object.entries(u)){let s=e.source?.type==="openrpc"?ZTa(d):d;r[l]={...i,body:RN.json(s)}}break}case"json":{let n=e.response.body.value;if(n.type==="response"){let{userExamples:a,autoExamples:u}=bEi(n.v2Examples);for(let[l,d]of Object.entries(a)){let s=e.source?.type==="openrpc"?ZTa(d):d;t[l]={...i,body:RN.json(s)}}for(let[l,d]of Object.entries(u)){let s=e.source?.type==="openrpc"?ZTa(d):d;r[l]={...i,body:RN.json(s)}}}break}case"streaming":{let n=e.response.body.value;if(n.type==="json"){let{userExamples:a,autoExamples:u}=bEi(n.v2Examples);for(let[l,d]of Object.entries(a))t[l]={...i,body:RN.stream([d])};for(let[l,d]of Object.entries(u))r[l]={...i,body:RN.stream([d])}}break}case"streamParameter":break;default:wo(e.response.body)}return{userResponseExamples:t,autoResponseExamples:r,baseExample:i}}function ZTa(e,t=1){return{id:t,jsonrpc:"2.0",result:e}}function DJp({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let i={},n={},{userRequestExamples:a,autoRequestExamples:u,baseExample:l}=wJp({endpoint:e,ir:t,skipOptionalRequestProperties:r}),{userResponseExamples:d,autoResponseExamples:s,baseExample:o}=SJp({endpoint:e}),c=Object.keys(u)[0],b=Object.values(u)[0],g=Object.values(s)[0];for(let[O,m]of Object.entries(a))i[O]={request:m,response:d[O]??g??o,codeSamples:void 0};for(let[O,m]of Object.entries(d))i[O]={request:a[O]??b??l,response:m,codeSamples:void 0};return Object.keys(i).length===0&&(n[c??p_(`${e.name.originalName}_example`)]={request:b??l,response:g??o,codeSamples:void 0}),{userFullExamples:i,autoFullExamples:n}}function kTa({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=XTa({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=Goc({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 Qoc({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}=DJp({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=Goc({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 QGi(e,t,r){let{environments:i,changedBaseUrlIds1:n,changedBaseUrlIds2:a}=LLD(e.environments,t.environments,r),{services:u,websocketChannels:l}=ULD(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:FLD(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 FLD(e,t){let r=e;for(let[i,n]of Object.entries(t))r[i]==null?r[i]=n:r[i]={name:n.name,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 LLD(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=EJp(e),n=EJp(t);if(i&&n&&e.environments.type==="singleBaseUrl"&&t.environments.type==="singleBaseUrl")return{environments:{defaultEnvironment:e.defaultEnvironment??t.defaultEnvironment,environments:rx.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}=VLD(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:rx.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}=WLD(d,s,r);return{environments:{defaultEnvironment:a,environments:rx.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}=HLD(u,l,r);return{environments:{defaultEnvironment:a,environments:rx.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 ULD(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 VLD(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=Joc(s.id,n);return i[s.id]=o,{...s,id:o,name:r.generateName(o)}}return s});return{deconflictedEnvironments2:rx.singleBaseUrl({environments:l}),changedBaseUrlIds2:i}}function WLD(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=Joc(d.id,n);return i[d.id]=s,{...d,id:s,name:r.generateName(s)}}return d});return{deconflictedEnvironments1:rx.singleBaseUrl({environments:u}),changedBaseUrlIds1:i}}function HLD(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=Joc(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:rx.multipleBaseUrls({baseUrls:u,environments:l}),changedBaseUrlIds:i}}function EJp(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 Joc(e,t){let r=e,i=1;for(;t.has(r);)r=`${e}-${i}`,i++;return r}function Yoc({rawApiFileSchema:e,casingsGenerator:t}){if(e.auth==null)return{docs:void 0,requirement:jne.All,schemes:[]};let r=typeof e.auth!="string"?e.auth.docs:void 0;return OWi(e.auth,{single:i=>{let n=MJp({reference:i,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t});return{docs:r,requirement:jne.All,schemes:[n]}},any:({any:i})=>({docs:r,requirement:jne.Any,schemes:i.map(n=>MJp({reference:n,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t}))})})}function MJp({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 A1a(l,{header:d=>xT.header({docs:u,name:r.generateNameAndWireValue({name:d.name??a,wireValue:d.header}),valueType:Kc.primitive({v1:Vh.String,v2:Ed.string({default:void 0,validation:void 0})}),prefix:d.prefix,headerEnvVar:d.env}),basic:d=>AJp({casingsGenerator:r,docs:u,rawScheme:d}),bearer:d=>Koc({casingsGenerator:r,docs:u,rawScheme:d}),oauth:d=>Koc({casingsGenerator:r,docs:u,rawScheme:void 0})})},n=typeof e=="string"?e:e.scheme;switch(n){case"bearer":case"oauth":return Koc({casingsGenerator:r,docs:void 0,rawScheme:void 0});case"basic":return AJp({casingsGenerator:r,docs:void 0,rawScheme:void 0});default:return i(n,typeof e!="string"?e.docs:void 0)}}function Koc({casingsGenerator:e,docs:t,rawScheme:r}){return xT.bearer({docs:t,token:e.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function AJp({casingsGenerator:e,docs:t,rawScheme:r}){return xT.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 eCa({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:gkt(i,{singleBaseUrl:()=>rx.singleBaseUrl($LD({environments:t,casingsGenerator:r})),multipleBaseUrls:n=>rx.multipleBaseUrls(GLD({baseUrls:Object.keys(n.urls),environments:t,casingsGenerator:r}))})},audiences:{...Object.fromEntries(Object.entries(t).map(([n,a])=>[n,gkt(a,{singleBaseUrl:u=>[...typeof u=="string"?[]:u.audiences??[]],multipleBaseUrls:u=>[...u.audiences??[]]})]))}}}function $LD({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,i])=>gkt(i,{singleBaseUrl:n=>({docs:typeof n=="string"?void 0:n.docs,id:r,name:t.generateName(r),url:qJp(typeof n=="string"?n:n.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function GLD({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(i=>({id:i,name:r.generateName(i)})),environments:Object.entries(t).map(([i,n])=>gkt(n,{multipleBaseUrls:a=>({docs:a.docs,id:i,name:r.generateName(i),urls:fd(a.urls,u=>qJp(u))}),singleBaseUrl:()=>{throw new Error(`Environment ${i} does not have multiple base URLs`)}}))}}function qJp(e){return e.endsWith("/")?e.slice(0,-1):e}function oMe(e){return e.allParts.map(t=>t.originalName).join("/")}var wm={generateTypeId:e=>`type_${oMe(e.fernFilepath)}:${e.name.originalName}`,generateErrorId:e=>`error_${oMe(e.fernFilepath)}:${e.name.originalName}`,generateServiceId:e=>`service_${oMe(e.fernFilepath)}`,generateServiceIdFromFernFilepath:e=>`service_${oMe(e)}`,generateSubpackageId:e=>`subpackage_${oMe(e)}`,generateEndpointId:(e,t)=>{let r=oMe(e.fernFilepath),i=t.name.originalName;return`endpoint_${r}.${i}`},generateWebhookGroupId:e=>`webhooks_${oMe(e)}`,generateWebhookId:(e,t)=>`webhooks_${oMe(e)}.${t}`,generateWebSocketChannelId:e=>`channel_${oMe(e)}`};function f4n(e){return e.type!=null}var CLo=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=wm.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=wm.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=wm.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)}};function JGi(e){let t={};for(let[r,i]of Object.entries(e))if(typeof i!="string")for(let n of i.audiences??[])t[n]==null&&(t[n]=new Set),t[n]?.add(r);return t}var KGi=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=QLD(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:i,descendantTypeIdsByAudience:n,propertiesByAudience:a}){let u=wm.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=wm.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=wm.generateErrorId(t.name),i=new Set,n=new Set;t.type!=null&&fx(t.type,i,n);let a={errorId:r,referencedTypes:i,referencedSubpackages:n};this.errors[r]=a}addEndpoint(t,r,i){let n=wm.generateServiceId(t.name),a=r.id,u=new Set,l=new Set,d=new Set;for(let s of[...t.headers,...r.headers])fx(s.valueType,u,d);for(let s of[...t.pathParameters,...r.pathParameters])fx(s.valueType,u,d);for(let s of r.queryParameters)fx(s.valueType,u,d);if(i!=null&&i.request!=null&&typeof i.request!="string"){let s=JGi(i.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:s}}r.requestBody!=null&&rA._visit(r.requestBody,{inlinedRequestBody:s=>{for(let o of s.extends)BLo(o,u,d);for(let o of s.properties)fx(o.valueType,u,d);if(i!=null&&typeof i.request=="object"&&typeof i.request.body=="object"&&XC(i.request.body)){let o=JGi(i.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:o}}},reference:({requestBodyType:s})=>{fx(s,u,d)},fileUpload:({properties:s})=>{for(let o of s)E6._visit(o,{file:Go,bodyProperty:({valueType:c})=>{fx(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&&Rw._visit(r.response.body,{fileDownload:Go,json:s=>{fx(s.responseBodyType,u,d)},streaming:s=>{s._visit({sse:o=>fx(o.payload,u,d),json:o=>fx(o.payload,u,d),text:Go,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.type)}})},streamParameter:s=>{s.streamResponse._visit({sse:o=>fx(o.payload,u,d),json:o=>fx(o.payload,u,d),text:Go,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.streamResponse.type)}}),s.nonStreamResponse.type==="json"&&fx(s.nonStreamResponse.value.responseBodyType,u,d)},text:Go,bytes:Go,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(s=>{l.add(wm.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=wm.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&&pW._visit(r.payload,{inlinedPayload:l=>{for(let d of l.extends)BLo(d,a,u);for(let d of l.properties)fx(d.valueType,a,u);if(i?.payload!=null&&typeof i.payload=="object"&&!f4n(i.payload)){let d=JGi(i.payload.properties??{});this.webhookProperties[n]={webhookId:n,propertiesByAudience:d}}},reference:({payloadType:l})=>{fx(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)M9._visit(l.body,{reference:({bodyType:d})=>{fx(d,a,u)},inlinedBody:d=>{for(let s of d.extends)BLo(s,a,u);for(let s of d.properties)fx(s.valueType,a,u)},_other:()=>{}});for(let l of i.queryParameters)fx(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 CLo({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:wo(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let i={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(wm.generateSubpackageId(i))}}};function QLD(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:wo(e)}}function fx(e,t,r){Kc._visit(e,{container:i=>{JLD(i,t,r)},named:i=>{BLo(i,t,r)},primitive:Go,unknown:Go,_other:Go})}function BLo(e,t,r){t.add(wm.generateTypeId(e)),r.add(e.fernFilepath)}function JLD(e,t,r){jy._visit(e,{list:i=>{fx(i,t,r)},map:i=>{fx(i.keyType,t,r),fx(i.valueType,t,r)},optional:i=>{fx(i,t,r)},nullable:i=>{fx(i,t,r)},set:i=>{fx(i,t,r)},literal:Go,_other:Go})}var Xoc=class{errors;constructor(){this.errors=[]}add(t){this.errors.push({message:t})}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}},tCa=class{errors;constructor(){this.errors=new Xoc}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:wo(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:wo(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:wo(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:wo(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:wo(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:wo(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:wo(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:wo(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:wo(i)}return r}getKeyForDeclaration({name:t,fernFilepath:r}){return`${r.allParts.map(n=>n.camelCase.unsafeName).join(".")}.${t.pascalCase.unsafeName}`}};function CJp({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:fR({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)}}:void 0;return i!==void 0?n3.samePropertiesAsObject(i):void 0},singleProperty:r=>{let i=fR({filteredIr:e,exampleTypeReference:r});return i!==void 0?n3.singleProperty(i):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function fR({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:i=>({...t,shape:Wh.container(Pm.list({...i,list:i.list.map(n=>fR({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),set:i=>({...t,shape:Wh.container(Pm.set({...i,set:i.set.map(n=>fR({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),optional:i=>{let n=i.optional!=null?fR({filteredIr:e,exampleTypeReference:i.optional}):void 0;return n!=null?{...t,shape:Wh.container(Pm.optional({optional:n,valueType:i.valueType}))}:void 0},nullable:i=>{let n=i.nullable!=null?fR({filteredIr:e,exampleTypeReference:i.nullable}):void 0;return n!=null?{...t,shape:Wh.container(Pm.nullable({nullable:n,valueType:i.valueType}))}:void 0},map:i=>({...t,shape:Wh.container(Pm.map({...i,map:i.map.map(n=>{let a=fR({filteredIr:e,exampleTypeReference:n.key}),u=fR({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=fR({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...t,shape:Wh.named({...r,shape:Nw.alias({...i,value:n})})}:void 0},enum:i=>({...t,shape:Wh.named({...r,shape:Nw.enum(i)})}),object:i=>({...t,shape:Wh.named({...r,shape:Nw.object({...i,properties:i.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:fR({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})})}),union:i=>{let n=CJp({filteredIr:e,singleUnionTypeProperties:i.singleUnionType.shape});return n!==void 0?{...t,shape:Wh.named({...r,shape:Nw.union({...i,singleUnionType:{...i.singleUnionType,shape:n}})})}:void 0},undiscriminatedUnion:i=>{let n=fR({filteredIr:e,exampleTypeReference:i.singleUnionType});return n!==void 0?{...t,shape:Wh.named({...r,shape:Nw.undiscriminatedUnion({...i,singleUnionType:n})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function Zoc({filteredIr:e,pathParameters:t}){return t.map(r=>{let i=fR({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function KLD({filteredIr:e,queryParameters:t}){return t.map(r=>{let i=fR({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function TJp({filteredIr:e,headers:t}){return t.map(r=>{let i=fR({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function YLD({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=fR({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...i,value:n}:void 0}).filter(i=>i!==void 0)}),reference:r=>{let i=fR({filteredIr:e,exampleTypeReference:r});return i!==void 0?OQ.reference(i):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function XLD({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:i=>RT.ok(kC.body(i!=null?fR({filteredIr:e,exampleTypeReference:i}):void 0)),stream:i=>RT.ok(kC.stream(i.map(n=>fR({filteredIr:e,exampleTypeReference:n})).filter(yv))),sse:i=>RT.ok(kC.sse(i.map(({event:n,data:a})=>{let u=fR({filteredIr:e,exampleTypeReference:a});return u!==void 0?{event:n,data:u}:void 0}).filter(yv))),_other:({type:i})=>{throw new Error(`Received unknown type for OK example: ${i}`)}}),error:({error:r,body:i})=>RT.error({error:r,body:i!=null?fR({filteredIr:e,exampleTypeReference:i}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function koc({filteredIr:e,example:t}){return{...t,rootPathParameters:Zoc({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:Zoc({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:Zoc({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:TJp({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:TJp({filteredIr:e,headers:t.endpointHeaders}),queryParameters:KLD({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?YLD({filteredIr:e,requestBody:t.request}):void 0,response:XLD({filteredIr:e,response:t.response})}}function BJp({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let i=fR({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...t,shape:Nw.alias({...r,value:i})}:void 0},enum:()=>t,object:r=>({...t,shape:Nw.object({...r,properties:r.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:fR({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})}),union:r=>{let i=CJp({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return i!==void 0?{...t,shape:Nw.union({...r,singleUnionType:{...r.singleUnionType,shape:i}})}:void 0},undiscriminatedUnion:r=>{let i=fR({filteredIr:e,exampleTypeReference:r.singleUnionType});return i!==void 0?{...t,shape:Nw.undiscriminatedUnion({...r,singleUnionType:i})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function euc(e,t){if(t==null)return e;let r=hUi(e.types,l=>t.hasType(l)),i=Object.fromEntries(Object.entries(r).map(([l,d])=>{let s=[];if(d.userProvidedExamples=d.userProvidedExamples.map(o=>BJp({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:Sb.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:hUi(e.errors,l=>t.hasError(l)),services:fd(hUi(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:koc({filteredIr:t,example:s.example})})),d.userSpecifiedExamples=d.userSpecifiedExamples.map(s=>({...s,example:s.example!=null?koc({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:ZLD(e.serviceTypeReferenceInfo,t)}}function ZLD(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}}var $p=class e{breadcrumbs=[];context;static STRING=Us.TypeReference.primitive({v1:"STRING",v2:Us.PrimitiveTypeV2.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=Us.TypeReference.container(Us.ContainerType.optional(e.STRING));constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r}};var zJp=require("fs/promises");var tuc=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}}},IJp=tuc;var tdi;(function(e){e.WARNING="warning",e.ERROR="error"})(tdi||(tdi={}));var gEi=class{errors=[];logger;breadcrumbToLineNumberMapper;relativeFilepathToSpec;constructor({logger:t,relativeFilepathToSpec:r}){this.logger=t,this.relativeFilepathToSpec=r,r&&(this.breadcrumbToLineNumberMapper=new ruc({logger:t,relativePathToFile:Na.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||tdi.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===tdi.ERROR?t++:r++;return{numErrors:t,numWarnings:r}}async logErrors({logWarnings:t}){this.dedupe();for(let r of this.errors)if(!(r.level===tdi.WARNING&&!t))switch(r.level){case tdi.ERROR:if(this.logger.log(Yv.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(Yv.Error,` - at location (${n})`)}break}}},ruc=class{logger;relativePathToFile;map=new IJp;initialized=!1;constructor({relativePathToFile:t,logger:r}){this.relativePathToFile=t,this.logger=r}async initialize(){if(!this.initialized)try{let t=await(0,zJp.readFile)(this.relativePathToFile,"utf-8");md.load(t,{listener:this.map.listen()}),this.initialized=!0}catch(t){this.logger.log(Yv.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 m3=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=RZ({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=p_(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:tdi.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1};n=n[u]}return n==null?(i||this.errorCollector.collect({level:tdi.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=md.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 i=this.resolveReference({reference:r});if(!i.resolved)return;r=i.value}if(!(r.readOnly&&r.writeOnly)){if(r.readOnly)return fkt.ReadOnly;if(r.writeOnly)return fkt.WriteOnly}}getAudiences({operation:t,breadcrumbs:r}){let n=new FW.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 FW.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(n!=null)return{status:n,message:void 0};if(t.deprecated===!0)return{status:j9.Deprecated,message:void 0}}getTypeIdFromSchemaReference(t){let r=t.$ref.match(/\/schemas\/(.+)$/);if(!(!r||!r[1]))return r[1]}createNamedTypeReference(t,r){return Kc.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 Ag=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 FW={};Po(FW,{AudienceExtension:()=>ILo,FernAvailabilityExtension:()=>zLo,FernEnumExtension:()=>xLo,FernIgnoreExtension:()=>YGi,FernOptionalExtension:()=>RLo,FernTypeExtension:()=>LLo,FernTypeNameExtension:()=>ULo,SdkGroupNameExtension:()=>NLo,SdkMethodNameExtension:()=>FLo});var ILo=class extends Ag{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 zLo=class extends Ag{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 j9.InDevelopment;case"PRE_RELEASE":case"BETA":return j9.PreRelease;case"GENERAL_AVAILABILITY":case"GA":return j9.GeneralAvailability;case"DEPRECATED":return j9.Deprecated;default:return}}};var kLD=du.object({snake:du.string().optional(),camel:du.string().optional(),screamingSnake:du.string().optional(),pascal:du.string().optional()}),eUD=du.object({description:du.string().optional(),name:du.string().optional(),casing:kLD.optional()}),xJp=du.record(eUD);var xLo=class extends Ag{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=xJp.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 YGi=class extends Ag{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 RLo=class extends Ag{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 NLo=class extends Ag{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 FLo=class extends Ag{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 LLo=class extends Ag{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 ULo=class extends Ag{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 LWt=class extends $p{ir;audiences;irGraph;constructor({breadcrumbs:t=[],context:r,audiences:i}){super({breadcrumbs:t,context:r}),this.audiences=i,this.irGraph=new KGi(i),this.ir={auth:{docs:void 0,requirement:Us.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:Us.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 YGi({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 YGi({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=Qoc({ir:t,exampleGeneration:r});if(this.context.generateV1Examples){let n=kTa({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=>p_(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=p_(n?.join(".")),u=p_(r),l=this.context.namespace?`${p_(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:ZN(""),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=>p_(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),...this.createPackage({name:a})});let d=this.ir.subpackages[l];i.subpackages.includes(l)||i.subpackages.push(l),i=d}return i}};var SM={};Po(SM,{AbstractConverters:()=>nuc,ExampleConverter:()=>JNe,SchemaConverters:()=>iuc,ServersConverter:()=>uMe});var nuc={};Po(nuc,{AbstractMediaTypeObjectConverter:()=>HLo,AbstractParameterConverter:()=>$Lo});var JNe=class e extends $p{MAX_DEPTH=12;EXAMPLE_STRING=bh.STRING;EXAMPLE_NUMBER=bh.DOUBLE;EXAMPLE_BOOLEAN=bh.BOOLEAN;EXAMPLE_INTEGER=bh.INT;EXAMPLE_DATE=bh.DATE;EXAMPLE_DATE_TIME=bh.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 iuc={};Po(iuc,{ArraySchemaConverter:()=>y4n,EnumSchemaConverter:()=>d4n,ObjectSchemaConverter:()=>p4n,OneOfSchemaConverter:()=>_4n,PrimitiveSchemaConverter:()=>h4n,SchemaConverter:()=>OEi,SchemaOrReferenceConverter:()=>GQ});function RJp(e){return I2({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return Kc.primitive({v1:"BASE_64",v2:Ed.base64({})});case"BOOLEAN":return Kc.primitive({v1:"BOOLEAN",v2:Ed.boolean({default:void 0})});case"DATE":return Kc.primitive({v1:"DATE",v2:Ed.date({})});case"DATE_TIME":return Kc.primitive({v1:"DATE_TIME",v2:Ed.dateTime({})});case"FLOAT":return Kc.primitive({v1:"FLOAT",v2:Ed.float({})});case"DOUBLE":return Kc.primitive({v1:"DOUBLE",v2:Ed.double({default:void 0,validation:void 0})});case"UINT":return Kc.primitive({v1:"UINT",v2:Ed.uint({})});case"UINT_64":return Kc.primitive({v1:"UINT_64",v2:Ed.uint64({})});case"INTEGER":return Kc.primitive({v1:"INTEGER",v2:Ed.integer({default:void 0,validation:void 0})});case"LONG":return Kc.primitive({v1:"LONG",v2:Ed.long({default:void 0})});case"STRING":return Kc.primitive({v1:"STRING",v2:Ed.string({default:void 0,validation:void 0})});case"UUID":return Kc.primitive({v1:"UUID",v2:Ed.uuid({})});case"BIG_INTEGER":return Kc.primitive({v1:"BIG_INTEGER",v2:Ed.bigInteger({default:void 0})});default:return}},unknown:()=>Kc.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return Kc.container(jy.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return Kc.container(jy.list(t))},optional:t=>{if(t!=null)return Kc.container(jy.optional(t))},nullable:t=>{if(t!=null)return Kc.container(jy.nullable(t))},set:t=>{if(t!=null)return Kc.container(jy.set(t))},literal:t=>Kc.container(jy.literal(t._visit({string:r=>E9.string(r),boolean:r=>E9.boolean(r),_other:()=>{throw new Error("Unexpected literal type")}}))),named:()=>{}}})}var d4n=class extends $p{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:Sb.enum({default:i!=null?r.find(n=>n.name.wireValue===i):void 0,values:r})}}};var VLo=class extends $p{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=Kc.container(jy.map({keyType:$p.STRING,valueType:Kc.unknown()}));return{type:Sb.alias({aliasOf:t,resolvedType:t}),referencedTypes:new Set,inlinedTypes:{}}}}tryConvertTypedMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean")return;let r=new GQ({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schemaOrReferenceOrBoolean}).convert();if(r!=null){let i=Kc.container(jy.map({keyType:$p.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:Sb.alias({aliasOf:i,resolvedType:i}),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}};function rCa({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=tUD(r,o,i)??i.convertBreadcrumbsToName(c),g="nullable"in o?o.nullable:!1,m=new GQ({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 tUD(e,t,r){return r.isReferenceObject(t)?void 0:new FW.FernTypeNameExtension({breadcrumbs:e,schema:t,context:r}).convert()}var p4n=class extends $p{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:Sb.object({properties:[],extends:[],extendedProperties:[],extraProperties:t}),propertiesByAudience:{},inlinedTypes:{},referencedTypes:new Set};let{convertedProperties:r,inlinedTypesFromProperties:i,referencedTypes:n,propertiesByAudience:a}=rCa({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 A=this.context.resolveMaybeReference({schemaOrReference:b,breadcrumbs:g});if(A==null)continue;if(O=A,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}=rCa({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(A=>{l.add(A)})}for(let c of Object.keys(s))l.add(c);return{type:Sb.object({properties:r,extends:u.map(c=>this.context.typeReferenceToDeclaredTypeName(c)).filter(yv),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 WLo=class extends Ag{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 _4n=class extends $p{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 WLo({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 GQ({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:D9.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}=rCa({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:Sb.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={};for(let[n,a]of[...(this.schema.oneOf??[]).entries(),...(this.schema.anyOf??[]).entries()]){if(this.context.isReferenceObject(a)){let c;if(this.context.isReferenceObjectWithIdentifier(a))c=this.context.convertReferenceToTypeReference({reference:a,displayNameOverride:a.title??a.name??a.messageId,displayNameOverrideSource:"reference_identifier"});else if(this.getDiscriminatorKeyForRef(a)!=null){let g=this.getDiscriminatorKeyForRef(a);c=this.context.convertReferenceToTypeReference({reference:a,displayNameOverride:g,displayNameOverrideSource:"discriminator_key"})}else c=this.context.convertReferenceToTypeReference({reference:a,displayNameOverrideSource:"schema_identifier"});c.ok&&t.push({type:c.reference,docs:a.description});let b=this.context.getTypeIdFromSchemaReference(a);b!=null&&r.add(b);continue}let u=this.extendSubSchema(a),l=this.context.convertBreadcrumbsToName([`${this.id}_${n}`]),d=a.title,o=new OEi({context:this.context,id:l,nameOverride:d,breadcrumbs:[...this.breadcrumbs,`oneOf[${n}]`],schema:u??a}).convert();if(o!=null){let c=o.convertedSchema.typeDeclaration.shape;c.type==="alias"&&this.typeReferenceIsWrappedPrimitive(c.aliasOf)?t.push({type:c.aliasOf,docs:a.description}):c.type==="object"&&c.properties.length===0?t.push({type:Kc.container(jy.map({keyType:$p.STRING,valueType:Kc.unknown()})),docs:a.description}):(t.push({type:this.context.createNamedTypeReference(l,d),docs:a.description}),i={...i,...o.inlinedTypes,[l]:o.convertedSchema}),o.convertedSchema.typeDeclaration.referencedTypes.forEach(b=>{r.add(b)})}}return{type:Sb.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 GQ({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(i==null)return;let n=this.wrapInNullable(i.type);return{type:Sb.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 Kc.container(jy.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 h4n=class extends $p{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 Kc.container(jy.literal(E9.string(t)));if(this.context.settings.typeDatesAsStrings===!1){if(this.schema.format==="date")return Kc.primitive({v1:Vh.Date,v2:Ed.date({})});if(this.schema.format==="date-time")return Kc.primitive({v1:Vh.DateTime,v2:Ed.dateTime({})})}return Kc.primitive({v1:"STRING",v2:Ed.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":switch(this.schema.format){case"double":return Kc.primitive({v1:"DOUBLE",v2:Ed.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return Kc.primitive({v1:"FLOAT",v2:Ed.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return Kc.primitive({v1:"INTEGER",v2:Ed.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return Kc.primitive({v1:"LONG",v2:Ed.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return Kc.primitive({v1:"UINT",v2:Ed.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return Kc.primitive({v1:"UINT_64",v2:Ed.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return Kc.primitive({v1:"DOUBLE",v2:Ed.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"integer":switch(this.schema.format){case"double":return Kc.primitive({v1:"DOUBLE",v2:Ed.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return Kc.primitive({v1:"FLOAT",v2:Ed.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return Kc.primitive({v1:"INTEGER",v2:Ed.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return Kc.primitive({v1:"LONG",v2:Ed.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return Kc.primitive({v1:"UINT",v2:Ed.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return Kc.primitive({v1:"UINT_64",v2:Ed.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return Kc.primitive({v1:"INTEGER",v2:Ed.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?Kc.container(jy.literal(E9.boolean(t))):Kc.primitive({v1:"BOOLEAN",v2:Ed.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 rUD=["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],OEi=class e extends $p{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 FW.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),n=new d4n({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=RCn(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 h4n({context:this.context,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Sb.alias({aliasOf:r,resolvedType:r}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertArraySchema(){if(this.schema.type==="array"){let r=new y4n({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Sb.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 _4n({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 VLo({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 p4n({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:Sb.alias({aliasOf:Kc.unknown(),resolvedType:Kc.unknown()}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertFernTypeDeclaration(){let r=new FW.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r==null)return;let i=RJp(r);if(i!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Sb.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=[...rUD,...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 JNe({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 GQ=class extends $p{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 OEi({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 Kc.container(jy.optional(t))}wrapInNullable(t){return Kc.container(jy.nullable(t))}};var y4n=class e extends $p{static LIST_UNKNOWN=Kc.container(jy.list(Kc.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 GQ({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:Kc.container(jy.list(r.type)),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var HLo=class extends $p{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 GQ({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 GQ({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=p_(`${[...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 JNe({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 $Lo=class extends $p{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??$p.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??$p.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??$p.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 JNe({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 GLo=class extends Ag{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 NJp="Base",uMe=class e extends $p{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:rx.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(yv);return{value:{defaultEnvironment:t[0]?.id,environments:rx.singleBaseUrl({environments:t})},defaultUrl:t[0]?.id}}static getServerExtensionName({server:t,context:r}){return new GLo({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(yv)}getDefaultBaseUrlName(){return this.servers==null||this.servers.length===0||this.servers[0]==null?NJp:e.getServerExtensionName({server:this.servers[0],context:this.context})??NJp}maybeRemoveTrailingSlashIfNotEmpty(t){return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}};var iCa={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"},iUD=new Set(Object.values(iCa));var v4n=class{enabled=!0;write(t,...r){this.enabled&&process.stderr.write(`[${t}] ${r.join(" ")}
1915
+ `)),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?(Yc(!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,E$p.mkdtemp)(this.getProfilePath())}`),o=d.length-1);let c=d[o].split("=",2)[1];Yc(typeof c=="string","`--user-data-dir` is malformed");let b=l;return b||(Yc(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 P6n(t)}catch(i){throw B0(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=${M$p.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?a9o({browser:$A.CHROME,channel:C2D(t)}):this.resolveExecutablePath()}};function C2D(e){switch(e){case"chrome":return b3.STABLE;case"chrome-dev":return b3.DEV;case"chrome-beta":return b3.BETA;case"chrome-canary":return b3.CANARY}}var Bac=ui(require("fs"),1),FGi=require("fs/promises"),A$p=ui(require("os"),1),iLo=ui(require("path"),1);yC();uA();var nLo=class extends X6n{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&&Yc(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||!Bac.default.existsSync(s))throw new Error(`Firefox profile not found at '${s}'`);o=!1}else s=await(0,FGi.mkdtemp)(this.getProfilePath()),d.push("--profile"),d.push(s);await anc($A.FIREFOX,{path:s,preferences:u});let b;return this.puppeteer._isPuppeteerCore||n?(Yc(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 P6n(t)}catch(i){throw B0(i),i}else try{await(0,FGi.unlink)(iLo.default.join(t,"user.js"));let i=iLo.default.join(t,"prefs.js.puppeteer");if(Bac.default.existsSync(i)){let n=iLo.default.join(t,"prefs.js");await(0,FGi.unlink)(n),await(0,FGi.rename)(i,n)}}catch(i){B0(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(A$p.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 q$p=require("path");var CTa=Object.freeze({chromium:"1108766",firefox:"latest"});var Iac=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},FWt=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)},Z6n,kfi,ITa,BTa,k6n=class extends Tqa{constructor(t){let{configuration:r,...i}=t;switch(super(i),Z6n.add(this),kfi.set(this,void 0),ITa.set(this,void 0),this.configuration={},r&&(this.configuration=r),this.configuration.defaultProduct){case"firefox":this.defaultBrowserRevision=CTa.firefox;break;default:this.configuration.defaultProduct="chrome",this.defaultBrowserRevision=CTa.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 Iac(this,ITa,r,"f"),FWt(this,Z6n,"a",BTa).launch(t)}executablePath(t){return FWt(this,Z6n,"a",BTa).executablePath(t)}get browserRevision(){var t,r,i;return(i=(r=(t=FWt(this,kfi,"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,q$p.join)(this.configuration.cacheDirectory,this.product)}get lastLaunchedProduct(){var t;return(t=FWt(this,ITa,"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 FWt(this,Z6n,"a",BTa).product}defaultArgs(t={}){return FWt(this,Z6n,"a",BTa).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 J5o(t)}};kfi=new WeakMap,ITa=new WeakMap,Z6n=new WeakSet,BTa=function(){if(FWt(this,kfi,"f")&&FWt(this,kfi,"f").product===this.lastLaunchedProduct)return FWt(this,kfi,"f");switch(this.lastLaunchedProduct){case"chrome":this.defaultBrowserRevision=CTa.chromium,Iac(this,kfi,new rLo(this),"f");break;case"firefox":this.defaultBrowserRevision=CTa.firefox,Iac(this,kfi,new nLo(this),"f");break;default:throw new Error(`Unknown product: ${FWt(this,ITa,"f")}`)}return FWt(this,kfi,"f")};Itc();JMa();var B2D=new k6n({isPuppeteerCore:!0}),{connect:Yp8,createBrowserFetcher:Xp8,defaultArgs:Zp8,executablePath:kp8,launch:e_8}=B2D;var aJp=require("os"),oJp=require("path"),uJp=ui(nJp(),1);function aLD(e){switch(e){case"chrome":case"firefox":return!0;default:return!1}}var sJp=()=>{var e,t,r,i,n,a,u,l,d,s,o,c,b,g,O,m,w,E,q,A,D,C,x,$,I,F,V,K,Y,Z,oe,pe,de,Oe,Ue,wt,De;let Te=(0,uJp.cosmiconfigSync)("puppeteer").search(),xt=Te?Te.config:{};if(xt.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:xt.defaultProduct)!==null&&i!==void 0?i:"chrome",xt.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:xt.executablePath,xt.executablePath&&(xt.skipDownload=!0),xt.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:xt.skipDownload),xt.skipDownload||(xt.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:xt.browserRevision,xt.downloadHost=(A=(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&&A!==void 0?A:xt.downloadHost,xt.downloadPath=(x=(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&&x!==void 0?x:xt.downloadPath),xt.cacheDirectory=(V=(F=(I=($=process.env.PUPPETEER_CACHE_DIR)!==null&&$!==void 0?$:process.env.npm_config_puppeteer_cache_dir)!==null&&I!==void 0?I:process.env.npm_package_config_puppeteer_cache_dir)!==null&&F!==void 0?F:xt.cacheDirectory)!==null&&V!==void 0?V:(0,oJp.join)((0,aJp.homedir)(),".cache","puppeteer"),xt.temporaryDirectory=(Z=(Y=(K=process.env.PUPPETEER_TMP_DIR)!==null&&K!==void 0?K:process.env.npm_config_puppeteer_tmp_dir)!==null&&Y!==void 0?Y:process.env.npm_package_config_puppeteer_tmp_dir)!==null&&Z!==void 0?Z:xt.temporaryDirectory,(oe=xt.experiments)!==null&&oe!==void 0||(xt.experiments={}),xt.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:xt.experiments.macArmChromiumEnabled),xt.logLevel=(De=(wt=(Ue=process.env.PUPPETEER_LOGLEVEL)!==null&&Ue!==void 0?Ue:process.env.npm_config_LOGLEVEL)!==null&&wt!==void 0?wt:process.env.npm_package_config_LOGLEVEL)!==null&&De!==void 0?De:xt.logLevel,!aLD(xt.defaultProduct))throw new Error(`Unsupported product ${xt.defaultProduct}`);return xt};var oLD=sJp(),uLD=new k6n({isPuppeteerCore:!1,configuration:oLD}),{connect:ch8,createBrowserFetcher:lh8,defaultArgs:fh8,executablePath:dh8,launch:cJp}=uLD;var sLD="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",cLD={"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 KTa(e,t=3,r=1e3,i=2){try{return await e()}catch(n){if(t>0)return await new Promise(a=>setTimeout(a,r)),KTa(e,t-1,r*i,i);throw n}}async function lJp(){try{return await cJp({headless:"new",ignoreHTTPSErrors:!0})}catch{throw new Error("Could not create a Puppeteer instance")}}async function lLD(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(cLD),await r.setUserAgent(sLD),await r.setJavaScriptEnabled(!0),await KTa(()=>r.goto(t.toString(),{waitUntil:"networkidle2",timeout:3e4}));let i=await KTa(()=>r.content());return await r.close(),i}catch{throw new Error("Failed to download page from Puppeteer")}}async function fLD(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 Uoc({url:e,browser:t}){try{let r;if(t?r=await lLD(t,e):r=await KTa(()=>fLD(e)),r)return r;throw new Error("An unknown error occurred.")}catch{throw new Error(`Error retrieving HTML for ${e.toString()}`)}}async function fJp(e){try{let t=await KTa(()=>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 dLD=["png","jpeg","jpg","webp","avif","svg","ico","jfif","pjpeg","pjp","svgz","bmp"];async function dJp(e){if(!e)return{success:!1,data:void 0};if(e.startsWith("data:image/"))return{success:!0,data:[e,e]};let t=(0,u4n.join)(process.cwd(),"fern");try{let r=await pLD(e,(0,u4n.join)(t,"images"));return r=r.replace(t,""),{success:!0,data:[e,r]}}catch{return{success:!1,data:void 0}}}async function pLD(e,t){let r=hLD(e),i=(0,u4n.join)(t,r);if(!_LD(r))throw new Error(`${r} - file extension not supported`);if((0,ELo.existsSync)(i))return i;try{(0,ELo.mkdirSync)((0,u4n.dirname)(i),{recursive:!0})}catch{throw new Error(`${i} - failed to create directory`)}try{let n=await fJp(e);return h8p(i,n),i}catch{throw new Error(`${i}: failed to download file from source`)}}function _LD(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&&!dLD.includes(i))}function hLD(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 yLD(e){let t=[];return Ff(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 pJp(e,t){let r=A3n(e),i=yLD(r);if(i!=null){let n=await Promise.all(i.map(async a=>{let u=await dJp(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 _Jp=28;async function hJp(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 pJp(a,r)))}let i=[...new Set(r).values()];if(i.length!==0){if(i.length===1&&i[0]!=null){let n=Na.of(YG(i[0]));return{light:n,dark:n,height:_Jp}}if(i[0]!=null&&i[1]!=null){let n=Na.of(YG(i[0])),a=Na.of(YG(i[1]));return{light:n,dark:a,height:_Jp}}}}var MLo=class extends s$i{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:UEa});let i=await this.getHastForUrl(this.url),n=S5p(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=Ru(this.absolutePathToFernDirectory,Na.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 lJp(),u=await hJp(this.url,a);u!=null&&r.setLogo({logo:u});let l=await K3p(i);r.setTitle({title:l});let d=await $3p(i);if(d!=null){let o=await this.getAndCreateAssetsDirectory(),c=await fetch(d);if(c.ok){let b=Buffer.from(await c.arrayBuffer()),g=Ru(o,Na.of("favicon"));await(0,vEi.writeFile)(g,new Uint8Array(b)),r.setFavicon({favicon:Rie(this.absolutePathToFernDirectory,g)})}}let s=await E5p(i);r.setColors({colors:s}),a&&await a.close(),r.build({outputDirectory:this.absolutePathToFernDirectory})}async getAndCreateAssetsDirectory(){let t=Ru(this.absolutePathToFernDirectory,Na.of("assets"));return await(0,vEi.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=P5p(n);if(!a){this.logger.debug(`No sidebar element found for tab: ${t} (${r})`);return}let u=j5p(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 Uoc({url:t});return A3n(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,vEi.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 Uoc({url:u}),d=await m5p({logger:this.logger,html:l,url:u});if(d.success&&d.data){let s=this.getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:n,page:a.slug});await(0,vEi.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=Ru(n,Na.of(c)),m=Cd(O);await(0,vEi.mkdir)(m,{recursive:!0}),await(0,vEi.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:Rie(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 Ru(t,Na.of(`${this.kebabCaseWithoutEmojis(r.split("/").pop()||r)}.mdx`))}getAbsolutePathToOutputDirectoryForSection({absolutePathToOutputDirectory:t,section:r}){return Ru(t,Na.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 yJp=require("fs/promises");async function Voc({readmeUrl:e,outputPath:t,taskContext:r,versionOfCli:i,organization:n}){let a=new c$i;a.setInstance({companyName:n}),await new MLo({url:e,context:r,builder:a,absolutePathToFernDirectory:Ru(ul.of(process.cwd()),Na.of("fern"))}).import({args:{},builder:a}),await a.build({outputDirectory:t}),await(0,yJp.writeFile)(Ru(ul.of(t),Na.of(GV),Na.of(Bie)),JSON.stringify({version:i,organization:n},void 0,4))}var Woc=async({readmeUrl:e,organization:t,taskContext:r,versionOfCli:i})=>{if(!e||!ZUi(e)){r.failAndThrow("Provide a URL to a readme-generated site");return}let n=ul.of(kz());await Voc({readmeUrl:e,outputPath:n,taskContext:r,versionOfCli:i,organization:t})};var vJp="0.0.0";var bJp={[Oy.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,GC(e)])),[Oy.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"]),[Oy.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"]),[Oy.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"]),[Oy.GenerationLanguage.GO]:new Set(["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var","any","bool","byte","complex64","complex128","error","float32","float64","int","int8","int16","int32","int64","make","new","rune","string","uint","uint8","uint16","uint32","uint64","uintptr"]),[Oy.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"]),[Oy.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"]),[Oy.GenerationLanguage.SWIFT]:new Set([])};var bLD=["go","ruby"];function RZ({generationLanguage:e,keywords:t,smartCasing:r}){let i={generateName:(n,a)=>{let u=c=>({unsafeName:c,safeName:gLD({name:c,keywords:OLD({generationLanguage:e,keywords:t})})}),l=p_(n),d=GC(l),s=yUi(n),o=dUi(l);return r&&(!jLD(o)&&(e==null||bLD.includes(e))&&(l=o.map((c,b)=>{if(b>0){let g=ALo(c);if(g!=null)return g;if(qLo(c))return c.toUpperCase()}return c}).join(""),d=GC(o.map((c,b)=>{let g=ALo(c);return g??(qLo(c)?c.toUpperCase():b===0?GC(c):c)}).join(""))),s=n.split(" ").map(c=>c.split(/(\d+)/).map(yUi).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 gLD({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":PLD(e)?"_"+e:e}function OLD({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return bJp[e]}var mLD=/^[0-9]/;function PLD(e){return mLD.test(e)}function jLD(e){return e.some((t,r)=>{if(r===0)return!1;let i=e[r-1];if(i==null)return!1;let n=ALo(i)!=null||qLo(i),a=ALo(t)!=null||qLo(t);return n&&a})}function ALo(e){return SLD.get(e.toUpperCase())}function qLo(e){return wLD.has(e.toUpperCase())}var wLD=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"]),SLD=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]);function ZN(e){let t=ELD(e),{value:r,done:i}=Hoc(t,"{");return i?{head:r,parts:[]}:{head:r,parts:[...DLD(t)]}}function*DLD(e){let t;do{let{value:r}=Hoc(e,"}"),i=Hoc(e,"{");t=i.done,yield{pathParameter:r,tail:i.value}}while(!t)}function*ELD(e){for(let t of e)yield t}function Hoc(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 YTa(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 zrr({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 gJp({fieldName:e,containerType:t,maxDepth:r,currentDepth:i,typeDeclarations:n,skipOptionalProperties:a}){if(i>=r)return xrr({containerType:t});switch(t.type){case"list":{let u=Fq({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?xrr({containerType:t}):{type:"success",example:Pm.list({list:[u.example,u.example],itemType:t.list}),jsonExample:[u.jsonExample,u.jsonExample]}}case"literal":return{type:"success",example:Pm.literal({literal:t.literal._visit({boolean:u=>Fd.boolean(u),string:u=>Fd.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 xrr({containerType:t});let u=Fq({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?xrr({containerType:t}):{type:"success",example:Pm.optional({optional:u.example,valueType:t.optional}),jsonExample:u.jsonExample}}case"nullable":{if(a)return xrr({containerType:t});let u=Fq({fieldName:e,typeReference:t.nullable,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?xrr({containerType:t}):{type:"success",example:Pm.nullable({nullable:u.example,valueType:t.nullable}),jsonExample:u.jsonExample}}case"set":{let u=Fq({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?xrr({containerType:t}):{type:"success",example:Pm.set({set:[u.example],itemType:t.set}),jsonExample:[u.jsonExample]}}case"map":{let u=Fq({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a}),l=Fq({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"||l.type==="failure"?xrr({containerType:t}):{type:"success",example:Pm.map({map:[{key:u.example,value:l.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[u.jsonExample]:l.jsonExample}}}default:wo(t)}}function xrr({containerType:e}){switch(e.type){case"list":return{type:"success",example:Pm.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:Pm.literal({literal:e.literal._visit({boolean:t=>Fd.boolean(t),string:t=>Fd.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:Pm.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"nullable":return{type:"success",example:Pm.nullable({nullable:void 0,valueType:e.nullable}),jsonExample:void 0};case"set":return{type:"success",example:Pm.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:Pm.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:wo(e)}}function mJp({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":return CLD({fieldName:e,default_:MLD(t.v2),validation:ALD(t.v2)});case"BASE_64":return{type:"success",example:Fd.base64(bh.BASE64),jsonExample:bh.BASE64};case"BOOLEAN":return{type:"success",example:Fd.boolean(bh.BOOLEAN),jsonExample:bh.BOOLEAN};case"DATE":return{type:"success",example:Fd.date(bh.DATE),jsonExample:bh.DATE};case"DATE_TIME":return{type:"success",example:Fd.datetime({datetime:new Date(bh.DATE_TIME),raw:bh.DATE_TIME}),jsonExample:bh.DATE_TIME};case"DOUBLE":return BLD({fieldName:e,validation:qLD(t.v2)});case"FLOAT":return{type:"success",example:Fd.float(bh.FLOAT),jsonExample:bh.FLOAT};case"INTEGER":return ILD({fieldName:e,validation:TLD(t.v2)});case"UINT_64":return{type:"success",example:Fd.uint64(bh.INT64),jsonExample:bh.INT64};case"UINT":return{type:"success",example:Fd.uint(bh.UINT),jsonExample:bh.UINT};case"BIG_INTEGER":return{type:"success",example:Fd.bigInteger(bh.INT64.toString()),jsonExample:`${bh.INT64}`};case"LONG":return{type:"success",example:Fd.long(bh.INT64),jsonExample:bh.INT64};case"UUID":return{type:"success",example:Fd.uuid(bh.UUID),jsonExample:bh.UUID};default:wo(t.v1)}}function MLD(e){if(e?.type==="string")return e.default}function ALD(e){if(e?.type==="string")return e.validation}function qLD(e){if(e?.type==="double")return e.validation}function TLD(e){if(e?.type==="integer")return e.validation}function OJp(e){if(e<=bh.SAMPLE_STRINGS.length){let t=bh.SAMPLE_STRINGS[e-1];if(t)return t;throw new Error(`Unexpected undefined value in SAMPLE_STRINGS at index ${e-1}`)}return bh.SAMPLE_STRINGS[bh.SAMPLE_STRINGS.length-1]+".".repeat(e-bh.SAMPLE_STRINGS.length)}function CLD({fieldName:e,default_:t,validation:r}){if(t!=null)return{type:"success",example:Fd.string({original:t}),jsonExample:t};if(r){let n=r.minLength,a=r.maxLength;if(n){let u=OJp(n);return{type:"success",example:Fd.string({original:u}),jsonExample:u}}else if(a!=null&&a<10){let u=OJp(a);return{type:"success",example:Fd.string({original:u}),jsonExample:u}}}let i=e??bh.STRING;return{type:"success",example:Fd.string({original:i}),jsonExample:i}}function BLD({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:Fd.double(r),jsonExample:r};if(i)return{type:"success",example:Fd.double(i),jsonExample:i}}return{type:"success",example:Fd.double(bh.DOUBLE),jsonExample:bh.DOUBLE}}function ILD({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:Fd.integer(r),jsonExample:r};if(i)return{type:"success",example:Fd.integer(i),jsonExample:i}}return{type:"success",example:Fd.integer(bh.INT),jsonExample:bh.INT}}function s4n({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let u=Fq({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:Nw.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:Nw.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=s4n({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=zLD({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:Nw.object({properties:[...l,...s.properties]}),jsonExample:Object.assign({},u,o)}}case"undiscriminatedUnion":{let u=0;for(let l of r.shape.members){let d=Fq({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:Nw.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=Fq({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:Nw.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:n3.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=s4n({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:Nw.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:n3.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=Fq({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:Nw.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:n3.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 zLD({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=Fq({fieldName:s.name.wireValue,typeReference:s.valueType,typeDeclarations:i,currentDepth:a+1,maxDepth:n,skipOptionalProperties:u});if(o.type==="failure"&&!zrr({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:Nw.object({properties:d}),jsonExample:l}}function Fq({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=s4n({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:Wh.named({shape:d,typeName:u.name})},jsonExample:s}}case"container":{let u=gJp({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure"){let{example:s,jsonExample:o}=xrr({containerType:t.container});return{type:"success",example:{jsonExample:o,shape:Wh.container(s)},jsonExample:o}}let{example:l,jsonExample:d}=u;return{type:"success",example:{jsonExample:d,shape:Wh.container(l)},jsonExample:d}}case"primitive":{let{jsonExample:u,example:l}=mJp({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:u,shape:Wh.primitive(l)},jsonExample:u}}case"unknown":{let u={key:"value"};return{type:"success",example:{jsonExample:u,shape:Wh.unknown(u)},jsonExample:u}}}}function GGi(e,t){let r=[];for(let i of e){let n=Fq({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 c4n(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&zrr({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=Fq({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 TLo(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&zrr({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=Fq({fieldName:i.name.name.originalName,currentDepth:0,maxDepth:t.maxDepth??10,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,shape:i.allowMultiple?B2.exploded():B2.single(),value:n.example})}return{type:"success",example:r,jsonExample:void 0}}var $oc=Kc.primitive({v1:Vh.String,v2:Ed.string({default:void 0,validation:void 0})});function XTa({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:RT.ok(kC.body(void 0)),docs:void 0},l=GGi(t.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(l.type==="failure")return l;u.endpointPathParameters=l.example;let d=GGi(r.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(d.type==="failure")return d;u.servicePathParameters=d.example;let s=GGi(e.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(s.type==="failure")return s;u.rootPathParameters=s.example;let o=TLo(t.queryParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:10});if(o.type==="failure")return o;u.queryParameters=o.example;let c=c4n(t.headers,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(c.type==="failure")return c;u.endpointHeaders=c.example;let b=c4n(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=s4n({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=Fq({fieldName:m.name.wireValue,typeReference:m.valueType,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});if(w.type==="failure"&&!zrr({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=OQ.inlinedRequestBody({jsonExample:g,properties:O});break}case"reference":{let g=Fq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:n});if(g.type==="failure")return g;let{example:O}=g;u.request=OQ.reference(O);break}default:wo(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=Fq({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=RT.ok(kC.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=Fq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.nonStreamResponse.value.responseBodyType,skipOptionalProperties:!1});break;case"text":g=Fq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:$oc,skipOptionalProperties:!1});break;default:wo(t.response.body.nonStreamResponse)}if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RT.ok(kC.body({...O,jsonExample:m}));break}case"streaming":{let g;switch(t.response.body.value.type){case"sse":{if(g=Fq({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=RT.ok(kC.sse([{data:{...O,jsonExample:m},event:""}]));break}case"json":{if(g=Fq({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=RT.ok(kC.stream([{...O,jsonExample:m}]));break}case"text":{if(g=Fq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:$oc,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RT.ok(kC.stream([{...O,jsonExample:m}]));break}default:wo(t.response.body.value)}break}case"text":{let g=Fq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:$oc,skipOptionalProperties:!1});if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=RT.ok(kC.body({...O,jsonExample:m}));break}case"bytes":return{type:"failure",message:"Bytes unsupported"};default:wo(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)u.response=RT.error({body:void 0,error:a.declaration.name});else{let g=Fq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:a.declaration.type,skipOptionalProperties:n});if(g.type==="failure")return g;let{example:O}=g;u.response=RT.error({body:O,error:a.declaration.name})}try{return{type:"success",example:{id:YTa(u),url:xLD(t,u),...u},jsonExample:void 0}}catch(g){return{type:"failure",message:`Parse failure with exceptions ${g}`}}}function xLD(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 Goc({ir:e,channel:t,typeDeclarations:r,skipOptionalRequestProperties:i}){let n={name:void 0,pathParameters:[],headers:[],queryParameters:[],messages:[],docs:void 0},a=GGi(t.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(a.type==="failure")return a;n.pathParameters.push(...a.example);let u=GGi(e.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(u.type==="failure")return u;n.pathParameters.push(...u.example);let l=TLo(t.queryParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:10});if(l.type==="failure")return l;n.queryParameters=l.example;let d=c4n(t.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(d.type==="failure")return d;n.headers.push(...d.example);let s=c4n(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=PJp({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=PJp({message:g,typeDeclarations:r,skipOptionalRequestProperties:i});O!=null&&n.messages.push({type:g.type,body:O})}return{type:"success",example:{...n,url:RLD(t,n)},jsonExample:void 0}}function PJp({message:e,typeDeclarations:t,skipOptionalRequestProperties:r}){if(e.body.type==="inlinedBody")return;let i=Fq({currentDepth:0,maxDepth:10,typeDeclarations:t,typeReference:e.body.bodyType,skipOptionalProperties:r});if(i.type==="success")return TEe.reference(i.example)}function RLD(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 l4n(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{},i=Object.values(t)[0],n=Object.values(r)[0];return{userExample:i,autoExample:n}}function bEi(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{};return{userExamples:t,autoExamples:r}}function jJp({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}=l4n(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}=l4n(u.v2Examples);if(l!==void 0)n.queryParameters[u.name.name.originalName]=l;else if(d!==void 0){if(r&&zrr({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}=l4n(u.v2Examples);if(l!==void 0)n.headers[u.name.wireValue]=l;else if(d!==void 0){if(r&&zrr({typeReference:u.valueType,typeDeclarations:i}))continue;n.headers[u.name.wireValue]=d}}return n}function wJp({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let{pathParameters:i,queryParameters:n,headers:a}=jJp({endpoint:e,ir:t,skipOptionalRequestProperties:r}),u={},l={},d={endpoint:{method:e.method,path:NLD(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}=bEi(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}=bEi(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}=bEi(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:wo(e.requestBody)}return{userRequestExamples:u,autoRequestExamples:l,baseExample:d}}function NLD(e){let t={};[...e.pathParameters,...e.allPathParameters].forEach(i=>{let{userExample:n,autoExample:a}=l4n(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 SJp({endpoint:e}){let t={},r={},i={statusCode:e.response?.statusCode,body:void 0,docs:void 0};if(e.response==null)return{userResponseExamples:{},autoResponseExamples:{},baseExample:i};if(e.response.body==null)return e.source?.type==="openrpc"?{userResponseExamples:{},autoResponseExamples:{},baseExample:{...i,body:RN.json(ZTa(null))}}:{userResponseExamples:{},autoResponseExamples:{},baseExample:i};switch(e.response.body.type){case"bytes":break;case"fileDownload":break;case"text":{let n=e.response.body,{userExamples:a,autoExamples:u}=bEi(n.v2Examples);for(let[l,d]of Object.entries(a)){let s=e.source?.type==="openrpc"?ZTa(d):d;t[l]={...i,body:RN.json(s)}}for(let[l,d]of Object.entries(u)){let s=e.source?.type==="openrpc"?ZTa(d):d;r[l]={...i,body:RN.json(s)}}break}case"json":{let n=e.response.body.value;if(n.type==="response"){let{userExamples:a,autoExamples:u}=bEi(n.v2Examples);for(let[l,d]of Object.entries(a)){let s=e.source?.type==="openrpc"?ZTa(d):d;t[l]={...i,body:RN.json(s)}}for(let[l,d]of Object.entries(u)){let s=e.source?.type==="openrpc"?ZTa(d):d;r[l]={...i,body:RN.json(s)}}}break}case"streaming":{let n=e.response.body.value;if(n.type==="json"){let{userExamples:a,autoExamples:u}=bEi(n.v2Examples);for(let[l,d]of Object.entries(a))t[l]={...i,body:RN.stream([d])};for(let[l,d]of Object.entries(u))r[l]={...i,body:RN.stream([d])}}break}case"streamParameter":break;default:wo(e.response.body)}return{userResponseExamples:t,autoResponseExamples:r,baseExample:i}}function ZTa(e,t=1){return{id:t,jsonrpc:"2.0",result:e}}function DJp({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let i={},n={},{userRequestExamples:a,autoRequestExamples:u,baseExample:l}=wJp({endpoint:e,ir:t,skipOptionalRequestProperties:r}),{userResponseExamples:d,autoResponseExamples:s,baseExample:o}=SJp({endpoint:e}),c=Object.keys(u)[0],b=Object.values(u)[0],g=Object.values(s)[0];for(let[O,m]of Object.entries(a))i[O]={request:m,response:d[O]??g??o,codeSamples:void 0};for(let[O,m]of Object.entries(d))i[O]={request:a[O]??b??l,response:m,codeSamples:void 0};return Object.keys(i).length===0&&(n[c??p_(`${e.name.originalName}_example`)]={request:b??l,response:g??o,codeSamples:void 0}),{userFullExamples:i,autoFullExamples:n}}function kTa({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=XTa({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=Goc({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 Qoc({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}=DJp({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=Goc({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 QGi(e,t,r){let{environments:i,changedBaseUrlIds1:n,changedBaseUrlIds2:a}=LLD(e.environments,t.environments,r),{services:u,websocketChannels:l}=ULD(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:FLD(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 FLD(e,t){let r=e;for(let[i,n]of Object.entries(t))r[i]==null?r[i]=n:r[i]={name:n.name,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 LLD(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=EJp(e),n=EJp(t);if(i&&n&&e.environments.type==="singleBaseUrl"&&t.environments.type==="singleBaseUrl")return{environments:{defaultEnvironment:e.defaultEnvironment??t.defaultEnvironment,environments:rx.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}=VLD(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:rx.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}=WLD(d,s,r);return{environments:{defaultEnvironment:a,environments:rx.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}=HLD(u,l,r);return{environments:{defaultEnvironment:a,environments:rx.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 ULD(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 VLD(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=Joc(s.id,n);return i[s.id]=o,{...s,id:o,name:r.generateName(o)}}return s});return{deconflictedEnvironments2:rx.singleBaseUrl({environments:l}),changedBaseUrlIds2:i}}function WLD(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=Joc(d.id,n);return i[d.id]=s,{...d,id:s,name:r.generateName(s)}}return d});return{deconflictedEnvironments1:rx.singleBaseUrl({environments:u}),changedBaseUrlIds1:i}}function HLD(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=Joc(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:rx.multipleBaseUrls({baseUrls:u,environments:l}),changedBaseUrlIds:i}}function EJp(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 Joc(e,t){let r=e,i=1;for(;t.has(r);)r=`${e}-${i}`,i++;return r}function Yoc({rawApiFileSchema:e,casingsGenerator:t}){if(e.auth==null)return{docs:void 0,requirement:jne.All,schemes:[]};let r=typeof e.auth!="string"?e.auth.docs:void 0;return OWi(e.auth,{single:i=>{let n=MJp({reference:i,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t});return{docs:r,requirement:jne.All,schemes:[n]}},any:({any:i})=>({docs:r,requirement:jne.Any,schemes:i.map(n=>MJp({reference:n,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t}))})})}function MJp({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 A1a(l,{header:d=>xT.header({docs:u,name:r.generateNameAndWireValue({name:d.name??a,wireValue:d.header}),valueType:Kc.primitive({v1:Vh.String,v2:Ed.string({default:void 0,validation:void 0})}),prefix:d.prefix,headerEnvVar:d.env}),basic:d=>AJp({casingsGenerator:r,docs:u,rawScheme:d}),bearer:d=>Koc({casingsGenerator:r,docs:u,rawScheme:d}),oauth:d=>Koc({casingsGenerator:r,docs:u,rawScheme:void 0})})},n=typeof e=="string"?e:e.scheme;switch(n){case"bearer":case"oauth":return Koc({casingsGenerator:r,docs:void 0,rawScheme:void 0});case"basic":return AJp({casingsGenerator:r,docs:void 0,rawScheme:void 0});default:return i(n,typeof e!="string"?e.docs:void 0)}}function Koc({casingsGenerator:e,docs:t,rawScheme:r}){return xT.bearer({docs:t,token:e.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function AJp({casingsGenerator:e,docs:t,rawScheme:r}){return xT.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 eCa({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:gkt(i,{singleBaseUrl:()=>rx.singleBaseUrl($LD({environments:t,casingsGenerator:r})),multipleBaseUrls:n=>rx.multipleBaseUrls(GLD({baseUrls:Object.keys(n.urls),environments:t,casingsGenerator:r}))})},audiences:{...Object.fromEntries(Object.entries(t).map(([n,a])=>[n,gkt(a,{singleBaseUrl:u=>[...typeof u=="string"?[]:u.audiences??[]],multipleBaseUrls:u=>[...u.audiences??[]]})]))}}}function $LD({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,i])=>gkt(i,{singleBaseUrl:n=>({docs:typeof n=="string"?void 0:n.docs,id:r,name:t.generateName(r),url:qJp(typeof n=="string"?n:n.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function GLD({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(i=>({id:i,name:r.generateName(i)})),environments:Object.entries(t).map(([i,n])=>gkt(n,{multipleBaseUrls:a=>({docs:a.docs,id:i,name:r.generateName(i),urls:fd(a.urls,u=>qJp(u))}),singleBaseUrl:()=>{throw new Error(`Environment ${i} does not have multiple base URLs`)}}))}}function qJp(e){return e.endsWith("/")?e.slice(0,-1):e}function oMe(e){return e.allParts.map(t=>t.originalName).join("/")}var wm={generateTypeId:e=>`type_${oMe(e.fernFilepath)}:${e.name.originalName}`,generateErrorId:e=>`error_${oMe(e.fernFilepath)}:${e.name.originalName}`,generateServiceId:e=>`service_${oMe(e.fernFilepath)}`,generateServiceIdFromFernFilepath:e=>`service_${oMe(e)}`,generateSubpackageId:e=>`subpackage_${oMe(e)}`,generateEndpointId:(e,t)=>{let r=oMe(e.fernFilepath),i=t.name.originalName;return`endpoint_${r}.${i}`},generateWebhookGroupId:e=>`webhooks_${oMe(e)}`,generateWebhookId:(e,t)=>`webhooks_${oMe(e)}.${t}`,generateWebSocketChannelId:e=>`channel_${oMe(e)}`};function f4n(e){return e.type!=null}var CLo=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=wm.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=wm.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=wm.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)}};function JGi(e){let t={};for(let[r,i]of Object.entries(e))if(typeof i!="string")for(let n of i.audiences??[])t[n]==null&&(t[n]=new Set),t[n]?.add(r);return t}var KGi=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=QLD(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:i,descendantTypeIdsByAudience:n,propertiesByAudience:a}){let u=wm.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=wm.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=wm.generateErrorId(t.name),i=new Set,n=new Set;t.type!=null&&fx(t.type,i,n);let a={errorId:r,referencedTypes:i,referencedSubpackages:n};this.errors[r]=a}addEndpoint(t,r,i){let n=wm.generateServiceId(t.name),a=r.id,u=new Set,l=new Set,d=new Set;for(let s of[...t.headers,...r.headers])fx(s.valueType,u,d);for(let s of[...t.pathParameters,...r.pathParameters])fx(s.valueType,u,d);for(let s of r.queryParameters)fx(s.valueType,u,d);if(i!=null&&i.request!=null&&typeof i.request!="string"){let s=JGi(i.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:s}}r.requestBody!=null&&rA._visit(r.requestBody,{inlinedRequestBody:s=>{for(let o of s.extends)BLo(o,u,d);for(let o of s.properties)fx(o.valueType,u,d);if(i!=null&&typeof i.request=="object"&&typeof i.request.body=="object"&&XC(i.request.body)){let o=JGi(i.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:o}}},reference:({requestBodyType:s})=>{fx(s,u,d)},fileUpload:({properties:s})=>{for(let o of s)E6._visit(o,{file:Go,bodyProperty:({valueType:c})=>{fx(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&&Rw._visit(r.response.body,{fileDownload:Go,json:s=>{fx(s.responseBodyType,u,d)},streaming:s=>{s._visit({sse:o=>fx(o.payload,u,d),json:o=>fx(o.payload,u,d),text:Go,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.type)}})},streamParameter:s=>{s.streamResponse._visit({sse:o=>fx(o.payload,u,d),json:o=>fx(o.payload,u,d),text:Go,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.streamResponse.type)}}),s.nonStreamResponse.type==="json"&&fx(s.nonStreamResponse.value.responseBodyType,u,d)},text:Go,bytes:Go,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(s=>{l.add(wm.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=wm.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&&pW._visit(r.payload,{inlinedPayload:l=>{for(let d of l.extends)BLo(d,a,u);for(let d of l.properties)fx(d.valueType,a,u);if(i?.payload!=null&&typeof i.payload=="object"&&!f4n(i.payload)){let d=JGi(i.payload.properties??{});this.webhookProperties[n]={webhookId:n,propertiesByAudience:d}}},reference:({payloadType:l})=>{fx(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)M9._visit(l.body,{reference:({bodyType:d})=>{fx(d,a,u)},inlinedBody:d=>{for(let s of d.extends)BLo(s,a,u);for(let s of d.properties)fx(s.valueType,a,u)},_other:()=>{}});for(let l of i.queryParameters)fx(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 CLo({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:wo(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let i={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(wm.generateSubpackageId(i))}}};function QLD(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:wo(e)}}function fx(e,t,r){Kc._visit(e,{container:i=>{JLD(i,t,r)},named:i=>{BLo(i,t,r)},primitive:Go,unknown:Go,_other:Go})}function BLo(e,t,r){t.add(wm.generateTypeId(e)),r.add(e.fernFilepath)}function JLD(e,t,r){jy._visit(e,{list:i=>{fx(i,t,r)},map:i=>{fx(i.keyType,t,r),fx(i.valueType,t,r)},optional:i=>{fx(i,t,r)},nullable:i=>{fx(i,t,r)},set:i=>{fx(i,t,r)},literal:Go,_other:Go})}var Xoc=class{errors;constructor(){this.errors=[]}add(t){this.errors.push({message:t})}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}},tCa=class{errors;constructor(){this.errors=new Xoc}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:wo(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:wo(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:wo(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:wo(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:wo(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:wo(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:wo(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:wo(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:wo(i)}return r}getKeyForDeclaration({name:t,fernFilepath:r}){return`${r.allParts.map(n=>n.camelCase.unsafeName).join(".")}.${t.pascalCase.unsafeName}`}};function CJp({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:fR({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)}}:void 0;return i!==void 0?n3.samePropertiesAsObject(i):void 0},singleProperty:r=>{let i=fR({filteredIr:e,exampleTypeReference:r});return i!==void 0?n3.singleProperty(i):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function fR({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:i=>({...t,shape:Wh.container(Pm.list({...i,list:i.list.map(n=>fR({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),set:i=>({...t,shape:Wh.container(Pm.set({...i,set:i.set.map(n=>fR({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),optional:i=>{let n=i.optional!=null?fR({filteredIr:e,exampleTypeReference:i.optional}):void 0;return n!=null?{...t,shape:Wh.container(Pm.optional({optional:n,valueType:i.valueType}))}:void 0},nullable:i=>{let n=i.nullable!=null?fR({filteredIr:e,exampleTypeReference:i.nullable}):void 0;return n!=null?{...t,shape:Wh.container(Pm.nullable({nullable:n,valueType:i.valueType}))}:void 0},map:i=>({...t,shape:Wh.container(Pm.map({...i,map:i.map.map(n=>{let a=fR({filteredIr:e,exampleTypeReference:n.key}),u=fR({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=fR({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...t,shape:Wh.named({...r,shape:Nw.alias({...i,value:n})})}:void 0},enum:i=>({...t,shape:Wh.named({...r,shape:Nw.enum(i)})}),object:i=>({...t,shape:Wh.named({...r,shape:Nw.object({...i,properties:i.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:fR({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})})}),union:i=>{let n=CJp({filteredIr:e,singleUnionTypeProperties:i.singleUnionType.shape});return n!==void 0?{...t,shape:Wh.named({...r,shape:Nw.union({...i,singleUnionType:{...i.singleUnionType,shape:n}})})}:void 0},undiscriminatedUnion:i=>{let n=fR({filteredIr:e,exampleTypeReference:i.singleUnionType});return n!==void 0?{...t,shape:Wh.named({...r,shape:Nw.undiscriminatedUnion({...i,singleUnionType:n})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function Zoc({filteredIr:e,pathParameters:t}){return t.map(r=>{let i=fR({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function KLD({filteredIr:e,queryParameters:t}){return t.map(r=>{let i=fR({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function TJp({filteredIr:e,headers:t}){return t.map(r=>{let i=fR({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function YLD({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=fR({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...i,value:n}:void 0}).filter(i=>i!==void 0)}),reference:r=>{let i=fR({filteredIr:e,exampleTypeReference:r});return i!==void 0?OQ.reference(i):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function XLD({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:i=>RT.ok(kC.body(i!=null?fR({filteredIr:e,exampleTypeReference:i}):void 0)),stream:i=>RT.ok(kC.stream(i.map(n=>fR({filteredIr:e,exampleTypeReference:n})).filter(yv))),sse:i=>RT.ok(kC.sse(i.map(({event:n,data:a})=>{let u=fR({filteredIr:e,exampleTypeReference:a});return u!==void 0?{event:n,data:u}:void 0}).filter(yv))),_other:({type:i})=>{throw new Error(`Received unknown type for OK example: ${i}`)}}),error:({error:r,body:i})=>RT.error({error:r,body:i!=null?fR({filteredIr:e,exampleTypeReference:i}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function koc({filteredIr:e,example:t}){return{...t,rootPathParameters:Zoc({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:Zoc({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:Zoc({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:TJp({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:TJp({filteredIr:e,headers:t.endpointHeaders}),queryParameters:KLD({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?YLD({filteredIr:e,requestBody:t.request}):void 0,response:XLD({filteredIr:e,response:t.response})}}function BJp({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let i=fR({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...t,shape:Nw.alias({...r,value:i})}:void 0},enum:()=>t,object:r=>({...t,shape:Nw.object({...r,properties:r.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:fR({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})}),union:r=>{let i=CJp({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return i!==void 0?{...t,shape:Nw.union({...r,singleUnionType:{...r.singleUnionType,shape:i}})}:void 0},undiscriminatedUnion:r=>{let i=fR({filteredIr:e,exampleTypeReference:r.singleUnionType});return i!==void 0?{...t,shape:Nw.undiscriminatedUnion({...r,singleUnionType:i})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function euc(e,t){if(t==null)return e;let r=hUi(e.types,l=>t.hasType(l)),i=Object.fromEntries(Object.entries(r).map(([l,d])=>{let s=[];if(d.userProvidedExamples=d.userProvidedExamples.map(o=>BJp({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:Sb.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:hUi(e.errors,l=>t.hasError(l)),services:fd(hUi(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:koc({filteredIr:t,example:s.example})})),d.userSpecifiedExamples=d.userSpecifiedExamples.map(s=>({...s,example:s.example!=null?koc({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:ZLD(e.serviceTypeReferenceInfo,t)}}function ZLD(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}}var $p=class e{breadcrumbs=[];context;static STRING=Us.TypeReference.primitive({v1:"STRING",v2:Us.PrimitiveTypeV2.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=Us.TypeReference.container(Us.ContainerType.optional(e.STRING));constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r}};var zJp=require("fs/promises");var tuc=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}}},IJp=tuc;var tdi;(function(e){e.WARNING="warning",e.ERROR="error"})(tdi||(tdi={}));var gEi=class{errors=[];logger;breadcrumbToLineNumberMapper;relativeFilepathToSpec;constructor({logger:t,relativeFilepathToSpec:r}){this.logger=t,this.relativeFilepathToSpec=r,r&&(this.breadcrumbToLineNumberMapper=new ruc({logger:t,relativePathToFile:Na.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||tdi.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===tdi.ERROR?t++:r++;return{numErrors:t,numWarnings:r}}async logErrors({logWarnings:t}){this.dedupe();for(let r of this.errors)if(!(r.level===tdi.WARNING&&!t))switch(r.level){case tdi.ERROR:if(this.logger.log(Yv.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(Yv.Error,` - at location (${n})`)}break}}},ruc=class{logger;relativePathToFile;map=new IJp;initialized=!1;constructor({relativePathToFile:t,logger:r}){this.relativePathToFile=t,this.logger=r}async initialize(){if(!this.initialized)try{let t=await(0,zJp.readFile)(this.relativePathToFile,"utf-8");md.load(t,{listener:this.map.listen()}),this.initialized=!0}catch(t){this.logger.log(Yv.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 m3=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=RZ({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=p_(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:tdi.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1};n=n[u]}return n==null?(i||this.errorCollector.collect({level:tdi.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=md.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 i=this.resolveReference({reference:r});if(!i.resolved)return;r=i.value}if(!(r.readOnly&&r.writeOnly)){if(r.readOnly)return fkt.ReadOnly;if(r.writeOnly)return fkt.WriteOnly}}getAudiences({operation:t,breadcrumbs:r}){let n=new FW.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 FW.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(n!=null)return{status:n,message:void 0};if(t.deprecated===!0)return{status:j9.Deprecated,message:void 0}}getTypeIdFromSchemaReference(t){let r=t.$ref.match(/\/schemas\/(.+)$/);if(!(!r||!r[1]))return r[1]}createNamedTypeReference(t,r){return Kc.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 Ag=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 FW={};Po(FW,{AudienceExtension:()=>ILo,FernAvailabilityExtension:()=>zLo,FernEnumExtension:()=>xLo,FernIgnoreExtension:()=>YGi,FernOptionalExtension:()=>RLo,FernTypeExtension:()=>LLo,FernTypeNameExtension:()=>ULo,SdkGroupNameExtension:()=>NLo,SdkMethodNameExtension:()=>FLo});var ILo=class extends Ag{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 zLo=class extends Ag{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 j9.InDevelopment;case"PRE_RELEASE":case"BETA":return j9.PreRelease;case"GENERAL_AVAILABILITY":case"GA":return j9.GeneralAvailability;case"DEPRECATED":return j9.Deprecated;default:return}}};var kLD=du.object({snake:du.string().optional(),camel:du.string().optional(),screamingSnake:du.string().optional(),pascal:du.string().optional()}),eUD=du.object({description:du.string().optional(),name:du.string().optional(),casing:kLD.optional()}),xJp=du.record(eUD);var xLo=class extends Ag{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=xJp.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 YGi=class extends Ag{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 RLo=class extends Ag{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 NLo=class extends Ag{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 FLo=class extends Ag{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 LLo=class extends Ag{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 ULo=class extends Ag{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 LWt=class extends $p{ir;audiences;irGraph;constructor({breadcrumbs:t=[],context:r,audiences:i}){super({breadcrumbs:t,context:r}),this.audiences=i,this.irGraph=new KGi(i),this.ir={auth:{docs:void 0,requirement:Us.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:Us.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 YGi({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 YGi({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=Qoc({ir:t,exampleGeneration:r});if(this.context.generateV1Examples){let n=kTa({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=>p_(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=p_(n?.join(".")),u=p_(r),l=this.context.namespace?`${p_(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:ZN(""),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=>p_(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),...this.createPackage({name:a})});let d=this.ir.subpackages[l];i.subpackages.includes(l)||i.subpackages.push(l),i=d}return i}};var SM={};Po(SM,{AbstractConverters:()=>nuc,ExampleConverter:()=>JNe,SchemaConverters:()=>iuc,ServersConverter:()=>uMe});var nuc={};Po(nuc,{AbstractMediaTypeObjectConverter:()=>HLo,AbstractParameterConverter:()=>$Lo});var JNe=class e extends $p{MAX_DEPTH=12;EXAMPLE_STRING=bh.STRING;EXAMPLE_NUMBER=bh.DOUBLE;EXAMPLE_BOOLEAN=bh.BOOLEAN;EXAMPLE_INTEGER=bh.INT;EXAMPLE_DATE=bh.DATE;EXAMPLE_DATE_TIME=bh.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 iuc={};Po(iuc,{ArraySchemaConverter:()=>y4n,EnumSchemaConverter:()=>d4n,ObjectSchemaConverter:()=>p4n,OneOfSchemaConverter:()=>_4n,PrimitiveSchemaConverter:()=>h4n,SchemaConverter:()=>OEi,SchemaOrReferenceConverter:()=>GQ});function RJp(e){return I2({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return Kc.primitive({v1:"BASE_64",v2:Ed.base64({})});case"BOOLEAN":return Kc.primitive({v1:"BOOLEAN",v2:Ed.boolean({default:void 0})});case"DATE":return Kc.primitive({v1:"DATE",v2:Ed.date({})});case"DATE_TIME":return Kc.primitive({v1:"DATE_TIME",v2:Ed.dateTime({})});case"FLOAT":return Kc.primitive({v1:"FLOAT",v2:Ed.float({})});case"DOUBLE":return Kc.primitive({v1:"DOUBLE",v2:Ed.double({default:void 0,validation:void 0})});case"UINT":return Kc.primitive({v1:"UINT",v2:Ed.uint({})});case"UINT_64":return Kc.primitive({v1:"UINT_64",v2:Ed.uint64({})});case"INTEGER":return Kc.primitive({v1:"INTEGER",v2:Ed.integer({default:void 0,validation:void 0})});case"LONG":return Kc.primitive({v1:"LONG",v2:Ed.long({default:void 0})});case"STRING":return Kc.primitive({v1:"STRING",v2:Ed.string({default:void 0,validation:void 0})});case"UUID":return Kc.primitive({v1:"UUID",v2:Ed.uuid({})});case"BIG_INTEGER":return Kc.primitive({v1:"BIG_INTEGER",v2:Ed.bigInteger({default:void 0})});default:return}},unknown:()=>Kc.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return Kc.container(jy.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return Kc.container(jy.list(t))},optional:t=>{if(t!=null)return Kc.container(jy.optional(t))},nullable:t=>{if(t!=null)return Kc.container(jy.nullable(t))},set:t=>{if(t!=null)return Kc.container(jy.set(t))},literal:t=>Kc.container(jy.literal(t._visit({string:r=>E9.string(r),boolean:r=>E9.boolean(r),_other:()=>{throw new Error("Unexpected literal type")}}))),named:()=>{}}})}var d4n=class extends $p{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:Sb.enum({default:i!=null?r.find(n=>n.name.wireValue===i):void 0,values:r})}}};var VLo=class extends $p{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=Kc.container(jy.map({keyType:$p.STRING,valueType:Kc.unknown()}));return{type:Sb.alias({aliasOf:t,resolvedType:t}),referencedTypes:new Set,inlinedTypes:{}}}}tryConvertTypedMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean")return;let r=new GQ({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schemaOrReferenceOrBoolean}).convert();if(r!=null){let i=Kc.container(jy.map({keyType:$p.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:Sb.alias({aliasOf:i,resolvedType:i}),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}};function rCa({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=tUD(r,o,i)??i.convertBreadcrumbsToName(c),g="nullable"in o?o.nullable:!1,m=new GQ({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 tUD(e,t,r){return r.isReferenceObject(t)?void 0:new FW.FernTypeNameExtension({breadcrumbs:e,schema:t,context:r}).convert()}var p4n=class extends $p{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:Sb.object({properties:[],extends:[],extendedProperties:[],extraProperties:t}),propertiesByAudience:{},inlinedTypes:{},referencedTypes:new Set};let{convertedProperties:r,inlinedTypesFromProperties:i,referencedTypes:n,propertiesByAudience:a}=rCa({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 A=this.context.resolveMaybeReference({schemaOrReference:b,breadcrumbs:g});if(A==null)continue;if(O=A,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}=rCa({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(A=>{l.add(A)})}for(let c of Object.keys(s))l.add(c);return{type:Sb.object({properties:r,extends:u.map(c=>this.context.typeReferenceToDeclaredTypeName(c)).filter(yv),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 WLo=class extends Ag{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 _4n=class extends $p{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 WLo({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 GQ({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:D9.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}=rCa({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:Sb.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={};for(let[n,a]of[...(this.schema.oneOf??[]).entries(),...(this.schema.anyOf??[]).entries()]){if(this.context.isReferenceObject(a)){let c;if(this.context.isReferenceObjectWithIdentifier(a))c=this.context.convertReferenceToTypeReference({reference:a,displayNameOverride:a.title??a.name??a.messageId,displayNameOverrideSource:"reference_identifier"});else if(this.getDiscriminatorKeyForRef(a)!=null){let g=this.getDiscriminatorKeyForRef(a);c=this.context.convertReferenceToTypeReference({reference:a,displayNameOverride:g,displayNameOverrideSource:"discriminator_key"})}else c=this.context.convertReferenceToTypeReference({reference:a,displayNameOverrideSource:"schema_identifier"});c.ok&&t.push({type:c.reference,docs:a.description});let b=this.context.getTypeIdFromSchemaReference(a);b!=null&&r.add(b);continue}let u=this.extendSubSchema(a),l=this.context.convertBreadcrumbsToName([`${this.id}_${n}`]),d=a.title,o=new OEi({context:this.context,id:l,nameOverride:d,breadcrumbs:[...this.breadcrumbs,`oneOf[${n}]`],schema:u??a}).convert();if(o!=null){let c=o.convertedSchema.typeDeclaration.shape;c.type==="alias"&&this.typeReferenceIsWrappedPrimitive(c.aliasOf)?t.push({type:c.aliasOf,docs:a.description}):c.type==="object"&&c.properties.length===0?t.push({type:Kc.container(jy.map({keyType:$p.STRING,valueType:Kc.unknown()})),docs:a.description}):(t.push({type:this.context.createNamedTypeReference(l,d),docs:a.description}),i={...i,...o.inlinedTypes,[l]:o.convertedSchema}),o.convertedSchema.typeDeclaration.referencedTypes.forEach(b=>{r.add(b)})}}return{type:Sb.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 GQ({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(i==null)return;let n=this.wrapInNullable(i.type);return{type:Sb.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 Kc.container(jy.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 h4n=class extends $p{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 Kc.container(jy.literal(E9.string(t)));if(this.context.settings.typeDatesAsStrings===!1){if(this.schema.format==="date")return Kc.primitive({v1:Vh.Date,v2:Ed.date({})});if(this.schema.format==="date-time")return Kc.primitive({v1:Vh.DateTime,v2:Ed.dateTime({})})}return Kc.primitive({v1:"STRING",v2:Ed.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":switch(this.schema.format){case"double":return Kc.primitive({v1:"DOUBLE",v2:Ed.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return Kc.primitive({v1:"FLOAT",v2:Ed.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return Kc.primitive({v1:"INTEGER",v2:Ed.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return Kc.primitive({v1:"LONG",v2:Ed.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return Kc.primitive({v1:"UINT",v2:Ed.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return Kc.primitive({v1:"UINT_64",v2:Ed.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return Kc.primitive({v1:"DOUBLE",v2:Ed.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"integer":switch(this.schema.format){case"double":return Kc.primitive({v1:"DOUBLE",v2:Ed.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return Kc.primitive({v1:"FLOAT",v2:Ed.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return Kc.primitive({v1:"INTEGER",v2:Ed.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return Kc.primitive({v1:"LONG",v2:Ed.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return Kc.primitive({v1:"UINT",v2:Ed.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return Kc.primitive({v1:"UINT_64",v2:Ed.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return Kc.primitive({v1:"INTEGER",v2:Ed.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?Kc.container(jy.literal(E9.boolean(t))):Kc.primitive({v1:"BOOLEAN",v2:Ed.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 rUD=["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],OEi=class e extends $p{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 FW.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),n=new d4n({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=RCn(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 h4n({context:this.context,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Sb.alias({aliasOf:r,resolvedType:r}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertArraySchema(){if(this.schema.type==="array"){let r=new y4n({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Sb.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 _4n({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 VLo({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 p4n({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:Sb.alias({aliasOf:Kc.unknown(),resolvedType:Kc.unknown()}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertFernTypeDeclaration(){let r=new FW.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r==null)return;let i=RJp(r);if(i!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Sb.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=[...rUD,...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 JNe({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 GQ=class extends $p{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 OEi({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 Kc.container(jy.optional(t))}wrapInNullable(t){return Kc.container(jy.nullable(t))}};var y4n=class e extends $p{static LIST_UNKNOWN=Kc.container(jy.list(Kc.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 GQ({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:Kc.container(jy.list(r.type)),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var HLo=class extends $p{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 GQ({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 GQ({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=p_(`${[...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 JNe({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 $Lo=class extends $p{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??$p.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??$p.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??$p.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 JNe({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 GLo=class extends Ag{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 NJp="Base",uMe=class e extends $p{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:rx.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(yv);return{value:{defaultEnvironment:t[0]?.id,environments:rx.singleBaseUrl({environments:t})},defaultUrl:t[0]?.id}}static getServerExtensionName({server:t,context:r}){return new GLo({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(yv)}getDefaultBaseUrlName(){return this.servers==null||this.servers.length===0||this.servers[0]==null?NJp:e.getServerExtensionName({server:this.servers[0],context:this.context})??NJp}maybeRemoveTrailingSlashIfNotEmpty(t){return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}};var iCa={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"},iUD=new Set(Object.values(iCa));var v4n=class{enabled=!0;write(t,...r){this.enabled&&process.stderr.write(`[${t}] ${r.join(" ")}
1916
1916
  `)}disable(){this.enabled=!1}enable(){this.enabled=!0}trace(...t){this.write(Yv.Trace,...t)}debug(...t){this.write(Yv.Debug,...t)}info(...t){this.write(Yv.Info,...t)}warn(...t){this.write(Yv.Warn,...t)}error(...t){this.write(Yv.Error,...t)}log(t,...r){this.write(t,...r)}};var UWt={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}},QLo={MESSAGE:4,ENUM:5,SERVICE:6};var JLo=class extends $p{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,UWt.ENUM.VALUE,i]),availability:void 0}});return{type:Sb.enum({default:void 0,values:t})}}};function FJp(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1)}var LJp=new Set([_g.DOUBLE,_g.FLOAT,_g.INT64,_g.UINT64,_g.INT32,_g.FIXED64,_g.FIXED32,_g.BOOL,_g.STRING,_g.BYTES,_g.UINT32,_g.SFIXED32,_g.SFIXED64,_g.SINT32,_g.SINT64]);var KLo=class e extends $p{static LIST_UNKNOWN=Kc.container(jy.list(Kc.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 mEi({context:this.context,breadcrumbs:this.breadcrumbs,field:{...this.field,label:kTn.OPTIONAL},sourceCodeInfoPath:this.sourceCodeInfoPath}).convert();if(r!=null){let i=new Set;return{typeReference:Kc.container(jy.list(r.type)),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var YLo=class extends $p{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 _g.STRING:return Kc.primitive({v1:Vh.String,v2:Ed.string({default:void 0,validation:void 0})});case _g.DOUBLE:return Kc.primitive({v1:Vh.Double,v2:Ed.double({default:void 0,validation:void 0})});case _g.FLOAT:return Kc.primitive({v1:Vh.Float,v2:Ed.float({})});case _g.INT32:return Kc.primitive({v1:Vh.Integer,v2:Ed.integer({default:void 0,validation:void 0})});case _g.INT64:return Kc.primitive({v1:Vh.Long,v2:Ed.long({default:void 0})});case _g.UINT32:return Kc.primitive({v1:Vh.Uint,v2:Ed.uint({default:void 0})});case _g.UINT64:return Kc.primitive({v1:Vh.Uint64,v2:Ed.uint64({default:void 0})});case _g.BOOL:return Kc.primitive({v1:Vh.Boolean,v2:Ed.boolean({default:void 0})});default:return Kc.unknown()}}};var mEi=class extends $p{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 KLo({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(LJp.has(this.field.type)){let i=new YLo({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===_g.MESSAGE||this.field.type===_g.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 Kc.container(jy.optional(t))}};function UJp({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 mEi({context:r,breadcrumbs:[...t,"fields",s.name],field:s,sourceCodeInfoPath:[...i,UWt.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,UWt.MESSAGE.FIELD,d]),availability:void 0,propertyAccess:void 0,v2Examples:void 0};if(Object.prototype.hasOwnProperty.call(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 XLo=class extends $p{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 mEi({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:Sb.undiscriminatedUnion({members:t}),referencedTypes:new Set,inlinedTypes:{}}}};var ZLo=class extends $p{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}=UJp({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 PEi({context:this.context,breadcrumbs:this.breadcrumbs,schema:d,sourceCodeInfoPath:[...this.sourceCodeInfoPath,UWt.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 PEi({context:this.context,breadcrumbs:this.breadcrumbs,schema:d,sourceCodeInfoPath:[...this.sourceCodeInfoPath,UWt.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 XLo({context:this.context,breadcrumbs:this.breadcrumbs,oneOfFields:u[l]??[],sourceCodeInfoPath:[...this.sourceCodeInfoPath,UWt.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(FJp(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:Sb.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 PEi=class extends $p{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 JLo({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 ZLo({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 b4n=class extends m3{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:Kc.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 auc(){return{4:{},5:{},6:{}}}function VJp(e){let t=auc();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 nCa=class e extends $p{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.prototype.hasOwnProperty.call(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.prototype.hasOwnProperty.call(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.prototype.hasOwnProperty.call(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===kTn.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 _g.DOUBLE:case _g.FLOAT:case _g.INT64:case _g.UINT64:case _g.INT32:case _g.FIXED64:case _g.FIXED32:case _g.UINT32:case _g.SFIXED32:case _g.SFIXED64:case _g.SINT32:case _g.SINT64:return this.convertNumber();case _g.BOOL:return this.convertBoolean();case _g.STRING:return this.convertString(this.EXAMPLE_STRING);case _g.BYTES:return this.convertBytes();case _g.ENUM:return this.convertEnum(t);case _g.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 b4n({...this.context,comments:auc(),codeGeneratorRequest:this.context.getCodeGeneratorRequest(),spec:s,logger:new v4n}):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 kLo=class extends $p{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,response:i?.responseBody,displayName:this.context.maybeRemoveGrpcPackagePrefix(this.operation.name),method:ZC.Post,baseUrl:void 0,v2BaseUrls:void 0,v2Examples:{autogeneratedExamples:{HELLO:{request:{endpoint:{method:"POST",path:"/users"},baseUrl:"",environment:void 0,auth:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:{},docs:void 0},response:{statusCode:200,body:RN.json({value:{id:"foo",name:"foo",email:"foo",createdAt:"foo"}}),docs:void 0},codeSamples:[]}},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:bQ.proto({methodType:this.getGrpcMethodType()}),audiences:[]}}}getGrpcMethodType(){return this.operation.clientStreaming&&this.operation.serverStreaming?MVt.BidirectionalStream:this.operation.clientStreaming?MVt.ClientStream:this.operation.serverStreaming?MVt.ServerStream:MVt.Unary}convertRequestBody(){let t=this.context.convertGrpcReferenceToTypeReference({typeName:this.operation.inputType,displayNameOverride:this.context.maybeRemoveGrpcPackagePrefix(this.operation.inputType)});return t.ok?{requestBody:rA.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:Rw.json(w9.response({responseBodyType:t.reference,docs:void 0,v2Examples:void 0})),statusCode:void 0},responseExample:void 0}:{responseBody:void 0,responseExample:void 0}}};var eUo=class extends $p{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 kLo({context:this.context,breadcrumbs:this.breadcrumbs,operation:i,serviceName:this.service.name,sourceCodeInfoPath:[...this.sourceCodeInfoPath,UWt.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 WJp(){return{request:{endpoint:{method:ukt.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:Us.V2HttpEndpointResponseBody.json({}),docs:void 0},codeSamples:[]}}var tUo=class extends LWt{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 PEi({context:this.context,breadcrumbs:[...this.breadcrumbs,this.context.spec.package],schema:r,sourceCodeInfoPath:[QLo.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 PEi({context:this.context,breadcrumbs:[...this.breadcrumbs,this.context.spec.package],schema:r,sourceCodeInfoPath:[QLo.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 eUo({context:this.context,breadcrumbs:this.breadcrumbs,service:r,sourceCodeInfoPath:[QLo.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=WJp(),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=RN.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 nCa({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 nCa({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=>p_(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),...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 HJp({req:e,options:t}){let r,i=RZ({generationLanguage:void 0,keywords:void 0,smartCasing:!1});for(let a of e.protoFile){let l=new tUo({context:new b4n({codeGeneratorRequest:e,spec:a,settings:{},errorCollector:new gEi({logger:{log:(d,...s)=>{}},relativeFilepathToSpec:void 0}),logger:new v4n,generationLanguage:void 0,smartCasing:!1,exampleGenerationArgs:{disabled:!0},enableUniqueErrorsPerEndpoint:!1,generateV1Examples:!1,comments:VJp(a)}),breadcrumbs:[],audiences:{type:"all"}}).convert();l!=null&&(r=r===void 0?l:QGi(r,l,i))}let n=Pp.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 $Jp(e){return{}}var ouc=nUD({name:"protoc-gen-fern",version:`v${String(vJp)}`,run:HJp});function nUD({name:e,version:t,run:r}){return{name:e,version:t,run(i){let n=$Jp(i.parameter),a=r({req:i,options:n});return aUD([a],Zcd,kcd)}}}function aUD(e,t,r){return tPa(Jho,{supportedFeatures:CT.parse(cPa.PROTO3_OPTIONAL|cPa.SUPPORTS_EDITIONS),minimumEdition:t,maximumEdition:r,file:e})}var GJp=require("fs/promises");var QJp=require("path"),JJp=ui(XX(),1);async function KJp({url:e,logger:t}){try{let r=await oUD({url:e,logger:t}),i=await JJp.default.dir(),n=(0,QJp.join)(i.path,e.endsWith(".json")?"openapi.json":"openapi.yaml");return t.debug("tmpDir",i.path),t.debug("filePath",n),await(0,GJp.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 oUD({url:e,logger:t}){let r=await GN.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:dOo(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)`),dOo(r.data))}var jEi=e=>e.name==="up"||e.name==="k"||e.ctrl&&e.name==="p",g4n=e=>e.name==="down"||e.name==="j"||e.ctrl&&e.name==="n",YJp=e=>e.name==="space",O4n=e=>e.name==="backspace",rUo=e=>"1234567890".includes(e.name),$6=e=>e.name==="enter"||e.name==="return";var iUo=class extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(t){super(),this.cause=t?.cause}},nUo=class extends Error{name="CancelPromptError";message="Prompt was canceled"},aCa=class extends Error{name="ExitPromptError"},aUo=class extends Error{name="HookError"},Rrr=class extends Error{name="ValidationError"};var eKp=require("async_hooks");var oUo=require("async_hooks");var XJp=new oUo.AsyncLocalStorage;function uUD(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function ZJp(e,t){let r=uUD(e);return XJp.run(r,()=>{function i(n){r.handleChange=()=>{r.index=0,n()},r.handleChange()}return t(i)})}function XGi(){let e=XJp.getStore();if(!e)throw new aUo("[Inquirer] Hook functions can only be called from within a prompt");return e}function uuc(){return XGi().rl}function suc(e){let t=(...r)=>{let i=XGi(),n=!1,a=i.handleChange;i.handleChange=()=>{n=!0};let u=e(...r);return n&&a(),i.handleChange=a,u};return oUo.AsyncResource.bind(t)}function m4n(e){let t=XGi(),{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 kJp(){XGi().handleChange()}var ZGi={queue(e){let t=XGi(),{index:r}=t;t.hooksEffect.push(()=>{t.hooksCleanup[r]?.();let i=e(uuc());if(i!=null&&typeof i!="function")throw new Rrr("useEffect return value must be a cleanup function or nothing.");t.hooksCleanup[r]=i})},run(){let e=XGi();suc(()=>{e.hooksEffect.forEach(t=>{t()}),e.hooksEffect.length=0})()},clearAll(){let e=XGi();e.hooksCleanup.forEach(t=>{t?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function D0(e){return m4n(t=>{let r=eKp.AsyncResource.bind(function(a){t.get()!==a&&(t.set(a),kJp())});if(t.initialized)return[t.get(),r];let i=typeof e=="function"?e():e;return t.set(i),[i,r]})}function VWt(e,t){m4n(r=>{let i=r.get();(!Array.isArray(i)||t.some((a,u)=>!Object.is(a,i[u])))&&ZGi.queue(e),r.set(t)})}var KNe=ui(F2(),1);var tKp={prefix:{idle:KNe.default.blue("?"),done:KNe.default.green(C6.tick)},spinner:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map(e=>KNe.default.yellow(e))},style:{answer:KNe.default.cyan,message:KNe.default.bold,error:e=>KNe.default.red(`> ${e}`),defaultAnswer:e=>KNe.default.dim(`(${e})`),help:KNe.default.dim,highlight:KNe.default.cyan,key:e=>KNe.default.cyan(KNe.default.bold(`<${e}>`))}};function rKp(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 iKp(...e){let t={};for(let r of e)for(let[i,n]of Object.entries(r)){let a=t[i];t[i]=rKp(a)&&rKp(n)?iKp(a,n):n}return t}function dR(...e){let t=[tKp,...e.filter(r=>r!=null)];return iKp(...t)}function P3({status:e="idle",theme:t}){let[r,i]=D0(!1),[n,a]=D0(0),{prefix:u,spinner:l}=dR(t);return VWt(()=>{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 Mae(e,t){return m4n(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 YNe(e){return D0({current:e})[0]}function j3(e){let t=YNe(e);t.current=e,VWt(r=>{let i=!1,n=suc((a,u)=>{i||t.current(u,r)});return r.input.on("keypress",n),()=>{i=!0,r.input.removeListener("keypress",n)}},[])}var nKp=ui(kGs(),1),aKp=ui(rQs(),1);function oCa(e,t){return e.split(`
1917
1917
  `).flatMap(r=>(0,aKp.default)(r,t,{trim:!1,hard:!0}).split(`
1918
1918
  `).map(i=>i.trimEnd())).join(`
@@ -1954,7 +1954,7 @@ ${A}${q}${D}${wKp.default.cursorHide}`});var sCa=ui(Rwi(),1);function juc(e,t){i
1954
1954
  Run ${Ss.cyan("fern generator upgrade")} to upgrade your generators.`),n.length>2&&(r+=`
1955
1955
  Run ${Ss.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),xFn(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function Iuc({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!JKp(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+=`
1956
1956
  ${await nVD(l.generatorName)} (${l.apiName!=null?"API: "+l.apiName+", ":""}Group: ${l.generatorGroup}) `+Ss.dim(l.currentVersion)+Ss.reset(" \u2192 ")+Ss.green(l.latestVersion);return n+=`
1957
- `,i?xFn(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function nVD(e){let r=await new QKp.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 aVD({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let l={type:"singleApi",versions:{}};return await YKp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,o,c)=>{l.versions[s]==null&&(l.versions[s]={});let b=xwi(o.name,c),g=await rkt({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 YKp({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=xwi(s.name,o),b=await rkt({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 YKp({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 xVt({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 XKp(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=Aae(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 bUo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let l=await aVD({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(...XKp(s,d,t.logger));else u.push(...XKp(l.versions,void 0,t.logger))}return u}var yCa=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 D4n=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var zuc=(()=>{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})(),ZKp=typeof globalThis.AbortController=="function",kKp=typeof globalThis.ReadableStream=="function",eYp=typeof globalThis.FormData=="function",gUo=["get","post","put","patch","head","delete"],oVD=()=>{};oVD();var tYp={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},OUo=2147483647,rYp=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,mUo=Symbol("stop"),iYp={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},nYp={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 uVD=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=rYp,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},aYp=(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})},oYp=(e,t)=>{let r=uVD(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 E4n=e=>e!==null&&typeof e=="object";var vCa=(...e)=>{for(let t of e)if((!E4n(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return Nuc({},...e)},xuc=(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 PUo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:Nuc(e[r]??[],t[r]??[])}var Ruc=(e={},t={})=>({beforeRequest:PUo(e,t,"beforeRequest"),beforeRetry:PUo(e,t,"beforeRetry"),afterResponse:PUo(e,t,"afterResponse"),beforeError:PUo(e,t,"beforeError")}),Nuc=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(E4n(n)){for(let[a,u]of Object.entries(n))E4n(u)&&a in t&&(u=Nuc(t[a],u)),t={...t,[a]:u};E4n(n.hooks)&&(i=Ruc(i,n.hooks),t.hooks=i),E4n(n.headers)&&(r=xuc(r,n.headers),t.headers=r)}return t};var sYp=e=>gUo.includes(e)?e.toUpperCase():e,sVD=["get","put","head","delete","options","trace"],cVD=[408,413,429,500,502,503,504],lVD=[413,429,503],uYp={limit:2,methods:sVD,statusCodes:cVD,afterStatusCodes:lVD,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},cYp=(e={})=>{if(typeof e=="number")return{...uYp,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{...uYp,...e}};async function Fuc(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new D4n(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function Luc(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 lYp=(e,t)=>{let r={};for(let i in t)!(i in nYp)&&!(i in iYp)&&!(i in e)&&(r[i]=t[i]);return r};var bCa=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>OUo)throw new RangeError(`The \`timeout\` option cannot be greater than ${OUo}`);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 yCa(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(!kKp)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return aYp(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(tYp))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:xuc(this._input.headers,r.headers),hooks:Ruc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:sYp(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:cYp(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(ZKp){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(zuc&&(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);(eYp&&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(!zuc)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=oYp(this.request,this._options.onUploadProgress))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof D4n)throw t;if(t instanceof yCa){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),OUo);if(this._retryCount<1)throw r;await Luc(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})===mUo)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=lYp(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):Fuc(r,t,this.abortController,this._options)}};var Uuc=e=>{let t=(r,i)=>bCa.create(r,vCa(e,i));for(let r of gUo)t[r]=(i,n)=>bCa.create(i,vCa(e,n,{method:r}));return t.create=r=>Uuc(vCa(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),Uuc(vCa(e,r))),t.stop=mUo,t},fVD=Uuc(),fYp=fVD;var IYp=ui(BYp(),1);function Guc(e){let t=(0,IYp.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var MXp=ui(EXp(),1),AXp=ui(Rwi(),1),asc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},osc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function usc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??Guc(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),l=(0,MXp.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 fYp(u,{headers:d,keepalive:!0}).json()}catch(c){throw c?.response?.status===404?new asc(e):c}if(t.allVersions)return s;let o=new osc(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=AXp.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 wCa(e,t){let{version:r}=await usc(e.toLowerCase(),t);return r}async function EEi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:wCa(e.packageName,{version:t?"prerelease":"latest"})}var qXp=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],IUo=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Yv.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new vUo(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.65.17"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Ss.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new d9}failWithoutThrowing(t,r){this.didSucceed=!1,pUo({message:t,error:r,logger:this.logger})}async exit({code:t}={}){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await EFn()).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 KKp({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1957
+ `,i?xFn(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function nVD(e){let r=await new QKp.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 aVD({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let l={type:"singleApi",versions:{}};return await YKp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,o,c)=>{l.versions[s]==null&&(l.versions[s]={});let b=xwi(o.name,c),g=await rkt({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 YKp({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=xwi(s.name,o),b=await rkt({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 YKp({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 xVt({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 XKp(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=Aae(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 bUo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let l=await aVD({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(...XKp(s,d,t.logger));else u.push(...XKp(l.versions,void 0,t.logger))}return u}var yCa=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 D4n=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var zuc=(()=>{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})(),ZKp=typeof globalThis.AbortController=="function",kKp=typeof globalThis.ReadableStream=="function",eYp=typeof globalThis.FormData=="function",gUo=["get","post","put","patch","head","delete"],oVD=()=>{};oVD();var tYp={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},OUo=2147483647,rYp=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,mUo=Symbol("stop"),iYp={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},nYp={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 uVD=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=rYp,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},aYp=(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})},oYp=(e,t)=>{let r=uVD(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 E4n=e=>e!==null&&typeof e=="object";var vCa=(...e)=>{for(let t of e)if((!E4n(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return Nuc({},...e)},xuc=(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 PUo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:Nuc(e[r]??[],t[r]??[])}var Ruc=(e={},t={})=>({beforeRequest:PUo(e,t,"beforeRequest"),beforeRetry:PUo(e,t,"beforeRetry"),afterResponse:PUo(e,t,"afterResponse"),beforeError:PUo(e,t,"beforeError")}),Nuc=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(E4n(n)){for(let[a,u]of Object.entries(n))E4n(u)&&a in t&&(u=Nuc(t[a],u)),t={...t,[a]:u};E4n(n.hooks)&&(i=Ruc(i,n.hooks),t.hooks=i),E4n(n.headers)&&(r=xuc(r,n.headers),t.headers=r)}return t};var sYp=e=>gUo.includes(e)?e.toUpperCase():e,sVD=["get","put","head","delete","options","trace"],cVD=[408,413,429,500,502,503,504],lVD=[413,429,503],uYp={limit:2,methods:sVD,statusCodes:cVD,afterStatusCodes:lVD,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},cYp=(e={})=>{if(typeof e=="number")return{...uYp,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{...uYp,...e}};async function Fuc(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new D4n(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function Luc(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 lYp=(e,t)=>{let r={};for(let i in t)!(i in nYp)&&!(i in iYp)&&!(i in e)&&(r[i]=t[i]);return r};var bCa=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>OUo)throw new RangeError(`The \`timeout\` option cannot be greater than ${OUo}`);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 yCa(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(!kKp)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return aYp(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(tYp))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:xuc(this._input.headers,r.headers),hooks:Ruc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:sYp(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:cYp(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(ZKp){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(zuc&&(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);(eYp&&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(!zuc)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=oYp(this.request,this._options.onUploadProgress))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof D4n)throw t;if(t instanceof yCa){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),OUo);if(this._retryCount<1)throw r;await Luc(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})===mUo)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=lYp(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):Fuc(r,t,this.abortController,this._options)}};var Uuc=e=>{let t=(r,i)=>bCa.create(r,vCa(e,i));for(let r of gUo)t[r]=(i,n)=>bCa.create(i,vCa(e,n,{method:r}));return t.create=r=>Uuc(vCa(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),Uuc(vCa(e,r))),t.stop=mUo,t},fVD=Uuc(),fYp=fVD;var IYp=ui(BYp(),1);function Guc(e){let t=(0,IYp.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var MXp=ui(EXp(),1),AXp=ui(Rwi(),1),asc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},osc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function usc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??Guc(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),l=(0,MXp.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 fYp(u,{headers:d,keepalive:!0}).json()}catch(c){throw c?.response?.status===404?new asc(e):c}if(t.allVersions)return s;let o=new osc(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=AXp.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 wCa(e,t){let{version:r}=await usc(e.toLowerCase(),t);return r}async function EEi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:wCa(e.packageName,{version:t?"prerelease":"latest"})}var qXp=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],IUo=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Yv.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new vUo(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.65.18"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Ss.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new d9}failWithoutThrowing(t,r){this.didSucceed=!1,pUo({message:t,error:r,logger:this.logger})}async exit({code:t}={}){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await EFn()).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 KKp({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1958
1958
  `)||(r+=`
1959
1959
  `),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=bIs(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 cCa(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 d9}finally{i.finish()}return n}async instrumentPostHogEvent(t){this.isLocal||(await EFn()).sendEvent(t)}logger=yXt((t,...r)=>this.log(t,...r));stderr=yXt((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=TXp(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?TXp(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=qXp[this.numTasks++%qXp.length],u=Ss.hex(a)(n);return{...this.constructTaskInit(),logPrefix:u}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===AB.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=>Qji.indexOf(n.level)>=Qji.indexOf(this.logLevel));this.ttyAwareLogger.log(i,{includeDebugInfo:this.logLevel===Yv.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 EEi({cliEnvironment:this.environment,includePreReleases:t}),i=Aae(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await bUo({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){return await buc({message:t,default:r})}async getInput(t){return await guc({message:t.message,default:t.default})}};function TXp(e){return`[${e}]:`}var ag_=require("fs/promises");function kNe({breadcrumbs:e=[],title:t,subtitle:r}){let i=[];return e.length>0&&i.push(Ss.blue(e.join(" -> "))),i.push(t),r!=null&&i.push(Ss.dim(r)),i.join(`
1960
1960
  `)}var o__=require("fs/promises");var HWt=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 cMe=class extends HWt{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 SCa=class{context;constructor(t){this.context=t}};var zUo=class e{files={};directories={};getAllFiles(){let t={},r=(i,n)=>{for(let[u,l]of Object.entries(i.files)){let d=n!=null?my.of(`${n}${ZUt}${u}`):my.of(u);t[d]=l}let a=Object.keys(i.directories).sort();for(let u of a){let l=n!=null?`${n}${ZUt}${u}`:u,d=i.directories[u];r(d,l)}};return r(this),t}getOrCreateFile(t){return this.getOrCreateFileRecursive(t.split(ZUt))}getOrCreateFileRecursive(t){if(t.length===1)return this.files[my.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 fQi=class{enableUniqueErrorsPerEndpoint;root;rootApiFile;packageMarkerFile={};basePath=void 0;constructor(t){this.enableUniqueErrorsPerEndpoint=t,this.root=new zUo,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 gkt(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"]))CXp(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(CXp(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??p_((fxe(r)+"/"+KUi(r,{stripExtension:!0})).replaceAll("__package__","root"));if(t===my.of($F))return this.rootApiFile.imports==null&&(this.rootApiFile.imports={}),this.rootApiFile.imports[n]=zgo(fxe(BBn.of(`/${t}`)),BBn.of(`/${r}`)),n;let a=this.getOrCreateFile(t);return a.imports==null&&(a.imports={}),a.imports[n]=zgo(fxe(BBn.of(`/${t}`)),BBn.of(`/${r}`)),n}addType(t,{name:r,schema:i}){if(t===my.of($F))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=>P2(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=qN(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:qN(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:qN(r,u.path)}]))})}return{rootApiFile:this.rootApiFile,packageMarkerFile:this.packageMarkerFile,definitionFiles:t}}getOrCreateFile(t){return t===CS?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 CXp(e){return e?.header!=null}var KQ={openapi:e=>({...e,type:"openapi",_visit:function(t){return KQ._visit(this,t)}}),protobuf:e=>({...e,type:"protobuf",_visit:function(t){return KQ._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 I4n={protobuf:e=>({...e,type:"protobuf",_visit:function(t){return I4n._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var K9={basic:e=>({...e,type:"basic",_visit:function(t){return K9._visit(this,t)}}),bearer:e=>({...e,type:"bearer",_visit:function(t){return K9._visit(this,t)}}),header:e=>({...e,type:"header",_visit:function(t){return K9._visit(this,t)}}),query:e=>({...e,type:"query",_visit:function(t){return K9._visit(this,t)}}),oauth:e=>({...e,type:"oauth",_visit:function(t){return K9._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 qg={primitive:e=>({value:e,type:"primitive",_visit:function(t){return qg._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return qg._visit(this,t)}}),array:e=>({value:e,type:"array",_visit:function(t){return qg._visit(this,t)}}),map:e=>({value:e,type:"map",_visit:function(t){return qg._visit(this,t)}}),enum:e=>({value:e,type:"enum",_visit:function(t){return qg._visit(this,t)}}),literal:e=>({value:e,type:"literal",_visit:function(t){return qg._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return qg._visit(this,t)}}),unknown:e=>({value:e,type:"unknown",_visit:function(t){return qg._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e.value);case"object":return t.object(e);case"array":return t.array(e.value);case"map":return t.map(e.value);case"enum":return t.enum(e.value);case"literal":return t.literal(e.value);case"oneOf":return t.oneOf(e.value);case"unknown":return t.unknown(e.value);default:return t._other(e)}}};var i_={int:e=>({value:e,type:"int",_visit:function(t){return i_._visit(this,t)}}),int64:e=>({value:e,type:"int64",_visit:function(t){return i_._visit(this,t)}}),uint:e=>({value:e,type:"uint",_visit:function(t){return i_._visit(this,t)}}),uint64:e=>({value:e,type:"uint64",_visit:function(t){return i_._visit(this,t)}}),float:e=>({value:e,type:"float",_visit:function(t){return i_._visit(this,t)}}),double:e=>({value:e,type:"double",_visit:function(t){return i_._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return i_._visit(this,t)}}),datetime:e=>({value:e,type:"datetime",_visit:function(t){return i_._visit(this,t)}}),date:e=>({value:e,type:"date",_visit:function(t){return i_._visit(this,t)}}),base64:e=>({value:e,type:"base64",_visit:function(t){return i_._visit(this,t)}}),boolean:e=>({value:e,type:"boolean",_visit:function(t){return i_._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e.value);case"int64":return t.int64(e.value);case"uint":return t.uint(e.value);case"uint64":return t.uint64(e.value);case"float":return t.float(e.value);case"double":return t.double(e.value);case"string":return t.string(e.value);case"datetime":return t.datetime(e.value);case"date":return t.date(e.value);case"base64":return t.base64(e.value);case"boolean":return t.boolean(e.value);default:return t._other(e)}}};var z4n={boolean:e=>({value:e,type:"boolean",_visit:function(t){return z4n._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return z4n._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 MEi={discriminated:e=>({value:e,type:"discriminated",_visit:function(t){return MEi._visit(this,t)}}),undiscriminated:e=>({value:e,type:"undiscriminated",_visit:function(t){return MEi._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 UW={GenerallyAvailable:"GenerallyAvailable",Beta:"Beta",Deprecated:"Deprecated",_visit:(e,t)=>{switch(e){case UW.GenerallyAvailable:return t.generallyAvailable();case UW.Beta:return t.beta();case UW.Deprecated:return t.deprecated();default:return t._other()}}};var eFe={cursor:e=>({...e,type:"cursor",_visit:function(t){return eFe._visit(this,t)}}),offset:e=>({...e,type:"offset",_visit:function(t){return eFe._visit(this,t)}}),custom:e=>({...e,type:"custom",_visit:function(t){return eFe._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 ndi={language:e=>({...e,type:"language",_visit:function(t){return ndi._visit(this,t)}}),sdk:e=>({...e,type:"sdk",_visit:function(t){return ndi._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 VW={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 VW.Curl:return t.curl();case VW.Python:return t.python();case VW.Javascript:return t.javascript();case VW.Typescript:return t.typescript();case VW.Go:return t.go();case VW.Ruby:return t.ruby();case VW.Csharp:return t.csharp();case VW.Java:return t.java();case VW.Js:return t.js();case VW.Node:return t.node();case VW.Ts:return t.ts();case VW.Nodets:return t.nodets();case VW.Golang:return t.golang();case VW.Dotnet:return t.dotnet();case VW.Jvm:return t.jvm();default:return t._other()}}};var $Wt={unknown:e=>({value:e,type:"unknown",_visit:function(t){return $Wt._visit(this,t)}}),full:e=>({...e,type:"full",_visit:function(t){return $Wt._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 GWt={withStreaming:e=>({...e,type:"withStreaming",_visit:function(t){return GWt._visit(this,t)}}),withoutStreaming:e=>({value:e,type:"withoutStreaming",_visit:function(t){return GWt._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 WW={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD",Options:"OPTIONS",Trace:"TRACE",_visit:(e,t)=>{switch(e){case WW.Get:return t.get();case WW.Post:return t.post();case WW.Put:return t.put();case WW.Patch:return t.patch();case WW.Delete:return t.delete();case WW.Head:return t.head();case WW.Options:return t.options();case WW.Trace:return t.trace();default:return t._other()}}};var AEi={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return AEi._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return AEi._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return AEi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"octetStream":return t.octetStream(e);case"multipart":return t.multipart(e);case"json":return t.json(e);default:return t._other(e)}}};var adi={file:e=>({...e,type:"file",_visit:function(t){return adi._visit(this,t)}}),json:e=>({value:e,type:"json",_visit:function(t){return adi._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 YQ={file:e=>({...e,type:"file",_visit:function(t){return YQ._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return YQ._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return YQ._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return YQ._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return YQ._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return YQ._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return YQ._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 Qy={primitive:e=>({...e,type:"primitive",_visit:function(t){return Qy._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Qy._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return Qy._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return Qy._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return Qy._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return Qy._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return Qy._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return Qy._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Qy._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return Qy._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return Qy._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 Xj={int:e=>({...e,type:"int",_visit:function(t){return Xj._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return Xj._visit(this,t)}}),uint:()=>({type:"uint",_visit:function(e){return Xj._visit(this,e)}}),uint64:()=>({type:"uint64",_visit:function(e){return Xj._visit(this,e)}}),float:()=>({type:"float",_visit:function(e){return Xj._visit(this,e)}}),double:e=>({...e,type:"double",_visit:function(t){return Xj._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return Xj._visit(this,t)}}),datetime:()=>({type:"datetime",_visit:function(e){return Xj._visit(this,e)}}),date:()=>({type:"date",_visit:function(e){return Xj._visit(this,e)}}),base64:()=>({type:"base64",_visit:function(e){return Xj._visit(this,e)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return Xj._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 lz={boolean:e=>({value:e,type:"boolean",_visit:function(t){return lz._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return lz._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 odi={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return odi._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return odi._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 lMe={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return lMe._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return lMe._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return lMe._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"octetStream":return t.octetStream(e);case"multipart":return t.multipart(e);case"json":return t.json(e);default:return t._other(e)}}};var gC={file:e=>({...e,type:"file",_visit:function(t){return gC._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return gC._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return gC._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return gC._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return gC._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return gC._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return gC._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 El={primitive:e=>({...e,type:"primitive",_visit:function(t){return El._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return El._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return El._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return El._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return El._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return El._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return El._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return El._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return El._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return El._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return El._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e);case"object":return t.object(e);case"array":return t.array(e);case"map":return t.map(e);case"optional":return t.optional(e);case"enum":return t.enum(e);case"reference":return t.reference(e);case"literal":return t.literal(e);case"oneOf":return t.oneOf(e.value);case"nullable":return t.nullable(e);case"unknown":return t.unknown(e);default:return t._other(e)}}};var NZ={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return NZ._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return NZ._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 tp={int:e=>({...e,type:"int",_visit:function(t){return tp._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return tp._visit(this,t)}}),uint:e=>({...e,type:"uint",_visit:function(t){return tp._visit(this,t)}}),uint64:e=>({...e,type:"uint64",_visit:function(t){return tp._visit(this,t)}}),float:e=>({...e,type:"float",_visit:function(t){return tp._visit(this,t)}}),double:e=>({...e,type:"double",_visit:function(t){return tp._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return tp._visit(this,t)}}),datetime:e=>({...e,type:"datetime",_visit:function(t){return tp._visit(this,t)}}),date:e=>({...e,type:"date",_visit:function(t){return tp._visit(this,t)}}),base64:e=>({...e,type:"base64",_visit:function(t){return tp._visit(this,t)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return tp._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 Cv={};Po(Cv,{AllOfPropertyConflict:()=>n2n,ArraySchema:()=>XVo,ArraySchemaWithExample:()=>SWo,Availability:()=>$Uo,Base64WithExample:()=>OWo,BasicSecurityScheme:()=>JUo,BearerSecurityScheme:()=>KUo,BooleanSchema:()=>$Vo,BooleanWithExample:()=>mWo,BytesResponse:()=>K4n,CasingOverrides:()=>ZUo,CommonProperty:()=>aWo,CommonPropertyWithExample:()=>IWo,CursorPagination:()=>MVo,CustomCodeSample:()=>DVo,CustomCodeSampleLanguage:()=>jVo,CustomCodeSampleSdk:()=>SVo,CustomPagination:()=>qVo,DateWithExample:()=>gWo,DatetimeWithExample:()=>bWo,DiscriminatedOneOfSchema:()=>iWo,DiscriminatedOneOfSchemaWithExample:()=>CWo,DoubleSchema:()=>WVo,DoubleWithExample:()=>yWo,Encoding:()=>HUo,Endpoint:()=>TVo,EndpointExample:()=>k4n,EndpointResponseExample:()=>PVo,EndpointSdkName:()=>Frr,EndpointWithExample:()=>sZp,EnumSchema:()=>F4n,EnumSchemaWithExample:()=>jWo,EnumValue:()=>CEi,ErrorExample:()=>vVo,FernExample:()=>gVo,FileResponse:()=>Q4n,FileSchema:()=>lVo,FloatWithExample:()=>hWo,FullEndpointExample:()=>EVo,FullExample:()=>Uq,FullObjectExample:()=>aVo,FullOneOfExample:()=>uVo,GlobalHeader:()=>QVo,Header:()=>IEi,HeaderExample:()=>Z4n,HeaderSecurityScheme:()=>YUo,HeaderWithExample:()=>REi,HttpEndpointServer:()=>Y4n,HttpError:()=>bVo,HttpErrorWithExample:()=>lWo,HttpMethod:()=>V4n,IdempotencyHeader:()=>JVo,Int64WithExample:()=>dWo,IntSchema:()=>UVo,IntWithExample:()=>fWo,JsonRequest:()=>_Vo,JsonRequestWithExample:()=>uWo,JsonResponse:()=>J4n,JsonResponseWithExample:()=>u2n,KeyValuePair:()=>oVo,LiteralExample:()=>nVo,LiteralSchema:()=>i2n,LiteralSchemaValue:()=>KVo,LongSchema:()=>VVo,MapSchema:()=>ZVo,MapSchemaWithExample:()=>DWo,MultipartRequest:()=>G4n,MultipartRequestProperty:()=>pVo,MultipartRequestPropertyEncoding:()=>dVo,MultipartSchema:()=>fVo,NamedFullExample:()=>Urr,Namespace:()=>kUo,NamespaceId:()=>iVo,NullableSchema:()=>eWo,NullableSchemaWithExample:()=>MWo,OauthSecurityScheme:()=>tVo,ObjectProperty:()=>rWo,ObjectPropertyConflictInfo:()=>a2n,ObjectPropertyWithExample:()=>TWo,ObjectSchema:()=>YVo,ObjectSchemaWithExample:()=>AWo,OctetStreamRequest:()=>$4n,OffsetPagination:()=>AVo,OneOfSchema:()=>tWo,OneOfSchemaWithExample:()=>qWo,OpenApiIntermediateRepresentation:()=>oZp,OpenApiSource:()=>LUo,OptionalSchema:()=>kVo,OptionalSchemaWithExample:()=>EWo,Pagination:()=>e2n,PathParameter:()=>W4n,PathParameterExample:()=>OVo,PathParameterWithExample:()=>oWo,PrimitiveExample:()=>U4n,PrimitiveSchema:()=>xEi,PrimitiveSchemaValue:()=>GVo,PrimitiveSchemaValueWithExample:()=>PWo,PrimitiveSchemaWithExample:()=>s2n,PropertyKey:()=>L4n,ProtobufEncoding:()=>WUo,ProtobufSource:()=>UUo,QueryParameter:()=>H4n,QueryParameterExample:()=>X4n,QueryParameterWithExample:()=>o2n,QuerySecurityScheme:()=>XUo,ReferencedSchema:()=>Lrr,Request:()=>hVo,RequestWithExample:()=>sWo,Response:()=>yVo,ResponseWithExample:()=>cWo,Schema:()=>Sm,SchemaId:()=>FZ,SchemaWithExample:()=>fA,Schemas:()=>LVo,SdkGroup:()=>eVo,SdkGroupInfo:()=>sVo,SdkGroupName:()=>BEi,SecurityScheme:()=>rVo,SecuritySchemeId:()=>QUo,Server:()=>ACa,Source:()=>VUo,StatusCode:()=>Nrr,StreamingResponseExample:()=>mVo,StringSchema:()=>HVo,StringSchemaWithExample:()=>vWo,SupportedSdkLanguage:()=>wVo,Tag:()=>GUo,TagId:()=>LZ,Tags:()=>cVo,TextResponse:()=>zEi,Uint64WithExample:()=>_Wo,UintWithExample:()=>pWo,UnDiscriminatedOneOfSchema:()=>nWo,UnDiscriminatedOneOfSchemaWithExample:()=>BWo,UnknownSchemaWithExample:()=>wWo,Webhook:()=>CVo,WebhookExampleCall:()=>r2n,WebhookHttpMethod:()=>t2n,WebhookWithExample:()=>cZp,WebsocketChannel:()=>FVo,WebsocketHandshake:()=>BVo,WebsocketHandshakeWithExample:()=>uZp,WebsocketMessageExample:()=>RVo,WebsocketMessageOrigin:()=>IVo,WebsocketMessageSchema:()=>zVo,WebsocketServer:()=>xVo,WebsocketSessionExample:()=>NVo,WithAvailability:()=>Bh,WithDescription:()=>gf,WithEncoding:()=>qae,WithInline:()=>WE,WithName:()=>z0,WithNamespace:()=>a0,WithSdkGroupName:()=>sm,WithSource:()=>kh,WithStatusCode:()=>tFe,WithTitle:()=>um,commons:()=>dsc,example:()=>psc,finalIr:()=>_sc,parseIr:()=>hsc});var dsc={};Po(dsc,{BasicSecurityScheme:()=>JUo,BearerSecurityScheme:()=>KUo,Encoding:()=>HUo,HeaderSecurityScheme:()=>YUo,Namespace:()=>kUo,NamespaceId:()=>iVo,OauthSecurityScheme:()=>tVo,OpenApiSource:()=>LUo,ProtobufEncoding:()=>WUo,ProtobufSource:()=>UUo,QuerySecurityScheme:()=>XUo,SchemaId:()=>FZ,SdkGroup:()=>eVo,SdkGroupName:()=>BEi,SecurityScheme:()=>rVo,SecuritySchemeId:()=>QUo,Server:()=>ACa,Source:()=>VUo,StatusCode:()=>Nrr,Tag:()=>GUo,TagId:()=>LZ,WithAvailability:()=>Bh,WithDescription:()=>gf,WithEncoding:()=>qae,WithInline:()=>WE,WithName:()=>z0,WithNamespace:()=>a0,WithSdkGroupName:()=>sm,WithSource:()=>kh,WithStatusCode:()=>tFe,WithTitle:()=>um});var Mt={};Po(Mt,{JsonError:()=>x4n,ParseError:()=>R4n,any:()=>QXp,bigint:()=>IXp,boolean:()=>JXp,booleanLiteral:()=>GXp,date:()=>zXp,discriminant:()=>iZp,enum_:()=>RUo,getObjectLikeUtils:()=>QWt,getObjectUtils:()=>dQi,getSchemaUtils:()=>Lq,isProperty:()=>TEi,lazy:()=>xXp,lazyObject:()=>WXp,list:()=>FUo,number:()=>KXp,object:()=>NUo,objectWithoutOptionalProperties:()=>VXp,optional:()=>ssc,property:()=>NXp,record:()=>kXp,set:()=>eZp,string:()=>YXp,stringLiteral:()=>$Xp,transform:()=>csc,undiscriminatedUnion:()=>rZp,union:()=>aZp,unknown:()=>XXp,withParsedProperties:()=>fsc});var Mj={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 lA(e,t){return`Expected ${t}. Received ${vWD(e)}.`}function vWD(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 Y9(e){return{...e,json:BXp(e.json),parse:BXp(e.parse)}}function BXp(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(`