fern-api 0.75.0 → 0.75.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.cjs +3 -3
- package/package.json +1 -1
package/cli.cjs
CHANGED
|
@@ -1717,7 +1717,7 @@ ${X$p.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&yfc(th
|
|
|
1717
1717
|
`+Ptn.default.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?Ptn.default.cyan(oGp(t,this.opt.mask)):Ptn.default.italic(Ptn.default.dim("[hidden]")):this.opt.mask?oGp(t,this.opt.mask):Ptn.default.italic(Ptn.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 uGo=ui(u5(),1),CQp=ui(TQp(),1),BQp=ui(YAe(),1);var s7a=class extends s5{_run(t){this.done=t,this.editorResult=new BQp.Subject;let r=t$(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"?uGo.default.dim("Received"):uGo.default.dim("Press <enter> to launch your preferred editor."),t&&(r=uGo.default.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),(0,CQp.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 NQp=require("stream");var xQp=ui(require("readline"),1),RQp=ui(zQp(),1),Atn=class{constructor(t){this.rl||=xQp.default.createInterface(GQD(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 GQD(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 RQp.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var c7a=class extends Atn{constructor(t={}){super(t),this.log=new NQp.Writable({write:(r,i,n)=>{this.writeLog(r),n()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return HNa(this.rl,this.bottomBar.split(`
|
|
1718
1718
|
`).length),this}updateBottomBar(t){return HNa(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+`
|
|
1719
1719
|
`}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&&z$o(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var CM=ui(YAe(),1),UQp=ui(fNa(),1);var sGo=ui(YAe(),1),FQp=ui(fNa(),1),cGo=function(e,t,r){return typeof e[t]!="function"?(0,sGo.of)(e):(0,sGo.from)((0,FQp.default)(e[t])(r).then(i=>(e[t]=i,e)))};var LQp={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,c)=>u!=null?u[c]:u,e),n=i(/[,[\]]+?/)||i(/[,.[\]]+?/);return n===void 0||n===e?r:n}},mWn=class extends Atn{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,CM.from)(t):(0,CM.isObservable)(t)?i=t:Object.values(t).every(n=>typeof n=="object"&&!Array.isArray(n)&&n!=null)?i=(0,CM.from)(Object.entries(t).map(([n,a])=>({name:n,...a}))):i=(0,CM.from)([t]),this.process=i.pipe((0,CM.concatMap)(this.processQuestion.bind(this)),(0,CM.publish)()),this.process.connect(),this.process.pipe((0,CM.reduce)((n,a)=>(LQp.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,CM.defer)(()=>(0,CM.of)(t).pipe((0,CM.concatMap)(this.setDefaultType.bind(this)),(0,CM.concatMap)(this.filterIfRunnable.bind(this)),(0,CM.concatMap)(()=>cGo(t,"message",this.answers)),(0,CM.concatMap)(()=>cGo(t,"default",this.answers)),(0,CM.concatMap)(()=>cGo(t,"choices",this.answers)),(0,CM.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,CM.defer)(()=>(0,CM.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,CM.defer)(()=>(0,CM.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&LQp.get(this.answers,t.name)!==void 0)return CM.EMPTY;if(t.when===!1)return CM.EMPTY;if(typeof t.when!="function")return(0,CM.of)(t);let{answers:r}=this;return(0,CM.defer)(()=>(0,CM.from)((0,UQp.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,CM.filter)(i=>i!=null)))}};function VQp(e){let t=function(r,i){let n;try{n=new mWn(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",GNa),this.registerPrompt("input",mtn),this.registerPrompt("number",QNa),this.registerPrompt("confirm",JNa),this.registerPrompt("rawlist",KNa),this.registerPrompt("expand",YNa),this.registerPrompt("checkbox",XNa),this.registerPrompt("password",ZNa),this.registerPrompt("editor",s7a)},t.restoreDefaultPrompts(),t}var cdc=VQp();function JQD(e,t){cdc.registerPrompt(e,t)}function KQD(){cdc.restoreDefaultPrompts()}var YQD={prompt:cdc,ui:{BottomBar:c7a,Prompt:mWn},createPromptModule:VQp,registerPrompt:JQD,restoreDefaultPrompts:KQD,Separator:uue},lGo=YQD;var BWn=require("path"),DKp=require("fs"),EKp=require("readline"),XJp="posthog-node";function NYD(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 c=a.tags[BGo.POSTHOG_ID_TAG];if(c===void 0)return a;let d=e.options.host??"https://us.i.posthog.com",s=new URL(`/project/${e.apiKey}/person/${c}`,d).toString();a.tags["PostHog Person URL"]=s;let o=a.exception?.values||[],l=o.map(g=>({...g,stacktrace:g.stacktrace?{...g.stacktrace,type:"raw",frames:(g.stacktrace.frames||[]).map(O=>({...O,platform:"node:javascript"}))}:void 0})),v={$exception_message:o[0]?.value||a.message,$exception_type:o[0]?.type,$exception_personURL:s,$exception_level:a.level,$exception_list:l,$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&&(v.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+a.event_id),e.capture({event:"$exception",distinctId:c,properties:v}),a}}var BGo=class{constructor(t,r,i,n){this.name=XJp,this.name=XJp,this.setupOnce=function(a,u){let c=u()?.getClient()?.getDsn()?.projectId;a(NYD(t,{organization:r,projectId:c,prefix:i,severityAllowList:n}))}}};BGo.POSTHOG_ID_TAG="posthog_distinct_id";var MGo="0123456789abcdef",IGo=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+=MGo.charAt(this.bytes[r]>>>4),t+=MGo.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+=MGo.charAt(this.bytes[r]>>>4),t+=MGo.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}},Zdc=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??FYD()}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 IGo.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,IGo.ofInner(t)}},FYD=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),ZJp,kdc=()=>LYD().toString(),LYD=()=>(ZJp||(ZJp=new Zdc)).generate();function UYD(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 VYD(e,t){global.process.on("uncaughtException",UYD(e,t))}function WYD(e){global.process.on("unhandledRejection",t=>{e(t,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var AGo,kJp,qGo;function HYD(e){let t=globalThis._posthogChunkIds;if(!t)return console.error("No chunk id map found"),{};let r=Object.keys(t);return qGo&&r.length===kJp||(kJp=r.length,qGo=r.reduce((i,n)=>{AGo||(AGo={});let a=AGo[n];if(a)i[a[0]]=a[1];else{let u=e(n);for(let c=u.length-1;c>=0;c--){let s=u[c]?.filename,o=t[n];if(s&&o){i[s]=o,AGo[n]=[s,o];break}}}return i},{})),qGo}function $YD(e){return typeof Event<"u"&&MKp(e,Event)}function GYD(e){return AKp(e,"Object")}function upc(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return MKp(e,Error)}}function MKp(e,t){try{return e instanceof t}catch{return!1}}function QYD(e){return AKp(e,"ErrorEvent")}function AKp(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}async function JYD(e,t,r,i){let a=i&&i.mechanism||{handled:!0,type:"generic"},u=qKp(a,r,i);return{$exception_list:await Promise.all(u.map(async s=>{let o=await tXD(e,t,s);return o.value=o.value||"",o.type=o.type||"Error",o.mechanism=a,o}))}}function qKp(e,t,r){let i=KYD(e,t,r);return i.cause?[i,...qKp(e,i.cause,r)]:[i]}function KYD(e,t,r){if(upc(t))return t;if(e.synthetic=!0,GYD(t)){let n=YYD(t);if(n)return n;let a=XYD(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 YYD(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(upc(r))return r}}function XYD(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=kYD(e);if(QYD(e))return`Event \`ErrorEvent\` captured as exception with message \`${e.message}\``;let r=ZYD(e);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${t}`}function ZYD(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{}}function kYD(e,t=40){let r=Object.keys(eXD(e));r.sort();let i=r[0];if(!i)return"[object has no keys]";if(i.length>=t)return eKp(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:eKp(a,t)}return""}function eKp(e,t=0){return typeof e!="string"||t===0||e.length<=t?e:`${e.slice(0,t)}...`}function eXD(e){return upc(e)?{message:e.message,name:e.name,stack:e.stack,...tKp(e)}:$YD(e)?{type:e.type,target:rKp(e.target),currentTarget:rKp(e.currentTarget),...tKp(e)}:e}function tKp(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 rKp(e){try{return Object.prototype.toString.call(e)}catch{return"<unknown>"}}async function tXD(e,t,r){let i={type:r.name||r.constructor.name,value:r.message},n=rXD(e,r);for(let a of t)n=await a(n);return n.length&&(i.stacktrace={frames:n,type:"raw"}),i}function rXD(e,t){return iXD(e(t.stack||"",1),e)}function iXD(e,t){let r=HYD(t);return e.forEach(i=>{i.filename&&(i.chunk_id=r[i.filename])}),e}var nXD=2e3,qWn=class e{static async captureException(t,r,i,n,a){let u={...a};n||(u.$process_person_profile=!1);let c=await JYD(this.stackParser,this.frameModifiers,r,i);t.capture({event:"$exception",distinctId:n||kdc(),properties:{...c,...u}})}constructor(t,r){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this.startAutocaptureIfEnabled()}startAutocaptureIfEnabled(){this.isEnabled()&&(VYD(this.onException.bind(this),this.onFatalError.bind(this)),WYD(this.onException.bind(this)))}onException(t,r){e.captureException(this.client,t,r)}async onFatalError(){await this.client.shutdown(nXD)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}};function aXD(e=process.argv[1]?(0,BWn.dirname)(process.argv[1]):process.cwd(),t=BWn.sep==="\\"){let r=t?iKp(e):e;return i=>{if(!i)return;let n=t?iKp(i):i,{dir:a,base:u,ext:c}=BWn.posix.parse(n);(c===".js"||c===".mjs"||c===".cjs")&&(u=u.slice(0,c.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 iKp(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var zGo=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)}}},CGo=new zGo(25),TKp=new zGo(20),spc=7,oXD=1e3,uXD=1e4;async function sXD(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"||dXD(u)||pXD(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(TKp.get(n))continue;let a=t[n];if(!a)continue;a.sort((d,s)=>d-s);let u=hXD(a);if(u.every(d=>_XD(n,d)))continue;let c=yXD(CGo,n,{});i.push(cXD(n,u,c))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&lXD(e,CGo),CGo.reduce(),e}function cXD(e,t,r){return new Promise(i=>{let n=(0,DKp.createReadStream)(e),a=(0,EKp.createInterface)({input:n});function u(){n.destroy(),i()}let c=0,d=0,s=t[d];if(s===void 0){u();return}let o=s[0],l=s[1];function v(){TKp.set(e,1),a.close(),a.removeAllListeners(),u()}n.on("error",v),a.on("error",v),a.on("close",u),a.on("line",g=>{if(c++,!(c<o)&&(r[c]=vXD(g,0),c>=l)){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],l=O[1]}})})}function lXD(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;fXD(r.lineno,r,i)}}function fXD(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=CKp(e);n<e;n++){let a=r[n];if(a===void 0){nKp(t);return}t.pre_context.push(a)}if(r[e]===void 0){nKp(t);return}t.context_line=r[e];let i=BKp(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 nKp(e){delete e.pre_context,delete e.context_line,delete e.post_context}function dXD(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function pXD(e){return e.lineno!==void 0&&e.lineno>uXD||e.colno!==void 0&&e.colno>oXD}function _XD(e,t){let r=CGo.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 hXD(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=aKp(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+spc:(n.push(i),i=aKp(a)),t++}return n}function aKp(e){return[CKp(e),BKp(e)]}function CKp(e){return Math.max(1,e-spc)}function BKp(e){return e+spc}function yXD(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function vXD(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 bXD="4.18.0",pue;(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"})(pue||(pue={}));var oKp;(function(e){e.Left="left",e.Right="right",e.Center="center"})(oKp||(oKp={}));var uKp;(function(e){e.Button="button",e.Tab="tab",e.Selector="selector"})(uKp||(uKp={}));var sKp;(function(e){e.Popover="popover",e.API="api",e.Widget="widget"})(sKp||(sKp={}));var cKp;(function(e){e.Html="html",e.Text="text"})(cKp||(cKp={}));var lKp;(function(e){e.Number="number",e.Emoji="emoji"})(lKp||(lKp={}));var fKp;(function(e){e.Open="open",e.MultipleChoice="multiple_choice",e.SingleChoice="single_choice",e.Rating="rating",e.Link="link"})(fKp||(fKp={}));var dKp;(function(e){e.NextQuestion="next_question",e.End="end",e.ResponseBased="response_based",e.SpecificQuestion="specific_question"})(dKp||(dKp={}));var pKp;(function(e){e.Regex="regex",e.NotRegex="not_regex",e.Exact="exact",e.IsNot="is_not",e.Icontains="icontains",e.NotIcontains="not_icontains"})(pKp||(pKp={}));var _Kp;(function(e){e.Contains="contains",e.Exact="exact",e.Regex="regex"})(_Kp||(_Kp={}));var gXD=e=>{if("flags"in e){let t=mXD(e.flags),r=PXD(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}else{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([n,a])=>[n,IKp(a)])),i=Object.fromEntries(Object.entries(t).map(([n,a])=>[n,OXD(n,a,r[n])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}};function OXD(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 mXD=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,cpc(r)]).filter(([,t])=>t!==void 0)),PXD=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?IKp(i):void 0]}))},cpc=e=>e===void 0?void 0:e.variant??e.enabled,IKp=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}},jXD=1,wXD=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"]),SXD="utf8";function DXD(e,t){if(!e||typeof e!="string"||EXD(e))throw new Error(t)}function EXD(e){return e.trim().length===0}function MXD(e){return e?.replace(/\/+$/,"")}async function AXD(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 hKp(){return new Date().getTime()}function Ydc(){return new Date().toISOString()}function xGo(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}function qXD(){return typeof fetch<"u"?fetch:typeof globalThis.fetch<"u"?globalThis.fetch:void 0}function TXD(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 CXD(e,t=0,r){let i=TXD(e);return r?.has(i)?!1:parseInt(i,16)/4294967295<t}function yKp(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var m7a=String.fromCharCode,vKp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",TGo={};function BXD(e,t){if(!TGo[e]){TGo[e]={};for(let r=0;r<e.length;r++)TGo[e][e.charAt(r)]=r}return TGo[e][t]}var MWn={compressToBase64:function(e){if(e==null)return"";let t=MWn._compress(e,6,function(r){return vKp.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:MWn._decompress(e.length,32,function(t){return BXD(vKp,e.charAt(t))})},compress:function(e){return MWn._compress(e,16,function(t){return m7a(t)})},_compress:function(e,t,r){if(e==null)return"";let i={},n={},a=[],u,c,d="",s="",o="",l=2,v=3,g=2,O=0,m=0,P;for(P=0;P<e.length;P+=1)if(d=e.charAt(P),Object.prototype.hasOwnProperty.call(i,d)||(i[d]=v++,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(c=o.charCodeAt(0),u=0;u<8;u++)O=O<<1|c&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,c=c>>1}else{for(c=1,u=0;u<g;u++)O=O<<1|c,m==t-1?(m=0,a.push(r(O)),O=0):m++,c=0;for(c=o.charCodeAt(0),u=0;u<16;u++)O=O<<1|c&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,c=c>>1}l--,l==0&&(l=Math.pow(2,g),g++),delete n[o]}else for(c=i[o],u=0;u<g;u++)O=O<<1|c&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,c=c>>1;l--,l==0&&(l=Math.pow(2,g),g++),i[s]=v++,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(c=o.charCodeAt(0),u=0;u<8;u++)O=O<<1|c&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,c=c>>1}else{for(c=1,u=0;u<g;u++)O=O<<1|c,m==t-1?(m=0,a.push(r(O)),O=0):m++,c=0;for(c=o.charCodeAt(0),u=0;u<16;u++)O=O<<1|c&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,c=c>>1}l--,l==0&&(l=Math.pow(2,g),g++),delete n[o]}else for(c=i[o],u=0;u<g;u++)O=O<<1|c&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,c=c>>1;l--,l==0&&(l=Math.pow(2,g),g++)}for(c=2,u=0;u<g;u++)O=O<<1|c&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,c=c>>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:MWn._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,c=4,d=3,s="",o,l,v,g,O,m,P;for(o=0;o<3;o+=1)i[o]=o;for(v=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++)),v|=(g>0?1:0)*m,m<<=1;switch(v){case 0:for(v=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++)),v|=(g>0?1:0)*m,m<<=1;P=m7a(v);break;case 1:for(v=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++)),v|=(g>0?1:0)*m,m<<=1;P=m7a(v);break;case 2:return""}for(i[3]=P,l=P,n.push(P);;){if(a.index>e)return"";for(v=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++)),v|=(g>0?1:0)*m,m<<=1;switch(P=v){case 0:for(v=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++)),v|=(g>0?1:0)*m,m<<=1;i[c++]=m7a(v),P=c-1,u--;break;case 1:for(v=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++)),v|=(g>0?1:0)*m,m<<=1;i[c++]=m7a(v),P=c-1,u--;break;case 2:return n.join("")}if(u==0&&(u=Math.pow(2,d),d++),i[P])s=i[P];else if(P===c)s=l+l.charAt(0);else return null;n.push(s),i[c++]=l+s.charAt(0),u--,l=s,u==0&&(u=Math.pow(2,d),d++)}}},epc=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)}},TWn=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()}},P7a=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function bKp(e){if(e instanceof TWn){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 Xdc(e){return typeof e=="object"&&(e instanceof TWn||e instanceof P7a)}function gKp(e){return typeof e=="object"&&e instanceof TWn&&e.status===413}var tpc;(function(e){e.FeatureFlags="feature_flags",e.Recordings="recordings"})(tpc||(tpc={}));var rpc=class{constructor(t,r){this.flushPromise=null,this.shutdownPromise=null,this.pendingPromises={},this._events=new epc,this._isInitialized=!1,DXD(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=MXD(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:Xdc},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(pue.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(pue.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(pue.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=kdc();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 c=this.buildPayload({distinct_id:a||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:i||{},...u||{}}});this.enqueue("capture",c,n)})}async getRemoteConfig(){await this._initPromise;let t=this.host;t==="https://us.i.posthog.com"?t="https://us-assets.i.posthog.com":t==="https://eu.i.posthog.com"&&(t="https://eu-assets.i.posthog.com");let r=`${t}/array/${this.apiKey}/config`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(r,i,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(n=>n.json()).catch(n=>{this.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 c=CXD(this.apiKey,jXD,wXD)?`${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",c)),this.fetchWithRetry(c,d,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(s=>s.json()).then(s=>gXD(s)).catch(s=>{this._events.emit("error",s)})}async getFeatureFlagStateless(t,r,i={},n={},a={},u){await this._initPromise;let c=await this.getFeatureFlagDetailStateless(t,r,i,n,a,u);if(c===void 0)return{response:void 0,requestId:void 0};let d=cpc(c.response);return d===void 0&&(d=!1),{response:d,requestId:c.requestId}}async getFeatureFlagDetailStateless(t,r,i={},n={},a={},u){await this._initPromise;let c=await this.getFeatureFlagDetailsStateless(r,i,n,a,u,[t]);return c===void 0?void 0:{response:c.flags[t],requestId:c.requestId}}async getFeatureFlagPayloadStateless(t,r,i={},n={},a={},u){await this._initPromise;let c=await this.getFeatureFlagPayloadsStateless(r,i,n,a,u,[t]);if(!c)return;let d=c[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 c=await this.getFeatureFlagDetailsStateless(t,r,i,n,a,u);return c?{flags:c.featureFlags,payloads:c.featureFlagPayloads,requestId:c.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(t,r={},i={},n={},a,u){await this._initPromise;let c={};(a??this.disableGeoip)&&(c.geoip_disable=!0),u&&(c.flag_keys_to_evaluate=u);let d=await this.getDecide(t,r,i,n,c);if(d!==void 0)return d.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),d.quotaLimited?.includes(tpc.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}`,c=new Error(u);this.logMsgIfDebug(()=>console.error(c)),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(pue.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(pue.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(pue.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(pue.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(pue.Queue,a),this._events.emit(t,n),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=xGo(()=>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:Ydc()};this.historicalMigration&&(n.historical_migration=!0);let a=JSON.stringify(n),u=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${hKp()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,c=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(MWn.compressToBase64(a))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:a};try{await this.fetchWithRetry(u,c)}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:Ydc(),uuid:i?.uuid?i.uuid:kdc()};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 bKp(t)})}async flush(){let t=yKp([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),yKp([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(pue.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(v=>v.message),u=()=>{let g=(this.getPersistedProperty(pue.Queue)||[]).slice(n.length);this.setPersistedProperty(pue.Queue,g),t=g},c={api_key:this.apiKey,batch:a,sent_at:Ydc()};this.historicalMigration&&(c.historical_migration=!0);let d=JSON.stringify(c),s=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${hKp()}&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(MWn.compressToBase64(d))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:d},l={retryCheck:v=>gKp(v)?!1:Xdc(v)};try{await this.fetchWithRetry(s,o,l)}catch(v){if(gKp(v)&&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 v instanceof P7a||u(),this._events.emit("error",v),v}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:"",c=-1;try{c=Buffer.byteLength(u,SXD)}catch{c=new TextEncoder().encode(u).length}return await AXD(async()=>{let d=null;try{d=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(o){throw new P7a(o)}if(!(r.mode==="no-cors")&&(d.status<200||d.status>=400))throw new TWn(d,c);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(pue.Queue)||[]).length===0||(await this.flush(),r)););}catch(n){if(!Xdc(n))throw n;await bKp(n)}};return Promise.race([new Promise((n,a)=>{xGo(()=>{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}},ipc=qXD();if(!ipc){let e=YJp();ipc=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 zKp=ipc,RGo=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()}},xKp=new RGo(async()=>{try{return await import("crypto")}catch{return}});async function IXD(){return await xKp.getValue()}var zXD=new RGo(async()=>{if(typeof globalThis.crypto?.subtle<"u")return globalThis.crypto.subtle;try{let e=await xKp.getValue();if(e?.webcrypto?.subtle)return e.webcrypto.subtle}catch{}});async function xXD(){return await zXD.getValue()}async function RXD(e){let t=await IXD();if(t)return t.createHash("sha1").update(e).digest("hex");let r=await xXD();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 NXD=60*1e3,FXD=1152921504606847e3,LXD=["is_not"],AWn=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},c5=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},npc=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:i,timeout:n,host:a,customHeaders:u,...c}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=n,this.projectApiKey=i,this.host=a,this.poller=void 0,this.fetch=c.fetch||zKp,this.onError=c.onError,this.customHeaders=u,this.onLoad=c.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,c;if(!this.loadedSuccessfullyOnce)return u;for(let d of this.featureFlags)if(t===d.key){c=d;break}if(c!==void 0)try{u=await this.computeFlagLocally(c,r,i,n,a),this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${u}`))}catch(d){d instanceof c5?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={},c=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 c5||s instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${d.key}: ${s}`)),c=!0}})),{response:a,payloads:u,fallbackToDecide:c}}async computeFlagLocally(t,r,i={},n={},a={}){if(t.ensure_experience_continuity)throw new c5("Flag has experience continuity enabled");if(!t.active)return!1;let c=(t.filters||{}).aggregation_group_type_index;if(c!=null){let d=this.groupTypeMapping[String(c)];if(!d)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new c5("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,c,d=[...a].sort((s,o)=>{let l=!!s.variant,v=!!o.variant;return l&&v?0:l?-1:v?1:0});for(let s of d)try{if(await this.isConditionMatch(t,r,s,i)){let o=s.variant,l=n.multivariate?.variants||[];o&&l.some(v=>v.key===o)?c=o:c=await this.getMatchingVariant(t,r)||!0;break}}catch(o){if(o instanceof c5)u=!0;else throw o}if(c!==void 0)return c;if(u)throw new c5("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=c=>{this.logMsgIfDebug(()=>console.warn(c))};if((i.properties||[]).length>0){for(let c of i.properties){let d=c.type,s=!1;if(d==="cohort"?s=NKp(c,n,this.cohorts,this.debugMode):s=RKp(c,n,u),!s)return!1}if(a==null)return!0}return!(a!=null&&await OKp(t.key,r)>a/100)}async getMatchingVariant(t,r){let i=await OKp(t.key,r,"variant"),n=this.variantLookupTable(t).find(a=>i>=a.valueMin&&i<a.valueMax);if(n)return n.key}variantLookupTable(t){let r=[],i=0,n=0;return((t.filters||{}).multivariate?.variants||[]).forEach(c=>{n=i+c.rollout_percentage/100,r.push({valueMin:i,valueMax:n,key:c.key}),i=n}),r}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(NXD,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 AWn(`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 AWn(`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 AWn(`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 AWn&&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=xGo(()=>{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=xGo(()=>{a.abort()},this.timeout),i.signal=a.signal}try{return this.fetch(r,i)}finally{clearTimeout(n)}}};async function OKp(e,t,r=""){let i=await RXD(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/FXD}function RKp(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 c5("Operator is_not_set is not supported")}else throw new c5(`Property ${i} not found in propertyValues`);let u=t[i];if(u==null&&!LXD.includes(a))return r&&r(`Property ${i} cannot have a value of null/undefined with the ${a} operator`),!1;function c(s,o){return Array.isArray(s)?s.map(l=>String(l).toLowerCase()).includes(String(o).toLowerCase()):String(s).toLowerCase()===String(o).toLowerCase()}function d(s,o,l){if(l==="gt")return s>o;if(l==="gte")return s>=o;if(l==="lt")return s<o;if(l==="lte")return s<=o;throw new Error(`Invalid operator: ${l}`)}switch(a){case"exact":return c(n,u);case"is_not":return!c(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 mKp(String(n))&&String(u).match(String(n))!==null;case"not_regex":return mKp(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=UXD(String(n));if(s==null&&(s=PKp(n)),s==null)throw new c5(`Invalid date: ${n}`);let o=PKp(u);return["is_date_before"].includes(a)?o<s:o>s}default:throw new c5(`Unknown operator: ${a}`)}}function NKp(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new c5("can't match cohort without a given cohort property value");let a=r[n];return FKp(a,t,r,i)}function FKp(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 c of a)try{let d=FKp(c,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof c5)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),u=!0;else throw d}if(u)throw new c5("Can't match cohort without a given cohort property value");return n==="AND"}else{for(let c of a)try{let d;c.type==="cohort"?d=NKp(c,t,r,i):d=RKp(c,t);let s=c.negation||!1;if(n==="AND"){if(!d&&!s||d&&s)return!1}else if(d&&!s||!d&&s)return!0}catch(d){if(d instanceof c5)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),u=!0;else throw d}if(u)throw new c5("can't match cohort without a given cohort property value");return n==="AND"}}function mKp(e){try{return new RegExp(e),!0}catch{return!1}}function PKp(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 c5(`${e} is in an invalid date format`)}else throw new c5(`The date provided ${e} must be a string, number, or date object`)}function UXD(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 apc=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},VXD=100,jKp=30*1e3,WXD=50*1e3,opc=class extends rpc{constructor(t,r={}){if(super(t,r),this._memoryStorage=new apc,this.options=r,this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,VXD):jKp,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 npc({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 qWn(this,r),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||WXD}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):zKp(t,r)}getLibraryVersion(){return bXD}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:c,disableGeoip:d,uuid:s}=t,o=g=>{super.captureStateless(r,i,g,{timestamp:c,disableGeoip:d,uuid:s})},l=async(g,O,m)=>(await super.getFeatureFlagsStateless(g,O,void 0,void 0,m)).flags,v=Promise.resolve().then(async()=>{if(u)return await l(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[P,D]of Object.entries(g))O[`$feature/${P}`]=D;let m=Object.keys(g||{}).filter(P=>g?.[P]!==!1).sort();return m.length>0&&(O.$active_feature_flags=m),O}).catch(()=>({})).then(g=>{o({...g,...n,$groups:a})});this.addPendingPromise(v)}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:c,disableGeoip:d,uuid:s}=t,o=g=>super.captureStatelessImmediate(r,i,g,{timestamp:c,disableGeoip:d,uuid:s}),l=async(g,O,m)=>(await super.getFeatureFlagsStateless(g,O,void 0,void 0,m)).flags;await Promise.resolve().then(async()=>{if(u)return await l(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[P,D]of Object.entries(g))O[`$feature/${P}`]=D;let m=Object.keys(g||{}).filter(P=>g?.[P]!==!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=jKp){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:c,personProperties:d,groupProperties:s}=i||{},o=this.addLocalPersonAndGroupProperties(r,n,d,s);d=o.allPersonProperties,s=o.allGroupProperties,u==null&&(u=!1),c==null&&(c=!0);let l=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,d,s),v=l!==void 0,g,O;if(!v&&!u){let P=await super.getFeatureFlagDetailStateless(t,r,n,d,s,a);if(P===void 0)return;O=P.response,l=cpc(O),g=P?.requestId}let m=`${t}_${l}`;return c&&(!(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:l,$feature_flag_id:O?.metadata?.id,$feature_flag_version:O?.metadata?.version,$feature_flag_reason:O?.reason?.description??O?.reason?.code,locally_evaluated:v,[`$feature/${t}`]:l,$feature_flag_request_id:g},groups:n,disableGeoip:a})),l}async getFeatureFlagPayload(t,r,i,n){let{groups:a,disableGeoip:u}=n||{},{onlyEvaluateLocally:c,sendFeatureFlagEvents:d,personProperties:s,groupProperties:o}=n||{},l=this.addLocalPersonAndGroupProperties(r,a,s,o);s=l.allPersonProperties,o=l.allGroupProperties;let v;return this.featureFlagsPoller!==void 0&&(i||(i=await this.getFeatureFlag(t,r,{...n,onlyEvaluateLocally:!0,sendFeatureFlagEvents:!1})),i&&(v=await this.featureFlagsPoller?.computeFeatureFlagPayloadLocally(t,i))),c==null&&(c=!1),d==null&&(d=!0),c==null&&(c=!1),!(v!==void 0)&&!c&&(v=await super.getFeatureFlagPayloadStateless(t,r,a,s,o,u)),v}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:c}=r||{},d=this.addLocalPersonAndGroupProperties(t,i,u,c);u=d.allPersonProperties,c=d.allGroupProperties,a==null&&(a=!1);let s=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,u,c),o={},l={},v=!0;if(s&&(o=s.response,l=s.payloads,v=s.fallbackToDecide),v&&!a){let g=await super.getFeatureFlagsAndPayloadsStateless(t,i,u,c,n);o={...o,...g.flags||{}},l={...l,...g.payloads||{}}}return{featureFlags:o,featureFlagPayloads:l}}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 c of Object.keys(r))u[c]={$group_key:r[c],...n?.[c]||{}};return{allPersonProperties:a,allGroupProperties:u}}captureException(t,r,i){let n=new Error("PostHog syntheticException");qWn.captureException(this,t,{syntheticException:n},r,i)}},wKp=/\(error: (.*)\)/,LKp=50,UKp="?";function HXD(e){let t=/^\s*[-]{4,}$/,r=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;return i=>{let n=i.match(r);if(n){let a,u,c,d,s;if(n[1]){c=n[1];let v=c.lastIndexOf(".");if(c[v-1]==="."&&v--,v>0){a=c.slice(0,v),u=c.slice(v+1);let g=a.indexOf(".Module");g>0&&(c=c.slice(g+1),a=a.slice(0,g))}d=void 0}u&&(d=a,s=u),u==="<anonymous>"&&(s=void 0,c=void 0),c===void 0&&(s=s||UKp,c=d?`${d}.${s}`:s);let o=n[2]?.startsWith("file://")?n[2].slice(7):n[2],l=n[5]==="native";return o?.match(/\/[A-Z]:/)&&(o=o.slice(1)),!o&&n[5]&&!l&&(o=n[5]),{filename:o?decodeURI(o):void 0,module:e?e(o):void 0,function:c,lineno:SKp(n[3]),colno:SKp(n[4]),in_app:$XD(o||"",l),platform:"node:javascript"}}if(i.match(t))return{filename:i,platform:"node:javascript"}}}function $XD(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 SKp(e){return parseInt(e||"",10)||void 0}function GXD(e){return[90,HXD(e)]}function QXD(e){let r=[GXD(e)].sort((i,n)=>i[0]-n[0]).map(i=>i[1]);return(i,n=0)=>{let a=[],u=i.split(`
|
|
1720
|
-
`);for(let c=n;c<u.length;c++){let d=u[c];if(d.length>1024)continue;let s=wKp.test(d)?d.replace(wKp,"$1"):d;if(!s.match(/\S*Error: /)){for(let o of r){let l=o(s);if(l){a.push(l);break}}if(a.length>=LKp)break}}return JXD(a)}}function JXD(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,LKp).map(r=>({...r,filename:r.filename||KXD(t).filename,function:r.function||UKp}))}function KXD(e){return e[e.length-1]||{}}qWn.stackParser=QXD(aXD());qWn.frameModifiers=[sXD];var CWn=class extends opc{getLibraryId(){return"posthog-node"}};var NGo=class{posthog;constructor({posthogApiKey:t}){this.posthog=new CWn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.75.0",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var j7a=class{async sendEvent(){}async identify(){}async flush(){}};var IWn=require("fs/promises"),$Kp=require("os"),GKp=require("path");var VKp=ui(require("crypto")),LGo=new Uint8Array(256),FGo=LGo.length;function lpc(){return FGo>LGo.length-16&&(VKp.default.randomFillSync(LGo),FGo=0),LGo.slice(FGo,FGo+=16)}var n$=[];for(let e=0;e<256;++e)n$.push((e+256).toString(16).slice(1));function WKp(e,t=0){return n$[e[t+0]]+n$[e[t+1]]+n$[e[t+2]]+n$[e[t+3]]+"-"+n$[e[t+4]]+n$[e[t+5]]+"-"+n$[e[t+6]]+n$[e[t+7]]+"-"+n$[e[t+8]]+n$[e[t+9]]+"-"+n$[e[t+10]]+n$[e[t+11]]+n$[e[t+12]]+n$[e[t+13]]+n$[e[t+14]]+n$[e[t+15]]}var HKp=ui(require("crypto")),fpc={randomUUID:HKp.default.randomUUID};function YXD(e,t,r){if(fpc.randomUUID&&!t&&!e)return fpc.randomUUID();e=e||{};let i=e.random||(e.rng||lpc)();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 WKp(i)}var _ue=YXD;var XXD="id",ZXD=".fern",w7a=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new CWn(r),this.userId=t==null?void 0:Xac(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.75.0",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Bu($c.of((0,$Kp.homedir)()),za.of(ZXD),za.of(XXD));await Cf(t)||(await(0,IWn.mkdir)((0,GKp.dirname)(t),{recursive:!0}),await(0,IWn.writeFile)(t,_ue())),this.persistedDistinctId=(await(0,IWn.readFile)(t)).toString()}return this.persistedDistinctId}};var dpc;async function zWn(){return dpc==null&&(dpc=await kXD()),dpc}async function kXD(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new j7a;let r=await tLo();return r!=null?new w7a({token:r,posthogApiKey:e}):await TUn()!=null?new NGo({posthogApiKey:e}):new w7a({token:void 0,posthogApiKey:e})}catch{return new j7a}}function S7a(e,t){return function(){return e.apply(t,arguments)}}var{toString:eZD}=Object.prototype,{getPrototypeOf:_pc}=Object,{iterator:VGo,toStringTag:JKp}=Symbol,WGo=(e=>t=>{let r=eZD.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),VGt=e=>(e=e.toLowerCase(),t=>WGo(t)===e),HGo=e=>t=>typeof t===e,{isArray:xWn}=Array,D7a=HGo("undefined");function E7a(e){return e!==null&&!D7a(e)&&e.constructor!==null&&!D7a(e.constructor)&&hue(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var KKp=VGt("ArrayBuffer");function tZD(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&KKp(e.buffer),t}var rZD=HGo("string"),hue=HGo("function"),YKp=HGo("number"),M7a=e=>e!==null&&typeof e=="object",iZD=e=>e===!0||e===!1,UGo=e=>{if(WGo(e)!=="object")return!1;let t=_pc(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(JKp in e)&&!(VGo in e)},nZD=e=>{if(!M7a(e)||E7a(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},aZD=VGt("Date"),oZD=VGt("File"),uZD=VGt("Blob"),sZD=VGt("FileList"),cZD=e=>M7a(e)&&hue(e.pipe),lZD=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||hue(e.append)&&((t=WGo(e))==="formdata"||t==="object"&&hue(e.toString)&&e.toString()==="[object FormData]"))},fZD=VGt("URLSearchParams"),[dZD,pZD,_ZD,hZD]=["ReadableStream","Request","Response","Headers"].map(VGt),yZD=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function A7a(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),xWn(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{if(E7a(e))return;let a=r?Object.getOwnPropertyNames(e):Object.keys(e),u=a.length,c;for(i=0;i<u;i++)c=a[i],t.call(null,e[c],c,e)}}function XKp(e,t){if(E7a(e))return null;t=t.toLowerCase();let r=Object.keys(e),i=r.length,n;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}var ztn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,ZKp=e=>!D7a(e)&&e!==ztn;function ppc(){let{caseless:e}=ZKp(this)&&this||{},t={},r=(i,n)=>{let a=e&&XKp(t,n)||n;UGo(t[a])&&UGo(i)?t[a]=ppc(t[a],i):UGo(i)?t[a]=ppc({},i):xWn(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&A7a(arguments[i],r);return t}var vZD=(e,t,r,{allOwnKeys:i}={})=>(A7a(t,(n,a)=>{r&&hue(n)?e[a]=S7a(n,r):e[a]=n},{allOwnKeys:i}),e),bZD=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),gZD=(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)},OZD=(e,t,r,i)=>{let n,a,u,c={};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))&&!c[u]&&(t[u]=e[u],c[u]=!0);e=r!==!1&&_pc(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},mZD=(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},PZD=e=>{if(!e)return null;if(xWn(e))return e;let t=e.length;if(!YKp(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},jZD=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&_pc(Uint8Array)),wZD=(e,t)=>{let i=(e&&e[VGo]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},SZD=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},DZD=VGt("HTMLFormElement"),EZD=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),QKp=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),MZD=VGt("RegExp"),kKp=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};A7a(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},AZD=e=>{kKp(e,(t,r)=>{if(hue(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(hue(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+"'")})}})},qZD=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return xWn(e)?i(e):i(String(e).split(t)),r},TZD=()=>{},CZD=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function BZD(e){return!!(e&&hue(e.append)&&e[JKp]==="FormData"&&e[VGo])}var IZD=e=>{let t=new Array(10),r=(i,n)=>{if(M7a(i)){if(t.indexOf(i)>=0)return;if(E7a(i))return i;if(!("toJSON"in i)){t[n]=i;let a=xWn(i)?[]:{};return A7a(i,(u,c)=>{let d=r(u,n+1);!D7a(d)&&(a[c]=d)}),t[n]=void 0,a}}return i};return r(e,0)},zZD=VGt("AsyncFunction"),xZD=e=>e&&(M7a(e)||hue(e))&&hue(e.then)&&hue(e.catch),eYp=((e,t)=>e?setImmediate:t?((r,i)=>(ztn.addEventListener("message",({source:n,data:a})=>{n===ztn&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),ztn.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",hue(ztn.postMessage)),RZD=typeof queueMicrotask<"u"?queueMicrotask.bind(ztn):typeof process<"u"&&process.nextTick||eYp,NZD=e=>e!=null&&hue(e[VGo]),hs={isArray:xWn,isArrayBuffer:KKp,isBuffer:E7a,isFormData:lZD,isArrayBufferView:tZD,isString:rZD,isNumber:YKp,isBoolean:iZD,isObject:M7a,isPlainObject:UGo,isEmptyObject:nZD,isReadableStream:dZD,isRequest:pZD,isResponse:_ZD,isHeaders:hZD,isUndefined:D7a,isDate:aZD,isFile:oZD,isBlob:uZD,isRegExp:MZD,isFunction:hue,isStream:cZD,isURLSearchParams:fZD,isTypedArray:jZD,isFileList:sZD,forEach:A7a,merge:ppc,extend:vZD,trim:yZD,stripBOM:bZD,inherits:gZD,toFlatObject:OZD,kindOf:WGo,kindOfTest:VGt,endsWith:mZD,toArray:PZD,forEachEntry:wZD,matchAll:SZD,isHTMLForm:DZD,hasOwnProperty:QKp,hasOwnProp:QKp,reduceDescriptors:kKp,freezeMethods:AZD,toObjectSet:qZD,toCamelCase:EZD,noop:TZD,toFiniteNumber:CZD,findKey:XKp,global:ztn,isContextDefined:ZKp,isSpecCompliantForm:BZD,toJSONObject:IZD,isAsyncFn:zZD,isThenable:xZD,setImmediate:eYp,asap:RZD,isIterable:NZD};function RWn(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)}hs.inherits(RWn,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:hs.toJSONObject(this.config),code:this.code,status:this.status}}});var tYp=RWn.prototype,rYp={};["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=>{rYp[e]={value:e}});Object.defineProperties(RWn,rYp);Object.defineProperty(tYp,"isAxiosError",{value:!0});RWn.from=(e,t,r,i,n,a)=>{let u=Object.create(tYp);return hs.toFlatObject(e,u,function(d){return d!==Error.prototype},c=>c!=="isAxiosError"),RWn.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var n_=RWn;var iYp=ui(pGo(),1),$Go=iYp.default;function hpc(e){return hs.isPlainObject(e)||hs.isArray(e)}function aYp(e){return hs.endsWith(e,"[]")?e.slice(0,-2):e}function nYp(e,t,r){return e?e.concat(t).map(function(n,a){return n=aYp(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function FZD(e){return hs.isArray(e)&&!e.some(hpc)}var LZD=hs.toFlatObject(hs,{},null,function(t){return/^is[A-Z]/.test(t)});function UZD(e,t,r){if(!hs.isObject(e))throw new TypeError("target must be an object");t=t||new($Go||FormData),r=hs.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,P){return!hs.isUndefined(P[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&hs.isSpecCompliantForm(t);if(!hs.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(hs.isDate(O))return O.toISOString();if(hs.isBoolean(O))return O.toString();if(!d&&hs.isBlob(O))throw new n_("Blob is not supported. Use a Buffer instead.");return hs.isArrayBuffer(O)||hs.isTypedArray(O)?d&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,P){let D=O;if(O&&!P&&typeof O=="object"){if(hs.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(hs.isArray(O)&&FZD(O)||(hs.isFileList(O)||hs.endsWith(m,"[]"))&&(D=hs.toArray(O)))return m=aYp(m),D.forEach(function(M,E){!(hs.isUndefined(M)||M===null)&&t.append(u===!0?nYp([m],E,a):u===null?m:m+"[]",s(M))}),!1}return hpc(O)?!0:(t.append(nYp(P,m,a),s(O)),!1)}let l=[],v=Object.assign(LZD,{defaultVisitor:o,convertValue:s,isVisitable:hpc});function g(O,m){if(!hs.isUndefined(O)){if(l.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));l.push(O),hs.forEach(O,function(D,A){(!(hs.isUndefined(D)||D===null)&&n.call(t,D,hs.isString(A)?A.trim():A,m,v))===!0&&g(D,m?m.concat(A):[A])}),l.pop()}}if(!hs.isObject(e))throw new TypeError("data must be an object");return g(e),t}var Exi=UZD;function oYp(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function uYp(e,t){this._pairs=[],e&&Exi(e,this,t)}var sYp=uYp.prototype;sYp.append=function(t,r){this._pairs.push([t,r])};sYp.toString=function(t){let r=t?function(i){return t.call(this,i,oYp)}:oYp;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var cYp=uYp;function VZD(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function xtn(e,t,r){if(!t)return e;let i=r&&r.encode||VZD;hs.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=hs.isURLSearchParams(t)?t.toString():new cYp(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var ypc=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){hs.forEach(this.handlers,function(i){i!==null&&t(i)})}},vpc=ypc;var NWn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var pYp=ui(require("crypto"),1);var lYp=ui(require("url"),1),fYp=lYp.default.URLSearchParams;var bpc="abcdefghijklmnopqrstuvwxyz",dYp="0123456789",_Yp={DIGIT:dYp,ALPHA:bpc,ALPHA_DIGIT:bpc+bpc.toUpperCase()+dYp},WZD=(e=16,t=_Yp.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);pYp.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},hYp={isNode:!0,classes:{URLSearchParams:fYp,FormData:$Go,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:_Yp,generateString:WZD,protocols:["http","https","file","data"]};var mpc={};Na(mpc,{hasBrowserEnv:()=>Opc,hasStandardBrowserEnv:()=>HZD,hasStandardBrowserWebWorkerEnv:()=>$ZD,navigator:()=>gpc,origin:()=>GZD});var Opc=typeof window<"u"&&typeof document<"u",gpc=typeof navigator=="object"&&navigator||void 0,HZD=Opc&&(!gpc||["ReactNative","NativeScript","NS"].indexOf(gpc.product)<0),$ZD=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",GZD=Opc&&window.location.href||"http://localhost";var rq={...mpc,...hYp};function Ppc(e,t){return Exi(e,new rq.classes.URLSearchParams,{visitor:function(r,i,n,a){return rq.isNode&&hs.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function QZD(e){return hs.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function JZD(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 KZD(e){function t(r,i,n,a){let u=r[a++];if(u==="__proto__")return!0;let c=Number.isFinite(+u),d=a>=r.length;return u=!u&&hs.isArray(n)?n.length:u,d?(hs.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!c):((!n[u]||!hs.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&hs.isArray(n[u])&&(n[u]=JZD(n[u])),!c)}if(hs.isFormData(e)&&hs.isFunction(e.entries)){let r={};return hs.forEachEntry(e,(i,n)=>{t(QZD(i),n,r,0)}),r}return null}var GGo=KZD;function YZD(e,t,r){if(hs.isString(e))try{return(t||JSON.parse)(e),hs.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var jpc={transitional:NWn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=hs.isObject(t);if(a&&hs.isHTMLForm(t)&&(t=new FormData(t)),hs.isFormData(t))return n?JSON.stringify(GGo(t)):t;if(hs.isArrayBuffer(t)||hs.isBuffer(t)||hs.isStream(t)||hs.isFile(t)||hs.isBlob(t)||hs.isReadableStream(t))return t;if(hs.isArrayBufferView(t))return t.buffer;if(hs.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return Ppc(t,this.formSerializer).toString();if((c=hs.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return Exi(c?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),YZD(t)):t}],transformResponse:[function(t){let r=this.transitional||jpc.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(hs.isResponse(t)||hs.isReadableStream(t))return t;if(t&&hs.isString(t)&&(i&&!this.responseType||n)){let u=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t)}catch(c){if(u)throw c.name==="SyntaxError"?n_.from(c,n_.ERR_BAD_RESPONSE,this,null,this.response):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:rq.classes.FormData,Blob:rq.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};hs.forEach(["delete","get","head","post","put","patch"],e=>{jpc.headers[e]={}});var FWn=jpc;var XZD=hs.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"]),yYp=e=>{let t={},r,i,n;return e&&e.split(`
|
|
1720
|
+
`);for(let c=n;c<u.length;c++){let d=u[c];if(d.length>1024)continue;let s=wKp.test(d)?d.replace(wKp,"$1"):d;if(!s.match(/\S*Error: /)){for(let o of r){let l=o(s);if(l){a.push(l);break}}if(a.length>=LKp)break}}return JXD(a)}}function JXD(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,LKp).map(r=>({...r,filename:r.filename||KXD(t).filename,function:r.function||UKp}))}function KXD(e){return e[e.length-1]||{}}qWn.stackParser=QXD(aXD());qWn.frameModifiers=[sXD];var CWn=class extends opc{getLibraryId(){return"posthog-node"}};var NGo=class{posthog;constructor({posthogApiKey:t}){this.posthog=new CWn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.75.1",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var j7a=class{async sendEvent(){}async identify(){}async flush(){}};var IWn=require("fs/promises"),$Kp=require("os"),GKp=require("path");var VKp=ui(require("crypto")),LGo=new Uint8Array(256),FGo=LGo.length;function lpc(){return FGo>LGo.length-16&&(VKp.default.randomFillSync(LGo),FGo=0),LGo.slice(FGo,FGo+=16)}var n$=[];for(let e=0;e<256;++e)n$.push((e+256).toString(16).slice(1));function WKp(e,t=0){return n$[e[t+0]]+n$[e[t+1]]+n$[e[t+2]]+n$[e[t+3]]+"-"+n$[e[t+4]]+n$[e[t+5]]+"-"+n$[e[t+6]]+n$[e[t+7]]+"-"+n$[e[t+8]]+n$[e[t+9]]+"-"+n$[e[t+10]]+n$[e[t+11]]+n$[e[t+12]]+n$[e[t+13]]+n$[e[t+14]]+n$[e[t+15]]}var HKp=ui(require("crypto")),fpc={randomUUID:HKp.default.randomUUID};function YXD(e,t,r){if(fpc.randomUUID&&!t&&!e)return fpc.randomUUID();e=e||{};let i=e.random||(e.rng||lpc)();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 WKp(i)}var _ue=YXD;var XXD="id",ZXD=".fern",w7a=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new CWn(r),this.userId=t==null?void 0:Xac(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.75.1",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Bu($c.of((0,$Kp.homedir)()),za.of(ZXD),za.of(XXD));await Cf(t)||(await(0,IWn.mkdir)((0,GKp.dirname)(t),{recursive:!0}),await(0,IWn.writeFile)(t,_ue())),this.persistedDistinctId=(await(0,IWn.readFile)(t)).toString()}return this.persistedDistinctId}};var dpc;async function zWn(){return dpc==null&&(dpc=await kXD()),dpc}async function kXD(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new j7a;let r=await tLo();return r!=null?new w7a({token:r,posthogApiKey:e}):await TUn()!=null?new NGo({posthogApiKey:e}):new w7a({token:void 0,posthogApiKey:e})}catch{return new j7a}}function S7a(e,t){return function(){return e.apply(t,arguments)}}var{toString:eZD}=Object.prototype,{getPrototypeOf:_pc}=Object,{iterator:VGo,toStringTag:JKp}=Symbol,WGo=(e=>t=>{let r=eZD.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),VGt=e=>(e=e.toLowerCase(),t=>WGo(t)===e),HGo=e=>t=>typeof t===e,{isArray:xWn}=Array,D7a=HGo("undefined");function E7a(e){return e!==null&&!D7a(e)&&e.constructor!==null&&!D7a(e.constructor)&&hue(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var KKp=VGt("ArrayBuffer");function tZD(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&KKp(e.buffer),t}var rZD=HGo("string"),hue=HGo("function"),YKp=HGo("number"),M7a=e=>e!==null&&typeof e=="object",iZD=e=>e===!0||e===!1,UGo=e=>{if(WGo(e)!=="object")return!1;let t=_pc(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(JKp in e)&&!(VGo in e)},nZD=e=>{if(!M7a(e)||E7a(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},aZD=VGt("Date"),oZD=VGt("File"),uZD=VGt("Blob"),sZD=VGt("FileList"),cZD=e=>M7a(e)&&hue(e.pipe),lZD=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||hue(e.append)&&((t=WGo(e))==="formdata"||t==="object"&&hue(e.toString)&&e.toString()==="[object FormData]"))},fZD=VGt("URLSearchParams"),[dZD,pZD,_ZD,hZD]=["ReadableStream","Request","Response","Headers"].map(VGt),yZD=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function A7a(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),xWn(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{if(E7a(e))return;let a=r?Object.getOwnPropertyNames(e):Object.keys(e),u=a.length,c;for(i=0;i<u;i++)c=a[i],t.call(null,e[c],c,e)}}function XKp(e,t){if(E7a(e))return null;t=t.toLowerCase();let r=Object.keys(e),i=r.length,n;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}var ztn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,ZKp=e=>!D7a(e)&&e!==ztn;function ppc(){let{caseless:e}=ZKp(this)&&this||{},t={},r=(i,n)=>{let a=e&&XKp(t,n)||n;UGo(t[a])&&UGo(i)?t[a]=ppc(t[a],i):UGo(i)?t[a]=ppc({},i):xWn(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&A7a(arguments[i],r);return t}var vZD=(e,t,r,{allOwnKeys:i}={})=>(A7a(t,(n,a)=>{r&&hue(n)?e[a]=S7a(n,r):e[a]=n},{allOwnKeys:i}),e),bZD=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),gZD=(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)},OZD=(e,t,r,i)=>{let n,a,u,c={};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))&&!c[u]&&(t[u]=e[u],c[u]=!0);e=r!==!1&&_pc(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},mZD=(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},PZD=e=>{if(!e)return null;if(xWn(e))return e;let t=e.length;if(!YKp(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},jZD=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&_pc(Uint8Array)),wZD=(e,t)=>{let i=(e&&e[VGo]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},SZD=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},DZD=VGt("HTMLFormElement"),EZD=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),QKp=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),MZD=VGt("RegExp"),kKp=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};A7a(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},AZD=e=>{kKp(e,(t,r)=>{if(hue(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(hue(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+"'")})}})},qZD=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return xWn(e)?i(e):i(String(e).split(t)),r},TZD=()=>{},CZD=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function BZD(e){return!!(e&&hue(e.append)&&e[JKp]==="FormData"&&e[VGo])}var IZD=e=>{let t=new Array(10),r=(i,n)=>{if(M7a(i)){if(t.indexOf(i)>=0)return;if(E7a(i))return i;if(!("toJSON"in i)){t[n]=i;let a=xWn(i)?[]:{};return A7a(i,(u,c)=>{let d=r(u,n+1);!D7a(d)&&(a[c]=d)}),t[n]=void 0,a}}return i};return r(e,0)},zZD=VGt("AsyncFunction"),xZD=e=>e&&(M7a(e)||hue(e))&&hue(e.then)&&hue(e.catch),eYp=((e,t)=>e?setImmediate:t?((r,i)=>(ztn.addEventListener("message",({source:n,data:a})=>{n===ztn&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),ztn.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",hue(ztn.postMessage)),RZD=typeof queueMicrotask<"u"?queueMicrotask.bind(ztn):typeof process<"u"&&process.nextTick||eYp,NZD=e=>e!=null&&hue(e[VGo]),hs={isArray:xWn,isArrayBuffer:KKp,isBuffer:E7a,isFormData:lZD,isArrayBufferView:tZD,isString:rZD,isNumber:YKp,isBoolean:iZD,isObject:M7a,isPlainObject:UGo,isEmptyObject:nZD,isReadableStream:dZD,isRequest:pZD,isResponse:_ZD,isHeaders:hZD,isUndefined:D7a,isDate:aZD,isFile:oZD,isBlob:uZD,isRegExp:MZD,isFunction:hue,isStream:cZD,isURLSearchParams:fZD,isTypedArray:jZD,isFileList:sZD,forEach:A7a,merge:ppc,extend:vZD,trim:yZD,stripBOM:bZD,inherits:gZD,toFlatObject:OZD,kindOf:WGo,kindOfTest:VGt,endsWith:mZD,toArray:PZD,forEachEntry:wZD,matchAll:SZD,isHTMLForm:DZD,hasOwnProperty:QKp,hasOwnProp:QKp,reduceDescriptors:kKp,freezeMethods:AZD,toObjectSet:qZD,toCamelCase:EZD,noop:TZD,toFiniteNumber:CZD,findKey:XKp,global:ztn,isContextDefined:ZKp,isSpecCompliantForm:BZD,toJSONObject:IZD,isAsyncFn:zZD,isThenable:xZD,setImmediate:eYp,asap:RZD,isIterable:NZD};function RWn(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)}hs.inherits(RWn,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:hs.toJSONObject(this.config),code:this.code,status:this.status}}});var tYp=RWn.prototype,rYp={};["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=>{rYp[e]={value:e}});Object.defineProperties(RWn,rYp);Object.defineProperty(tYp,"isAxiosError",{value:!0});RWn.from=(e,t,r,i,n,a)=>{let u=Object.create(tYp);return hs.toFlatObject(e,u,function(d){return d!==Error.prototype},c=>c!=="isAxiosError"),RWn.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var n_=RWn;var iYp=ui(pGo(),1),$Go=iYp.default;function hpc(e){return hs.isPlainObject(e)||hs.isArray(e)}function aYp(e){return hs.endsWith(e,"[]")?e.slice(0,-2):e}function nYp(e,t,r){return e?e.concat(t).map(function(n,a){return n=aYp(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function FZD(e){return hs.isArray(e)&&!e.some(hpc)}var LZD=hs.toFlatObject(hs,{},null,function(t){return/^is[A-Z]/.test(t)});function UZD(e,t,r){if(!hs.isObject(e))throw new TypeError("target must be an object");t=t||new($Go||FormData),r=hs.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,P){return!hs.isUndefined(P[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&hs.isSpecCompliantForm(t);if(!hs.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(hs.isDate(O))return O.toISOString();if(hs.isBoolean(O))return O.toString();if(!d&&hs.isBlob(O))throw new n_("Blob is not supported. Use a Buffer instead.");return hs.isArrayBuffer(O)||hs.isTypedArray(O)?d&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,P){let D=O;if(O&&!P&&typeof O=="object"){if(hs.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(hs.isArray(O)&&FZD(O)||(hs.isFileList(O)||hs.endsWith(m,"[]"))&&(D=hs.toArray(O)))return m=aYp(m),D.forEach(function(M,E){!(hs.isUndefined(M)||M===null)&&t.append(u===!0?nYp([m],E,a):u===null?m:m+"[]",s(M))}),!1}return hpc(O)?!0:(t.append(nYp(P,m,a),s(O)),!1)}let l=[],v=Object.assign(LZD,{defaultVisitor:o,convertValue:s,isVisitable:hpc});function g(O,m){if(!hs.isUndefined(O)){if(l.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));l.push(O),hs.forEach(O,function(D,A){(!(hs.isUndefined(D)||D===null)&&n.call(t,D,hs.isString(A)?A.trim():A,m,v))===!0&&g(D,m?m.concat(A):[A])}),l.pop()}}if(!hs.isObject(e))throw new TypeError("data must be an object");return g(e),t}var Exi=UZD;function oYp(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function uYp(e,t){this._pairs=[],e&&Exi(e,this,t)}var sYp=uYp.prototype;sYp.append=function(t,r){this._pairs.push([t,r])};sYp.toString=function(t){let r=t?function(i){return t.call(this,i,oYp)}:oYp;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var cYp=uYp;function VZD(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function xtn(e,t,r){if(!t)return e;let i=r&&r.encode||VZD;hs.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=hs.isURLSearchParams(t)?t.toString():new cYp(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var ypc=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){hs.forEach(this.handlers,function(i){i!==null&&t(i)})}},vpc=ypc;var NWn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var pYp=ui(require("crypto"),1);var lYp=ui(require("url"),1),fYp=lYp.default.URLSearchParams;var bpc="abcdefghijklmnopqrstuvwxyz",dYp="0123456789",_Yp={DIGIT:dYp,ALPHA:bpc,ALPHA_DIGIT:bpc+bpc.toUpperCase()+dYp},WZD=(e=16,t=_Yp.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);pYp.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},hYp={isNode:!0,classes:{URLSearchParams:fYp,FormData:$Go,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:_Yp,generateString:WZD,protocols:["http","https","file","data"]};var mpc={};Na(mpc,{hasBrowserEnv:()=>Opc,hasStandardBrowserEnv:()=>HZD,hasStandardBrowserWebWorkerEnv:()=>$ZD,navigator:()=>gpc,origin:()=>GZD});var Opc=typeof window<"u"&&typeof document<"u",gpc=typeof navigator=="object"&&navigator||void 0,HZD=Opc&&(!gpc||["ReactNative","NativeScript","NS"].indexOf(gpc.product)<0),$ZD=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",GZD=Opc&&window.location.href||"http://localhost";var rq={...mpc,...hYp};function Ppc(e,t){return Exi(e,new rq.classes.URLSearchParams,{visitor:function(r,i,n,a){return rq.isNode&&hs.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function QZD(e){return hs.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function JZD(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 KZD(e){function t(r,i,n,a){let u=r[a++];if(u==="__proto__")return!0;let c=Number.isFinite(+u),d=a>=r.length;return u=!u&&hs.isArray(n)?n.length:u,d?(hs.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!c):((!n[u]||!hs.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&hs.isArray(n[u])&&(n[u]=JZD(n[u])),!c)}if(hs.isFormData(e)&&hs.isFunction(e.entries)){let r={};return hs.forEachEntry(e,(i,n)=>{t(QZD(i),n,r,0)}),r}return null}var GGo=KZD;function YZD(e,t,r){if(hs.isString(e))try{return(t||JSON.parse)(e),hs.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var jpc={transitional:NWn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=hs.isObject(t);if(a&&hs.isHTMLForm(t)&&(t=new FormData(t)),hs.isFormData(t))return n?JSON.stringify(GGo(t)):t;if(hs.isArrayBuffer(t)||hs.isBuffer(t)||hs.isStream(t)||hs.isFile(t)||hs.isBlob(t)||hs.isReadableStream(t))return t;if(hs.isArrayBufferView(t))return t.buffer;if(hs.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return Ppc(t,this.formSerializer).toString();if((c=hs.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return Exi(c?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),YZD(t)):t}],transformResponse:[function(t){let r=this.transitional||jpc.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(hs.isResponse(t)||hs.isReadableStream(t))return t;if(t&&hs.isString(t)&&(i&&!this.responseType||n)){let u=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t)}catch(c){if(u)throw c.name==="SyntaxError"?n_.from(c,n_.ERR_BAD_RESPONSE,this,null,this.response):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:rq.classes.FormData,Blob:rq.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};hs.forEach(["delete","get","head","post","put","patch"],e=>{jpc.headers[e]={}});var FWn=jpc;var XZD=hs.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"]),yYp=e=>{let t={},r,i,n;return e&&e.split(`
|
|
1721
1721
|
`).forEach(function(u){n=u.indexOf(":"),r=u.substring(0,n).trim().toLowerCase(),i=u.substring(n+1).trim(),!(!r||t[r]&&XZD[r])&&(r==="set-cookie"?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t};var vYp=Symbol("internals");function q7a(e){return e&&String(e).trim().toLowerCase()}function QGo(e){return e===!1||e==null?e:hs.isArray(e)?e.map(QGo):String(e)}function ZZD(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 kZD=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function wpc(e,t,r,i,n){if(hs.isFunction(i))return i.call(this,t,r);if(n&&(t=r),!!hs.isString(t)){if(hs.isString(i))return t.indexOf(i)!==-1;if(hs.isRegExp(i))return i.test(t)}}function ekD(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,i)=>r.toUpperCase()+i)}function tkD(e,t){let r=hs.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 LWn=class{constructor(t){t&&this.set(t)}set(t,r,i){let n=this;function a(c,d,s){let o=q7a(d);if(!o)throw new Error("header name must be a non-empty string");let l=hs.findKey(n,o);(!l||n[l]===void 0||s===!0||s===void 0&&n[l]!==!1)&&(n[l||d]=QGo(c))}let u=(c,d)=>hs.forEach(c,(s,o)=>a(s,o,d));if(hs.isPlainObject(t)||t instanceof this.constructor)u(t,r);else if(hs.isString(t)&&(t=t.trim())&&!kZD(t))u(yYp(t),r);else if(hs.isObject(t)&&hs.isIterable(t)){let c={},d,s;for(let o of t){if(!hs.isArray(o))throw TypeError("Object iterator must return a key-value pair");c[s=o[0]]=(d=c[s])?hs.isArray(d)?[...d,o[1]]:[d,o[1]]:o[1]}u(c,r)}else t!=null&&a(r,t,i);return this}get(t,r){if(t=q7a(t),t){let i=hs.findKey(this,t);if(i){let n=this[i];if(!r)return n;if(r===!0)return ZZD(n);if(hs.isFunction(r))return r.call(this,n,i);if(hs.isRegExp(r))return r.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=q7a(t),t){let i=hs.findKey(this,t);return!!(i&&this[i]!==void 0&&(!r||wpc(this,this[i],i,r)))}return!1}delete(t,r){let i=this,n=!1;function a(u){if(u=q7a(u),u){let c=hs.findKey(i,u);c&&(!r||wpc(i,i[c],c,r))&&(delete i[c],n=!0)}}return hs.isArray(t)?t.forEach(a):a(t),n}clear(t){let r=Object.keys(this),i=r.length,n=!1;for(;i--;){let a=r[i];(!t||wpc(this,this[a],a,t,!0))&&(delete this[a],n=!0)}return n}normalize(t){let r=this,i={};return hs.forEach(this,(n,a)=>{let u=hs.findKey(i,a);if(u){r[u]=QGo(n),delete r[a];return}let c=t?ekD(a):String(a).trim();c!==a&&delete r[a],r[c]=QGo(n),i[c]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return hs.forEach(this,(i,n)=>{i!=null&&i!==!1&&(r[n]=t&&hs.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(`
|
|
1722
1722
|
`)}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[vYp]=this[vYp]={accessors:{}}).accessors,n=this.prototype;function a(u){let c=q7a(u);i[c]||(tkD(n,u),i[c]=!0)}return hs.isArray(t)?t.forEach(a):a(t),this}};LWn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);hs.reduceDescriptors(LWn.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(i){this[r]=i}}});hs.freezeMethods(LWn);var h3=LWn;function T7a(e,t){let r=this||FWn,i=t||r,n=h3.from(i.headers),a=i.data;return hs.forEach(e,function(c){a=c.call(r,a,n.normalize(),t?t.status:void 0)}),n.normalize(),a}function C7a(e){return!!(e&&e.__CANCEL__)}function bYp(e,t,r){n_.call(this,e??"canceled",n_.ERR_CANCELED,t,r),this.name="CanceledError"}hs.inherits(bYp,n_,{__CANCEL__:!0});var ZAe=bYp;function rar(e,t,r){let i=r.config.validateStatus;!r.status||!i||i(r.status)?e(r):t(new n_("Request failed with status code "+r.status,[n_.ERR_BAD_REQUEST,n_.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function Spc(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Dpc(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function Rtn(e,t,r){let i=!Spc(t);return e&&(i||r==!1)?Dpc(e,t):t}var IYp=ui(l7a(),1),zYp=ui(require("http"),1),xYp=ui(require("https"),1),RYp=ui(require("util"),1),NYp=ui(Ddc(),1),TOi=ui(require("zlib"),1);var Ntn="1.11.0";function B7a(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var rkD=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function Epc(e,t,r){let i=r&&r.Blob||rq.classes.Blob,n=B7a(e);if(t===void 0&&i&&(t=!0),n==="data"){e=n.length?e.slice(n.length+1):e;let a=rkD.exec(e);if(!a)throw new n_("Invalid URL",n_.ERR_INVALID_URL);let u=a[1],c=a[2],d=a[3],s=Buffer.from(decodeURIComponent(d),c?"base64":"utf8");if(t){if(!i)throw new n_("Blob is not supported",n_.ERR_NOT_SUPPORT);return new i([s],{type:u})}return s}throw new n_("Unsupported protocol "+n,n_.ERR_NOT_SUPPORT)}var Ltn=ui(require("stream"),1);var gYp=ui(require("stream"),1);var Mpc=Symbol("internals"),Apc=class extends gYp.default.Transform{constructor(t){t=hs.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(i,n)=>!hs.isUndefined(n[i])),super({readableHighWaterMark:t.chunkSize});let r=this[Mpc]={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[Mpc];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,i){let n=this[Mpc],a=n.maxRate,u=this.readableHighWaterMark,c=n.timeWindow,d=1e3/c,s=a/d,o=n.minChunkSize!==!1?Math.max(n.minChunkSize,s*.01):0,l=(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)}},v=(g,O)=>{let m=Buffer.byteLength(g),P=null,D=u,A,M=0;if(a){let E=Date.now();(!n.ts||(M=E-n.ts)>=c)&&(n.ts=E,A=s-n.bytes,n.bytes=A<0?-A:0,M=0),A=s-n.bytes}if(a){if(A<=0)return setTimeout(()=>{O(null,g)},c-M);A<D&&(D=A)}D&&m>D&&m-D>o&&(P=g.subarray(D),g=g.subarray(0,D)),l(g,P?()=>{process.nextTick(O,null,P)}:O)};v(t,function g(O,m){if(O)return i(O);m?v(m,g):i(null)})}},qpc=Apc;var FYp=require("events");var mYp=ui(require("util"),1),PYp=require("stream");var{asyncIterator:OYp}=Symbol,ikD=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[OYp]?yield*e[OYp]():yield e},JGo=ikD;var nkD=rq.ALPHABET.ALPHA_DIGIT+"-_",I7a=typeof TextEncoder=="function"?new TextEncoder:new mYp.default.TextEncoder,Ftn=`\r
|
|
1723
1723
|
`,akD=I7a.encode(Ftn),okD=2,Tpc=class{constructor(t,r){let{escapeName:i}=this.constructor,n=hs.isString(r),a=`Content-Disposition: form-data; name="${i(t)}"${!n&&r.name?`; filename="${i(r.name)}"`:""}${Ftn}`;n?r=I7a.encode(String(r).replace(/\r?\n|\r\n?/g,Ftn)):a+=`Content-Type: ${r.type||"application/octet-stream"}${Ftn}`,this.headers=I7a.encode(a+Ftn),this.contentLength=n?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+okD,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;hs.isTypedArray(t)?yield t:yield*JGo(t),yield akD}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},ukD=(e,t,r)=>{let{tag:i="form-data-boundary",size:n=25,boundary:a=i+"-"+rq.generateString(n,nkD)}=r||{};if(!hs.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=I7a.encode("--"+a+Ftn),c=I7a.encode("--"+a+"--"+Ftn),d=c.byteLength,s=Array.from(e.entries()).map(([l,v])=>{let g=new Tpc(l,v);return d+=g.size,g});d+=u.byteLength*s.length,d=hs.toFiniteNumber(d);let o={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(d)&&(o["Content-Length"]=d),t&&t(o),PYp.Readable.from((async function*(){for(let l of s)yield u,yield*l.encode();yield c})())},jYp=ukD;var wYp=ui(require("stream"),1),Cpc=class extends wYp.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)}},SYp=Cpc;var skD=(e,t)=>hs.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,DYp=skD;function ckD(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 l=a,v=0;for(;l!==n;)v+=r[l++],l=l%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(v*1e3/g):void 0}}var EYp=ckD;function lkD(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(...s)};return[(...s)=>{let o=Date.now(),l=o-r;l>=i?u(s,o):(n=s,a||(a=setTimeout(()=>{a=null,u(n)},i-l)))},()=>n&&u(n)]}var MYp=lkD;var qOi=(e,t,r=3)=>{let i=0,n=EYp(50,250);return MYp(a=>{let u=a.loaded,c=a.lengthComputable?a.total:void 0,d=u-i,s=n(d),o=u<=c;i=u;let l={loaded:u,total:c,progress:c?u/c:void 0,bytes:d,rate:s||void 0,estimated:s&&c&&o?(c-u)/s:void 0,event:a,lengthComputable:c!=null,[t?"download":"upload"]:!0};e(l)},r)},UWn=(e,t)=>{let r=e!=null;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},VWn=e=>(...t)=>hs.asap(()=>e(...t));var AYp={flush:TOi.default.constants.Z_SYNC_FLUSH,finishFlush:TOi.default.constants.Z_SYNC_FLUSH},fkD={flush:TOi.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:TOi.default.constants.BROTLI_OPERATION_FLUSH},qYp=hs.isFunction(TOi.default.createBrotliDecompress),{http:dkD,https:pkD}=NYp.default,_kD=/https:?/,TYp=rq.protocols.map(e=>e+":"),CYp=(e,[t,r])=>(e.on("end",r).on("error",r),t);function hkD(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function LYp(e,t,r){let i=t;if(!i&&i!==!1){let n=IYp.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){LYp(a,t,a.href)}}var ykD=typeof process<"u"&&hs.kindOf(process)==="process",vkD=e=>new Promise((t,r)=>{let i,n,a=(d,s)=>{n||(n=!0,i&&i(d,s))},u=d=>{a(d),t(d)},c=d=>{a(d,!0),r(d)};e(u,c,d=>i=d).catch(c)}),bkD=({address:e,family:t})=>{if(!hs.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},BYp=(e,t)=>bkD(hs.isObject(e)?e:{address:e,family:t}),UYp=ykD&&function(t){return vkD(async function(i,n,a){let{data:u,lookup:c,family:d}=t,{responseType:s,responseEncoding:o}=t,l=t.method.toUpperCase(),v,g=!1,O;if(c){let me=DYp(c,Le=>hs.isArray(Le)?Le:[Le]);c=(Le,yt,De)=>{me(Le,yt,(Ae,Ct,Pe)=>{if(Ae)return De(Ae);let St=hs.isArray(Ct)?Ct.map(at=>BYp(at)):[BYp(Ct,Pe)];yt.all?De(Ae,St):De(Ae,St[0].address,St[0].family)})}}let m=new FYp.EventEmitter,P=()=>{t.cancelToken&&t.cancelToken.unsubscribe(D),t.signal&&t.signal.removeEventListener("abort",D),m.removeAllListeners()};a((me,Le)=>{v=!0,Le&&(g=!0,P())});function D(me){m.emit("abort",!me||me.type?new ZAe(null,t,O):me)}m.once("abort",n),(t.cancelToken||t.signal)&&(t.cancelToken&&t.cancelToken.subscribe(D),t.signal&&(t.signal.aborted?D():t.signal.addEventListener("abort",D)));let A=Rtn(t.baseURL,t.url,t.allowAbsoluteUrls),M=new URL(A,rq.hasBrowserEnv?rq.origin:void 0),E=M.protocol||TYp[0];if(E==="data:"){let me;if(l!=="GET")return rar(i,n,{status:405,statusText:"method not allowed",headers:{},config:t});try{me=Epc(t.url,s==="blob",{Blob:t.env&&t.env.Blob})}catch(Le){throw n_.from(Le,n_.ERR_BAD_REQUEST,t)}return s==="text"?(me=me.toString(o),(!o||o==="utf8")&&(me=hs.stripBOM(me))):s==="stream"&&(me=Ltn.default.Readable.from(me)),rar(i,n,{data:me,status:200,statusText:"OK",headers:new h3,config:t})}if(TYp.indexOf(E)===-1)return n(new n_("Unsupported protocol "+E,n_.ERR_BAD_REQUEST,t));let T=h3.from(t.headers).normalize();T.set("User-Agent","axios/"+Ntn,!1);let{onUploadProgress:z,onDownloadProgress:G}=t,I=t.maxRate,R,U;if(hs.isSpecCompliantForm(u)){let me=T.getContentType(/boundary=([-_\w\d]{10,70})/i);u=jYp(u,Le=>{T.set(Le)},{tag:`axios-${Ntn}-boundary`,boundary:me&&me[1]||void 0})}else if(hs.isFormData(u)&&hs.isFunction(u.getHeaders)){if(T.set(u.getHeaders()),!T.hasContentLength())try{let me=await RYp.default.promisify(u.getLength).call(u);Number.isFinite(me)&&me>=0&&T.setContentLength(me)}catch{}}else if(hs.isBlob(u)||hs.isFile(u))u.size&&T.setContentType(u.type||"application/octet-stream"),T.setContentLength(u.size||0),u=Ltn.default.Readable.from(JGo(u));else if(u&&!hs.isStream(u)){if(!Buffer.isBuffer(u))if(hs.isArrayBuffer(u))u=Buffer.from(new Uint8Array(u));else if(hs.isString(u))u=Buffer.from(u,"utf-8");else return n(new n_("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",n_.ERR_BAD_REQUEST,t));if(T.setContentLength(u.length,!1),t.maxBodyLength>-1&&u.length>t.maxBodyLength)return n(new n_("Request body larger than maxBodyLength limit",n_.ERR_BAD_REQUEST,t))}let Y=hs.toFiniteNumber(T.getContentLength());hs.isArray(I)?(R=I[0],U=I[1]):R=U=I,u&&(z||R)&&(hs.isStream(u)||(u=Ltn.default.Readable.from(u,{objectMode:!1})),u=Ltn.default.pipeline([u,new qpc({maxRate:hs.toFiniteNumber(R)})],hs.noop),z&&u.on("progress",CYp(u,UWn(Y,qOi(VWn(z),!1,3)))));let J;if(t.auth){let me=t.auth.username||"",Le=t.auth.password||"";J=me+":"+Le}if(!J&&M.username){let me=M.username,Le=M.password;J=me+":"+Le}J&&T.delete("authorization");let X;try{X=xtn(M.pathname+M.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch(me){let Le=new Error(me.message);return Le.config=t,Le.url=t.url,Le.exists=!0,n(Le)}T.set("Accept-Encoding","gzip, compress, deflate"+(qYp?", br":""),!1);let ae={path:X,method:l,headers:T.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:J,protocol:E,family:d,beforeRedirect:hkD,beforeRedirects:{}};!hs.isUndefined(c)&&(ae.lookup=c),t.socketPath?ae.socketPath=t.socketPath:(ae.hostname=M.hostname.startsWith("[")?M.hostname.slice(1,-1):M.hostname,ae.port=M.port,LYp(ae,t.proxy,E+"//"+M.hostname+(M.port?":"+M.port:"")+ae.path));let pe,de=_kD.test(ae.protocol);if(ae.agent=de?t.httpsAgent:t.httpAgent,t.transport?pe=t.transport:t.maxRedirects===0?pe=de?xYp.default:zYp.default:(t.maxRedirects&&(ae.maxRedirects=t.maxRedirects),t.beforeRedirect&&(ae.beforeRedirects.config=t.beforeRedirect),pe=de?pkD:dkD),t.maxBodyLength>-1?ae.maxBodyLength=t.maxBodyLength:ae.maxBodyLength=1/0,t.insecureHTTPParser&&(ae.insecureHTTPParser=t.insecureHTTPParser),O=pe.request(ae,function(Le){if(O.destroyed)return;let yt=[Le],De=+Le.headers["content-length"];if(G||U){let at=new qpc({maxRate:hs.toFiniteNumber(U)});G&&at.on("progress",CYp(at,UWn(De,qOi(VWn(G),!0,3)))),yt.push(at)}let Ae=Le,Ct=Le.req||O;if(t.decompress!==!1&&Le.headers["content-encoding"])switch((l==="HEAD"||Le.statusCode===204)&&delete Le.headers["content-encoding"],(Le.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":yt.push(TOi.default.createUnzip(AYp)),delete Le.headers["content-encoding"];break;case"deflate":yt.push(new SYp),yt.push(TOi.default.createUnzip(AYp)),delete Le.headers["content-encoding"];break;case"br":qYp&&(yt.push(TOi.default.createBrotliDecompress(fkD)),delete Le.headers["content-encoding"])}Ae=yt.length>1?Ltn.default.pipeline(yt,hs.noop):yt[0];let Pe=Ltn.default.finished(Ae,()=>{Pe(),P()}),St={status:Le.statusCode,statusText:Le.statusMessage,headers:new h3(Le.headers),config:t,request:Ct};if(s==="stream")St.data=Ae,rar(i,n,St);else{let at=[],Oe=0;Ae.on("data",function(bt){at.push(bt),Oe+=bt.length,t.maxContentLength>-1&&Oe>t.maxContentLength&&(g=!0,Ae.destroy(),n(new n_("maxContentLength size of "+t.maxContentLength+" exceeded",n_.ERR_BAD_RESPONSE,t,Ct)))}),Ae.on("aborted",function(){if(g)return;let bt=new n_("stream has been aborted",n_.ERR_BAD_RESPONSE,t,Ct);Ae.destroy(bt),n(bt)}),Ae.on("error",function(bt){O.destroyed||n(n_.from(bt,null,t,Ct))}),Ae.on("end",function(){try{let bt=at.length===1?at[0]:Buffer.concat(at);s!=="arraybuffer"&&(bt=bt.toString(o),(!o||o==="utf8")&&(bt=hs.stripBOM(bt))),St.data=bt}catch(bt){return n(n_.from(bt,null,t,St.request,St))}rar(i,n,St)})}m.once("abort",at=>{Ae.destroyed||(Ae.emit("error",at),Ae.destroy())})}),m.once("abort",me=>{n(me),O.destroy(me)}),O.on("error",function(Le){n(n_.from(Le,null,t,O))}),O.on("socket",function(Le){Le.setKeepAlive(!0,1e3*60)}),t.timeout){let me=parseInt(t.timeout,10);if(Number.isNaN(me)){n(new n_("error trying to parse `config.timeout` to int",n_.ERR_BAD_OPTION_VALUE,t,O));return}O.setTimeout(me,function(){if(v)return;let yt=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",De=t.transitional||NWn;t.timeoutErrorMessage&&(yt=t.timeoutErrorMessage),n(new n_(yt,De.clarifyTimeoutError?n_.ETIMEDOUT:n_.ECONNABORTED,t,O)),D()})}if(hs.isStream(u)){let me=!1,Le=!1;u.on("end",()=>{me=!0}),u.once("error",yt=>{Le=!0,O.destroy(yt)}),u.on("close",()=>{!me&&!Le&&D(new ZAe("Request stream has been aborted",t,O))}),u.pipe(O)}else O.end(u)})};var VYp=rq.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,rq.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(rq.origin),rq.navigator&&/(msie|trident)/i.test(rq.navigator.userAgent)):()=>!0;var WYp=rq.hasStandardBrowserEnv?{write(e,t,r,i,n,a){let u=[e+"="+encodeURIComponent(t)];hs.isNumber(r)&&u.push("expires="+new Date(r).toGMTString()),hs.isString(i)&&u.push("path="+i),hs.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 HYp=e=>e instanceof h3?{...e}:e;function WGt(e,t){t=t||{};let r={};function i(s,o,l,v){return hs.isPlainObject(s)&&hs.isPlainObject(o)?hs.merge.call({caseless:v},s,o):hs.isPlainObject(o)?hs.merge({},o):hs.isArray(o)?o.slice():o}function n(s,o,l,v){if(hs.isUndefined(o)){if(!hs.isUndefined(s))return i(void 0,s,l,v)}else return i(s,o,l,v)}function a(s,o){if(!hs.isUndefined(o))return i(void 0,o)}function u(s,o){if(hs.isUndefined(o)){if(!hs.isUndefined(s))return i(void 0,s)}else return i(void 0,o)}function c(s,o,l){if(l in t)return i(s,o);if(l 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:c,headers:(s,o,l)=>n(HYp(s),HYp(o),l,!0)};return hs.forEach(Object.keys({...e,...t}),function(o){let l=d[o]||n,v=l(e[o],t[o],o);hs.isUndefined(v)&&l!==c||(r[o]=v)}),r}var KGo=e=>{let t=WGt({},e),{data:r,withXSRFToken:i,xsrfHeaderName:n,xsrfCookieName:a,headers:u,auth:c}=t;t.headers=u=h3.from(u),t.url=xtn(Rtn(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&u.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):"")));let d;if(hs.isFormData(r)){if(rq.hasStandardBrowserEnv||rq.hasStandardBrowserWebWorkerEnv)u.setContentType(void 0);else if((d=u.getContentType())!==!1){let[s,...o]=d?d.split(";").map(l=>l.trim()).filter(Boolean):[];u.setContentType([s||"multipart/form-data",...o].join("; "))}}if(rq.hasStandardBrowserEnv&&(i&&hs.isFunction(i)&&(i=i(t)),i||i!==!1&&VYp(t.url))){let s=n&&a&&WYp.read(a);s&&u.set(n,s)}return t};var gkD=typeof XMLHttpRequest<"u",$Yp=gkD&&function(e){return new Promise(function(r,i){let n=KGo(e),a=n.data,u=h3.from(n.headers).normalize(),{responseType:c,onUploadProgress:d,onDownloadProgress:s}=n,o,l,v,g,O;function m(){g&&g(),O&&O(),n.cancelToken&&n.cancelToken.unsubscribe(o),n.signal&&n.signal.removeEventListener("abort",o)}let P=new XMLHttpRequest;P.open(n.method.toUpperCase(),n.url,!0),P.timeout=n.timeout;function D(){if(!P)return;let M=h3.from("getAllResponseHeaders"in P&&P.getAllResponseHeaders()),T={data:!c||c==="text"||c==="json"?P.responseText:P.response,status:P.status,statusText:P.statusText,headers:M,config:e,request:P};rar(function(G){r(G),m()},function(G){i(G),m()},T),P=null}"onloadend"in P?P.onloadend=D:P.onreadystatechange=function(){!P||P.readyState!==4||P.status===0&&!(P.responseURL&&P.responseURL.indexOf("file:")===0)||setTimeout(D)},P.onabort=function(){P&&(i(new n_("Request aborted",n_.ECONNABORTED,e,P)),P=null)},P.onerror=function(){i(new n_("Network Error",n_.ERR_NETWORK,e,P)),P=null},P.ontimeout=function(){let E=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded",T=n.transitional||NWn;n.timeoutErrorMessage&&(E=n.timeoutErrorMessage),i(new n_(E,T.clarifyTimeoutError?n_.ETIMEDOUT:n_.ECONNABORTED,e,P)),P=null},a===void 0&&u.setContentType(null),"setRequestHeader"in P&&hs.forEach(u.toJSON(),function(E,T){P.setRequestHeader(T,E)}),hs.isUndefined(n.withCredentials)||(P.withCredentials=!!n.withCredentials),c&&c!=="json"&&(P.responseType=n.responseType),s&&([v,O]=qOi(s,!0),P.addEventListener("progress",v)),d&&P.upload&&([l,g]=qOi(d),P.upload.addEventListener("progress",l),P.upload.addEventListener("loadend",g)),(n.cancelToken||n.signal)&&(o=M=>{P&&(i(!M||M.type?new ZAe(null,e,P):M),P.abort(),P=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));let A=B7a(n.url);if(A&&rq.protocols.indexOf(A)===-1){i(new n_("Unsupported protocol "+A+":",n_.ERR_BAD_REQUEST,e));return}P.send(a||null)})};var OkD=(e,t)=>{let{length:r}=e=e?e.filter(Boolean):[];if(t||r){let i=new AbortController,n,a=function(s){if(!n){n=!0,c();let o=s instanceof Error?s:this.reason;i.abort(o instanceof n_?o:new ZAe(o instanceof Error?o.message:o))}},u=t&&setTimeout(()=>{u=null,a(new n_(`timeout ${t} of ms exceeded`,n_.ETIMEDOUT))},t),c=()=>{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=()=>hs.asap(c),d}},GYp=OkD;var mkD=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},PkD=async function*(e,t){for await(let r of jkD(e))yield*mkD(r,t)},jkD=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()}},Bpc=(e,t,r,i)=>{let n=PkD(e,t),a=0,u,c=d=>{u||(u=!0,i&&i(d))};return new ReadableStream({async pull(d){try{let{done:s,value:o}=await n.next();if(s){c(),d.close();return}let l=o.byteLength;if(r){let v=a+=l;r(v)}d.enqueue(new Uint8Array(o))}catch(s){throw c(s),s}},cancel(d){return c(d),n.return()}},{highWaterMark:2})};var XGo=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",JYp=XGo&&typeof ReadableStream=="function",wkD=XGo&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),KYp=(e,...t)=>{try{return!!e(...t)}catch{return!1}},SkD=JYp&&KYp(()=>{let e=!1,t=new Request(rq.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),QYp=64*1024,Ipc=JYp&&KYp(()=>hs.isReadableStream(new Response("").body)),YGo={stream:Ipc&&(e=>e.body)};XGo&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!YGo[t]&&(YGo[t]=hs.isFunction(e[t])?r=>r[t]():(r,i)=>{throw new n_(`Response type '${t}' is not supported`,n_.ERR_NOT_SUPPORT,i)})})})(new Response);var DkD=async e=>{if(e==null)return 0;if(hs.isBlob(e))return e.size;if(hs.isSpecCompliantForm(e))return(await new Request(rq.origin,{method:"POST",body:e}).arrayBuffer()).byteLength;if(hs.isArrayBufferView(e)||hs.isArrayBuffer(e))return e.byteLength;if(hs.isURLSearchParams(e)&&(e=e+""),hs.isString(e))return(await wkD(e)).byteLength},EkD=async(e,t)=>{let r=hs.toFiniteNumber(e.getContentLength());return r??DkD(t)},YYp=XGo&&(async e=>{let{url:t,method:r,data:i,signal:n,cancelToken:a,timeout:u,onDownloadProgress:c,onUploadProgress:d,responseType:s,headers:o,withCredentials:l="same-origin",fetchOptions:v}=KGo(e);s=s?(s+"").toLowerCase():"text";let g=GYp([n,a&&a.toAbortSignal()],u),O,m=g&&g.unsubscribe&&(()=>{g.unsubscribe()}),P;try{if(d&&SkD&&r!=="get"&&r!=="head"&&(P=await EkD(o,i))!==0){let T=new Request(t,{method:"POST",body:i,duplex:"half"}),z;if(hs.isFormData(i)&&(z=T.headers.get("content-type"))&&o.setContentType(z),T.body){let[G,I]=UWn(P,qOi(VWn(d)));i=Bpc(T.body,QYp,G,I)}}hs.isString(l)||(l=l?"include":"omit");let D="credentials"in Request.prototype;O=new Request(t,{...v,signal:g,method:r.toUpperCase(),headers:o.normalize().toJSON(),body:i,duplex:"half",credentials:D?l:void 0});let A=await fetch(O,v),M=Ipc&&(s==="stream"||s==="response");if(Ipc&&(c||M&&m)){let T={};["status","statusText","headers"].forEach(R=>{T[R]=A[R]});let z=hs.toFiniteNumber(A.headers.get("content-length")),[G,I]=c&&UWn(z,qOi(VWn(c),!0))||[];A=new Response(Bpc(A.body,QYp,G,()=>{I&&I(),m&&m()}),T)}s=s||"text";let E=await YGo[hs.findKey(YGo,s)||"text"](A,e);return!M&&m&&m(),await new Promise((T,z)=>{rar(T,z,{data:E,headers:h3.from(A.headers),status:A.status,statusText:A.statusText,config:e,request:O})})}catch(D){throw m&&m(),D&&D.name==="TypeError"&&/Load failed|fetch/i.test(D.message)?Object.assign(new n_("Network Error",n_.ERR_NETWORK,e,O),{cause:D.cause||D}):n_.from(D,D&&D.code,e,O)}});var zpc={http:UYp,xhr:$Yp,fetch:YYp};hs.forEach(zpc,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var XYp=e=>`- ${e}`,MkD=e=>hs.isFunction(e)||e===null||e===!1,ZGo={getAdapter:e=>{e=hs.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,!MkD(r)&&(i=zpc[(u=String(r)).toLowerCase()],i===void 0))throw new n_(`Unknown adapter '${u}'`);if(i)break;n[u||"#"+a]=i}if(!i){let a=Object.entries(n).map(([c,d])=>`adapter ${c} `+(d===!1?"is not supported by the environment":"is not available in the build")),u=t?a.length>1?`since :
|
|
@@ -1961,7 +1961,7 @@ ${E}${A}${T}${gm_.default.cursorHide}`});function Sru({message:e,error:t,logger:
|
|
|
1961
1961
|
Run ${Bs.cyan("fern generator upgrade")} to upgrade your generators.`),n.length>2&&(r+=`
|
|
1962
1962
|
Run ${Bs.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),HWn(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function aSc({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!Vm_(e))return;let n=t??"",a=e.filter(c=>c.isUpgradeAvailable);r!=null&&(a=a.slice(0,r+1));let u=a.sort((c,d)=>c.generatorName.localeCompare(d.generatorName)||c.currentVersion.localeCompare(d.currentVersion));for(let c of u)n+=`
|
|
1963
1963
|
${await GTE(c.generatorName)} (${c.apiName!=null?"API: "+c.apiName+", ":""}Group: ${c.generatorGroup}) `+Bs.dim(c.currentVersion)+Bs.reset(" \u2192 ")+Bs.green(c.latestVersion);return n+=`
|
|
1964
|
-
`,i?HWn(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function GTE(e){let r=await new Um_.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 QTE({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await Hm_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,o,l)=>{c.versions[s]==null&&(c.versions[s]={});let v=vIi(o.name,l),g=await Qrr({generatorName:v,cliVersion:e.environment.packageVersion,currentGeneratorVersion:o.version,channel:n,includeMajor:a,context:l});g!=null&&(c.versions[s][o.name]={previousVersion:o.version,latestVersion:g})},generatorFilter:r,groupFilter:i}),c}let u={type:"multiApi",versions:{}};return await Hm_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,d,s,o)=>{if(c==null)return;u.versions[c]==null&&(u.versions[c]={}),u.versions[c][d]==null&&(u.versions[c][d]={});let l=vIi(s.name,o),v=await Qrr({generatorName:l,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:o});v!=null&&(u.versions[c][d][s.name]={previousVersion:s.version,latestVersion:v})},generatorFilter:r,groupFilter:i}),u}async function Hm_({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async u=>{let c=await gGt({absolutePathToWorkspace:a.absoluteFilePath,context:u});if(!(c==null||c.groups==null)){for(let d of c.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 $m_(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[u,c]of Object.entries(a)){r.debug(`Checking if ${u} in group ${n} has an upgrade available...`);let d=Mue(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:u,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return i}async function Aru({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let c=await QTE({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(c.type==="multiApi")for(let[d,s]of Object.entries(c.versions))u.push(...$m_(s,d,t.logger));else u.push(...$m_(c.versions,void 0,t.logger))}return u}var V8a=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(),c=u?`status code ${u}`:"an unknown error";super(`Request failed with ${c}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var YQn=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var oSc=(()=>{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})(),Gm_=typeof globalThis.AbortController=="function",Qm_=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",Jm_=typeof globalThis.ReadableStream=="function",Km_=typeof globalThis.FormData=="function",qru=["get","post","put","patch","head","delete"],JTE=()=>{};JTE();var Ym_={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},Tru=2147483647,Xm_=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,Cru=Symbol("stop"),Zm_={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},km_={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 KTE=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=Xm_,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},eP_=(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:c,value:d}=await a.read();if(c){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})},tP_=(e,t,r)=>{let i=KTE(r??e.body),n=0;return new Request(e,{duplex:"half",body:new ReadableStream({async start(a){let u=e.body instanceof ReadableStream?e.body.getReader():new Response("").body.getReader();async function c(){let{done:d,value:s}=await u.read();if(d){t&&t({percent:1,transferredBytes:n,totalBytes:Math.max(i,n)},new Uint8Array),a.close();return}n+=s.byteLength;let o=i===0?0:n/i;(i<n||o===1)&&(o=.99),t&&t({percent:Number(o.toFixed(2)),transferredBytes:n,totalBytes:i},s),a.enqueue(s),await c()}await c()}})})};var XQn=e=>e!==null&&typeof e=="object";var W8a=(...e)=>{for(let t of e)if((!XQn(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return cSc({},...e)},uSc=(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 Bru(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:cSc(e[r]??[],t[r]??[])}var sSc=(e={},t={})=>({beforeRequest:Bru(e,t,"beforeRequest"),beforeRetry:Bru(e,t,"beforeRetry"),afterResponse:Bru(e,t,"afterResponse"),beforeError:Bru(e,t,"beforeError")}),cSc=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(XQn(n)){for(let[a,u]of Object.entries(n))XQn(u)&&a in t&&(u=cSc(t[a],u)),t={...t,[a]:u};XQn(n.hooks)&&(i=sSc(i,n.hooks),t.hooks=i),XQn(n.headers)&&(r=uSc(r,n.headers),t.headers=r)}return t};var iP_=e=>qru.includes(e)?e.toUpperCase():e,YTE=["get","put","head","delete","options","trace"],XTE=[408,413,429,500,502,503,504],ZTE=[413,429,503],rP_={limit:2,methods:YTE,statusCodes:XTE,afterStatusCodes:ZTE,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},nP_=(e={})=>{if(typeof e=="number")return{...rP_,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");return{...rP_,...e}};async function lSc(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new YQn(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function fSc(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 aP_=(e,t)=>{let r={};for(let i in t)!(i in km_)&&!(i in Zm_)&&!(i in e)&&(r[i]=t[i]);return r},oP_=e=>e===void 0?!1:Array.isArray(e)?e.length>0:e instanceof URLSearchParams?e.size>0:typeof e=="object"?Object.keys(e).length>0:typeof e=="string"?e.trim().length>0:!!e;var H8a=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>Tru)throw new RangeError(`The \`timeout\` option cannot be greater than ${Tru}`);await Promise.resolve();let c=await i._fetch();for(let d of i._options.hooks.afterResponse){let s=await d(i.request,i._options,i._decorateResponse(c.clone()));s instanceof globalThis.Response&&(c=s)}if(i._decorateResponse(c),!c.ok&&i._options.throwHttpErrors){let d=new V8a(c,i.request,i._options);for(let s of i._options.hooks.beforeError)d=await s(d);throw d}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Jm_)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return eP_(c.clone(),i._options.onDownloadProgress)}return c},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[c,d]of Object.entries(Ym_))c==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(u[c]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||d);let s=await u;if(c==="json"){if(s.status===204||(await s.clone().arrayBuffer()).byteLength===0)return"";if(r.parseJson)return r.parseJson(await s.text())}return s[c]()});return u}request;abortController;_retryCount=0;_input;_options;constructor(t,r={}){if(this._input=t,this._options={...r,headers:uSc(this._input.headers,r.headers),hooks:sSc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:iP_(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:nP_(r.retry),throwHttpErrors:r.throwHttpErrors!==!1,timeout:r.timeout??1e4,fetch:r.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(Gm_&&Qm_){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(oSc&&(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),oP_(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);(Km_&&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(!oSc)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=tP_(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof YQn)throw t;if(t instanceof V8a){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),Tru);if(this._retryCount<1)throw r;await fSc(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})===Cru)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=aP_(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):lSc(r,t,this.abortController,this._options)}};var dSc=e=>{let t=(r,i)=>H8a.create(r,W8a(e,i));for(let r of qru)t[r]=(i,n)=>H8a.create(i,W8a(e,n,{method:r}));return t.create=r=>dSc(W8a(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),dSc(W8a(e,r))),t.stop=Cru,t},kTE=dSc(),uP_=kTE;var qP_=ui(AP_(),1);function vSc(e){let t=(0,qP_.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var wj_=ui(jj_(),1),Sj_=ui(agi(),1),qSc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},TSc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function CSc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??vSc(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,wj_.default)(a.toString(),{recursive:!0}),d={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete d.accept,c&&(d.authorization=`${c.type} ${c.token}`);let s;try{s=await uP_(u,{headers:d,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new qSc(e):l}if(t.allVersions)return s;let o=new TSc(e,r);if(s["dist-tags"][r]){let{time:l}=s;s=s.versions[s["dist-tags"][r]],s.time=l}else if(r){let l=!!s.versions[r];if(i&&!l)for(let[g,O]of Object.entries(s.versions))O.deprecated&&delete s.versions[g];if(!l){let g=Object.keys(s.versions);if(r=Sj_.default.maxSatisfying(g,r),!r)throw o}let{time:v}=s;if(s=s.versions[r],s.time=v,!s)throw o}return s}async function Y8a(e,t){let{version:r}=await CSc(e.toLowerCase(),t);return r}async function n3i({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:Y8a(e.packageName,{version:t?"prerelease":"latest"})}var Dj_=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],$ru=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Sb.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new Mru(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.75.0"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Bs.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new H8}failWithoutThrowing(t,r){this.didSucceed=!1,Sru({message:t,error:r,logger:this.logger})}async exit({code:t}={}){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await zWn()).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 Wm_({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
1964
|
+
`,i?HWn(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function GTE(e){let r=await new Um_.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 QTE({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await Hm_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,o,l)=>{c.versions[s]==null&&(c.versions[s]={});let v=vIi(o.name,l),g=await Qrr({generatorName:v,cliVersion:e.environment.packageVersion,currentGeneratorVersion:o.version,channel:n,includeMajor:a,context:l});g!=null&&(c.versions[s][o.name]={previousVersion:o.version,latestVersion:g})},generatorFilter:r,groupFilter:i}),c}let u={type:"multiApi",versions:{}};return await Hm_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,d,s,o)=>{if(c==null)return;u.versions[c]==null&&(u.versions[c]={}),u.versions[c][d]==null&&(u.versions[c][d]={});let l=vIi(s.name,o),v=await Qrr({generatorName:l,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:o});v!=null&&(u.versions[c][d][s.name]={previousVersion:s.version,latestVersion:v})},generatorFilter:r,groupFilter:i}),u}async function Hm_({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async u=>{let c=await gGt({absolutePathToWorkspace:a.absoluteFilePath,context:u});if(!(c==null||c.groups==null)){for(let d of c.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 $m_(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[u,c]of Object.entries(a)){r.debug(`Checking if ${u} in group ${n} has an upgrade available...`);let d=Mue(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:u,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return i}async function Aru({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let c=await QTE({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(c.type==="multiApi")for(let[d,s]of Object.entries(c.versions))u.push(...$m_(s,d,t.logger));else u.push(...$m_(c.versions,void 0,t.logger))}return u}var V8a=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(),c=u?`status code ${u}`:"an unknown error";super(`Request failed with ${c}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var YQn=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var oSc=(()=>{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})(),Gm_=typeof globalThis.AbortController=="function",Qm_=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",Jm_=typeof globalThis.ReadableStream=="function",Km_=typeof globalThis.FormData=="function",qru=["get","post","put","patch","head","delete"],JTE=()=>{};JTE();var Ym_={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},Tru=2147483647,Xm_=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,Cru=Symbol("stop"),Zm_={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},km_={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 KTE=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=Xm_,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},eP_=(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:c,value:d}=await a.read();if(c){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})},tP_=(e,t,r)=>{let i=KTE(r??e.body),n=0;return new Request(e,{duplex:"half",body:new ReadableStream({async start(a){let u=e.body instanceof ReadableStream?e.body.getReader():new Response("").body.getReader();async function c(){let{done:d,value:s}=await u.read();if(d){t&&t({percent:1,transferredBytes:n,totalBytes:Math.max(i,n)},new Uint8Array),a.close();return}n+=s.byteLength;let o=i===0?0:n/i;(i<n||o===1)&&(o=.99),t&&t({percent:Number(o.toFixed(2)),transferredBytes:n,totalBytes:i},s),a.enqueue(s),await c()}await c()}})})};var XQn=e=>e!==null&&typeof e=="object";var W8a=(...e)=>{for(let t of e)if((!XQn(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return cSc({},...e)},uSc=(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 Bru(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:cSc(e[r]??[],t[r]??[])}var sSc=(e={},t={})=>({beforeRequest:Bru(e,t,"beforeRequest"),beforeRetry:Bru(e,t,"beforeRetry"),afterResponse:Bru(e,t,"afterResponse"),beforeError:Bru(e,t,"beforeError")}),cSc=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(XQn(n)){for(let[a,u]of Object.entries(n))XQn(u)&&a in t&&(u=cSc(t[a],u)),t={...t,[a]:u};XQn(n.hooks)&&(i=sSc(i,n.hooks),t.hooks=i),XQn(n.headers)&&(r=uSc(r,n.headers),t.headers=r)}return t};var iP_=e=>qru.includes(e)?e.toUpperCase():e,YTE=["get","put","head","delete","options","trace"],XTE=[408,413,429,500,502,503,504],ZTE=[413,429,503],rP_={limit:2,methods:YTE,statusCodes:XTE,afterStatusCodes:ZTE,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},nP_=(e={})=>{if(typeof e=="number")return{...rP_,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");return{...rP_,...e}};async function lSc(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new YQn(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function fSc(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 aP_=(e,t)=>{let r={};for(let i in t)!(i in km_)&&!(i in Zm_)&&!(i in e)&&(r[i]=t[i]);return r},oP_=e=>e===void 0?!1:Array.isArray(e)?e.length>0:e instanceof URLSearchParams?e.size>0:typeof e=="object"?Object.keys(e).length>0:typeof e=="string"?e.trim().length>0:!!e;var H8a=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>Tru)throw new RangeError(`The \`timeout\` option cannot be greater than ${Tru}`);await Promise.resolve();let c=await i._fetch();for(let d of i._options.hooks.afterResponse){let s=await d(i.request,i._options,i._decorateResponse(c.clone()));s instanceof globalThis.Response&&(c=s)}if(i._decorateResponse(c),!c.ok&&i._options.throwHttpErrors){let d=new V8a(c,i.request,i._options);for(let s of i._options.hooks.beforeError)d=await s(d);throw d}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Jm_)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return eP_(c.clone(),i._options.onDownloadProgress)}return c},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[c,d]of Object.entries(Ym_))c==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(u[c]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||d);let s=await u;if(c==="json"){if(s.status===204||(await s.clone().arrayBuffer()).byteLength===0)return"";if(r.parseJson)return r.parseJson(await s.text())}return s[c]()});return u}request;abortController;_retryCount=0;_input;_options;constructor(t,r={}){if(this._input=t,this._options={...r,headers:uSc(this._input.headers,r.headers),hooks:sSc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:iP_(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:nP_(r.retry),throwHttpErrors:r.throwHttpErrors!==!1,timeout:r.timeout??1e4,fetch:r.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(Gm_&&Qm_){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(oSc&&(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),oP_(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);(Km_&&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(!oSc)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=tP_(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof YQn)throw t;if(t instanceof V8a){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),Tru);if(this._retryCount<1)throw r;await fSc(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})===Cru)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=aP_(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):lSc(r,t,this.abortController,this._options)}};var dSc=e=>{let t=(r,i)=>H8a.create(r,W8a(e,i));for(let r of qru)t[r]=(i,n)=>H8a.create(i,W8a(e,n,{method:r}));return t.create=r=>dSc(W8a(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),dSc(W8a(e,r))),t.stop=Cru,t},kTE=dSc(),uP_=kTE;var qP_=ui(AP_(),1);function vSc(e){let t=(0,qP_.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var wj_=ui(jj_(),1),Sj_=ui(agi(),1),qSc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},TSc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function CSc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??vSc(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,wj_.default)(a.toString(),{recursive:!0}),d={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete d.accept,c&&(d.authorization=`${c.type} ${c.token}`);let s;try{s=await uP_(u,{headers:d,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new qSc(e):l}if(t.allVersions)return s;let o=new TSc(e,r);if(s["dist-tags"][r]){let{time:l}=s;s=s.versions[s["dist-tags"][r]],s.time=l}else if(r){let l=!!s.versions[r];if(i&&!l)for(let[g,O]of Object.entries(s.versions))O.deprecated&&delete s.versions[g];if(!l){let g=Object.keys(s.versions);if(r=Sj_.default.maxSatisfying(g,r),!r)throw o}let{time:v}=s;if(s=s.versions[r],s.time=v,!s)throw o}return s}async function Y8a(e,t){let{version:r}=await CSc(e.toLowerCase(),t);return r}async function n3i({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:Y8a(e.packageName,{version:t?"prerelease":"latest"})}var Dj_=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],$ru=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Sb.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new Mru(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.75.1"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Bs.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new H8}failWithoutThrowing(t,r){this.didSucceed=!1,Sru({message:t,error:r,logger:this.logger})}async exit({code:t}={}){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await zWn()).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 Wm_({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
1965
1965
|
`)||(r+=`
|
|
1966
1966
|
`),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=MHs(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 x8a(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 H8}finally{i.finish()}return n}async instrumentPostHogEvent(t){this.isLocal||(await zWn()).sendEvent(t)}logger=utr((t,...r)=>this.log(t,...r));stderr=utr((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=Ej_(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?Ej_(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=Dj_[this.numTasks++%Dj_.length],u=Bs.hex(a)(n);return{...this.constructTaskInit(),logPrefix:u}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===CI.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=>ABi.indexOf(n.level)>=ABi.indexOf(this.logLevel));this.ttyAwareLogger.log(i,{includeDebugInfo:this.logLevel===Sb.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 n3i({cliEnvironment:this.environment,includePreReleases:t}),i=Mue(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await Aru({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){return await H1c({message:t,default:r})}async getInput(t){return await $1c({message:t.message,default:t.default})}};function Ej_(e){return`[${e}]:`}var EQt=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 Eqe=class extends EQt{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 Smi={enableUniqueErrorsPerEndpoint:!1,detectGlobalHeaders:!0,objectQueryParameters:!1,respectReadonlySchemas:!1,respectNullableSchemas:!1,onlyIncludeReferencedSchemas:!1,inlinePathParameters:!1,useBytesForBinaryResponse:!1,respectForwardCompatibleEnums:!1};function X8a({options:e,overrides:t}){return{enableUniqueErrorsPerEndpoint:t?.enableUniqueErrorsPerEndpoint??e?.enableUniqueErrorsPerEndpoint??Smi.enableUniqueErrorsPerEndpoint,detectGlobalHeaders:t?.detectGlobalHeaders??e?.detectGlobalHeaders??Smi.detectGlobalHeaders,objectQueryParameters:t?.objectQueryParameters??e?.objectQueryParameters??Smi.objectQueryParameters,respectReadonlySchemas:t?.respectReadonlySchemas??e?.respectReadonlySchemas??Smi.respectReadonlySchemas,respectNullableSchemas:t?.respectNullableSchemas??e?.respectNullableSchemas??Smi.respectNullableSchemas,onlyIncludeReferencedSchemas:t?.onlyIncludeReferencedSchemas??e?.onlyIncludeReferencedSchemas??Smi.onlyIncludeReferencedSchemas,inlinePathParameters:t?.inlinePathParameters??e?.inlinePathParameters??Smi.inlinePathParameters,useBytesForBinaryResponse:t?.useBytesForBinaryResponse??e?.useBytesForBinaryResponse??Smi.useBytesForBinaryResponse,respectForwardCompatibleEnums:t?.respectForwardCompatibleEnums??e?.respectForwardCompatibleEnums??Smi.respectForwardCompatibleEnums}}var qK={openapi:e=>({...e,type:"openapi",_visit:function(t){return qK._visit(this,t)}}),protobuf:e=>({...e,type:"protobuf",_visit:function(t){return qK._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 nJn={protobuf:e=>({...e,type:"protobuf",_visit:function(t){return nJn._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var PU={basic:e=>({...e,type:"basic",_visit:function(t){return PU._visit(this,t)}}),bearer:e=>({...e,type:"bearer",_visit:function(t){return PU._visit(this,t)}}),header:e=>({...e,type:"header",_visit:function(t){return PU._visit(this,t)}}),query:e=>({...e,type:"query",_visit:function(t){return PU._visit(this,t)}}),oauth:e=>({...e,type:"oauth",_visit:function(t){return PU._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"basic":return t.basic(e);case"bearer":return t.bearer(e);case"header":return t.header(e);case"query":return t.query(e);case"oauth":return t.oauth(e);default:return t._other(e)}}};var Yg={primitive:e=>({value:e,type:"primitive",_visit:function(t){return Yg._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Yg._visit(this,t)}}),array:e=>({value:e,type:"array",_visit:function(t){return Yg._visit(this,t)}}),map:e=>({value:e,type:"map",_visit:function(t){return Yg._visit(this,t)}}),enum:e=>({value:e,type:"enum",_visit:function(t){return Yg._visit(this,t)}}),literal:e=>({value:e,type:"literal",_visit:function(t){return Yg._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Yg._visit(this,t)}}),unknown:e=>({value:e,type:"unknown",_visit:function(t){return Yg._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e.value);case"object":return t.object(e);case"array":return t.array(e.value);case"map":return t.map(e.value);case"enum":return t.enum(e.value);case"literal":return t.literal(e.value);case"oneOf":return t.oneOf(e.value);case"unknown":return t.unknown(e.value);default:return t._other(e)}}};var D_={int:e=>({value:e,type:"int",_visit:function(t){return D_._visit(this,t)}}),int64:e=>({value:e,type:"int64",_visit:function(t){return D_._visit(this,t)}}),uint:e=>({value:e,type:"uint",_visit:function(t){return D_._visit(this,t)}}),uint64:e=>({value:e,type:"uint64",_visit:function(t){return D_._visit(this,t)}}),float:e=>({value:e,type:"float",_visit:function(t){return D_._visit(this,t)}}),double:e=>({value:e,type:"double",_visit:function(t){return D_._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return D_._visit(this,t)}}),datetime:e=>({value:e,type:"datetime",_visit:function(t){return D_._visit(this,t)}}),date:e=>({value:e,type:"date",_visit:function(t){return D_._visit(this,t)}}),base64:e=>({value:e,type:"base64",_visit:function(t){return D_._visit(this,t)}}),boolean:e=>({value:e,type:"boolean",_visit:function(t){return D_._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 a3i={boolean:e=>({value:e,type:"boolean",_visit:function(t){return a3i._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return a3i._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 o3i={discriminated:e=>({value:e,type:"discriminated",_visit:function(t){return o3i._visit(this,t)}}),undiscriminated:e=>({value:e,type:"undiscriminated",_visit:function(t){return o3i._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 v$={GenerallyAvailable:"GenerallyAvailable",Beta:"Beta",Deprecated:"Deprecated",_visit:(e,t)=>{switch(e){case v$.GenerallyAvailable:return t.generallyAvailable();case v$.Beta:return t.beta();case v$.Deprecated:return t.deprecated();default:return t._other()}}};var O6e={cursor:e=>({...e,type:"cursor",_visit:function(t){return O6e._visit(this,t)}}),offset:e=>({...e,type:"offset",_visit:function(t){return O6e._visit(this,t)}}),custom:e=>({...e,type:"custom",_visit:function(t){return O6e._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 Dmi={language:e=>({...e,type:"language",_visit:function(t){return Dmi._visit(this,t)}}),sdk:e=>({...e,type:"sdk",_visit:function(t){return Dmi._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 b$={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 b$.Curl:return t.curl();case b$.Python:return t.python();case b$.Javascript:return t.javascript();case b$.Typescript:return t.typescript();case b$.Go:return t.go();case b$.Ruby:return t.ruby();case b$.Csharp:return t.csharp();case b$.Java:return t.java();case b$.Js:return t.js();case b$.Node:return t.node();case b$.Ts:return t.ts();case b$.Nodets:return t.nodets();case b$.Golang:return t.golang();case b$.Dotnet:return t.dotnet();case b$.Jvm:return t.jvm();default:return t._other()}}};var MQt={unknown:e=>({value:e,type:"unknown",_visit:function(t){return MQt._visit(this,t)}}),full:e=>({...e,type:"full",_visit:function(t){return MQt._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 AQt={withStreaming:e=>({...e,type:"withStreaming",_visit:function(t){return AQt._visit(this,t)}}),withoutStreaming:e=>({value:e,type:"withoutStreaming",_visit:function(t){return AQt._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 g$={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD",Options:"OPTIONS",Trace:"TRACE",_visit:(e,t)=>{switch(e){case g$.Get:return t.get();case g$.Post:return t.post();case g$.Put:return t.put();case g$.Patch:return t.patch();case g$.Delete:return t.delete();case g$.Head:return t.head();case g$.Options:return t.options();case g$.Trace:return t.trace();default:return t._other()}}};var Zar={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return Zar._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return Zar._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return Zar._visit(this,t)}}),formUrlEncoded:e=>({...e,type:"formUrlEncoded",_visit:function(t){return Zar._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"octetStream":return t.octetStream(e);case"multipart":return t.multipart(e);case"json":return t.json(e);case"formUrlEncoded":return t.formUrlEncoded(e);default:return t._other(e)}}};var Emi={file:e=>({...e,type:"file",_visit:function(t){return Emi._visit(this,t)}}),json:e=>({value:e,type:"json",_visit:function(t){return Emi._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 TK={file:e=>({...e,type:"file",_visit:function(t){return TK._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return TK._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return TK._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return TK._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return TK._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return TK._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return TK._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 Ov={primitive:e=>({...e,type:"primitive",_visit:function(t){return Ov._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Ov._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return Ov._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return Ov._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return Ov._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return Ov._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return Ov._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return Ov._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Ov._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return Ov._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return Ov._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 xw={int:e=>({...e,type:"int",_visit:function(t){return xw._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return xw._visit(this,t)}}),uint:()=>({type:"uint",_visit:function(e){return xw._visit(this,e)}}),uint64:()=>({type:"uint64",_visit:function(e){return xw._visit(this,e)}}),float:()=>({type:"float",_visit:function(e){return xw._visit(this,e)}}),double:e=>({...e,type:"double",_visit:function(t){return xw._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return xw._visit(this,t)}}),datetime:()=>({type:"datetime",_visit:function(e){return xw._visit(this,e)}}),date:()=>({type:"date",_visit:function(e){return xw._visit(this,e)}}),base64:()=>({type:"base64",_visit:function(e){return xw._visit(this,e)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return xw._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 px={boolean:e=>({value:e,type:"boolean",_visit:function(t){return px._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return px._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 Mmi={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return Mmi._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return Mmi._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 qee={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return qee._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return qee._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return qee._visit(this,t)}}),formUrlEncoded:e=>({...e,type:"formUrlEncoded",_visit:function(t){return qee._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"octetStream":return t.octetStream(e);case"multipart":return t.multipart(e);case"json":return t.json(e);case"formUrlEncoded":return t.formUrlEncoded(e);default:return t._other(e)}}};var gB={file:e=>({...e,type:"file",_visit:function(t){return gB._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return gB._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return gB._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return gB._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return gB._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return gB._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return gB._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 zl={primitive:e=>({...e,type:"primitive",_visit:function(t){return zl._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return zl._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return zl._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return zl._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return zl._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return zl._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return zl._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return zl._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return zl._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return zl._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return zl._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 Tee={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return Tee._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return Tee._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 vp={int:e=>({...e,type:"int",_visit:function(t){return vp._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return vp._visit(this,t)}}),uint:e=>({...e,type:"uint",_visit:function(t){return vp._visit(this,t)}}),uint64:e=>({...e,type:"uint64",_visit:function(t){return vp._visit(this,t)}}),float:e=>({...e,type:"float",_visit:function(t){return vp._visit(this,t)}}),double:e=>({...e,type:"double",_visit:function(t){return vp._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return vp._visit(this,t)}}),datetime:e=>({...e,type:"datetime",_visit:function(t){return vp._visit(this,t)}}),date:e=>({...e,type:"date",_visit:function(t){return vp._visit(this,t)}}),base64:e=>({...e,type:"base64",_visit:function(t){return vp._visit(this,t)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return vp._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 Av={};Na(Av,{AllOfPropertyConflict:()=>EJn,ArraySchema:()=>snu,ArraySchemaWithExample:()=>Fnu,Availability:()=>tiu,Base64WithExample:()=>Inu,BasicSecurityScheme:()=>niu,BearerSecurityScheme:()=>aiu,BooleanSchema:()=>rnu,BooleanWithExample:()=>znu,BytesResponse:()=>bJn,CasingOverrides:()=>siu,CommonProperty:()=>ynu,CommonPropertyWithExample:()=>Jnu,CursorPagination:()=>Fiu,CustomCodeSample:()=>Riu,CustomCodeSampleLanguage:()=>Iiu,CustomCodeSampleSdk:()=>xiu,CustomPagination:()=>Uiu,DateWithExample:()=>Bnu,DatetimeWithExample:()=>Cnu,DiscriminatedOneOfSchema:()=>_nu,DiscriminatedOneOfSchemaWithExample:()=>Gnu,DoubleSchema:()=>enu,DoubleWithExample:()=>qnu,Encoding:()=>eiu,Endpoint:()=>Viu,EndpointExample:()=>PJn,EndpointResponseExample:()=>Biu,EndpointSdkName:()=>tor,EndpointWithExample:()=>iw_,EnumSchema:()=>sJn,EnumSchemaWithExample:()=>Rnu,EnumValue:()=>c3i,ErrorExample:()=>Miu,FernExample:()=>qiu,FileResponse:()=>yJn,FileSchema:()=>Oiu,FloatWithExample:()=>Anu,FormUrlEncodedRequest:()=>Siu,FullEndpointExample:()=>Niu,FullExample:()=>FT,FullObjectExample:()=>hiu,FullOneOfExample:()=>viu,GlobalHeader:()=>nnu,Header:()=>f3i,HeaderExample:()=>mJn,HeaderSecurityScheme:()=>oiu,HeaderWithExample:()=>_3i,HttpEndpointServer:()=>gJn,HttpError:()=>Aiu,HttpErrorWithExample:()=>wnu,HttpMethod:()=>fJn,IdempotencyHeader:()=>anu,Int64WithExample:()=>Dnu,IntSchema:()=>Ziu,IntWithExample:()=>Snu,JsonRequest:()=>wiu,JsonRequestWithExample:()=>Onu,JsonResponse:()=>vJn,JsonResponseWithExample:()=>qJn,KeyValuePair:()=>yiu,LiteralExample:()=>_iu,LiteralSchema:()=>DJn,LiteralSchemaValue:()=>onu,LongSchema:()=>kiu,MapSchema:()=>cnu,MapSchemaWithExample:()=>Lnu,MultipartRequest:()=>hJn,MultipartRequestProperty:()=>jiu,MultipartRequestPropertyEncoding:()=>Piu,MultipartSchema:()=>miu,NamedFullExample:()=>P6e,Namespace:()=>ciu,NamespaceId:()=>piu,NullableSchema:()=>fnu,NullableSchemaWithExample:()=>Vnu,OauthSecurityScheme:()=>fiu,ObjectProperty:()=>pnu,ObjectPropertyConflictInfo:()=>MJn,ObjectPropertyWithExample:()=>$nu,ObjectSchema:()=>unu,ObjectSchemaWithExample:()=>Wnu,OctetStreamRequest:()=>_Jn,OffsetPagination:()=>Liu,OneOfSchema:()=>dnu,OneOfSchemaWithExample:()=>Hnu,OpenApiIntermediateRepresentation:()=>tw_,OpenApiSource:()=>Yru,OptionalSchema:()=>lnu,OptionalSchemaWithExample:()=>Unu,Pagination:()=>jJn,ParseFormUrlEncodedRequest:()=>mnu,ParseMultipartRequest:()=>gnu,ParseOctetStreamRequest:()=>bnu,PathParameter:()=>dJn,PathParameterExample:()=>Tiu,PathParameterWithExample:()=>vnu,PrimitiveExample:()=>lJn,PrimitiveSchema:()=>p3i,PrimitiveSchemaValue:()=>inu,PrimitiveSchemaValueWithExample:()=>xnu,PrimitiveSchemaWithExample:()=>TJn,PropertyKey:()=>cJn,ProtobufEncoding:()=>kru,ProtobufSource:()=>Xru,QueryParameter:()=>pJn,QueryParameterExample:()=>OJn,QueryParameterWithExample:()=>AJn,QuerySecurityScheme:()=>uiu,ReferencedSchema:()=>ror,Request:()=>Diu,RequestWithExample:()=>Pnu,Response:()=>Eiu,ResponseWithExample:()=>jnu,Schema:()=>tm,SchemaId:()=>Cee,SchemaWithExample:()=>xM,Schemas:()=>Xiu,SdkGroup:()=>liu,SdkGroupInfo:()=>biu,SdkGroupName:()=>l3i,SecurityScheme:()=>diu,SecuritySchemeId:()=>iiu,Server:()=>t5a,Source:()=>Zru,StatusCode:()=>kar,StreamingResponseExample:()=>Ciu,StringSchema:()=>tnu,StringSchemaWithExample:()=>Tnu,SupportedSdkLanguage:()=>ziu,Tag:()=>riu,TagId:()=>Bee,Tags:()=>giu,TextResponse:()=>d3i,Uint64WithExample:()=>Mnu,UintWithExample:()=>Enu,UnDiscriminatedOneOfSchema:()=>hnu,UnDiscriminatedOneOfSchemaWithExample:()=>Qnu,UnknownSchemaWithExample:()=>Nnu,Webhook:()=>Wiu,WebhookExampleCall:()=>SJn,WebhookHttpMethod:()=>wJn,WebhookWithExample:()=>nw_,WebsocketChannel:()=>Yiu,WebsocketHandshake:()=>Hiu,WebsocketHandshakeWithExample:()=>rw_,WebsocketMessageExample:()=>Jiu,WebsocketMessageOrigin:()=>$iu,WebsocketMessageSchema:()=>Giu,WebsocketServer:()=>Qiu,WebsocketSessionExample:()=>Kiu,WithAvailability:()=>oy,WithDescription:()=>Of,WithEncoding:()=>Tue,WithInline:()=>zM,WithName:()=>pg,WithNamespace:()=>x0,WithSdkGroupName:()=>Vm,WithSdkMethodName:()=>eor,WithSource:()=>Ch,WithStatusCode:()=>m6e,WithTitle:()=>Um,commons:()=>RSc,example:()=>NSc,finalIr:()=>FSc,parseIr:()=>LSc});var RSc={};Na(RSc,{BasicSecurityScheme:()=>niu,BearerSecurityScheme:()=>aiu,Encoding:()=>eiu,HeaderSecurityScheme:()=>oiu,Namespace:()=>ciu,NamespaceId:()=>piu,OauthSecurityScheme:()=>fiu,OpenApiSource:()=>Yru,ProtobufEncoding:()=>kru,ProtobufSource:()=>Xru,QuerySecurityScheme:()=>uiu,SchemaId:()=>Cee,SdkGroup:()=>liu,SdkGroupName:()=>l3i,SecurityScheme:()=>diu,SecuritySchemeId:()=>iiu,Server:()=>t5a,Source:()=>Zru,StatusCode:()=>kar,Tag:()=>riu,TagId:()=>Bee,WithAvailability:()=>oy,WithDescription:()=>Of,WithEncoding:()=>Tue,WithInline:()=>zM,WithName:()=>pg,WithNamespace:()=>x0,WithSdkGroupName:()=>Vm,WithSdkMethodName:()=>eor,WithSource:()=>Ch,WithStatusCode:()=>m6e,WithTitle:()=>Um});var gt={};Na(gt,{JsonError:()=>aJn,ParseError:()=>oJn,any:()=>Vj_,bigint:()=>Aj_,boolean:()=>Wj_,booleanLiteral:()=>Uj_,date:()=>qj_,discriminant:()=>Zj_,enum_:()=>Qru,getObjectLikeUtils:()=>qQt,getObjectUtils:()=>ynn,getSchemaUtils:()=>NT,isProperty:()=>s3i,lazy:()=>Tj_,lazyObject:()=>Nj_,list:()=>Kru,number:()=>Hj_,object:()=>Jru,objectWithoutOptionalProperties:()=>Rj_,optional:()=>BSc,property:()=>Bj_,record:()=>Jj_,set:()=>Kj_,string:()=>$j_,stringLiteral:()=>Lj_,transform:()=>ISc,undiscriminatedUnion:()=>Xj_,union:()=>ew_,unknown:()=>Gj_,withParsedProperties:()=>xSc});var fw={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 oq(e,t){return`Expected ${t}. Received ${aBE(e)}.`}function aBE(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 jU(e){return{...e,json:Mj_(e.json),parse:Mj_(e.parse)}}function Mj_(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(`
|
|
1967
1967
|
`)),{ok:!0,value:t}):i}}function Gru(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var aJn=class e extends Error{errors;constructor(t){super(t.map(Gru).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var oJn=class e extends Error{errors;constructor(t){super(t.map(Gru).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function NT(e){return{optional:()=>BSc(e),transform:t=>ISc(e,t),parseOrThrow:(t,r)=>{let i=e.parse(t,r);if(i.ok)return i.value;throw new oJn(i.errors)},jsonOrThrow:(t,r)=>{let i=e.json(t,r);if(i.ok)return i.value;throw new aJn(i.errors)}}}function BSc(e){let t={parse:(r,i)=>r==null?{ok:!0,value:void 0}:e.parse(r,i),json:(r,i)=>i?.omitUndefined&&r===void 0?{ok:!0,value:void 0}:r==null?{ok:!0,value:null}:e.json(r,i),getType:()=>fw.OPTIONAL};return{...t,...NT(t)}}function ISc(e,t){let r={parse:(i,n)=>{let a=e.parse(i,n);return a.ok?{ok:!0,value:t.transform(a.value)}:a},json:(i,n)=>{let a=t.untransform(i);return e.json(a,n)},getType:()=>e.getType()};return{...r,...NT(r)}}function Aj_(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:oq(t,"string")}]}:{ok:!0,value:BigInt(t)},json:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t=="bigint"?{ok:!0,value:t.toString()}:{ok:!1,errors:[{path:r,message:oq(t,"bigint")}]},getType:()=>fw.BIGINT};return{...jU(e),...NT(e)}}var oBE=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;function qj_(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:oq(t,"string")}]}:oBE.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:oq(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:oq(t,"Date object")}]},getType:()=>fw.DATE};return{...jU(e),...NT(e)}}function CK(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{...jU(r),...NT(r)}}}function Qru(e){let t=new Set(e);return CK(fw.ENUM,(i,{allowUnrecognizedEnumValues:n,breadcrumbsPrefix:a=[]}={})=>typeof i!="string"?{ok:!1,errors:[{path:a,message:oq(i,"string")}]}:!t.has(i)&&!n?{ok:!1,errors:[{path:a,message:oq(i,"enum")}]}:{ok:!0,value:i})()}function Tj_(e){let t=zSc(e);return{...t,...NT(t)}}function zSc(e){return{parse:(t,r)=>uJn(e).parse(t,r),json:(t,r)=>uJn(e).json(t,r),getType:()=>uJn(e).getType()}}function uJn(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function Z8a(e){return Object.entries(e)}function k8a(e,t){let r=new Set(t);return Object.entries(e).reduce((i,[n,a])=>(r.has(n)&&(i[n]=a),i),{})}function u3i(e){if(typeof e!="object"||e===null)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function e5a(e){return Object.keys(e)}function Cj_(e,t){let r=[],i=[];for(let n of e)t(n)?r.push(n):i.push(n);return[r,i]}function qQt(e){return{withParsedProperties:t=>xSc(e,t)}}function xSc(e,t){let r={parse:(i,n)=>{let a=e.parse(i,n);if(!a.ok)return a;let u=Object.entries(t).reduce((c,[d,s])=>({...c,[d]:typeof s=="function"?s(a.value):s}),{});return{ok:!0,value:{...a.value,...u}}},json:(i,n)=>{if(!u3i(i))return{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:oq(i,"object")}]};let a=new Set(Object.keys(t)),u=k8a(i,Object.keys(i).filter(c=>!a.has(c)));return e.json(u,n)},getType:()=>e.getType()};return{...r,...NT(r),...qQt(r)}}function Bj_(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function s3i(e){return e.isProperty}function Jru(e){let t={_getRawProperties:()=>Object.entries(e).map(([r,i])=>s3i(i)?i.rawKey:r),_getParsedProperties:()=>e5a(e),parse:(r,i)=>{let n={},a=[];for(let[u,c]of Z8a(e)){let d=s3i(c)?c.rawKey:u,s=s3i(c)?c.valueSchema:c,o={rawKey:d,parsedKey:u,valueSchema:s};n[d]=o,xj_(s)&&a.push(d)}return Ij_({value:r,requiredKeys:a,getProperty:u=>{let c=n[u];if(c!=null)return{transformedKey:c.parsedKey,transform:d=>c.valueSchema.parse(d,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],u]})}},unrecognizedObjectKeys:i?.unrecognizedObjectKeys,skipValidation:i?.skipValidation,breadcrumbsPrefix:i?.breadcrumbsPrefix,omitUndefined:i?.omitUndefined})},json:(r,i)=>{let n=[];for(let[a,u]of Z8a(e)){let c=s3i(u)?u.valueSchema:u;xj_(c)&&n.push(a)}return Ij_({value:r,requiredKeys:n,getProperty:a=>{let u=e[a];if(u!=null)return s3i(u)?{transformedKey:u.rawKey,transform:c=>u.valueSchema.json(c,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],a]})}:{transformedKey:a,transform:c=>u.json(c,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],a]})}},unrecognizedObjectKeys:i?.unrecognizedObjectKeys,skipValidation:i?.skipValidation,breadcrumbsPrefix:i?.breadcrumbsPrefix,omitUndefined:i?.omitUndefined})},getType:()=>fw.OBJECT};return{...jU(t),...NT(t),...qQt(t),...ynn(t)}}function Ij_({value:e,requiredKeys:t,getProperty:r,unrecognizedObjectKeys:i="fail",skipValidation:n=!1,breadcrumbsPrefix:a=[]}){if(!u3i(e))return{ok:!1,errors:[{path:a,message:oq(e,"object")}]};let u=new Set(t),c=[],d={};for(let[s,o]of Object.entries(e)){let l=r(s);if(l!=null){u.delete(s);let v=l.transform(o);v.ok?d[l.transformedKey]=v.value:(d[s]=o,c.push(...v.errors))}else switch(i){case"fail":c.push({path:[...a,s],message:`Unexpected key "${s}"`});break;case"strip":break;case"passthrough":d[s]=o;break}}return c.push(...t.filter(s=>u.has(s)).map(s=>({path:a,message:`Missing required key "${s}"`}))),c.length===0||n?{ok:!0,value:d}:{ok:!1,errors:c}}function ynn(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(i,n)=>zj_({extensionKeys:t._getRawProperties(),value:i,transformBase:a=>e.parse(a,n),transformExtension:a=>t.parse(a,n)}),json:(i,n)=>zj_({extensionKeys:t._getParsedProperties(),value:i,transformBase:a=>e.json(a,n),transformExtension:a=>t.json(a,n)}),getType:()=>fw.OBJECT};return{...r,...NT(r),...qQt(r),...ynn(r)}},passthrough:()=>{let t={_getParsedProperties:()=>e._getParsedProperties(),_getRawProperties:()=>e._getRawProperties(),parse:(r,i)=>{let n=e.parse(r,{...i,unrecognizedObjectKeys:"passthrough"});return n.ok?{ok:!0,value:{...r,...n.value}}:n},json:(r,i)=>{let n=e.json(r,{...i,unrecognizedObjectKeys:"passthrough"});return n.ok?{ok:!0,value:{...r,...n.value}}:n},getType:()=>fw.OBJECT};return{...t,...NT(t),...qQt(t),...ynn(t)}}}}function zj_({extensionKeys:e,value:t,transformBase:r,transformExtension:i}){let n=new Set(e),[a,u]=Cj_(e5a(t),s=>n.has(s)),c=r(k8a(t,u)),d=i(k8a(t,a));return c.ok&&d.ok?{ok:!0,value:{...c.value,...d.value}}:{ok:!1,errors:[...c.ok?[]:c.errors,...d.ok?[]:d.errors]}}function xj_(e){return!uBE(e)}function uBE(e){switch(e.getType()){case fw.ANY:case fw.UNKNOWN:case fw.OPTIONAL:return!0;default:return!1}}function Rj_(e){return Jru(e)}function Nj_(e){let t={...zSc(e),_getRawProperties:()=>uJn(e)._getRawProperties(),_getParsedProperties:()=>uJn(e)._getParsedProperties()};return{...t,...NT(t),...qQt(t),...ynn(t)}}function Kru(e){let t={parse:(r,i)=>Fj_(r,(n,a)=>e.parse(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),json:(r,i)=>Fj_(r,(n,a)=>e.json(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),getType:()=>fw.LIST};return{...jU(t),...NT(t)}}function Fj_(e,t){return Array.isArray(e)?e.map((i,n)=>t(i,n)).reduce((i,n)=>{if(i.ok&&n.ok)return{ok:!0,value:[...i.value,n.value]};let a=[];return i.ok||a.push(...i.errors),n.ok||a.push(...n.errors),{ok:!1,errors:a}},{ok:!0,value:[]}):{ok:!1,errors:[{message:oq(e,"list"),path:[]}]}}function Lj_(e){return CK(fw.STRING_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:oq(r,`"${e}"`)}]})()}function Uj_(e){return CK(fw.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:oq(r,`${e.toString()}`)}]})()}var Vj_=CK(fw.ANY,e=>({ok:!0,value:e}));var Wj_=CK(fw.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:oq(e,"boolean")}]});var Hj_=CK(fw.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:oq(e,"number")}]});var $j_=CK(fw.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:oq(e,"string")}]});var Gj_=CK(fw.UNKNOWN,e=>({ok:!0,value:e}));function Jj_(e,t){let r={parse:(i,n)=>Qj_({value:i,isKeyNumeric:e.getType()===fw.NUMBER,transformKey:a=>e.parse(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,u)=>t.parse(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${u}`]}),breadcrumbsPrefix:n?.breadcrumbsPrefix}),json:(i,n)=>Qj_({value:i,isKeyNumeric:e.getType()===fw.NUMBER,transformKey:a=>e.json(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,u)=>t.json(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${u}`]}),breadcrumbsPrefix:n?.breadcrumbsPrefix}),getType:()=>fw.RECORD};return{...jU(r),...NT(r)}}function Qj_({value:e,isKeyNumeric:t,transformKey:r,transformValue:i,breadcrumbsPrefix:n=[]}){return u3i(e)?Z8a(e).reduce((a,[u,c])=>{if(c==null)return a;let d=a,s=u;if(t){let g=u.length>0?Number(u):NaN;isNaN(g)||(s=g)}let o=r(s),l=i(c,s);if(d.ok&&o.ok&&l.ok)return{ok:!0,value:{...d.value,[o.value]:l.value}};let v=[];return d.ok||v.push(...d.errors),o.ok||v.push(...o.errors),l.ok||v.push(...l.errors),{ok:!1,errors:v}},{ok:!0,value:{}}):{ok:!1,errors:[{path:n,message:oq(e,"object")}]}}function Kj_(e){let t=Kru(e),r={parse:(i,n)=>{let a=t.parse(i,n);return a.ok?{ok:!0,value:new Set(a.value)}:a},json:(i,n)=>i instanceof Set?t.json([...i],n):{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:oq(i,"Set")}]},getType:()=>fw.SET};return{...jU(r),...NT(r)}}function Xj_(e){let t={parse:(r,i)=>Yj_((n,a)=>n.parse(r,a),e,i),json:(r,i)=>Yj_((n,a)=>n.json(r,a),e,i),getType:()=>fw.UNDISCRIMINATED_UNION};return{...jU(t),...NT(t)}}function Yj_(e,t,r){let i=[];for(let[n,a]of t.entries()){let u=e(a,{...r,skipValidation:!1});if(u.ok)return u;for(let c of u.errors)i.push({path:c.path,message:`[Variant ${n}] ${c.message}`})}return{ok:!1,errors:i}}function Zj_(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}function ew_(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,i=typeof e=="string"?e:e.parsedDiscriminant,n=Qru(e5a(t)),a={parse:(u,c)=>kj_({value:u,discriminant:r,transformedDiscriminant:i,transformDiscriminantValue:d=>n.parse(d,{allowUnrecognizedEnumValues:c?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...c?.breadcrumbsPrefix??[],r]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:c?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,s)=>s.parse(d,c),breadcrumbsPrefix:c?.breadcrumbsPrefix}),json:(u,c)=>kj_({value:u,discriminant:i,transformedDiscriminant:r,transformDiscriminantValue:d=>n.json(d,{allowUnrecognizedEnumValues:c?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...c?.breadcrumbsPrefix??[],i]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:c?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,s)=>s.json(d,c),breadcrumbsPrefix:c?.breadcrumbsPrefix}),getType:()=>fw.UNION};return{...jU(a),...NT(a),...qQt(a)}}function kj_({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:i,getAdditionalPropertiesSchema:n,allowUnrecognizedUnionMembers:a=!1,transformAdditionalProperties:u,breadcrumbsPrefix:c=[]}){if(!u3i(e))return{ok:!1,errors:[{path:c,message:oq(e,"object")}]};let{[t]:d,...s}=e;if(d==null)return{ok:!1,errors:[{path:c,message:`Missing discriminant ("${t}")`}]};let o=i(d);if(!o.ok)return{ok:!1,errors:o.errors};let l=n(o.value);if(l==null)return a?{ok:!0,value:{[r]:o.value,...s}}:{ok:!1,errors:[{path:[...c,t],message:"Unexpected discriminant value"}]};let v=u(s,l);return v.ok?{ok:!0,value:{[r]:d,...v.value}}:v}var Um=gt.objectWithoutOptionalProperties({title:gt.string().optional()});var Yru=gt.objectWithoutOptionalProperties({file:gt.string()});var Xru=gt.objectWithoutOptionalProperties({file:gt.string()});var Zru=gt.union("type",{openapi:Yru,protobuf:Xru}).transform({transform:e=>{switch(e.type){case"openapi":return qK.openapi(e);case"protobuf":return qK.protobuf(e);default:return e}},untransform:({_visit:e,...t})=>t});var Ch=gt.objectWithoutOptionalProperties({source:Zru.optional()});var kru=gt.objectWithoutOptionalProperties({typeName:gt.string()});var eiu=gt.union("type",{protobuf:kru}).transform({transform:e=>{switch(e.type){case"protobuf":return nJn.protobuf(e);default:return e}},untransform:({_visit:e,...t})=>t});var Tue=gt.objectWithoutOptionalProperties({encoding:eiu.optional()});var Of=gt.objectWithoutOptionalProperties({description:gt.string().optional()});var tiu=gt.enum_(["GenerallyAvailable","Beta","Deprecated"]);var oy=gt.objectWithoutOptionalProperties({availability:tiu.optional()});var kar=gt.number();var m6e=gt.objectWithoutOptionalProperties({statusCode:kar.optional()});var pg=gt.objectWithoutOptionalProperties({nameOverride:gt.string().optional(),generatedName:gt.string()});var zM=gt.objectWithoutOptionalProperties({inline:gt.boolean().optional()});var Cee=gt.string();var Bee=gt.string();var riu=gt.objectWithoutOptionalProperties({id:Bee}).extend(Of);var iiu=gt.string();var niu=gt.objectWithoutOptionalProperties({usernameVariableName:gt.string().optional(),usernameEnvVar:gt.string().optional(),passwordVariableName:gt.string().optional(),passwordEnvVar:gt.string().optional()});var aiu=gt.objectWithoutOptionalProperties({tokenVariableName:gt.string().optional(),tokenEnvVar:gt.string().optional()});var oiu=gt.objectWithoutOptionalProperties({headerName:gt.string(),prefix:gt.string().optional(),headerVariableName:gt.string().optional(),headerEnvVar:gt.string().optional()});var uiu=gt.objectWithoutOptionalProperties({queryParameterName:gt.string()});var siu=gt.objectWithoutOptionalProperties({snake:gt.string().optional(),camel:gt.string().optional(),screamingSnake:gt.string().optional(),pascal:gt.string().optional()});var c3i=gt.objectWithoutOptionalProperties({nameOverride:gt.string().optional(),generatedName:gt.string(),value:gt.string(),casing:siu.optional()}).extend(Of).extend(oy);var ciu=gt.objectWithoutOptionalProperties({type:gt.stringLiteral("namespace"),name:gt.string()});var liu=gt.undiscriminatedUnion([gt.string(),ciu]);var l3i=gt.list(liu);var Vm=gt.objectWithoutOptionalProperties({groupName:l3i.optional()});var x0=gt.objectWithoutOptionalProperties({namespace:gt.string().optional()});var sJn=gt.objectWithoutOptionalProperties({default:c3i.optional(),values:gt.list(c3i)}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Ch).extend(Um).extend(zM);var fiu=gt.objectWithoutOptionalProperties({scopesEnum:sJn.optional()});var diu=gt.union("type",{basic:niu,bearer:aiu,header:oiu,query:uiu,oauth:fiu}).transform({transform:e=>{switch(e.type){case"basic":return PU.basic(e);case"bearer":return PU.bearer(e);case"header":return PU.header(e);case"query":return PU.query(e);case"oauth":return PU.oauth(e);default:return e}},untransform:({_visit:e,...t})=>t});var t5a=gt.objectWithoutOptionalProperties({name:gt.string().optional(),url:gt.string(),audiences:gt.list(gt.string()).optional()}).extend(Of);var piu=gt.string();var eor=gt.objectWithoutOptionalProperties({sdkMethodName:gt.string().optional()});var NSc={};Na(NSc,{FullExample:()=>FT,FullObjectExample:()=>hiu,FullOneOfExample:()=>viu,KeyValuePair:()=>yiu,LiteralExample:()=>_iu,PrimitiveExample:()=>lJn,PropertyKey:()=>cJn});var cJn=gt.string();var lJn=gt.union("type",{int:gt.object({value:gt.number()}),int64:gt.object({value:gt.number()}),uint:gt.object({value:gt.number()}),uint64:gt.object({value:gt.number()}),float:gt.object({value:gt.number()}),double:gt.object({value:gt.number()}),string:gt.object({value:gt.string()}),datetime:gt.object({value:gt.string()}),date:gt.object({value:gt.string()}),base64:gt.object({value:gt.string()}),boolean:gt.object({value:gt.boolean()})}).transform({transform:e=>{switch(e.type){case"int":return D_.int(e.value);case"int64":return D_.int64(e.value);case"uint":return D_.uint(e.value);case"uint64":return D_.uint64(e.value);case"float":return D_.float(e.value);case"double":return D_.double(e.value);case"string":return D_.string(e.value);case"datetime":return D_.datetime(e.value);case"date":return D_.date(e.value);case"base64":return D_.base64(e.value);case"boolean":return D_.boolean(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var _iu=gt.union("type",{boolean:gt.object({value:gt.boolean()}),string:gt.object({value:gt.string()})}).transform({transform:e=>{switch(e.type){case"boolean":return a3i.boolean(e.value);case"string":return a3i.string(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var FT=gt.union("type",{primitive:gt.object({value:lJn}),object:gt.lazyObject(()=>hiu),array:gt.object({value:gt.list(gt.lazy(()=>FT))}),map:gt.object({value:gt.list(gt.lazyObject(()=>yiu))}),enum:gt.object({value:gt.string()}),literal:gt.object({value:_iu}),oneOf:gt.object({value:gt.lazy(()=>viu)}),unknown:gt.object({value:gt.lazy(()=>FT)})}).transform({transform:e=>{switch(e.type){case"primitive":return Yg.primitive(e.value);case"object":return Yg.object(e);case"array":return Yg.array(e.value);case"map":return Yg.map(e.value);case"enum":return Yg.enum(e.value);case"literal":return Yg.literal(e.value);case"oneOf":return Yg.oneOf(e.value);case"unknown":return Yg.unknown(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var hiu=gt.objectWithoutOptionalProperties({properties:gt.record(cJn,gt.lazy(()=>FT))});var yiu=gt.objectWithoutOptionalProperties({key:lJn,value:gt.lazy(()=>FT)});var viu=gt.union("type",{discriminated:gt.object({value:gt.record(cJn,gt.lazy(()=>FT))}),undiscriminated:gt.object({value:gt.lazy(()=>FT)})}).transform({transform:e=>{switch(e.type){case"discriminated":return o3i.discriminated(e.value);case"undiscriminated":return o3i.undiscriminated(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var FSc={};Na(FSc,{AllOfPropertyConflict:()=>EJn,ArraySchema:()=>snu,Availability:()=>tiu,BooleanSchema:()=>rnu,BytesResponse:()=>bJn,CasingOverrides:()=>siu,CommonProperty:()=>ynu,CursorPagination:()=>Fiu,CustomCodeSample:()=>Riu,CustomCodeSampleLanguage:()=>Iiu,CustomCodeSampleSdk:()=>xiu,CustomPagination:()=>Uiu,DiscriminatedOneOfSchema:()=>_nu,DoubleSchema:()=>enu,Endpoint:()=>Viu,EndpointExample:()=>PJn,EndpointResponseExample:()=>Biu,EndpointSdkName:()=>tor,EnumSchema:()=>sJn,EnumValue:()=>c3i,ErrorExample:()=>Miu,FernExample:()=>qiu,FileResponse:()=>yJn,FileSchema:()=>Oiu,FormUrlEncodedRequest:()=>Siu,FullEndpointExample:()=>Niu,GlobalHeader:()=>nnu,Header:()=>f3i,HeaderExample:()=>mJn,HttpEndpointServer:()=>gJn,HttpError:()=>Aiu,HttpMethod:()=>fJn,IdempotencyHeader:()=>anu,IntSchema:()=>Ziu,JsonRequest:()=>wiu,JsonResponse:()=>vJn,LiteralSchema:()=>DJn,LiteralSchemaValue:()=>onu,LongSchema:()=>kiu,MapSchema:()=>cnu,MultipartRequest:()=>hJn,MultipartRequestProperty:()=>jiu,MultipartRequestPropertyEncoding:()=>Piu,MultipartSchema:()=>miu,NullableSchema:()=>fnu,ObjectProperty:()=>pnu,ObjectPropertyConflictInfo:()=>MJn,ObjectSchema:()=>unu,OctetStreamRequest:()=>_Jn,OffsetPagination:()=>Liu,OneOfSchema:()=>dnu,OpenApiIntermediateRepresentation:()=>tw_,OptionalSchema:()=>lnu,Pagination:()=>jJn,PathParameter:()=>dJn,PathParameterExample:()=>Tiu,PrimitiveSchema:()=>p3i,PrimitiveSchemaValue:()=>inu,QueryParameter:()=>pJn,QueryParameterExample:()=>OJn,ReferencedSchema:()=>ror,Request:()=>Diu,Response:()=>Eiu,Schema:()=>tm,Schemas:()=>Xiu,SdkGroupInfo:()=>biu,StreamingResponseExample:()=>Ciu,StringSchema:()=>tnu,SupportedSdkLanguage:()=>ziu,Tags:()=>giu,TextResponse:()=>d3i,UnDiscriminatedOneOfSchema:()=>hnu,Webhook:()=>Wiu,WebhookExampleCall:()=>SJn,WebhookHttpMethod:()=>wJn,WebsocketChannel:()=>Yiu,WebsocketHandshake:()=>Hiu,WebsocketMessageExample:()=>Jiu,WebsocketMessageOrigin:()=>$iu,WebsocketMessageSchema:()=>Giu,WebsocketServer:()=>Qiu,WebsocketSessionExample:()=>Kiu});var biu=gt.objectWithoutOptionalProperties({summary:gt.string().optional(),description:gt.string().optional()});var giu=gt.objectWithoutOptionalProperties({tagsById:gt.record(Bee,riu),orderedTagIds:gt.list(Bee).optional()});var fJn=gt.enum_(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS","TRACE"]);var dJn=gt.objectWithoutOptionalProperties({name:gt.string(),schema:gt.lazy(()=>tm),variableReference:gt.string().optional(),parameterNameOverride:gt.string().optional()}).extend(Of).extend(oy).extend(Ch);var pJn=gt.objectWithoutOptionalProperties({name:gt.string(),schema:gt.lazy(()=>tm),parameterNameOverride:gt.string().optional()}).extend(Of).extend(oy).extend(Ch);var f3i=gt.objectWithoutOptionalProperties({name:gt.string(),schema:gt.lazy(()=>tm),env:gt.string().optional(),parameterNameOverride:gt.string().optional()}).extend(Of).extend(oy).extend(Ch);var tor=gt.objectWithoutOptionalProperties({groupName:l3i,methodName:gt.string()});var _Jn=gt.objectWithoutOptionalProperties({contentType:gt.string().optional()}).extend(Of).extend(Ch);var Oiu=gt.objectWithoutOptionalProperties({isOptional:gt.boolean(),isArray:gt.boolean()}).extend(Of);var miu=gt.union("type",{file:Oiu,json:gt.object({value:gt.lazy(()=>tm)})}).transform({transform:e=>{switch(e.type){case"file":return Emi.file(e);case"json":return Emi.json(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var Piu=gt.enum_(["json","form"]);var jiu=gt.objectWithoutOptionalProperties({key:gt.string(),schema:miu,contentType:gt.string().optional(),exploded:gt.boolean().optional(),encoding:Piu.optional()}).extend(Of);var hJn=gt.objectWithoutOptionalProperties({name:gt.string().optional(),properties:gt.list(jiu)}).extend(Of).extend(Ch);var wiu=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>tm),contentType:gt.string().optional(),additionalProperties:gt.boolean()}).extend(Of).extend(Ch);var Siu=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>tm),contentType:gt.string().optional(),additionalProperties:gt.boolean()}).extend(Of).extend(Ch);var Diu=gt.union("type",{octetStream:_Jn,multipart:hJn,json:wiu,formUrlEncoded:Siu}).transform({transform:e=>{switch(e.type){case"octetStream":return Zar.octetStream(e);case"multipart":return Zar.multipart(e);case"json":return Zar.json(e);case"formUrlEncoded":return Zar.formUrlEncoded(e);default:return e}},untransform:({_visit:e,...t})=>t});var yJn=gt.objectWithoutOptionalProperties({}).extend(Of).extend(Ch).extend(m6e);var vJn=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>tm),responseProperty:gt.string().optional()}).extend(Of).extend(Ch).extend(m6e);var d3i=gt.objectWithoutOptionalProperties({}).extend(Of).extend(Ch).extend(m6e);var bJn=gt.objectWithoutOptionalProperties({}).extend(Of).extend(Ch).extend(m6e);var Eiu=gt.union("type",{file:yJn,json:vJn,text:d3i,bytes:bJn,streamingSse:vJn,streamingText:d3i,streamingJson:vJn}).transform({transform:e=>{switch(e.type){case"file":return TK.file(e);case"json":return TK.json(e);case"text":return TK.text(e);case"bytes":return TK.bytes(e);case"streamingSse":return TK.streamingSse(e);case"streamingText":return TK.streamingText(e);case"streamingJson":return TK.streamingJson(e);default:return e}},untransform:({_visit:e,...t})=>t});var Miu=gt.objectWithoutOptionalProperties({name:gt.string().optional(),description:gt.string().optional(),example:gt.lazy(()=>FT)});var Aiu=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>tm).optional(),examples:gt.list(Miu).optional()}).extend(Of).extend(pg).extend(Ch);var gJn=gt.objectWithoutOptionalProperties({name:gt.string().optional(),url:gt.string().optional(),audiences:gt.list(gt.string()).optional()});var qiu=gt.unknown();var Tiu=gt.objectWithoutOptionalProperties({name:gt.string(),parameterNameOverride:gt.string().optional(),value:gt.lazy(()=>FT)});var OJn=gt.objectWithoutOptionalProperties({name:gt.string(),value:gt.lazy(()=>FT)});var mJn=gt.objectWithoutOptionalProperties({name:gt.string(),value:gt.lazy(()=>FT)});var Ciu=gt.objectWithoutOptionalProperties({sse:gt.boolean(),events:gt.list(gt.lazy(()=>FT))});var Biu=gt.union("type",{withStreaming:Ciu,withoutStreaming:gt.object({value:gt.lazy(()=>FT)})}).transform({transform:e=>{switch(e.type){case"withStreaming":return AQt.withStreaming(e);case"withoutStreaming":return AQt.withoutStreaming(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var Iiu=gt.objectWithoutOptionalProperties({name:gt.string().optional(),language:gt.string(),code:gt.string(),install:gt.string().optional()}).extend(Of);var ziu=gt.enum_(["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm"]);var xiu=gt.objectWithoutOptionalProperties({name:gt.string().optional(),sdk:ziu,code:gt.string()}).extend(Of);var Riu=gt.union("type",{language:Iiu,sdk:xiu}).transform({transform:e=>{switch(e.type){case"language":return Dmi.language(e);case"sdk":return Dmi.sdk(e);default:return e}},untransform:({_visit:e,...t})=>t});var Niu=gt.objectWithoutOptionalProperties({name:gt.string().optional(),pathParameters:gt.list(Tiu).optional(),queryParameters:gt.list(OJn).optional(),headers:gt.list(mJn).optional(),request:gt.lazy(()=>FT).optional(),response:Biu.optional(),codeSamples:gt.list(Riu)}).extend(Of);var PJn=gt.union("type",{unknown:gt.object({value:qiu}),full:Niu}).transform({transform:e=>{switch(e.type){case"unknown":return MQt.unknown(e.value);case"full":return MQt.full(e);default:return e}},untransform:({_visit:e,...t})=>t});var Fiu=gt.objectWithoutOptionalProperties({cursor:gt.string(),nextCursor:gt.property("next_cursor",gt.string()),results:gt.string()});var Liu=gt.objectWithoutOptionalProperties({offset:gt.string(),results:gt.string(),step:gt.string().optional(),hasNextPage:gt.string().optional()});var Uiu=gt.objectWithoutOptionalProperties({results:gt.string()});var jJn=gt.union("type",{cursor:Fiu,offset:Liu,custom:Uiu}).transform({transform:e=>{switch(e.type){case"cursor":return O6e.cursor(e);case"offset":return O6e.offset(e);case"custom":return O6e.custom(e);default:return e}},untransform:({_visit:e,...t})=>t});var Viu=gt.objectWithoutOptionalProperties({authed:gt.boolean(),internal:gt.boolean().optional(),idempotent:gt.boolean().optional(),method:fJn,audiences:gt.list(gt.string()),path:gt.string(),summary:gt.string().optional(),operationId:gt.string().optional(),tags:gt.list(Bee),pathParameters:gt.list(dJn),queryParameters:gt.list(pJn),headers:gt.list(f3i),sdkName:tor.optional(),generatedRequestName:gt.string(),requestNameOverride:gt.string().optional(),request:Diu.optional(),response:Eiu.optional(),errors:gt.record(kar,Aiu),servers:gt.list(gJn),examples:gt.list(PJn),pagination:jJn.optional()}).extend(Of).extend(oy).extend(Ch).extend(x0);var wJn=gt.enum_(["GET","POST"]);var SJn=gt.objectWithoutOptionalProperties({name:gt.string().optional(),payload:gt.lazy(()=>FT)}).extend(Of);var Wiu=gt.objectWithoutOptionalProperties({audiences:gt.list(gt.string()),sdkName:tor.optional(),method:wJn,summary:gt.string().optional(),operationId:gt.string(),tags:gt.list(Bee),headers:gt.list(f3i),generatedPayloadName:gt.string(),payload:gt.lazy(()=>tm),examples:gt.list(SJn)}).extend(Of).extend(Ch).extend(x0);var Hiu=gt.objectWithoutOptionalProperties({queryParameters:gt.list(pJn),headers:gt.list(f3i),pathParameters:gt.list(dJn)});var $iu=gt.enum_(["client","server"]);var Giu=gt.objectWithoutOptionalProperties({name:gt.string(),origin:$iu,body:gt.lazy(()=>tm)});var Qiu=gt.objectWithoutOptionalProperties({name:gt.string(),url:gt.string()});var Jiu=gt.objectWithoutOptionalProperties({messageType:gt.string(),payload:gt.lazy(()=>FT)}).extend(Of);var Kiu=gt.objectWithoutOptionalProperties({name:gt.string().optional(),queryParameters:gt.list(OJn).optional(),headers:gt.list(mJn).optional(),messages:gt.list(Jiu)}).extend(Of);var Yiu=gt.objectWithoutOptionalProperties({audiences:gt.list(gt.string()),path:gt.string(),groupName:l3i,summary:gt.string().optional(),handshake:Hiu,messages:gt.list(Giu),servers:gt.list(Qiu),examples:gt.list(Kiu)}).extend(Of).extend(Ch);var Xiu=gt.objectWithoutOptionalProperties({rootSchemas:gt.record(Cee,gt.lazy(()=>tm)),namespacedSchemas:gt.record(piu,gt.record(Cee,gt.lazy(()=>tm)))});var Ziu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),minimum:gt.number().optional(),maximum:gt.number().optional(),exclusiveMinimum:gt.boolean().optional(),exclusiveMaximum:gt.boolean().optional(),multipleOf:gt.number().optional()});var kiu=gt.objectWithoutOptionalProperties({default:gt.number().optional()});var enu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),minimum:gt.number().optional(),maximum:gt.number().optional(),exclusiveMinimum:gt.boolean().optional(),exclusiveMaximum:gt.boolean().optional(),multipleOf:gt.number().optional()});var tnu=gt.objectWithoutOptionalProperties({default:gt.string().optional(),pattern:gt.string().optional(),format:gt.string().optional(),minLength:gt.number().optional(),maxLength:gt.number().optional()});var rnu=gt.objectWithoutOptionalProperties({default:gt.boolean().optional()});var inu=gt.union("type",{int:Ziu,int64:kiu,uint:gt.object({}),uint64:gt.object({}),float:gt.object({}),double:enu,string:tnu,datetime:gt.object({}),date:gt.object({}),base64:gt.object({}),boolean:rnu}).transform({transform:e=>{switch(e.type){case"int":return xw.int(e);case"int64":return xw.int64(e);case"uint":return xw.uint();case"uint64":return xw.uint64();case"float":return xw.float();case"double":return xw.double(e);case"string":return xw.string(e);case"datetime":return xw.datetime();case"date":return xw.date();case"base64":return xw.base64();case"boolean":return xw.boolean(e);default:return e}},untransform:({_visit:e,...t})=>t});var p3i=gt.objectWithoutOptionalProperties({schema:inu}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Um);var nnu=gt.objectWithoutOptionalProperties({header:gt.string(),name:gt.string().optional(),optional:gt.boolean().optional(),env:gt.string().optional(),schema:gt.lazy(()=>tm).optional()});var anu=gt.objectWithoutOptionalProperties({header:gt.string(),name:gt.string().optional(),env:gt.string().optional(),schema:gt.lazy(()=>tm).optional()});var tw_=gt.objectWithoutOptionalProperties({apiVersion:gt.unknown().optional(),title:gt.string().optional(),description:gt.string().optional(),basePath:gt.string().optional(),servers:gt.list(t5a),websocketServers:gt.list(t5a),groups:gt.record(gt.string(),biu),tags:giu,hasEndpointsMarkedInternal:gt.boolean(),endpoints:gt.list(Viu),webhooks:gt.list(Wiu),channels:gt.record(gt.string(),Yiu),groupedSchemas:Xiu,variables:gt.record(gt.string(),p3i),nonRequestReferencedSchemas:gt.set(Cee),securitySchemes:gt.record(iiu,diu),globalHeaders:gt.list(nnu).optional(),idempotencyHeaders:gt.list(anu).optional()});var ror=gt.objectWithoutOptionalProperties({schema:Cee}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Ch).extend(Um);var onu=gt.union("type",{boolean:gt.object({value:gt.boolean()}),string:gt.object({value:gt.string()})}).transform({transform:e=>{switch(e.type){case"boolean":return px.boolean(e.value);case"string":return px.string(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var DJn=gt.objectWithoutOptionalProperties({value:onu}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Um);var tm=gt.union("type",{primitive:p3i,object:gt.lazyObject(()=>unu),array:gt.lazyObject(()=>snu),map:gt.lazyObject(()=>cnu),optional:gt.lazyObject(()=>lnu),enum:sJn,reference:ror,literal:DJn,oneOf:gt.object({value:gt.lazy(()=>dnu)}),nullable:gt.lazyObject(()=>fnu),unknown:pg}).transform({transform:e=>{switch(e.type){case"primitive":return Ov.primitive(e);case"object":return Ov.object(e);case"array":return Ov.array(e);case"map":return Ov.map(e);case"optional":return Ov.optional(e);case"enum":return Ov.enum(e);case"reference":return Ov.reference(e);case"literal":return Ov.literal(e);case"oneOf":return Ov.oneOf(e.value);case"nullable":return Ov.nullable(e);case"unknown":return Ov.unknown(e);default:return e}},untransform:({_visit:e,...t})=>t});var EJn=gt.objectWithoutOptionalProperties({propertyKey:gt.string(),allOfSchemaIds:gt.list(Cee),conflictingTypeSignatures:gt.boolean()});var unu=gt.objectWithoutOptionalProperties({allOf:gt.list(ror),properties:gt.list(gt.lazyObject(()=>pnu)),allOfPropertyConflicts:gt.list(EJn),additionalProperties:gt.boolean()}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Ch).extend(Um).extend(zM);var MJn=gt.objectWithoutOptionalProperties({differentSchema:gt.boolean()});var pnu=gt.objectWithoutOptionalProperties({key:gt.string(),schema:gt.lazy(()=>tm),readonly:gt.boolean().optional(),writeonly:gt.boolean().optional(),conflict:gt.record(Cee,MJn),generatedName:gt.string(),nameOverride:gt.string().optional(),audiences:gt.list(gt.string())}).extend(oy);var snu=gt.objectWithoutOptionalProperties({value:gt.lazy(()=>tm)}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Um).extend(zM);var cnu=gt.objectWithoutOptionalProperties({key:p3i,value:gt.lazy(()=>tm)}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Tue).extend(Um).extend(zM);var lnu=gt.objectWithoutOptionalProperties({value:gt.lazy(()=>tm)}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Um).extend(zM);var fnu=gt.objectWithoutOptionalProperties({value:gt.lazy(()=>tm)}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Um).extend(zM);var dnu=gt.union("type",{discriminated:gt.lazyObject(()=>_nu),undiscriminated:gt.lazyObject(()=>hnu)}).transform({transform:e=>{switch(e.type){case"discriminated":return Mmi.discriminated(e);case"undiscriminated":return Mmi.undiscriminated(e);default:return e}},untransform:({_visit:e,...t})=>t});var _nu=gt.objectWithoutOptionalProperties({discriminantProperty:gt.string(),commonProperties:gt.list(gt.lazyObject(()=>ynu)),schemas:gt.record(gt.string(),gt.lazy(()=>tm))}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Tue).extend(Ch).extend(Um).extend(zM);var ynu=gt.objectWithoutOptionalProperties({key:gt.string(),schema:gt.lazy(()=>tm)});var hnu=gt.objectWithoutOptionalProperties({schemas:gt.list(gt.lazy(()=>tm))}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Tue).extend(Ch).extend(Um).extend(zM);var LSc={};Na(LSc,{ArraySchemaWithExample:()=>Fnu,Base64WithExample:()=>Inu,BooleanWithExample:()=>znu,CommonPropertyWithExample:()=>Jnu,DateWithExample:()=>Bnu,DatetimeWithExample:()=>Cnu,DiscriminatedOneOfSchemaWithExample:()=>Gnu,DoubleWithExample:()=>qnu,EndpointWithExample:()=>iw_,EnumSchemaWithExample:()=>Rnu,FloatWithExample:()=>Anu,HeaderWithExample:()=>_3i,HttpErrorWithExample:()=>wnu,Int64WithExample:()=>Dnu,IntWithExample:()=>Snu,JsonRequestWithExample:()=>Onu,JsonResponseWithExample:()=>qJn,MapSchemaWithExample:()=>Lnu,NamedFullExample:()=>P6e,NullableSchemaWithExample:()=>Vnu,ObjectPropertyWithExample:()=>$nu,ObjectSchemaWithExample:()=>Wnu,OneOfSchemaWithExample:()=>Hnu,OptionalSchemaWithExample:()=>Unu,ParseFormUrlEncodedRequest:()=>mnu,ParseMultipartRequest:()=>gnu,ParseOctetStreamRequest:()=>bnu,PathParameterWithExample:()=>vnu,PrimitiveSchemaValueWithExample:()=>xnu,PrimitiveSchemaWithExample:()=>TJn,QueryParameterWithExample:()=>AJn,RequestWithExample:()=>Pnu,ResponseWithExample:()=>jnu,SchemaWithExample:()=>xM,StringSchemaWithExample:()=>Tnu,Uint64WithExample:()=>Mnu,UintWithExample:()=>Enu,UnDiscriminatedOneOfSchemaWithExample:()=>Qnu,UnknownSchemaWithExample:()=>Nnu,WebhookWithExample:()=>nw_,WebsocketHandshakeWithExample:()=>rw_});var P6e=gt.objectWithoutOptionalProperties({name:gt.string().optional(),value:gt.unknown()}).extend(Of);var AJn=gt.objectWithoutOptionalProperties({name:gt.string(),schema:gt.lazy(()=>xM),parameterNameOverride:gt.string().optional()}).extend(Of).extend(oy).extend(Ch);var _3i=gt.objectWithoutOptionalProperties({name:gt.string(),schema:gt.lazy(()=>xM),env:gt.string().optional(),parameterNameOverride:gt.string().optional()}).extend(Of).extend(oy).extend(Ch);var rw_=gt.objectWithoutOptionalProperties({queryParameters:gt.list(AJn),headers:gt.list(_3i)});var vnu=gt.objectWithoutOptionalProperties({name:gt.string(),schema:gt.lazy(()=>xM),variableReference:gt.string().optional(),parameterNameOverride:gt.string().optional()}).extend(Of).extend(oy).extend(Ch);var bnu=gt.objectWithoutOptionalProperties({}).extend(_Jn).extend(eor);var gnu=gt.objectWithoutOptionalProperties({}).extend(hJn).extend(eor);var Onu=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>xM),contentType:gt.string().optional(),fullExamples:gt.list(P6e).optional(),additionalProperties:gt.boolean()}).extend(Of).extend(Ch).extend(eor);var mnu=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>xM),contentType:gt.string().optional(),fullExamples:gt.list(P6e).optional(),additionalProperties:gt.boolean()}).extend(Of).extend(Ch).extend(eor);var Pnu=gt.union("type",{octetStream:bnu,multipart:gnu,json:Onu,formUrlEncoded:mnu}).transform({transform:e=>{switch(e.type){case"octetStream":return qee.octetStream(e);case"multipart":return qee.multipart(e);case"json":return qee.json(e);case"formUrlEncoded":return qee.formUrlEncoded(e);default:return e}},untransform:({_visit:e,...t})=>t});var qJn=gt.objectWithoutOptionalProperties({schema:gt.lazy(()=>xM),responseProperty:gt.string().optional(),fullExamples:gt.list(P6e).optional()}).extend(Of).extend(Ch).extend(m6e);var jnu=gt.union("type",{file:yJn,json:qJn,text:d3i,bytes:bJn,streamingSse:qJn,streamingText:d3i,streamingJson:qJn}).transform({transform:e=>{switch(e.type){case"file":return gB.file(e);case"json":return gB.json(e);case"text":return gB.text(e);case"bytes":return gB.bytes(e);case"streamingSse":return gB.streamingSse(e);case"streamingText":return gB.streamingText(e);case"streamingJson":return gB.streamingJson(e);default:return e}},untransform:({_visit:e,...t})=>t});var wnu=gt.objectWithoutOptionalProperties({statusCode:kar,schema:gt.lazy(()=>xM),fullExamples:gt.list(P6e).optional()}).extend(Of).extend(pg).extend(Ch);var iw_=gt.objectWithoutOptionalProperties({authed:gt.boolean(),internal:gt.boolean().optional(),idempotent:gt.boolean().optional(),method:fJn,audiences:gt.list(gt.string()),path:gt.string(),summary:gt.string().optional(),operationId:gt.string().optional(),tags:gt.list(Bee),pathParameters:gt.list(vnu),queryParameters:gt.list(AJn),headers:gt.list(_3i),sdkName:tor.optional(),generatedRequestName:gt.string(),requestNameOverride:gt.string().optional(),request:Pnu.optional(),response:jnu.optional(),errors:gt.record(kar,wnu),servers:gt.list(gJn),examples:gt.list(PJn),pagination:jJn.optional()}).extend(Of).extend(oy).extend(Ch).extend(x0);var nw_=gt.objectWithoutOptionalProperties({audiences:gt.list(gt.string()),sdkName:tor.optional(),method:wJn,summary:gt.string().optional(),operationId:gt.string(),tags:gt.list(Bee),headers:gt.list(_3i),generatedPayloadName:gt.string(),payload:gt.lazy(()=>xM),examples:gt.list(SJn)}).extend(Of).extend(Ch).extend(x0);var Snu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),minimum:gt.number().optional(),maximum:gt.number().optional(),exclusiveMinimum:gt.boolean().optional(),exclusiveMaximum:gt.boolean().optional(),multipleOf:gt.number().optional(),example:gt.number().optional()});var Dnu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),example:gt.number().optional()});var Enu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),example:gt.number().optional()});var Mnu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),example:gt.number().optional()});var Anu=gt.objectWithoutOptionalProperties({example:gt.number().optional()});var qnu=gt.objectWithoutOptionalProperties({default:gt.number().optional(),minimum:gt.number().optional(),maximum:gt.number().optional(),exclusiveMinimum:gt.boolean().optional(),exclusiveMaximum:gt.boolean().optional(),multipleOf:gt.number().optional(),example:gt.number().optional()});var Tnu=gt.objectWithoutOptionalProperties({default:gt.string().optional(),pattern:gt.string().optional(),format:gt.string().optional(),minLength:gt.number().optional(),maxLength:gt.number().optional(),example:gt.string().optional()});var Cnu=gt.objectWithoutOptionalProperties({example:gt.string().optional()});var Bnu=gt.objectWithoutOptionalProperties({example:gt.string().optional()});var Inu=gt.objectWithoutOptionalProperties({example:gt.string().optional()});var znu=gt.objectWithoutOptionalProperties({default:gt.boolean().optional(),example:gt.boolean().optional()});var xnu=gt.union("type",{int:Snu,int64:Dnu,uint:Enu,uint64:Mnu,float:Anu,double:qnu,string:Tnu,datetime:Cnu,date:Bnu,base64:Inu,boolean:znu}).transform({transform:e=>{switch(e.type){case"int":return vp.int(e);case"int64":return vp.int64(e);case"uint":return vp.uint(e);case"uint64":return vp.uint64(e);case"float":return vp.float(e);case"double":return vp.double(e);case"string":return vp.string(e);case"datetime":return vp.datetime(e);case"date":return vp.date(e);case"base64":return vp.base64(e);case"boolean":return vp.boolean(e);default:return e}},untransform:({_visit:e,...t})=>t});var TJn=gt.objectWithoutOptionalProperties({schema:xnu}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Um);var Rnu=gt.objectWithoutOptionalProperties({default:c3i.optional(),values:gt.list(c3i),example:gt.string().optional()}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Ch).extend(Um).extend(zM);var Nnu=gt.objectWithoutOptionalProperties({example:gt.unknown()}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Um);var xM=gt.union("type",{primitive:TJn,object:gt.lazyObject(()=>Wnu),array:gt.lazyObject(()=>Fnu),map:gt.lazyObject(()=>Lnu),optional:gt.lazyObject(()=>Unu),enum:Rnu,reference:ror,literal:DJn,oneOf:gt.object({value:gt.lazy(()=>Hnu)}),nullable:gt.lazyObject(()=>Vnu),unknown:Nnu}).transform({transform:e=>{switch(e.type){case"primitive":return zl.primitive(e);case"object":return zl.object(e);case"array":return zl.array(e);case"map":return zl.map(e);case"optional":return zl.optional(e);case"enum":return zl.enum(e);case"reference":return zl.reference(e);case"literal":return zl.literal(e);case"oneOf":return zl.oneOf(e.value);case"nullable":return zl.nullable(e);case"unknown":return zl.unknown(e);default:return e}},untransform:({_visit:e,...t})=>t});var Fnu=gt.objectWithoutOptionalProperties({value:gt.lazy(()=>xM),example:gt.list(gt.unknown()).optional()}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Um).extend(zM);var Lnu=gt.objectWithoutOptionalProperties({key:TJn,value:gt.lazy(()=>xM),example:gt.unknown().optional()}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Tue).extend(Um).extend(zM);var Unu=gt.objectWithoutOptionalProperties({value:gt.lazy(()=>xM)}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Um).extend(zM);var Vnu=gt.objectWithoutOptionalProperties({value:gt.lazy(()=>xM)}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Um).extend(zM);var Wnu=gt.objectWithoutOptionalProperties({allOf:gt.list(ror),properties:gt.list(gt.lazyObject(()=>$nu)),allOfPropertyConflicts:gt.list(EJn),fullExamples:gt.list(P6e).optional(),additionalProperties:gt.boolean()}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Ch).extend(Um).extend(zM);var $nu=gt.objectWithoutOptionalProperties({key:gt.string(),schema:gt.lazy(()=>xM),readonly:gt.boolean().optional(),writeonly:gt.boolean().optional(),audiences:gt.list(gt.string()),conflict:gt.record(Cee,MJn),nameOverride:gt.string().optional(),generatedName:gt.string()}).extend(oy);var Hnu=gt.union("type",{discriminated:gt.lazyObject(()=>Gnu),undiscriminated:gt.lazyObject(()=>Qnu)}).transform({transform:e=>{switch(e.type){case"discriminated":return Tee.discriminated(e);case"undiscriminated":return Tee.undiscriminated(e);default:return e}},untransform:({_visit:e,...t})=>t});var Gnu=gt.objectWithoutOptionalProperties({discriminantProperty:gt.string(),commonProperties:gt.list(gt.lazyObject(()=>Jnu)),schemas:gt.record(gt.string(),gt.lazy(()=>xM))}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Tue).extend(Ch).extend(Um).extend(zM);var Jnu=gt.objectWithoutOptionalProperties({key:gt.string(),schema:gt.lazy(()=>xM)});var Qnu=gt.objectWithoutOptionalProperties({schemas:gt.list(gt.lazy(()=>xM))}).extend(Vm).extend(x0).extend(pg).extend(Of).extend(oy).extend(Tue).extend(Ch).extend(Um).extend(zM);var aw_=/^(\d+)/,CJn=/^[a-zA-Z][a-zA-Z0-9_]*$/,ow_={"<":"LESS_THAN",">":"GREATER_THAN",">=":"GREATER_THAN_OR_EQUAL_TO","<=":"LESS_THAN_OR_EQUAL_TO","!=":"NOT_EQUALS","=":"EQUAL_TO","==":"EQUAL_TO","*":"ALL","":"EMPTY",'""':"EMPTY_STRING","-":"HYPHEN","|":"PIPE",".":"DOT","/":"SLASH"};function h3i(e){let t=["zero","one","two","three","four","five","six","seven","eight","nine"],r=["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],i=["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"];if(e<0||e>9999)return;if(e<10)return t[e];if(e<20)return r[e-10];if(e<100){let u=Math.floor(e/10),c=e%10;return c===0?i[u]:`${i[u]}_${t[c]}`}if(e<1e3){let u=Math.floor(e/100),c=e%100;return c===0?`${t[u]}_hundred`:`${t[u]}_hundred_${h3i(c)}`}let n=Math.floor(e/1e3),a=e%1e3;return a===0?`${t[n]}_thousand`:`${t[n]}_thousand_${h3i(a)}`}function r5a(e){let t=e.match(aw_);if(t&&t[0]!=null){let r=t[0],i=e.substring(r.length),n=parseFloat(r);if(!isNaN(n)&&isFinite(n)){let a=h3i(n);return i.length>0?`${a}_${i}`:a}}}function BJn(e){let t=r5a(e),r=ow_[e];return t!=null?GB(R_(t)):r??(e.toLowerCase()==="n/a"?"NOT_APPLICABLE":GB(R_(e)))}function Cue(e,t){return e.type==="primitive"&&t.type==="primitive"?uw_(e.schema,t.schema):e.type==="enum"&&t.type==="enum"?sBE(e.values,t.values):e.type==="array"&&t.type==="array"?Cue(e.value,t.value):e.type==="unknown"&&t.type==="unknown"?!0:e.type==="reference"&&t.type==="reference"?e.schema===t.schema:e.type==="optional"&&t.type==="optional"?Cue(e.value,t.value):e.type==="oneOf"&&t.type==="oneOf"?cBE(e.value,t.value):e.type==="object"&&t.type==="object"?lBE(e,t):e.type==="map"&&t.type==="map"?uw_(e.key.schema,t.key.schema)&&Cue(e.value,t.value):e.type==="literal"&&t.type==="literal"?e.value===t.value:!1}function uw_(e,t){return e.type===t.type}function sBE(e,t){let r=new Set(...e.map(n=>n.value)),i=new Set(...t.map(n=>n.value));return W8(r,i)}function cBE(e,t){return e.type==="discriminated"&&t.type==="discriminated"?e.discriminantProperty===t.discriminantProperty&&Object.keys(e.schemas).length===Object.keys(t.schemas).length&&Object.entries(e.schemas).every(([r,i])=>{let n=t.schemas[r];return n==null?!1:Cue(i,n)}):e.type==="undiscriminated"&&t.type==="undiscriminated"?e.schemas.length===t.schemas.length&&e.schemas.every((r,i)=>{let n=t.schemas[i];return n==null?!1:Cue(r,n)}):!1}function lBE(e,t){if(Object.keys(e.properties).length!==Object.keys(t.properties).length)return!1;let r=Object.fromEntries(e.properties.map(i=>[i.key,i.schema]));return Object.entries(t.properties).every(([i,n])=>{let a=r[i];return a==null?!1:Cue(a,n.schema)})}function mR(e){switch(e){case v$.Deprecated:return"deprecated";case v$.Beta:return"pre-release";case v$.GenerallyAvailable:return"generally-available";default:return}}function fBE(e){let t=e.find(i=>typeof i=="object"&&i.type==="namespace"),r=e.filter(i=>typeof i=="string"||i.type!=="namespace");return t?[t,...r]:r}function sw_(e){let t=e?fBE(e):void 0;if(t==null||t.length===0)return jZi;let r=[];for(let[i,n]of t.entries())if(typeof n=="string")r.push(R_(n));else if(typeof n=="object")switch(n.type){case"namespace":{i<t.length-1?r.push(R_(n.name)):r.push(n.name,jZi);break}default:Ao(n.type)}else Ao(n);return r.join("/")}function y3i(e){return wy.of(`${sw_(e)}.yml`)}function USc({sdkName:e,namespaceOverride:t}){let r;return e==null||e.groupName.length===0&&t==null?jZi:(t!=null?r=[{type:"namespace",name:t},...e.groupName.filter(i=>typeof i=="string"||i.type!=="namespace")]:r=e.groupName,sw_(r))}function cw_({sdkName:e,namespaceOverride:t}){return wy.of(`${USc({sdkName:e,namespaceOverride:t})}.yml`)}function lw_({location:e,namespaceOverride:t}){return t!=null?GN(wy.of(t),e):e}function Knu(e){switch(e.type){case"protobuf":return{proto:{type:e.typeName}};default:Ao(e.type)}}function IJn(e){switch(e.type){case"object":case"enum":case"array":case"map":case"reference":case"literal":case"optional":case"nullable":case"primitive":return e.groupName??void 0;case"oneOf":return e.value.groupName??void 0;case"unknown":return;default:Ao(e)}}function uq(e){return typeof e=="string"?e:e.type}function zJn(e){if(typeof e!="string")return e.docs}function i5a(e){if(typeof e!="string")return e.default}function VSc(e){if(typeof e!="string")return e.validation}var dBE=-2147483648,pBE=2147483647,_BE=-17976931348623157e292,hBE=17976931348623157e292;function Xg({schema:e,fileContainingReference:t,declarationFile:r=t,context:i,namespace:n,declarationDepth:a}){switch(i.shouldMarkSchemaAsReferenced()&&i.markSchemaAsReferenced(e,n),e.type){case"primitive":return Ynu(e);case"array":return $Sc({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"map":return GSc({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"reference":return HSc({schema:e,fileContainingReference:t,context:i,namespace:n});case"unknown":return JSc();case"optional":return Xnu({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"nullable":return QSc({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"enum":return wBE({schema:e,fileContainingReference:t,context:i,declarationFile:r,declarationDepth:a});case"literal":return e.value,KSc(e);case"object":return SBE({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"oneOf":return DBE({schema:e.value,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});default:Ao(e)}}function Ynu(e){switch(e.schema.type){case"string":return bBE({description:e.description,schema:e.schema});case"int":return gBE({description:e.description,schema:e.schema});case"float":return OBE({description:e.description,schema:e.schema});case"double":return mBE({description:e.description,schema:e.schema});case"boolean":return yBE({description:e.description,schema:e.schema});case"int64":return vBE({description:e.description,schema:e.schema})}let t=e.schema._visit({int:()=>"integer",int64:()=>"long",uint:()=>"uint",uint64:()=>"uint64",float:()=>"double",double:()=>"double",string:()=>"string",datetime:()=>"datetime",date:()=>"date",base64:()=>"base64",boolean:()=>"boolean",_other:()=>"unknown"});return e.description==null&&e.title==null?t:{type:t,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:mR(e.availability)}:{}}}function yBE({description:e,schema:t}){let r="boolean";if(e==null&&t.default==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),i}function vBE({description:e,schema:t}){let r="long";if(e==null&&t.default==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),i}function bBE({description:e,schema:t}){let r="string",i=PBE(t);if(e==null&&t.default==null&&i==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),i!=null&&(n.validation=i),n}function gBE({description:e,schema:t}){let r="integer",i=dw_(t,r);if(e==null&&t.default==null&&i==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),i!=null&&(n.validation=i),n}function OBE({description:e,schema:t}){let r="float";if(e==null)return r;let i={type:r};return e!=null&&(i.docs=e),i}function mBE({description:e,schema:t}){let r="double",i=dw_(t,r);if(e==null&&t.default==null&&i==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),i!=null&&(n.validation=i),n}function PBE(e){if(e==null)return;let{format:t,pattern:r,minLength:i,maxLength:n}=e,a=jBE(t);if(!(a==null&&r==null&&i==null&&n==null))return{format:a,pattern:r,minLength:i,maxLength:n}}function jBE(e){switch(e){case"date":case"date-time":case"password":case"byte":case"bytes":case"binary":case"email":case"uuid":case"uri":case"hostname":case"ipv4":case"ipv6":return e;default:return}}function dw_(e,t){if(e==null)return;let{minimum:r,maximum:i,multipleOf:n}=e,{exclusiveMinimum:a,exclusiveMaximum:u}=e;if(r=WSc(r,t),i=WSc(i,t),n=WSc(n,t),!(r==null&&i==null&&a==null&&u==null&&n==null))return{min:r,max:i,exclusiveMin:a,exclusiveMax:u,multipleOf:n}}function WSc(e,t){if(e===void 0)return;let[r,i]=t==="integer"?[dBE,pBE]:[_BE,hBE];return e<r||e>i?void 0:e}function HSc({schema:e,fileContainingReference:t,context:r,namespace:i}){let n=r.getSchema(e.schema,i);if(n==null)return"unknown";let a=EBE(n)??e.schema,u=IJn(n),c=MBE(n),d=Znu({context:r,fileContainingReference:t,declarationFile:y3i(u),type:a}),s=n.type==="nullable"?`optional<${d}>`:d;return e.description==null&&c==null?s:{type:n.type==="nullable"?`optional<${d}>`:d,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:mR(e.availability)}:{}}}function $Sc({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=Xg({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),c=`list<${uq(u)}>`;return e.description==null&&e.title==null?c:{...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:mR(e.availability)}:{},type:c}}function GSc({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=Ynu(e.key),c=Xg({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),d=e.encoding!=null?Knu(e.encoding):void 0,s=`map<${uq(u)}, ${uq(c)}>`;if(e.description==null&&d==null&&e.title==null)return s;let o={type:s};return e.description!=null&&(o.docs=e.description),e.encoding!=null&&(o.encoding=d),e.availability!=null&&(o.availability=mR(e.availability)),o}function QSc({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){if(!i.respectNullableSchemas)return Xnu({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});let u=Xg({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),c=uq(u),d=zJn(u),s=i5a(u),o=VSc(u),l=c.startsWith("nullable<")?c:`nullable<${c}>`;if(e.availability==null&&e.description==null&&d==null&&s==null&&o==null&&e.title==null)return fw_({typeReference:l,itemType:c});let v={type:l};return(e.description!=null||d!=null)&&(v.docs=e.description??d),s!=null&&(v.default=s),o!=null&&(v.validation=o),e.availability!=null&&(v.availability=mR(e.availability)),fw_({typeReference:v,itemType:c})}function Xnu({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=Xg({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),c=uq(u),d=zJn(u),s=i5a(u),o=VSc(u),l=c.startsWith("optional<")?c:`optional<${c}>`;if(e.availability==null&&e.description==null&&d==null&&s==null&&o==null&&e.title==null)return l;let v={type:l};return(e.description!=null||d!=null)&&(v.docs=e.description??d),s!=null&&(v.default=s),o!=null&&(v.validation=o),e.availability!=null&&(v.availability=mR(e.availability)),v}function JSc(){return"unknown"}function KSc(e){let t;switch(e.value.type){case"boolean":{t=`literal<${e.value.value}>`;break}case"string":{t=`literal<"${e.value.value}">`;break}default:Ao(e.value)}return e.description==null&&e.title==null?t:{type:t,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:mR(e.availability)}:{}}}function wBE({schema:e,fileContainingReference:t,declarationFile:r,context:i,declarationDepth:n}){let a=n5a(e,n),u=e.nameOverride??e.generatedName;i.builder.addType(r,{name:u,schema:a.schema});let c=Znu({type:u,fileContainingReference:t,declarationFile:r,context:i});if(e.description==null&&e.default==null&&e.title==null)return c;let d={type:c};return e.description!=null&&(d.docs=e.description),e.default!=null&&(d.default=e.default.value),e.availability!=null&&(d.availability=mR(e.availability)),d}function SBE({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=YSc({schema:e,declarationFile:r,context:i,namespace:n,declarationDepth:a}),c=e.nameOverride??e.generatedName;i.builder.addType(r,{name:c,schema:u.schema});let d=Znu({type:c,fileContainingReference:t,declarationFile:r,context:i});return e.description==null&&e.title==null?d:{type:d,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:mR(e.availability)}:{}}}function DBE({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=XSc({schema:e,declarationFile:r,context:i,namespace:n,declarationDepth:a}),c=e.nameOverride??e.generatedName;i.builder.addType(r,{name:c,schema:u.schema});let d=Znu({type:c,fileContainingReference:t,declarationFile:r,context:i});return e.description==null&&e.title==null?d:{...e.title!=null?{"display-name":e.title}:{},type:d,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:mR(e.availability)}:{}}}function Znu({type:e,fileContainingReference:t,declarationFile:r,context:i}){if(r===t)return e;let n=i.builder.addImport({file:t,fileToImport:r});return n!=null?`${n}.${e}`:e}function EBE(e){return Ov._visit(e,{primitive:t=>t.nameOverride??t.generatedName,object:t=>t.nameOverride??t.generatedName,array:t=>t.nameOverride??t.generatedName,map:t=>t.nameOverride??t.generatedName,enum:t=>t.nameOverride??t.generatedName,reference:t=>t.nameOverride??t.generatedName,literal:t=>t.nameOverride??t.generatedName,oneOf:t=>t.nameOverride??t.generatedName,optional:t=>t.nameOverride??t.generatedName,nullable:t=>t.nameOverride??t.generatedName,unknown:t=>t.nameOverride??t.generatedName,_other:()=>{}})}function MBE(e){return Ov._visit(e,{primitive:t=>t.title,object:t=>t.title,array:t=>t.title,map:t=>t.title,enum:t=>t.title,reference:t=>t.title,literal:t=>t.title,oneOf:t=>t.title,optional:t=>t.title,nullable:t=>t.title,unknown:t=>{},_other:()=>{}})}function fw_({typeReference:e,itemType:t}){return t.startsWith("optional<")?e:typeof e=="string"?`optional<${e}>`:{...e,type:`optional<${e.type}>`}}var v5;(function(e){e[e.Channel=0]="Channel",e[e.Endpoint=1]="Endpoint",e[e.Request=2]="Request",e[e.Webhook=3]="Webhook"})(v5||(v5={}));function Ami(e){switch(e.type){case"openapi":return{openapi:e.file};case"protobuf":return{proto:e.file};default:Ao(e)}}function _w_({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){let a;switch(e.type){case"primitive":a=TBE(e);break;case"array":a=ABE({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"map":a=qBE({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"reference":a=CBE({schema:e,context:t,declarationFile:r,namespace:i});break;case"unknown":a=IBE(e.nameOverride,e.generatedName);break;case"optional":a=hw_({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"nullable":a=BBE({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"enum":a=n5a(e,n);break;case"literal":a=zBE(e,e.nameOverride,e.generatedName);break;case"object":a=YSc({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"oneOf":a=XSc({schema:e.value,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;default:Ao(e)}return a}function YSc({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){let a=t.isInState(v5.Request)&&t.respectReadonlySchemas&&(t.getEndpointMethod()==="POST"||t.getEndpointMethod()==="PUT"||t.getEndpointMethod()==="PATCH"),u=!1,c={},d=new Set;for(let g of e.properties){if(g.readonly&&(u=!0),a&&g.readonly)continue;if(Object.keys(g.conflict).length>0){if(Object.entries(g.conflict).every(([E,T])=>!T.differentSchema))continue;Object.entries(g.conflict).forEach(([E])=>{ZSc({property:g.key,schemaId:E,context:t,namespace:i}).forEach(z=>{d.add(z)})})}let O=Xg({schema:g.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1}),m=g.audiences,P=g.nameOverride,D=mR(g.availability),A=FBE(g);c[g.key]=NBE({typeReference:O,audiences:m,name:P,availability:D,propertyAccess:A})}let s=new Set;for(let g of e.allOfPropertyConflicts)g.allOfSchemaIds.forEach(O=>d.add(O)),g.conflictingTypeSignatures&&s.add(g.propertyKey);let o=[];for(let g of e.allOf){let O=yw_({schema:g.schema,context:t,namespace:i});if(O==null||d.has(g.schema)||d.has(O))continue;let m=Xg({schema:Ov.reference(g),context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1});o.push(uq(m))}for(let g of d){let O=kSc(t,g,i);for(let m of O.properties)c[m.key]==null&&(s.has(m.key)&&(c[m.key]="unknown"),c[m.key]=Xg({schema:m.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1}));for(let m of O.allOf){if(d.has(m.schema))continue;let P=Xg({schema:Ov.reference(m),context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1});o.push(uq(P))}}let l={docs:e.description??void 0,properties:Object.fromEntries(Object.entries(c).map(([g,O])=>RBE(g)?[g,typeof O=="string"?{type:O,name:`_${g}`}:{...O,name:`_${g}`}]:[g,O]))};o.length>0&&(l.extends=o),e.additionalProperties&&(l["extra-properties"]=!0),e.availability!=null&&(l.availability=mR(e.availability)),e.source!=null&&(l.source=Ami(e.source)),l.inline=eDc(e,n);let v=e.nameOverride??e.generatedName;return{name:u&&t.respectReadonlySchemas&&!a?`${v}Read`:v,schema:l}}function ZSc({property:e,schemaId:t,context:r,namespace:i}){let n=r.getSchema(t,i);if(n==null)return[];if(n.type==="reference")return ZSc({property:e,schemaId:n.schema,context:r,namespace:i});if(n.type==="object"){let{properties:a,allOf:u}=kSc(r,t,i),c=a.some(s=>s.key===e),d=[...u.flatMap(s=>ZSc({property:e,context:r,schemaId:s.schema,namespace:i}))];if(c||d.length>0)return[t,...d]}return[]}function kSc(e,t,r){let i=e.getSchema(t,r);if(i==null)return{properties:[],allOf:[]};if(i.type==="object")return{properties:i.properties,allOf:i.allOf};if(i.type==="reference")return kSc(e,i.schema,r);throw new Error(`Cannot getAllProperties for a non-object schema. schemaId=${t}, type=${i.type}`)}function ABE({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return{name:e.nameOverride??e.generatedName,schema:$Sc({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:i,declarationDepth:n})}}function qBE({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return{name:e.nameOverride??e.generatedName,schema:GSc({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:i,declarationDepth:n})}}function TBE(e){let t=Ynu(e);if(typeof t=="string")return{name:e.nameOverride??e.generatedName,schema:t};let{default:r,...i}=t;return{name:e.nameOverride??e.generatedName,schema:{...i}}}function pw_(e){return e.camel==null&&e.pascal==null&&e.screamingSnake==null&&e.snake==null}function n5a(e,t){let r={enum:e.values.map(a=>{let u=a.nameOverride??a.generatedName,c=a.value;if(u===c&&a.description==null&&(a.casing==null||pw_(a.casing)))return u;let d={value:a.value};if(u!==c&&(d.name=u),a.description!=null&&(d.docs=a.description),a.casing!=null&&!pw_(a.casing)){let s={},o=!1;a.casing.camel!=null&&(s.camel=a.casing.camel,o=!0),a.casing.screamingSnake!=null&&(s["screaming-snake"]=a.casing.screamingSnake,o=!0),a.casing.snake!=null&&(s.snake=a.casing.snake,o=!0),a.casing.pascal!=null&&(s.pascal=a.casing.pascal,o=!0),o&&(d.casing=s)}return d})};e.description!=null&&(r.docs=e.description),e.default!=null&&(r.default=e.default.value),r.inline=eDc(e,t);let i=new Set,n={...r,enum:[],source:e.source!=null?Ami(e.source):void 0};for(let a of r.enum){let u=typeof a=="string"?a:a.name??a.value;i.has(u.toLowerCase())||(n.enum.push(a),i.add(u.toLowerCase()))}return{name:e.nameOverride??e.generatedName,schema:n}}function CBE({schema:e,context:t,declarationFile:r,namespace:i}){return{name:e.nameOverride??e.generatedName,schema:HSc({schema:e,context:t,fileContainingReference:r,namespace:i})}}function BBE({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return t.respectNullableSchemas?{name:e.nameOverride??e.generatedName,schema:QSc({schema:e,context:t,fileContainingReference:r,declarationFile:r,namespace:i,declarationDepth:n})}:hw_({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n})}function hw_({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return{name:e.nameOverride??e.generatedName,schema:Xnu({schema:e,context:t,fileContainingReference:r,declarationFile:r,namespace:i,declarationDepth:n})}}function IBE(e,t){return{name:e??t,schema:JSc()}}function zBE(e,t,r){return{name:t??r,schema:KSc(e)}}function XSc({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){let a=e.encoding!=null?Knu(e.encoding):void 0;if(e.type==="discriminated"){let c={};for(let s of e.commonProperties)c[s.key]=Xg({schema:s.schema,fileContainingReference:r,context:t,namespace:i,declarationDepth:n+1});let d={};for(let[s,o]of Object.entries(e.schemas))d[s]=Xg({schema:o,context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1});return{name:e.nameOverride??e.generatedName,schema:{discriminant:e.discriminantProperty,"base-properties":c,docs:e.description??void 0,availability:e.availability!=null?mR(e.availability):void 0,union:d,encoding:a,source:e.source!=null?Ami(e.source):void 0}}}let u=[];for(let c of e.schemas)u.push(Xg({schema:c,fileContainingReference:r,context:t,namespace:i,declarationDepth:n+1}));return{name:e.nameOverride??e.generatedName,schema:{discriminated:!1,docs:e.description??void 0,union:u,encoding:a,source:e.source!=null?Ami(e.source):void 0,inline:eDc(e,n)}}}var xBE=/^[0-9]/;function RBE(e){return xBE.test(e)}function yw_({schema:e,context:t,namespace:r}){let i=t.getSchema(e,r);if(i!=null)return i.type==="reference"?yw_({context:t,schema:i.schema,namespace:r}):e}function NBE({typeReference:e,audiences:t,name:r,availability:i,propertyAccess:n}){return t.length===0&&r==null&&i==null&&n==null?e:{...typeof e=="string"?{type:e}:{...e},...t.length>0?{audiences:t}:{},...r!=null?{name:r}:{},...i!=null?{availability:i}:{},...n!=null?{access:n}:{}}}function eDc(e,t){return e.inline===!0||t>0?!0:void 0}function FBE(e){if(!(e.readonly&&e.writeonly)){if(e.readonly)return ZN.ObjectPropertyAccess.ReadOnly;if(e.writeonly)return ZN.ObjectPropertyAccess.WriteOnly}}function vw_(e){let t=e.replace(/^x-|^X-/,"");return R_(t)}var bw_="BasicAuthScheme",knu="BearerAuthScheme";function gw_(e){if(e.authOverrides!=null){for(let[r,i]of Object.entries(e.authOverrides["auth-schemes"]??{}))e.builder.addAuthScheme({name:r,schema:i});e.authOverrides.auth!=null&&e.builder.setAuth(e.authOverrides.auth);return}let t=!1;for(let[r,i]of Object.entries(e.ir.securitySchemes))if(i.type==="basic"){let n={scheme:"basic"};i.usernameVariableName!=null&&(n.username===void 0?n.username={name:i.usernameVariableName}:n.username.name=i.usernameVariableName),i.usernameEnvVar!=null&&(n.username===void 0?n.username={env:i.usernameEnvVar}:n.username.env=i.usernameEnvVar),i.passwordVariableName!=null&&(n.password===void 0?n.password={name:i.passwordVariableName}:n.password.name=i.passwordVariableName),i.passwordEnvVar!=null&&(n.password===void 0?n.password={env:i.passwordEnvVar}:n.password.env=i.passwordEnvVar),e.builder.addAuthScheme({name:bw_,schema:n}),t||(e.builder.setAuth(bw_),t=!0)}else if(i.type==="bearer"){let n={scheme:"bearer"};i.tokenVariableName!=null&&(n.token===void 0?n.token={name:i.tokenVariableName}:n.token.name=i.tokenVariableName),i.tokenEnvVar!=null&&(n.token===void 0?n.token={env:i.tokenEnvVar}:n.token.env=i.tokenEnvVar),e.builder.addAuthScheme({name:knu,schema:n}),t||(e.builder.setAuth(knu),t=!0)}else if(i.type==="header")if(t)e.builder.addGlobalHeader({name:i.headerName,schema:{type:"string",name:i.headerVariableName??vw_(i.headerName),env:i.headerEnvVar}});else{let n={header:i.headerName,name:i.headerVariableName??"apiKey",type:"string"};i.headerEnvVar!=null&&(n.env=i.headerEnvVar),i.prefix!=null&&(n.prefix=i.prefix),e.builder.addAuthScheme({name:r,schema:n}),e.builder.setAuth(r),t=!0}else if(i.type==="oauth"){let n={scheme:"bearer"};e.builder.addAuthScheme({name:knu,schema:n}),t||(e.builder.setAuth(knu),t=!0),i.scopesEnum!=null&&i.scopesEnum.values.length>0&&e.builder.addType(wy.of("__package__.yml"),{name:"OauthScope",schema:n5a(i.scopesEnum,0).schema})}}function ior({header:e,context:t,fileContainingReference:r,namespace:i}){let n=Xg({schema:e.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),a=uq(n),u=e.name.replace(/^x-|^X-/,""),c=e.parameterNameOverride!=null?e.parameterNameOverride:R_(u);if(e.description==null&&e.name===c&&e.env==null&&e.availability==null)return a;let d={type:a};return c!==e.name&&(d.name=c),e.description!=null&&(d.docs=e.description),e.env!=null&&(d.env=e.env),e.availability!=null&&(d.availability=mR(e.availability)),d}function eau({pathParameter:e,context:t,fileContainingReference:r,namespace:i}){let n=Xg({schema:e.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:0});if(e.variableReference==null&&e.description==null&&e.availability==null)return uq(n);let a=e.variableReference!=null?{variable:`$${e.variableReference}`}:{type:uq(n)};return e.description!=null&&(a.docs=e.description),e.availability!=null&&(a.availability=mR(e.availability)),a}function rau({queryParameter:e,context:t,fileContainingReference:r,namespace:i}){let n=tDc({schema:e.schema,context:t,fileContainingReference:r,namespace:i});if(n==null)return;let a=uq(n.value),u=i5a(n.value);a==="unknown"?a="string":a==="optional<unknown>"&&(a="optional<string>");let c={type:a};return u!=null&&(c.default=u),n.allowMultiple&&(c["allow-multiple"]=!0),e.description!=null&&(c.docs=e.description),e.parameterNameOverride!=null&&(c.name=e.parameterNameOverride),e.availability!=null&&(c.availability=mR(e.availability)),LBE(n.value)&&n.value.validation!==void 0&&(c.validation=n.value.validation),c.default==null&&c["allow-multiple"]==null&&c.docs==null&&c.name==null&&c.availability==null&&c.validation==null?a:c}function tDc({schema:e,context:t,fileContainingReference:r,namespace:i}){if(e.type==="reference"){let n=t.getSchema(e.schema,i);if(n==null)return;if(n.type==="array")return{value:Xg({schema:Ov.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:n.value,description:e.description??n.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:void 0}),context:t,declarationFile:wy.of(SS),fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(n.type==="oneOf"&&n.value.type==="undiscriminated"){let a=[],u=!1;for(let[c,d]of Object.entries(n.value.schemas))d.type==="primitive"&&d.schema.type==="string"&&(u=!0),d.type==="literal"&&d.value.type==="string"&&(CJn.test(d.value.value)?a.push(d.value.value):a.push({value:d.value.value,name:BJn(d.value.value)}));if(a.length>0)return t.builder.addType(r,{name:e.generatedName,schema:{enum:a}}),u&&t.respectForwardCompatibleEnums?(t.builder.addType(r,{name:`${e.generatedName}OrString`,schema:{discriminated:!1,union:[{type:"string"},{type:e.generatedName}]}}),{value:`${e.generatedName}OrString`,allowMultiple:!1}):{value:e.generatedName,allowMultiple:!1};if(n.value.schemas.length===2){let[c,d]=n.value.schemas;if(c!=null&&d!=null&&tau({array:c,primitive:d}))return{value:Xg({schema:Ov.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:d,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:void 0}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(c!=null&&d!=null&&tau({array:c,primitive:d}))return{value:Xg({schema:Ov.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:c,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:void 0}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0}}for(let[c,d]of Object.entries(n.value.schemas))return tDc({schema:d,context:t,fileContainingReference:r,namespace:i})}else if(t.objectQueryParameters)return{value:Xg({schema:e,context:t,fileContainingReference:r,declarationFile:wy.of(SS),namespace:i,declarationDepth:0}),allowMultiple:!1}}if(e.type==="optional"||e.type==="nullable"){if(e.value.type==="reference"){let n=t.getSchema(e.value.schema,i);if(n==null)return;if(n.type==="array")return{value:Xg({schema:Ov.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:n.value,description:e.description??n.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,declarationFile:wy.of(SS),namespace:i,declarationDepth:0}),allowMultiple:!0};if(t.objectQueryParameters)return{value:Xg({schema:e,context:t,fileContainingReference:r,declarationFile:wy.of(SS),namespace:i,declarationDepth:0}),allowMultiple:!1}}if(e.value.type==="array")return{value:Xg({schema:Ov.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value.value,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(e.value.type==="oneOf"&&e.value.value.type==="undiscriminated"){let n=[],a=!1;for(let[u,c]of Object.entries(e.value.value.schemas))c.type==="primitive"&&c.schema.type==="string"&&(a=!0),c.type==="literal"&&c.value.type==="string"&&(CJn.test(c.value.value)?n.push(c.value.value):n.push({value:c.value.value,name:BJn(c.value.value)}));if(n.length>0)return t.builder.addType(r,{name:e.generatedName,schema:{enum:n}}),a&&t.respectForwardCompatibleEnums?(t.builder.addType(r,{name:`${e.generatedName}OrString`,schema:{discriminated:!1,union:[{type:"string"},{type:`optional<${e.value.value.generatedName}>`}]}}),{value:`optional<${e.value.value.generatedName}OrString>`,allowMultiple:!1}):{value:`optional<${e.value.value.generatedName}>`,allowMultiple:!1};if(e.value.value.schemas.length===2){let[u,c]=e.value.value.schemas;if(u!=null&&c!=null&&tau({array:u,primitive:c}))return{value:Xg({schema:Ov.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:c,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(u!=null&&c!=null&&tau({array:c,primitive:u}))return{value:Xg({schema:Ov.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:u,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0}}if(t.objectQueryParameters)return{value:Xg({schema:e,context:t,fileContainingReference:r,declarationFile:wy.of(SS),namespace:i,declarationDepth:0}),allowMultiple:!1};for(let[u,c]of Object.entries(e.value.value.schemas))return tDc({schema:Ov.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:c,description:void 0,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i})}else if(e.value.type==="object")return t.objectQueryParameters?{value:Xg({schema:e,context:t,fileContainingReference:r,declarationFile:wy.of(SS),namespace:i,declarationDepth:0}),allowMultiple:!1}:void 0;return{value:Xg({schema:e,context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!1}}return e.type==="array"?{value:Xg({schema:Ov.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0}:{value:Xg({schema:e,context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!1}}function tau({array:e,primitive:t}){return e?.type==="array"&&e.value.type==="primitive"&&t?.type==="primitive"&&e.value.schema.type===t.schema.type}function LBE(e){return e.type!=null}function Ow_({websocketExample:e,context:t}){let r={messages:[]};e.name!=null&&(r.name=e.name),e.description!=null&&(r.docs=e.description),e.queryParameters!=null&&e.queryParameters.length>0&&(r["query-parameters"]=UBE(e.queryParameters)),e.headers!=null&&e.headers.length>0&&(r.headers=VBE({context:t,namedFullExamples:e.headers}));for(let i of e.messages){let n=v3i(i.payload);n!=null&&r.messages.push({type:i.messageType,body:n})}return r}function UBE(e){let t={};return e.forEach(r=>{let i=v3i(r.value);Array.isArray(i)?t[r.name]=i[0]:i!=null&&(t[r.name]=i)}),t}function VBE({context:e,namedFullExamples:t}){let r=e.builder.getGlobalHeaderNames(),i={};return t.forEach(n=>{let a=v3i(n.value);r.has(n.name)||a!=null&&(i[n.name]=a)}),i}function v3i(e){switch(e.type){case"primitive":return mw_(e.value);case"object":return Pw_(e.properties);case"array":return WBE(e.value);case"map":return HBE(e.value);case"oneOf":return $BE(e.value);case"enum":return e.value;case"literal":return GBE(e.value);case"unknown":return v3i(e.value);default:Ao(e)}}function mw_(e){switch(e.type){case"int":return e.value;case"int64":return e.value;case"uint":return e.value;case"uint64":return e.value;case"float":return e.value;case"double":return e.value;case"string":return e.value.startsWith("$")?`${e.value.slice(1)}`:e.value;case"datetime":try{return new Date(e.value).toISOString().replace(/\.\d{3}Z$/,"Z")}catch{return"2024-01-15T09:30:00Z"}case"date":return e.value;case"base64":case"boolean":return e.value;default:Ao(e)}}function Pw_(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,v3i(r)]))}function WBE(e){return e.map(t=>v3i(t))}function HBE(e){return Object.fromEntries(e.map(t=>[mw_(t.key),v3i(t.value)]))}function $BE(e){return e.type==="discriminated"?Pw_(e.value):v3i(e.value)}function GBE(e){switch(e.type){case"string":return e.value;case"boolean":return e.value;default:Ao(e)}}function qmi(e){return e.find(t=>typeof t!="string"&&t.type==="namespace")?.name}function iau(e,t){return t??(e?.groupName!=null?qmi(e.groupName):void 0)}function jw_({channel:e,context:t,declarationFile:r}){let i={path:e.path,url:e.servers[0]?.name,auth:!1};e.audiences!=null&&e.audiences.length>0&&(i.audiences=e.audiences),e.summary!=null&&(i["display-name"]=e.summary),e.description!=null&&(i.docs=e.description);let n=qmi(e.groupName),a={};if(e.handshake.pathParameters.length>0)for(let d of e.handshake.pathParameters)a[d.name]=eau({pathParameter:d,context:t,fileContainingReference:r,namespace:n});Object.keys(a).length>0&&(i["path-parameters"]=a);let u={};if(e.handshake.queryParameters.length>0)for(let d of e.handshake.queryParameters){let s=rau({queryParameter:d,context:t,fileContainingReference:r,namespace:n});s!=null&&(u[d.name]=s)}Object.keys(u).length>0&&(i["query-parameters"]=u);let c={};if(e.handshake.headers.length>0)for(let d of e.handshake.headers){let s=ior({header:d,context:t,fileContainingReference:r,namespace:n});c[d.name]=s}Object.keys(c).length>0&&(i.headers=c),t.builder.addChannel(r,{channel:i});for(let d of e.messages)t.builder.addChannelMessage(r,{messageId:d.name,message:{origin:d.origin,body:Xg({schema:d.body,context:t,fileContainingReference:r,namespace:n,declarationDepth:0})}});for(let d of e.examples){let s=Ow_({context:t,websocketExample:d});t.builder.addChannelExample(r,{example:s})}}function ww_(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="grouped"}var Tmi="Base",QBE="Default";function vnn(e){return Object.entries(e).reduce((t,[r,i])=>(VAe(i)?Object.entries(i.urls).forEach(([n,a])=>{t[n]=a}):t[r]=typeof i=="string"?i:i.url,t),{})}function Sw_(e){if(e.environmentOverrides!=null){for(let[D,A]of Object.entries(e.environmentOverrides.environments??{}))e.builder.addEnvironment({name:D,schema:A});e.environmentOverrides["default-environment"]!=null&&e.builder.setDefaultEnvironment(e.environmentOverrides["default-environment"]),e.environmentOverrides["default-url"]!=null&&e.builder.setDefaultUrl(e.environmentOverrides["default-url"]);return}let t={},r=[],i=e.ir.servers.some(D=>ww_(D)),n=e.ir.servers;for(let D of n)if(ww_(D)){let A={urls:{}};for(let[M,E]of Object.entries(D.urls))A.urls[M]=E.url;D.name&&(t[D.name]=A)}else if("url"in D&&D.url){let A=D.audiences?{url:D.url,audiences:D.audiences}:D.url;if(D.name==null){r.push(A);continue}t[D.name]=A}let a={},u={},c=[];for(let D of e.ir.endpoints)for(let A of D.servers){if(A.url==null&&A.name!=null){a[A.name]||(a[A.name]=[]);continue}if(A.url==null)continue;let M=A.audiences?{url:A.url,audiences:A.audiences}:A.url;if(A.name==null){c.push(M);continue}a[A.name]||(a[A.name]=[]),a[A.name]?.push({url:A.url,audiences:A.audiences}),u[A.name]=M}let d={},s=[];for(let D of e.ir.websocketServers){let A=D.audiences?{url:D.url,audiences:D.audiences}:D.url;if(D.name==null){s.push(A);continue}d[D.name]=A}let o=Object.keys(t).length,l=o>0,v=Object.keys(u).length>0,g=Object.keys(a).some(D=>a[D]?.length===0),O=Object.keys(d).length>0;if(!l&&!v&&O&&e.ir.servers.length===0){for(let[D,A]of Object.entries(d))e.builder.addEnvironment({name:D,schema:A});e.builder.setDefaultEnvironment(Object.keys(d)[0]),e.builder.setDefaultUrl(Tmi);return}if(c.length>0&&e.logger.error(`Skipping endpoint level servers ${c.map(D=>typeof D=="string"?D:D.url).join(", ")} because x-fern-server-name was not provided.`),!l){let D=e.ir.servers[0]?.url,A=e.ir.servers[0]?.audiences;if(D!=null){let M=A?{url:D,audiences:A}:D;t[QBE]=M}}let m=Object.values(t).map(D=>typeof D=="string"?D:VAe(D)?Object.values(D.urls)[0]:D.url),P=r.filter(D=>{let A=typeof D=="string"?D:D.url;return!m.includes(A)});if(P.length>0&&e.logger.error(`Skipping top level servers ${P.map(D=>typeof D=="string"?D:D.url).join(", ")} because x-fern-server-name was not provided.`),i){let D=!0;for(let[A,M]of Object.entries(t))if(e.builder.addEnvironment({name:A,schema:M}),D){if(e.builder.setDefaultEnvironment(A),VAe(M)){let E=Object.keys(M.urls)[0];E&&e.builder.setDefaultUrl(E)}D=!1}return}if(!v&&!g){let D=!0;for(let[A,M]of Object.entries(t))if(D){if(O){let E=typeof M=="string"?M:VAe(M)?Object.values(M.urls)[0]:M.url;e.builder.addEnvironment({name:A,schema:{urls:{[Tmi]:E??"",...vnn(d)}}})}else e.builder.addEnvironment({name:A,schema:M});e.builder.setDefaultEnvironment(A),D=!1}else if(O){let E=typeof M=="string"?M:VAe(M)?Object.values(M.urls)[0]:M.url;e.builder.addEnvironment({name:A,schema:{urls:{[Tmi]:E??"",...vnn(d)}}})}else e.builder.addEnvironment({name:A,schema:M});O&&e.builder.setDefaultUrl(Tmi)}else if(o===1){let D=Object.keys(t)[0],A=Object.values(t)[0],M=typeof A=="string"?A:VAe(A)?Object.values(A.urls)[0]:A.url;e.builder.addEnvironment({name:D,schema:{urls:{[Tmi]:M??"",...vnn(u),...vnn(d)}}}),e.builder.setDefaultEnvironment(D),e.builder.setDefaultUrl(Tmi)}else{let D=new Map;for(let A of e.ir.endpoints)for(let M of A.servers)if(M.url!=null&&M.name!=null){D.has(M.name)||D.set(M.name,new Map);let E=M.url.match(/[-]([a-z0-9]+)\./i)?.[1]?.toLowerCase()||"production",T=D.get(M.name);T&&T.set(E,M.url)}if(D.size>0){let A=!0;for(let[M,E]of Object.entries(t)){let T=typeof E=="string"?E:VAe(E)?Object.values(E.urls)[0]:E.url;if(!T)continue;let z=T.match(/[-]([a-z0-9]+)\./i)?.[1]?.toLowerCase()||"production",G={[Tmi]:T};for(let[I,R]of D.entries()){let U=R.get(z)||R.get("production")||R.values().next().value;U&&(G[I]=U)}O&&Object.assign(G,vnn(d)),Object.keys(G).length>1?e.builder.addEnvironment({name:M,schema:{urls:G}}):e.builder.addEnvironment({name:M,schema:T}),A&&(e.builder.setDefaultEnvironment(M),A=!1)}D.size>0&&e.builder.setDefaultUrl(Tmi)}else{let A=!0;for(let[M,E]of Object.entries(t)){if(O||Object.keys(u).length>0){let T=typeof E=="string"?E:VAe(E)?Object.values(E.urls)[0]:E.url;e.builder.addEnvironment({name:M,schema:{urls:{[Tmi]:T??"",...vnn(u),...vnn(d)}}})}else e.builder.addEnvironment({name:M,schema:E});A&&(e.builder.setDefaultEnvironment(M),A=!1)}}}}function nau(e){return uq(e).startsWith("optional")?e:typeof e=="string"?`optional<${e}>`:{...e,type:`optional<${e.type}>`}}var rDc=class{schema;count=0;constructor(t){this.schema=t}increment(){this.count+=1}},JBE=.75,KBE=new Set("authorization");function Dw_(e){if(e.globalHeaderOverrides!=null){for(let[r,i]of Object.entries(e.globalHeaderOverrides.headers??{}))e.builder.addGlobalHeader({name:r,schema:i});return}let t=Object.fromEntries((e.ir.globalHeaders??[]).map(r=>[r.header,r]));for(let[r,i]of Object.entries(t)){let n="optional<string>";if(i.name==null&&i.env==null&&typeof i.schema=="string")n=i.schema;else if(i!=null){let a=i.schema?IJn(i.schema):void 0,u=a!=null?qmi(a):void 0,c=wy.of("api.yml");n={name:i.name,env:i.env,type:i.schema!=null?uq(Xg({schema:i.schema,context:e,fileContainingReference:u?GN(wy.of(R_(u)),c):c,namespace:u,declarationDepth:0}))??"optional<string>":"optional<string>"}}e.builder.addGlobalHeader({name:r,schema:n})}if(e.detectGlobalHeaders){let r={};for(let n of e.ir.endpoints)for(let a of n.headers){if(KBE.has(a.name.toLowerCase()))continue;let u=r[a.name];if(u==null){let c=t[a.name],d=ior({header:{...a,schema:c?.schema??a.schema,name:c?.name??a.name},fileContainingReference:wy.of(i6),context:e,namespace:void 0});u=new rDc(d),r[a.name]=u}u.increment()}let i=e.ir.endpoints.length*JBE;for(let[n,a]of Object.entries(r)){let u=t[n],c=a.count===e.ir.endpoints.length,d=a.count>=i;u==null&&(c?e.builder.addGlobalHeader({name:n,schema:a.schema}):d&&e.builder.addGlobalHeader({name:n,schema:nau(a.schema)}))}}}function Ew_(e){for(let t of e.ir.idempotencyHeaders??[]){let r=t.schema?IJn(t.schema):void 0,i=r!=null?qmi(r):void 0,n=ior({header:{...t,schema:t.schema??Ov.primitive({description:void 0,availability:void 0,generatedName:"",title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0,schema:xw.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0})}),name:t.name??t.header,parameterNameOverride:void 0,description:void 0,availability:void 0,source:void 0},fileContainingReference:wy.of(i6),context:e,namespace:i});e.builder.addIdempotencyHeader({name:t.header,schema:nau(n)})}}function BK(e){switch(e.type){case"primitive":return Aw_(e.value);case"object":return qw_(e.properties);case"array":return Tw_(e.value);case"map":return XBE(e.value);case"oneOf":return ZBE(e.value);case"enum":return typeof e.value=="string"&&e.value.startsWith("$")?`\\${e.value}`:e.value;case"literal":return kBE(e.value);case"unknown":return BK(e.value);default:Ao(e)}}function Mw_(e){switch(e.type){case"withStreaming":return e.sse?{stream:YBE(e.events)}:{stream:Tw_(e.events)};case"withoutStreaming":return{body:BK(e.value)};default:Ao(e)}}function Aw_(e){switch(e.type){case"int":return e.value;case"int64":return e.value;case"uint":return e.value;case"uint64":return e.value;case"float":return e.value;case"double":return e.value;case"string":return e.value.startsWith("$")?`\\${e.value}`:e.value;case"datetime":try{return!e.value.endsWith("Z")&&!e.value.includes("+")&&(e.value+="Z"),new Date(e.value).toISOString().replace(/\.\d{3}Z$/,"Z")}catch{return"2024-01-15T09:30:00Z"}case"date":return e.value;case"base64":case"boolean":return e.value;default:Ao(e)}}function qw_(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,BK(r)]))}function YBE(e){return e.map(t=>({event:"",data:BK(t)}))}function Tw_(e){return e.map(t=>BK(t))}function XBE(e){return Object.fromEntries(e.map(t=>[Aw_(t.key),BK(t.value)]))}function ZBE(e){return e.type==="discriminated"?qw_(e.value):BK(e.value)}function kBE(e){switch(e.type){case"string":return e.value;case"boolean":return e.value;default:Ao(e)}}function Cw_({endpointExample:e,context:t}){let r={};if(e.type!=="full")return e.value;e.name!=null&&(r.name=e.name),e.description!=null&&(r.docs=e.description),e.pathParameters!=null&&e.pathParameters.length>0&&(r["path-parameters"]=eIE(e.pathParameters)),e.queryParameters!=null&&e.queryParameters.length>0&&(r["query-parameters"]=tIE(e.queryParameters));let i=e.headers!=null&&e.headers.length>0,n=t.builder.getGlobalHeaders(),a=Object.keys(n).length>0,u=new Set(e.headers?.map(c=>c.name)??[]);if(i||a){let c=[];if(e.headers!=null)for(let d of e.headers)d.name!==t.builder.getAuthHeaderName()&&c.push(d);for(let[d,s]of Object.entries(n))if(!u.has(d))if(s!=null&&typeof s=="object"&&s.type!=null){let o=v6({type:s.type,_default:void 0,validation:void 0,visitor:{primitive:l=>l.toString(),map:l=>l.toString(),list:l=>l,optional:l=>l,nullable:l=>l,set:l=>l,named:l=>l,literal:l=>{if(l.type==="string")return l.string;if(l.type==="boolean")return l.boolean.toString()},unknown:$o}});o!=null&&c.push({name:d,value:Yg.literal(a3i.string(o))})}else c.push({name:d,value:Yg.primitive(D_.string(d))});r.headers=rIE({context:t,namedFullExamples:c})}return e.request!=null&&(r.request=BK(e.request)),e.response!=null&&(r.response=Mw_(e.response)),e.codeSamples!=null&&e.codeSamples.length>0&&(r["code-samples"]=e.codeSamples.map(c=>c.type==="language"?{name:c.name??void 0,docs:c.description??void 0,language:c.language,code:c.code,install:c.install??void 0}:{name:c.name??void 0,docs:c.description??void 0,sdk:c.sdk,code:c.code}).filter(yy)),r}function eIE(e){let t={};return e.forEach(r=>{let i=BK(r.value);i!=null&&(t[r.parameterNameOverride??r.name]=i)}),t}function tIE(e){let t={};return e.forEach(r=>{let i=BK(r.value);Array.isArray(i)?t[r.name]=i[0]:i!=null&&(t[r.name]=i)}),t}function rIE({context:e,namedFullExamples:t}){let r={};return t.forEach(i=>{let n=BK(i.value);n!=null&&(r[i.name]=n)}),r}function Bw_(e){return g$._visit(e,{get:()=>ZN.HttpMethodSchema.Get,post:()=>ZN.HttpMethodSchema.Post,put:()=>ZN.HttpMethodSchema.Put,patch:()=>ZN.HttpMethodSchema.Patch,delete:()=>ZN.HttpMethodSchema.Delete,head:()=>ZN.HttpMethodSchema.Head,options:()=>{throw new Error("OPTIONS is unsupported")},trace:()=>{throw new Error("TRACE is unsupported")},_other:()=>{throw new Error("Unknown http method is unsupported")}})}function Iw_(e){return e==="POST"||e==="PUT"||e==="PATCH"}function zw_({endpoint:e,declarationFile:t,context:r}){let{nonRequestReferencedSchemas:i}=r.ir,n=[],a=new Set,u=e.path,c=iau(e.sdkName,e.namespace),d={};for(let P of e.pathParameters)P.parameterNameOverride&&(u=u.replace(P.name,P.parameterNameOverride)),d[P.parameterNameOverride??P.name]=eau({pathParameter:P,context:r,fileContainingReference:t,namespace:c}),a.add(P.name);let s={};for(let P of e.queryParameters){let D=rau({queryParameter:P,context:r,fileContainingReference:t,namespace:c});D!=null&&(s[P.name]=D,a.add(P.name))}let o;if(e.pagination!=null)switch(e.pagination.type){case"cursor":o={cursor:e.pagination.cursor,next_cursor:e.pagination.nextCursor,results:e.pagination.results};break;case"offset":o={offset:e.pagination.offset,step:e.pagination.step,results:e.pagination.results,"has-next-page":e.pagination.hasNextPage};break;case"custom":o={type:"custom",results:e.pagination.results};break;default:Ao(e.pagination)}let l={path:u,method:Bw_(e.method),auth:e.authed,docs:e.description??void 0,pagination:o,source:e.source!=null?Ami(e.source):void 0};!aIE({context:r,request:e.request})&&Object.keys(d).length>0&&(l["path-parameters"]=d),e.summary!=null&&(l["display-name"]=e.summary);let v={},g=r.builder.getGlobalHeaderNames(),O=r.builder.getAuthHeaderName();O!=null&&g.add(O);let m=e.headers.filter(P=>!g.has(P.name));for(let P of m){let D=ior({header:P,context:r,fileContainingReference:t,namespace:c});v[P.name]=D,a.add(typeof D=="string"?P.name:D.name??P.name)}if(e.request!=null){r.setInState(v5.Request);let P=nIE({endpoint:e,context:r,declarationFile:t,request:e.request,generatedRequestName:e.generatedRequestName,requestNameOverride:e.requestNameOverride??void 0,pathParameters:r.inlinePathParameters&&Object.keys(d).length>0?d:void 0,queryParameters:Object.keys(s).length>0?s:void 0,nonRequestReferencedSchemas:Array.from(i),headers:Object.keys(v).length>0?v:void 0,usedNames:a,namespace:c});l.request=P.value,n=[...n,...P.schemaIdsToExclude??[]],r.unsetInState(v5.Request)}else{let P=r.inlinePathParameters&&Object.keys(d).length>0,D=Object.keys(s).length>0,A=Object.keys(v).length>0,M={};(P||D||A)&&(M.name=e.requestNameOverride??e.generatedRequestName),P&&(M["path-parameters"]=d),D&&(M["query-parameters"]=s),A&&(M.headers=v),Object.keys(M).length>0&&(l.request=M)}if(e.response!=null&&e.response._visit({json:P=>{let D=Xg({schema:P.schema,context:r,fileContainingReference:t,namespace:c,declarationDepth:0});l.response={docs:P.description??void 0,type:uq(D)},P.statusCode!=null&&(l.response["status-code"]=P.statusCode),P.responseProperty!=null&&(l.response.property=P.responseProperty)},streamingJson:P=>{let D=Xg({schema:P.schema,context:r,fileContainingReference:t,namespace:c,declarationDepth:0});l["response-stream"]={docs:P.description??void 0,type:uq(D),format:"json"}},streamingSse:P=>{let D=Xg({schema:P.schema,context:r,fileContainingReference:t,namespace:c,declarationDepth:0});l["response-stream"]={docs:P.description??void 0,type:uq(D),format:"sse"}},file:P=>{l.response={docs:P.description??void 0,type:"file","status-code":P.statusCode}},bytes:P=>{l.response={docs:P.description??void 0,type:"bytes","status-code":P.statusCode}},streamingText:P=>{l["response-stream"]={docs:P.description??void 0,type:"text"}},text:P=>{l.response={docs:P.description??void 0,type:"text","status-code":P.statusCode}},_other:()=>{throw new Error("Unrecognized Response type: "+e.response?.type)}}),r.builder.getEnvironmentType()==="multi"){let P=r.getDefaultServerName(),D=e.servers[0];D==null?P!=null&&(l.url=P):l.url=D.name??void 0}return e.idempotent&&(l.idempotent=!0),e.availability!=null&&(l.availability=mR(e.availability)),Object.entries(e.errors).forEach(([P,D])=>{let A=D.generatedName,M=wy.of(SS);r.builder.enableUniqueErrorsPerEndpoint&&(A=`${e.generatedRequestName}${D.generatedName}`,D.schema!=null&&(D.schema.type!=="reference"&&D.schema.type!=="oneOf"?D.schema.generatedName=`${e.generatedRequestName}${D.schema.generatedName}`:D.schema.type==="oneOf"&&(D.schema.value.generatedName=`${e.generatedRequestName}${D.schema.value.generatedName}`)));let E={"status-code":parseInt(P)},T=lw_({location:xw_,namespaceOverride:c});if(D.schema!=null){let I=Xg({schema:D.schema,context:r,fileContainingReference:T,declarationFile:T,namespace:c,declarationDepth:0});E.type=uq(I),E.docs=D.description}r.builder.addError(T,{name:A,schema:r.isErrorUnknownSchema(parseInt(P))?{...E,type:"unknown"}:E}),l.errors==null&&(l.errors=[]);let z=r.builder.addImport({file:t,fileToImport:T});l.errors.push(z!=null?`${z}.${A}`:A),E.type!=null&&D.examples?.forEach(I=>{let R={value:BK(I.example),name:I.name,docs:I.description};r.builder.addErrorExample(T,{name:A,example:R})})}),e.examples.length>0&&(l.examples=iIE({endpointExamples:e.examples,context:r})),r.ir.hasEndpointsMarkedInternal&&(e.internal==null||!e.internal)?l.audiences=[iDc,...e.audiences]:e.audiences.length>0&&(l.audiences=e.audiences),{value:l,schemaIdsToExclude:n}}function iIE({endpointExamples:e,context:t}){return e.map(r=>{try{return Cw_({endpointExample:r,context:t})}catch(i){throw console.error(`Error building endpoint example: ${i}`),i}})}function nIE({endpoint:e,declarationFile:t,context:r,request:i,requestNameOverride:n,generatedRequestName:a,pathParameters:u,queryParameters:c,nonRequestReferencedSchemas:d,headers:s,usedNames:o,namespace:l}){if(i.type==="json"||i.type==="formUrlEncoded"){let v=i.schema.type==="reference"?i.schema.schema:void 0,g=i.schema.type==="reference"?r.getSchema(i.schema.schema,l):i.schema;if(g?.type!=="object"||v!=null&&d.includes(v)){let A=Xg({schema:i.schema,fileContainingReference:t,context:r,namespace:l,declarationDepth:0}),M={schemaIdsToExclude:[],value:{body:A}},E=Object.keys(u??{}).length>0,T=Object.keys(c??{}).length>0,z=Object.keys(s??{}).length>0;return E&&(M.value["path-parameters"]=u),T&&(M.value["query-parameters"]=c),z&&(M.value.headers=s),(E||T||z)&&(M.value.name=n??a),i.contentType!=null&&(M.value["content-type"]=i.contentType),i.description!=null&&(M.value.docs=i.description),M}let O=Object.fromEntries(g.properties.filter(A=>A.readonly==null?!0:!(Iw_(e.method)&&A.readonly)).map(A=>{let M=Xg({schema:A.schema,fileContainingReference:t,context:r,namespace:l,declarationDepth:1}),E=A.nameOverride??A.key,T=mR(A.availability);if(!o.has(E)&&A.audiences.length<=0)return o.add(E),A.nameOverride!=null?[A.key,{type:uq(M),docs:zJn(M),name:A.nameOverride,availability:T}]:[A.key,T?{...typeof M=="string"?{type:M}:M,availability:T}:M];let z={type:uq(M),docs:zJn(M)};return o.has(E)&&(z.name=A.generatedName),A.audiences.length>0&&(z.audiences=A.audiences),T!=null&&(z.availability=T),o.add(E),[A.key,z]})),m=g.allOf.map(A=>{let M=Xg({schema:Ov.reference(A),fileContainingReference:t,context:r,namespace:l,declarationDepth:0});return uq(M)}).filter(A=>A!=="unknown"),P={properties:O};m.length>0&&(P.extends=m),i.additionalProperties&&(P["extra-properties"]=!0);let D={name:n??g.nameOverride??g.generatedName,"path-parameters":u,"query-parameters":c,headers:s,body:P};return i.contentType!=null&&(D["content-type"]=i.contentType),i.description!=null&&(D.docs=i.description),{schemaIdsToExclude:v!=null?[v]:[],value:D}}else if(i.type==="octetStream"){let v={body:"bytes","content-type":i.contentType??Bq.APPLICATION_OCTET_STREAM,"query-parameters":c};return c!=null&&(v.name=n??a),i.description!=null&&(v.docs=i.description),{schemaIdsToExclude:[],value:v}}else if(i.type==="multipart"){let v=Object.fromEntries(i.properties.map(g=>{if(g.schema.type==="file"){let O=g.schema.isArray?"list<file>":"file";if(O=g.schema.isOptional?`optional<${O}>`:O,g.description!=null||g.contentType!=null){let m={type:O};if(g.description!=null&&(m.docs=g.description),g.contentType!=null){let P=g.contentType.split(",")[0];m["content-type"]=P}return[g.key,m]}return[g.key,O]}else{let O=Xg({schema:g.schema.value,fileContainingReference:t,context:r,namespace:l,declarationDepth:1});if(g.contentType||g.exploded||g.encoding){let m=typeof O=="string"?{type:O}:O;g.contentType!=null&&(m["content-type"]=g.contentType),g.encoding==="form"?m.style="form":g.encoding==="json"?m.style="json":g.exploded&&(m.style="exploded"),O=m}return[g.key,O]}}));return{schemaIdsToExclude:i.name==null?[]:[i.name],value:{name:n??i.name??a,"path-parameters":u,"query-parameters":c,headers:s,body:{properties:v},"content-type":Bq.MULTIPART_FORM_DATA,...i.description?{docs:i.description}:{}}}}else Ao(i)}function aIE({context:e,request:t}){if(!e.inlinePathParameters)return!1;if(t==null)return!0;switch(t.type){case"octetStream":return!1;case"multipart":return!0;case"json":return!0;case"formUrlEncoded":return!0;default:Ao(t)}}function oIE({location:e,namespaceOverride:t}){return t!=null?{...e,file:GN(wy.of(t),e.file)}:e}function uIE(e){let t=e.namespace,r=e.tags.filter(d=>d!==t)[0],i=e.operationId;if(i==null)return r!=null?{file:wy.of(`${R_(r)}.yml`),endpointId:e.summary!=null?R_(e.summary):R_(`${e.method}_${e.path.split("/").join("_")}`)}:e.summary!=null?{file:wy.of(SS),endpointId:R_(e.summary)}:{file:wy.of(SS),endpointId:R_(`${e.method}_${e.path.split("/").join("_")}`)};if(r==null)return{file:wy.of(SS),endpointId:i};let n=a5a(r),a=a5a(i);if(W8(n,a))return{file:wy.of("__package__.yml"),endpointId:r};let u=lIE({operationId:i,tag:r,path:e.path,method:e.method});if(u!=null)return u;let c=[];for(let d=0;d<n.length;++d){let s=n[d];if(s!=null&&s===a[d])c.push(s);else{let o=R_(r);return{file:wy.of(`${o}.yml`),endpointId:i,tag:r}}}if(c.length>=a.length)throw new Error(`Cannot get file for endpoint ${JSON.stringify(e)}`);return{file:wy.of(R_(c.join("_"))+".yml"),endpointId:R_(a.slice(c.length).join("_")),tag:r}}function o5a(e){let t=e.tags[0];if(e.sdkName!=null){let r=USc({sdkName:e.sdkName,namespaceOverride:e.namespace}),i=`${r}.yml`,n=r.toLowerCase()===t?.toLowerCase().replaceAll(" ","");return{file:wy.of(i),endpointId:e.sdkName.methodName,tag:n?t:void 0}}return oIE({namespaceOverride:e.namespace,location:uIE(e)})}function a5a(e){let t;return/^[a-z]+(?:[A-Z][a-z]+)*$/.test(e)?t=e.split(/(?=[A-Z])/):t=e.split(/[^a-zA-Z0-9]+/),t=t.map(r=>r.toLowerCase()),t=j3e(t),t}var sIE=new RegExp("[^a-zA-Z0-9{}]+"),cIE=new RegExp("[{}]","g");function lIE({operationId:e,tag:t,path:r,method:i}){let a=`${r.split(sIE).join("_").replaceAll(cIE,"_")}_${i.toLowerCase()}`;if(e.endsWith(a))return{file:wy.of(R_(t)+".yml"),endpointId:R_(e.slice(0,-1*a.length)),tag:t}}function Rw_(e){let t=new Set,{endpoints:r,tags:i}=e.ir,n=[];for(let a of r){let{endpointId:u,file:c,tag:d}=o5a(a),s=c.split(".")[0];s!=null&&t.add(s);let o;if(a.sdkName!=null){let g=e.ir.groups;for(let O of a.sdkName.groupName){let m=typeof O=="string"?O:O.name,P=g[m];if(P==null)break;if(P.summary!=null||P.description!=null){o=g[m];break}}}let l=d==null?void 0:i.tagsById[d];e.setInState(v5.Endpoint),e.setEndpointMethod(a.method);let v=zw_({context:e,endpoint:a,declarationFile:c});e.unsetEndpointMethod(),e.unsetInState(v5.Endpoint),n=[...n,...v.schemaIdsToExclude],e.builder.addEndpoint(c,{name:u,schema:v.value,source:a.source!=null?Ami(a.source):void 0}),(l?.id!=null||l?.description!=null)&&e.builder.setServiceInfo(c,{"display-name":o?.summary??l?.id,docs:o?.description??l?.description??void 0})}return{schemaIdsToExclude:n,sdkGroups:t}}function Nw_(e){for(let[t,r]of Object.entries(e.ir.variables)){let i=r.groupName!=null?qmi(r.groupName):void 0,n=Xg({schema:Ov.primitive(r),context:e,fileContainingReference:wy.of(SS),namespace:i,declarationDepth:0});e.builder.addVariable({name:t,schema:{type:uq(n),docs:r.description??void 0}})}}function Fw_(e){for(let t of e.ir.webhooks){let r=pIE({webhook:t,context:e});if(r==null)continue;let i=iau(t.sdkName,t.namespace),n={};for(let u of t.headers)n[u.name]=ior({header:u,context:e,fileContainingReference:r.file,namespace:i});let a={audiences:t.audiences,method:t.method,"display-name":t.summary??void 0,headers:n,payload:Xg({schema:t.payload,context:e,fileContainingReference:r.file,namespace:i,declarationDepth:0}),examples:t.examples!=null?t.examples.map(u=>({docs:u.description,name:u.name,payload:BK(u.payload)})):void 0};e.builder.addWebhook(r.file,{name:r.endpointId,schema:a}),t.description!=null&&(a.docs=t.description)}}function fIE({location:e,namespaceOverride:t}){if(e!=null)return t!=null?{...e,file:GN(wy.of(t),e.file)}:e}function dIE({webhook:e,context:t}){let r=e.tags[0],i=e.operationId;if(r==null)return{file:wy.of(SS),endpointId:i};let n=a5a(r),a=a5a(i);if(W8(n,a))return{file:wy.of("__package__.yml"),endpointId:r};let u=[];for(let c=0;c<n.length;++c){let d=n[c];if(d!=null&&d===a[c])u.push(d);else{let s=R_(r);return{file:wy.of(`${s}.yml`),endpointId:i,tag:r}}}if(u.length>=a.length){t.logger.warn(`Skipping webhook ${e.operationId} because couldn't compute file location`);return}return{file:wy.of(R_(u.join("_"))+".yml"),endpointId:R_(a.slice(u.length).join("_")),tag:r}}function pIE({webhook:e,context:t}){return e.sdkName!=null?{file:cw_({sdkName:e.sdkName,namespaceOverride:e.namespace}),endpointId:e.sdkName.methodName}:fIE({namespaceOverride:e.namespace,location:dIE({webhook:e,context:t})})}var _IE=wy.of(SS);function Uw_(e){switch(e.type){case"object":case"primitive":case"enum":case"array":case"map":case"reference":case"literal":case"optional":case"nullable":return Lw_({namespace:e.namespace,groupName:e.groupName});case"oneOf":return Lw_({namespace:e.value.namespace,groupName:e.value.groupName});case"unknown":return _IE;default:Ao(e)}}function Lw_({namespace:e,groupName:t}){return e!=null&&t!=null?y3i([{type:"namespace",name:e},...t]):e!=null?y3i([{type:"namespace",name:e}]):y3i(t)}var iDc="external",xw_=wy.of(SS);function Vw_({schemas:e,schemaIdsToExclude:t,namespace:r,context:i}){for(let[n,a]of Object.entries(e)){if(t.includes(n))continue;let u=Uw_(a),c=_w_({schema:a,context:i,declarationFile:u,namespace:r,declarationDepth:0});if(tzi(c.schema)){let d=uq(c.schema);if(d===(c.name??n)||d===`optional<${c.name??n}>`||d===`optional<nullable<${c.name??n}>>`)continue}i.builder.addType(u,{name:c.name??n,schema:c.schema})}}function Ww_(e){e.ir.apiVersion!=null&&e.builder.setApiVersion(e.ir.apiVersion),Sw_(e),Dw_(e),Ew_(e),gw_(e),Nw_(e),e.ir.basePath!=null&&e.builder.setBasePath(e.ir.basePath),e.ir.hasEndpointsMarkedInternal&&e.builder.addAudience(iDc);let t=Rw_(e),r=t.sdkGroups;e.setInState(v5.Webhook),Fw_(e),e.unsetInState(v5.Webhook),e.setInState(v5.Channel);for(let n of Object.values(e.ir.channels)){let a=y3i(n.groupName);jw_({channel:n,context:e,declarationFile:a})}e.unsetInState(v5.Channel);let i=hIE({context:e,schemaIdsToExcludeFromServices:t.schemaIdsToExclude});Vw_({schemas:e.ir.groupedSchemas.rootSchemas,schemaIdsToExclude:i,namespace:void 0,context:e});for(let[n,a]of Object.entries(e.ir.groupedSchemas.namespacedSchemas))Vw_({schemas:a,schemaIdsToExclude:i,namespace:n,context:e});return e.ir.tags.orderedTagIds!=null&&e.ir.tags.orderedTagIds.length>0&&e.ir.tags.orderedTagIds.every(a=>r.has(a))&&e.builder.addNavigation({navigation:e.ir.tags.orderedTagIds}),e.builder.build()}function hIE({context:e,schemaIdsToExcludeFromServices:t}){let r=e.getReferencedSchemaIds();if(r==null)return t;let i=new Set([...Object.keys(e.ir.groupedSchemas.rootSchemas),...Object.values(e.ir.groupedSchemas.namespacedSchemas).flatMap(a=>Object.keys(a))]),n=new Set(t);for(let a of i)r.includes(a)||n.add(a);return Array.from(n)}var u5a=class{context;constructor(t){this.context=t}};var aau=class e{files={};directories={};getAllFiles(){let t={},r=(i,n)=>{for(let[u,c]of Object.entries(i.files)){let d=n!=null?wy.of(`${n}${"/"}${u}`):wy.of(u);t[d]=c}let a=Object.keys(i.directories).sort();for(let u of a){let c=n!=null?`${n}${"/"}${u}`:u,d=i.directories[u];r(d,c)}};return r(this),t}getOrCreateFile(t){return this.getOrCreateFileRecursive(t.split("/"))}getOrCreateFileRecursive(t){if(t.length===1)return this.files[wy.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 bnn=class{enableUniqueErrorsPerEndpoint;root;rootApiFile;packageMarkerFile={};basePath=void 0;constructor(t){this.enableUniqueErrorsPerEndpoint=t,this.root=new aau,this.rootApiFile={name:"api","error-discrimination":{strategy:"status-code"}}}setDisplayName({displayName:t}){this.rootApiFile["display-name"]=t}addNavigation({navigation:t}){this.packageMarkerFile.navigation=t}setServiceInfo(t,{auth:r,"base-path":i,"display-name":n,docs:a}){let u=this.getOrCreateFile(t);u.service==null&&(u.service={auth:!1,"base-path":"",endpoints:{}}),r!=null&&(u.service.auth=r),i!=null&&(u.service["base-path"]=i),n!=null&&(u.service["display-name"]=n),a!=null&&(u.docs=a)}addAudience(t){this.rootApiFile.audiences==null&&(this.rootApiFile.audiences=[]),this.rootApiFile.audiences.push(t)}setAuth(t){this.rootApiFile.auth=t}addAuthScheme({name:t,schema:r}){this.rootApiFile["auth-schemes"]==null&&(this.rootApiFile["auth-schemes"]={}),this.rootApiFile["auth-schemes"][t]==null&&(this.rootApiFile["auth-schemes"][t]=r)}setDefaultEnvironment(t){this.rootApiFile["default-environment"]=t}setDefaultUrl(t){this.rootApiFile["default-url"]=t}setBasePath(t){this.basePath=t}setApiVersion(t){this.rootApiFile.version=t}getEnvironmentType(){let t=Object.entries(this.rootApiFile.environments??{})[0];if(t!=null)return cir(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"]))Hw_(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(Hw_(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??R_((x3e(r)+"/"+HZi(r,{stripExtension:!0})).replaceAll("__package__","root"));if(t===wy.of(i6))return this.rootApiFile.imports==null&&(this.rootApiFile.imports={}),this.rootApiFile.imports[n]=nBo(x3e(K8n.of(`/${t}`)),K8n.of(`/${r}`)),n;let a=this.getOrCreateFile(t);return a.imports==null&&(a.imports={}),a.imports[n]=nBo(x3e(K8n.of(`/${t}`)),K8n.of(`/${r}`)),n}addType(t,{name:r,schema:i}){if(t===wy.of(i6))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(c=>W8(c,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=GN(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:GN(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:GN(r,u.path)}]))})}return{rootApiFile:this.rootApiFile,packageMarkerFile:this.packageMarkerFile,definitionFiles:t}}getOrCreateFile(t){return t===SS?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 Hw_(e){return e?.header!=null}var oau=class{logger;taskContext;ir;builder;environmentOverrides;authOverrides;globalHeaderOverrides;detectGlobalHeaders;objectQueryParameters;respectReadonlySchemas;respectNullableSchemas;onlyIncludeReferencedSchemas;inlinePathParameters;useBytesForBinaryResponse;respectForwardCompatibleEnums;enableUniqueErrorsPerEndpoint;defaultServerName=void 0;unknownSchema=new Set;referencedSchemaIds;endpointMethod;state=new Set;constructor({taskContext:t,ir:r,options:i,environmentOverrides:n,globalHeaderOverrides:a,authOverrides:u}){this.logger=t.logger,this.taskContext=t,this.ir=r,this.environmentOverrides=n,this.authOverrides=u,this.globalHeaderOverrides=a,this.detectGlobalHeaders=i?.detectGlobalHeaders??!0,this.objectQueryParameters=i?.objectQueryParameters??!1,this.respectReadonlySchemas=i?.respectReadonlySchemas??!1,this.respectNullableSchemas=i?.respectNullableSchemas??!1,this.onlyIncludeReferencedSchemas=i?.onlyIncludeReferencedSchemas??!1,this.inlinePathParameters=i?.inlinePathParameters??!1,this.useBytesForBinaryResponse=i?.useBytesForBinaryResponse??!1,this.respectForwardCompatibleEnums=i?.respectForwardCompatibleEnums??!1,this.referencedSchemaIds=i?.onlyIncludeReferencedSchemas?new Set:void 0,this.enableUniqueErrorsPerEndpoint=i?.enableUniqueErrorsPerEndpoint??!1,this.builder=new bnn(this.enableUniqueErrorsPerEndpoint),r.title!=null&&this.builder.setDisplayName({displayName:r.title});let c={};if(!this.enableUniqueErrorsPerEndpoint)for(let d of r.endpoints)for(let[s,o]of Object.entries(d.errors)){let l=parseInt(s),v=c[l];v==null&&o.schema!=null?c[l]=o.schema:v!=null&&o.schema!=null&&Cue(v,o.schema)||this.unknownSchema.add(l)}}getReferencedSchemaIds(){if(this.referencedSchemaIds!=null)return Array.from(this.referencedSchemaIds)}getSchema(t,r){return r==null?this.ir.groupedSchemas.rootSchemas[t]:this.ir.groupedSchemas.namespacedSchemas[r]?.[t]}getDefaultServerName(){return this.defaultServerName}setDefaultServerName(t){this.defaultServerName=t}isErrorUnknownSchema(t){return this.unknownSchema.has(t)}getEndpointMethod(){return this.endpointMethod}setEndpointMethod(t){this.endpointMethod=t}unsetEndpointMethod(){this.endpointMethod=void 0}isInState(t){return this.state.has(t)}setInState(t){this.state.add(t)}unsetInState(t){this.state.delete(t)}shouldMarkSchemaAsReferenced(){return this.onlyIncludeReferencedSchemas&&this.isInAnyState(v5.Channel,v5.Endpoint,v5.Webhook)}markSchemaAsReferenced(t,r){switch(t.type){case"primitive":return;case"object":this.markObjectSchemaAsReferenced(t,r);return;case"array":this.markSchemaAsReferenced(t.value,r);return;case"map":this.markSchemaAsReferenced(t.value,r);return;case"optional":this.markSchemaAsReferenced(t.value,r);return;case"reference":this.markSchemaIdAsReferenced(t.schema,r);return;case"oneOf":this.markOneofSchemaAsReferenced(t.value,r);return;case"nullable":this.markSchemaAsReferenced(t.value,r);return;case"enum":return;case"literal":return;case"unknown":return;default:Ao(t)}}markObjectSchemaAsReferenced(t,r){for(let i of t.allOf)this.markSchemaIdAsReferenced(i.schema,r);for(let i of t.properties)this.markSchemaAsReferenced(i.schema,r)}markOneofSchemaAsReferenced(t,r){switch(t.type){case"discriminated":for(let i of Object.values(t.schemas))this.markSchemaAsReferenced(i,r);return;case"undiscriminated":for(let i of t.schemas)this.markSchemaAsReferenced(i,r);return;default:Ao(t)}}markSchemaIdAsReferenced(t,r){if(this.referencedSchemaIds!=null&&!this.referencedSchemaIds.has(t)){this.referencedSchemaIds.add(t);let i=this.getSchema(t,r);i!=null&&this.markSchemaAsReferenced(i,r)}}isInAnyState(...t){return t.some(r=>this.isInState(r))}};function nDc(e){let t=new oau(e);return Ww_(t)}var uau=class{args;constructor(t){this.args=t}convert({context:t,ir:r,settings:i,absoluteFilePath:n}){let a=nDc({taskContext:t,ir:r,options:X8a({overrides:{...i,respectReadonlySchemas:i?.respectReadonlySchemas??this.args.respectReadonlySchemas,respectNullableSchemas:i?.respectNullableSchemas??this.args.respectNullableSchemas,onlyIncludeReferencedSchemas:i?.onlyIncludeReferencedSchemas??this.args.onlyIncludeReferencedSchemas,inlinePathParameters:i?.inlinePathParameters??this.args.inlinePathParameters,objectQueryParameters:i?.objectQueryParameters??this.args.objectQueryParameters,useBytesForBinaryResponse:i?.useBytesForBinaryResponse??this.args.useBytesForBinaryResponse,respectForwardCompatibleEnums:i?.respectForwardCompatibleEnums??this.args.respectForwardCompatibleEnums}}),authOverrides:i?.auth!=null?{auth:i.auth}:this.args.generatorsConfiguration?.api?.auth!=null?{...this.args.generatorsConfiguration.api}:void 0,environmentOverrides:this.args.generatorsConfiguration?.api?.environments!=null?{...this.args.generatorsConfiguration?.api}:void 0,globalHeaderOverrides:this.args.generatorsConfiguration?.api?.headers!=null?{...this.args.generatorsConfiguration?.api}:void 0});return{absoluteFilePath:n??this.args.absoluteFilePath,rootApiFile:{defaultUrl:a.rootApiFile["default-url"],contents:a.rootApiFile,rawContents:xd.dump(a.rootApiFile)},namedDefinitionFiles:{...Sd(a.definitionFiles,u=>({absoluteFilepath:n??this.args.absoluteFilePath,rawContents:xd.dump(u),contents:u})),[wy.of(SS)]:{absoluteFilepath:n??this.args.absoluteFilePath,rawContents:xd.dump(a.packageMarkerFile),contents:a.packageMarkerFile}},packageMarkers:{},importedDefinitions:{}}}};var s5a=class extends EQt{inlinePathParameters;objectQueryParameters;onlyIncludeReferencedSchemas;respectReadonlySchemas;respectNullableSchemas;exampleGeneration;useBytesForBinaryResponse;respectForwardCompatibleEnums;inlineAllOfSchemas;converter;constructor(t){super(t),this.inlinePathParameters=t.inlinePathParameters,this.objectQueryParameters=t.objectQueryParameters,this.onlyIncludeReferencedSchemas=t.onlyIncludeReferencedSchemas,this.respectReadonlySchemas=t.respectReadonlySchemas,this.respectNullableSchemas=t.respectNullableSchemas,this.exampleGeneration=t.exampleGeneration,this.useBytesForBinaryResponse=t.useBytesForBinaryResponse,this.respectForwardCompatibleEnums=t.respectForwardCompatibleEnums,this.inlineAllOfSchemas=t.inlineAllOfSchemas,this.converter=new uau(t)}async getDefinition({context:t,absoluteFilePath:r,relativePathToDependency:i},n){let a=await this.getOpenAPIIr({context:t,relativePathToDependency:i},n);return this.converter.convert({context:t,ir:a,settings:n,absoluteFilePath:r})}async toFernWorkspace({context:t},r){let i=await this.getDefinition({context:t},r);return new Eqe({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:i,cliVersion:this.cliVersion})}};var O$={BEARER_FORMAT:"x-bearer-format",ENUM_VAR_NAMES:"x-enum-varnames",INTERNAL:"x-internal",EXAMPLES:"x-examples",TAGS:"x-tags",REDOCLY_CODE_SAMPLES_KEBAB:"x-code-samples",REDOCLY_CODE_SAMPLES_CAMEL:"x-codeSamples"};var xJn={of(e){return e}};var $w_={properties:{"stream-condition":{type:"string"},response:"Schema","response-stream":"Schema"},required:["stream-condition","response","response-stream"],extensionsPrefix:"x-"},aDc={id:"",typeExtension:{oas3:e=>({...e,XFernStreaming:$w_,Operation:{...e.Operation,properties:{...e.Operation?.properties,"x-fern-streaming":"XFernStreaming"}}})}},ad={SOURCE:xJn.of("source"),SDK_NAMESPACE:xJn.of("x-fern-sdk-namespace"),SDK_METHOD_NAME:xJn.of("x-fern-sdk-method-name"),SDK_GROUP_NAME:xJn.of("x-fern-sdk-group-name"),REQUEST_NAME_V1:"x-request-name",REQUEST_NAME_V2:"x-fern-request-name",TYPE_NAME:"x-fern-type-name",BOOLEAN_LITERAL:"x-fern-boolean-literal",SERVER_NAME_V1:"x-name",SERVER_NAME_V2:"x-fern-server-name",BASE_PATH:"x-fern-base-path",GROUPS:xJn.of("x-fern-groups"),OPENAPI_OVERIDES_FILEPATH:"x-fern-overrides-filepath",TYPE_DEFINITION:"x-fern-type",STREAMING:"x-fern-streaming",PAGINATION:"x-fern-pagination",WEBHOOK:"x-fern-webhook",ASYNC_CONFIG:"x-fern-async-config",SDK_VARIABLES:"x-fern-sdk-variables",SDK_VARIABLE:"x-fern-sdk-variable",PARAMETER_NAME:"x-fern-parameter-name",BASIC_AUTH_USERNAME_VARIABLE_NAME:"x-fern-username-variable-name",BASIC_AUTH_PASSWORD_VARIABLE_NAME:"x-fern-password-variable-name",BEARER_TOKEN_VARIABLE_NAME:"x-fern-token-variable-name",HEADER_VARIABLE_NAME:"x-fern-header-variable-name",FERN_ENUM:"x-fern-enum",AUDIENCES:"x-fern-audiences",IGNORE:"x-fern-ignore",AVAILABILITY:"x-fern-availability",RESPONSE_PROPERTY:"x-fern-sdk-return-value",RESOLUTIONS:"x-fern-resolutions",EXAMPLES:"x-fern-examples",FERN_BEARER_TOKEN:"x-fern-bearer",FERN_HEADER_AUTH:"x-fern-header",FERN_BASIC_AUTH:"x-fern-basic",FERN_GLOBAL_HEADERS:"x-fern-global-headers",FERN_IDEMPOTENCY_HEADERS:"x-fern-idempotency-headers",IDEMPOTENT:"x-fern-idempotent",FERN_PROPERTY_NAME:"x-fern-property-name",IS_UNDISCRIMINATED:"x-fern-undiscriminated",FERN_VERSION:"x-fern-version",ENCODING:"x-fern-encoding",TRANSPORT:"x-fern-transport",IS_DISCRIMINATED:"x-fern-discriminated"};var w3={disableExamples:!1,discriminatedUnionV2:!1,useTitlesAsName:!0,audiences:void 0,optionalAdditionalProperties:!0,coerceEnumsToLiterals:!0,respectReadonlySchemas:!1,respectNullableSchemas:!1,onlyIncludeReferencedSchemas:!1,inlinePathParameters:!1,preserveSchemaIds:!1,objectQueryParameters:!1,shouldUseUndiscriminatedUnionsWithLiterals:!1,shouldUseIdiomaticRequestNames:!1,filter:void 0,asyncApiNaming:"v1",exampleGeneration:void 0,defaultFormParameterEncoding:"json",useBytesForBinaryResponse:!1,respectForwardCompatibleEnums:!1,additionalPropertiesDefaultsTo:!1,typeDatesAsStrings:!0,preserveSingleSchemaOneOf:!1,inlineAllOfSchemas:!1,groupMultiApiEnvironments:!1};function j6e({options:e,overrides:t}){return{disableExamples:t?.disableExamples??w3.disableExamples,discriminatedUnionV2:t?.discriminatedUnionV2??e?.discriminatedUnionV2??w3.discriminatedUnionV2,useTitlesAsName:t?.useTitlesAsName??e?.useTitlesAsName??w3.useTitlesAsName,audiences:t?.audiences??e?.audiences??w3.audiences,optionalAdditionalProperties:t?.optionalAdditionalProperties??e?.optionalAdditionalProperties??w3.optionalAdditionalProperties,coerceEnumsToLiterals:t?.coerceEnumsToLiterals??e?.coerceEnumsToLiterals??w3.coerceEnumsToLiterals,respectReadonlySchemas:t?.respectReadonlySchemas??e?.respectReadonlySchemas??w3.respectReadonlySchemas,respectNullableSchemas:t?.respectNullableSchemas??e?.respectNullableSchemas??w3.respectNullableSchemas,onlyIncludeReferencedSchemas:t?.onlyIncludeReferencedSchemas??e?.onlyIncludeReferencedSchemas??w3.onlyIncludeReferencedSchemas,inlinePathParameters:t?.inlinePathParameters??e?.inlinePathParameters??w3.inlinePathParameters,preserveSchemaIds:t?.preserveSchemaIds??w3.preserveSchemaIds,shouldUseUndiscriminatedUnionsWithLiterals:t?.shouldUseUndiscriminatedUnionsWithLiterals??e?.shouldUseUndiscriminatedUnionsWithLiterals??w3.shouldUseUndiscriminatedUnionsWithLiterals,shouldUseIdiomaticRequestNames:t?.shouldUseIdiomaticRequestNames??e?.shouldUseIdiomaticRequestNames??w3.shouldUseIdiomaticRequestNames,objectQueryParameters:t?.objectQueryParameters??e?.objectQueryParameters??w3.objectQueryParameters,filter:t?.filter??e?.filter??w3.filter,asyncApiNaming:t?.asyncApiNaming??e?.asyncApiNaming??w3.asyncApiNaming,useBytesForBinaryResponse:t?.useBytesForBinaryResponse??e?.useBytesForBinaryResponse??w3.useBytesForBinaryResponse,exampleGeneration:t?.exampleGeneration??e?.exampleGeneration??void 0,defaultFormParameterEncoding:t?.defaultFormParameterEncoding??e?.defaultFormParameterEncoding??void 0,respectForwardCompatibleEnums:t?.respectForwardCompatibleEnums??e?.respectForwardCompatibleEnums??w3.respectForwardCompatibleEnums,additionalPropertiesDefaultsTo:t?.additionalPropertiesDefaultsTo??e?.additionalPropertiesDefaultsTo??w3.additionalPropertiesDefaultsTo,typeDatesAsStrings:t?.typeDatesAsStrings??e?.typeDatesAsStrings??w3.typeDatesAsStrings,preserveSingleSchemaOneOf:t?.preserveSingleSchemaOneOf??e?.preserveSingleSchemaOneOf??w3.preserveSingleSchemaOneOf,inlineAllOfSchemas:t?.inlineAllOfSchemas??e?.inlineAllOfSchemas??w3.inlineAllOfSchemas,groupMultiApiEnvironments:t?.groupMultiApiEnvironments??e?.groupMultiApiEnvironments??w3.groupMultiApiEnvironments}}var Gw_={naming:"v1"};function hf(e,t){let r=Array.isArray(t)?t:[t];for(let i of r){let n=e[i];if(n!=null)return n}}function c5a(e,t,r,i,n=[]){try{let a=hf(e,t);if(a!=null)return r.parse(a)}catch{let u=j3e(n).join(" -> ");i.error(`${u.length>0?`${u}: `:""}Failed to parse ${t}`)}}function gnn(e){let t=hf(e,"examples");if(t!=null){if(Array.isArray(t))return t;if(typeof t=="object"&&t!==null)return Object.values(t).map(r=>typeof r=="object"&&r!==null&&"value"in r?r.value:r)}return[]}function Qw_({schema:e,logger:t}){return hf(e,ad.ENCODING)??void 0}function Jw_(e){return hf(e,ad.FERN_ENUM)}function Kw_({nameOverride:e,generatedName:t,title:r,schema:i,description:n,availability:a}){let u=hf(i,ad.SDK_NAMESPACE),c=hf(i,ad.SDK_GROUP_NAME),d=hf(i,ad.TYPE_DEFINITION);if(d!=null)return l5a({fernType:d,nameOverride:e,generatedName:t,title:r,description:n,availability:a,namespace:u,groupName:typeof c=="string"?[c]:c})}function l5a({fernType:e,nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c}){return v6({type:e,_default:void 0,validation:void 0,visitor:{primitive:d=>{switch(d.v1){case"BASE_64":return zl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.base64({example:void 0})});case"BOOLEAN":return zl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.boolean({default:void 0,example:void 0})});case"DATE":return zl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.date({example:void 0})});case"DATE_TIME":return zl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.datetime({example:void 0})});case"FLOAT":return zl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.float({example:void 0})});case"DOUBLE":return zl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.double({default:void 0,minimum:void 0,maximum:void 0,exclusiveMinimum:void 0,exclusiveMaximum:void 0,multipleOf:void 0,example:void 0})});case"UINT":return zl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.uint({default:void 0,example:void 0})});case"INTEGER":return zl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.int({default:void 0,minimum:void 0,maximum:void 0,exclusiveMinimum:void 0,exclusiveMaximum:void 0,multipleOf:void 0,example:void 0})});case"UINT_64":return zl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.uint64({default:void 0,example:void 0})});case"LONG":return zl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.int64({default:void 0,example:void 0})});case"STRING":case"UUID":case"BIG_INTEGER":return zl.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,schema:vp.string({default:void 0,pattern:void 0,maxLength:void 0,minLength:void 0,example:void 0,format:void 0})});default:Ao(d.v1)}},unknown:()=>zl.unknown({nameOverride:t,generatedName:r,title:i,example:void 0,description:n,availability:a,namespace:u,groupName:c}),map:({keyType:d,valueType:s})=>d?.type==="primitive"&&s!=null?zl.map({nameOverride:t,generatedName:r,title:i,key:d,value:s,description:n,availability:a,namespace:u,groupName:c,encoding:void 0,example:void 0,inline:void 0}):void 0,list:d=>d!=null?zl.array({nameOverride:t,generatedName:r,title:i,value:d,description:n,availability:a,namespace:u,groupName:c,example:void 0,inline:void 0}):void 0,optional:d=>d!=null?zl.optional({nameOverride:t,generatedName:r,title:i,value:d,description:n,availability:a,namespace:u,groupName:c,inline:void 0}):void 0,nullable:d=>d!=null?zl.nullable({nameOverride:t,generatedName:r,title:i,value:d,description:n,availability:a,namespace:u,groupName:c,inline:void 0}):void 0,set:d=>d!=null?zl.array({nameOverride:t,generatedName:r,title:i,value:d,description:n,availability:a,namespace:u,groupName:c,example:void 0,inline:void 0}):void 0,literal:d=>zl.literal({nameOverride:t,generatedName:r,title:i,value:d._visit({string:s=>px.string(s),boolean:s=>px.boolean(s),_other:()=>{throw new Error("Unexpected literal type")}}),description:n,availability:a,namespace:u,groupName:c}),named:d=>zl.reference({schema:d,nameOverride:t,generatedName:r,title:i,description:n,availability:a,namespace:u,groupName:c,source:qK.openapi({file:"<memory>"})})}})}function Yw_(e){let t=hf(e,ad.SOURCE);if(t!=null)return t.endsWith(".proto")?qK.protobuf({file:t}):qK.openapi({file:t})}function Onn(e){if(e!=null&&typeof e=="boolean")return e}function ep(e){return e?.$ref!=null}function Xw_({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,additionalProperties:n,description:a,availability:u,wrapAsNullable:c,context:d,namespace:s,groupName:o,example:l,encoding:v,source:g}){return n===void 0&&(n=d.options.additionalPropertiesDefaultsTo),typeof n=="boolean"||RJn(n,d.options)?sau({nameOverride:e,generatedName:t,title:r,wrapAsNullable:c,description:a,availability:u,keySchema:{nameOverride:void 0,generatedName:`${t}Key`,title:void 0,description:void 0,availability:void 0,schema:vp.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:void 0}),namespace:void 0,groupName:void 0},valueSchema:zl.unknown({nameOverride:void 0,generatedName:`${t}Value`,title:void 0,description:void 0,availability:void 0,example:void 0,namespace:void 0,groupName:void 0}),namespace:s,groupName:o,example:l,encoding:v}):sau({nameOverride:e,generatedName:t,title:r,wrapAsNullable:c,description:a,availability:u,keySchema:{nameOverride:void 0,generatedName:`${t}Key`,title:void 0,description:void 0,availability:void 0,schema:vp.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:void 0}),namespace:void 0,groupName:void 0},valueSchema:Zw_(n0(n,d.options.optionalAdditionalProperties?c:!1,d,[...i,"Value"],g,s,void 0,void 0,void 0)),namespace:s,groupName:o,example:l,encoding:v})}function Zw_(e){switch(e.type){case"array":case"enum":case"map":case"object":e.inline=!0;break;case"literal":case"primitive":case"reference":case"unknown":break;case"nullable":case"optional":e.inline=!0,e.value=Zw_(e.value);break;case"oneOf":e.value.inline=!0;break;default:Ao(e)}return e}function sau({nameOverride:e,generatedName:t,title:r,keySchema:i,valueSchema:n,wrapAsNullable:a,description:u,availability:c,namespace:d,groupName:s,example:o,encoding:l}){return a?zl.nullable({nameOverride:e,generatedName:t,title:r,value:zl.map({nameOverride:e,generatedName:t,title:r,description:u,availability:i.availability,key:i,value:n,namespace:d,groupName:s,encoding:l,example:o,inline:void 0}),description:u,availability:c,namespace:d,groupName:s,inline:void 0}):zl.map({nameOverride:e,generatedName:t,title:r,description:u,availability:c,key:i,value:n,namespace:d,groupName:s,encoding:l,example:o,inline:void 0})}function RJn(e,t){return e==null?t.additionalPropertiesDefaultsTo:typeof e=="boolean"?e:!ep(e)&&Object.keys(e).length===0}function kw_({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,item:n,description:a,availability:u,wrapAsNullable:c,context:d,namespace:s,groupName:o,example:l,source:v}){let g=n==null?zl.unknown({nameOverride:e,generatedName:t,title:r,description:void 0,availability:void 0,example:void 0,namespace:s,groupName:o}):n0(n,!1,d,[...i,"Item"],v,s);return yIE({nameOverride:e,generatedName:t,title:r,namespace:s,groupName:o,itemSchema:g,wrapAsNullable:c,description:a,availability:u,example:l})}function yIE({nameOverride:e,generatedName:t,title:r,itemSchema:i,wrapAsNullable:n,description:a,availability:u,namespace:c,groupName:d,example:s}){return n?zl.nullable({nameOverride:e,generatedName:t,title:r,value:zl.array({nameOverride:e,generatedName:t,title:r,value:i,description:a,availability:u,namespace:c,groupName:d,example:s,inline:void 0}),description:a,availability:u,namespace:c,groupName:d,inline:void 0}):zl.array({nameOverride:e,generatedName:t,title:r,value:i,description:a,availability:u,namespace:c,groupName:d,example:s,inline:void 0})}function IK(e){switch(hf(e,ad.AVAILABILITY)){case"deprecated":return v$.Deprecated;case"beta":return v$.Beta;case"generally-available":return v$.GenerallyAvailable;default:break}if(!ep(e)&&e.deprecated)return v$.Deprecated}function oDc({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,properties:n,description:a,availability:u,required:c,wrapAsNullable:d,discriminator:s,context:o,namespace:l,groupName:v,encoding:g,source:O}){let m=s.propertyName,P=Object.fromEntries(Object.entries(s.mapping??{}).map(([A,M])=>{let E=Cmi({$ref:M},!1,o,[M],g,O,l);return o.markReferencedByDiscriminatedUnion({$ref:M},m,1),[A,E]})),D=Object.entries(n).filter(([A])=>A!==m).map(([A,M])=>{let E=c!=null&&c.includes(A),T=n0(M,!E,o,[...i,A],O,l);return{key:A,schema:T}});return e1_({nameOverride:e,generatedName:t,title:r,wrapAsNullable:d,properties:D,description:a,availability:u,discriminant:m,subtypes:P,namespace:l,groupName:v,source:O})}function uDc({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,properties:n,description:a,availability:u,required:c,wrapAsNullable:d,discriminant:s,variants:o,context:l,namespace:v,groupName:g,encoding:O,source:m}){let P=Object.fromEntries(Object.entries(o).map(([A,M])=>{if(ep(M)){let E=Cmi(M,!1,l,[M.$ref],O,m,v);return l.markReferencedByDiscriminatedUnion(M,s,1),[A,E]}else{let E=NJn(M,!1,l,[...i,A],O,m,v,new Set([s]));return[A,E]}})),D=Object.entries(n).filter(([A])=>A!==s).map(([A,M])=>{let E=c!=null&&c.includes(A),T=n0(M,!E,l,[...i,A],m,v);return{key:A,schema:T}});return e1_({nameOverride:e,generatedName:t,title:r,wrapAsNullable:d,properties:D,description:a,availability:u,discriminant:s,subtypes:P,namespace:v,groupName:g,source:m})}function e1_({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,properties:n,description:a,availability:u,discriminant:c,subtypes:d,namespace:s,groupName:o,source:l}){return i?zl.nullable({nameOverride:e,generatedName:t,title:r,value:zl.oneOf(Tee.discriminated({description:a,availability:u,discriminantProperty:c,nameOverride:e,generatedName:t,title:r,schemas:d,commonProperties:n,namespace:s,groupName:o,encoding:void 0,source:l,inline:void 0})),namespace:s,groupName:o,description:a,availability:u,inline:void 0}):zl.oneOf(Tee.discriminated({description:a,availability:u,discriminantProperty:c,nameOverride:e,generatedName:t,title:r,schemas:d,commonProperties:n,namespace:s,groupName:o,encoding:void 0,source:l,inline:void 0}))}function t1_(e){if(e.proto!=null)return nJn.protobuf({typeName:e.proto.type})}function b3i({nameOverride:e,generatedName:t,title:r,fernEnum:i,enumVarNames:n,enumValues:a,_default:u,description:c,availability:d,wrapAsNullable:s,namespace:o,groupName:l,context:v,source:g,inline:O}){let m=bIE(n??[]),P=new Set(a),D=Array.from(P).map((M,E)=>{let T=i?.[M],z=m[E],G=CJn.test(M),I=T?.name??z,R=G?M:BJn(M);return I!=null&&!CJn.test(I)&&(v?.logger.warn(`Enum name override ${I} is not a valid name. Falling back on ${R}.`),I=void 0),{nameOverride:I,generatedName:R,value:M,description:T?.description,availability:d,casing:{snake:T?.casing?.snake??void 0,pascal:T?.casing?.pascal??void 0,screamingSnake:T?.casing?.screamingSnake??void 0,camel:T?.casing?.camel??void 0}}}),A=u!=null?D.find(M=>M.value===u):void 0;return vIE({wrapAsNullable:s,nameOverride:e,generatedName:t,title:r,values:D,_default:A,description:c,availability:d,namespace:o,groupName:l,source:g,inline:O})}function vIE({wrapAsNullable:e,nameOverride:t,generatedName:r,title:i,values:n,_default:a,description:u,availability:c,namespace:d,groupName:s,source:o,inline:l}){return e?zl.nullable({nameOverride:t,generatedName:r,title:i,value:zl.enum({nameOverride:t,generatedName:r,title:i,values:n,description:u,default:a,availability:c,example:void 0,namespace:d,groupName:s,source:o,inline:l}),description:u,availability:c,namespace:d,groupName:s,inline:l}):zl.enum({nameOverride:t,generatedName:r,title:i,values:n,description:u,availability:c,default:a,example:void 0,namespace:d,groupName:s,source:o,inline:l})}function bIE(e){if(e.length<=1||e[0]==null)return e;let t=e[0],r=0;for(;t[r]!=null&&e.every(i=>i[r]===t[r]);)r++;return e.map(i=>i.substring(r))}function r1_({nameOverride:e,generatedName:t,title:r,format:i,_default:n,minimum:a,maximum:u,exclusiveMinimum:c,exclusiveMaximum:d,multipleOf:s,description:o,availability:l,wrapAsNullable:v,example:g,namespace:O,groupName:m}){return i==="int64"?b5({nameOverride:e,generatedName:t,title:r,primitive:vp.int64({default:n,example:g}),wrapAsNullable:v,description:o,availability:l,namespace:O,groupName:m}):i==="uint32"?b5({nameOverride:e,generatedName:t,title:r,primitive:vp.uint({default:n,example:g}),wrapAsNullable:v,description:o,availability:l,namespace:O,groupName:m}):i==="uint64"?b5({nameOverride:e,generatedName:t,title:r,primitive:vp.uint64({default:n,example:g}),wrapAsNullable:v,description:o,availability:l,namespace:O,groupName:m}):b5({nameOverride:e,generatedName:t,title:r,primitive:vp.int({default:n,minimum:a,maximum:u,exclusiveMinimum:c,exclusiveMaximum:d,multipleOf:s,example:g}),wrapAsNullable:v,description:o,availability:l,namespace:O,groupName:m})}function i1_(e){return typeof e=="string"?px.string(e):typeof e=="boolean"?px.boolean(e):px.string(`${e}`)}function n1_({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,value:n,description:a,availability:u,namespace:c,groupName:d}){return i?zl.nullable({nameOverride:e,generatedName:t,title:r,value:zl.literal({nameOverride:e,generatedName:t,title:r,value:i1_(n),description:a,availability:u,namespace:c,groupName:d}),description:a,availability:u,namespace:c,groupName:d,inline:void 0}):zl.literal({nameOverride:e,generatedName:t,title:r,value:i1_(n),description:a,availability:u,namespace:c,groupName:d})}function sDc({nameOverride:e,generatedName:t,title:r,format:i,_default:n,minimum:a,maximum:u,exclusiveMinimum:c,exclusiveMaximum:d,multipleOf:s,description:o,availability:l,wrapAsNullable:v,example:g,namespace:O,groupName:m}){return i==null||i==="double"?b5({nameOverride:e,generatedName:t,title:r,primitive:vp.double({default:n,minimum:a,maximum:u,exclusiveMinimum:c,exclusiveMaximum:d,multipleOf:s,example:g}),wrapAsNullable:v,description:o,availability:l,namespace:O,groupName:m}):i==="float"?b5({nameOverride:e,generatedName:t,title:r,primitive:vp.float({example:g}),wrapAsNullable:v,description:o,availability:l,namespace:O,groupName:m}):i==="int32"?b5({nameOverride:e,generatedName:t,title:r,primitive:vp.int({default:n,minimum:a,maximum:u,exclusiveMinimum:c,exclusiveMaximum:d,multipleOf:s,example:g}),wrapAsNullable:v,description:o,availability:l,namespace:O,groupName:m}):i==="int64"?b5({nameOverride:e,generatedName:t,title:r,primitive:vp.int64({default:n,example:g}),wrapAsNullable:v,description:o,availability:l,namespace:O,groupName:m}):i==="uint32"?b5({nameOverride:e,generatedName:t,title:r,primitive:vp.uint({default:n,example:g}),wrapAsNullable:v,description:o,availability:l,namespace:O,groupName:m}):i==="uint64"?b5({nameOverride:e,generatedName:t,title:r,primitive:vp.uint64({default:n,example:g}),wrapAsNullable:v,description:o,availability:l,namespace:O,groupName:m}):i==="time-delta"?b5({nameOverride:e,generatedName:t,title:r,primitive:vp.float({example:g}),wrapAsNullable:v,description:o,availability:l,namespace:O,groupName:m}):b5({nameOverride:e,generatedName:t,title:r,primitive:vp.float({example:g}),wrapAsNullable:v,description:o,availability:l,namespace:O,groupName:m})}var gIE={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="schemas",applyStrategy:e=>{let t=[e[3]??""];return{refUnderProcessing:e.slice(4),newBreadcrumbs:t}}},OIE={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="responses",applyStrategy:e=>{let t=[e[3]??""];return e=e.slice(4),{refUnderProcessing:e.slice(4),newBreadcrumbs:t}}},mIE={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="parameters",applyStrategy:e=>{let t=[e[3]??""];return e=e.slice(4),e[0]==="schema"&&(e=e.slice(1)),{refUnderProcessing:e,newBreadcrumbs:t}}},PIE={isApplicable:e=>e[0]==="properties",applyStrategy:e=>{let t=[e[1]??""];return{refUnderProcessing:e.slice(2),newBreadcrumbs:t}}},jIE={isApplicable:e=>e[0]==="items",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},wIE={isApplicable:e=>e[0]==="allOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},SIE={isApplicable:e=>e[0]==="anyOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},DIE={isApplicable:e=>e[0]==="oneOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})};function cau(e){let t=e.split("/").map(a=>a.replace(/~1/g,"/")),r=[],i=[gIE,OIE,mIE,PIE,jIE,wIE,SIE,DIE],n;do{n=t;for(let a of i)if(a.isApplicable(t)){let{refUnderProcessing:u,newBreadcrumbs:c}=a.applyStrategy(t);t=u,r=[...r,...c]}}while(t.join("")!==n.join(""));return r}function g5(e,t){let i=e.map(n=>/^[^a-zA-Z0-9]+$/.test(n)?n:GB(R_(n))).join("");return/^\d/.test(i)?r5a(i)??i:i}function cDc(e){let t=e.join("_");return R_(t)}function bA(e){switch(e.type){case"object":return Ov.object({allOf:e.allOf,properties:e.properties.map(t=>MIE(t)),allOfPropertyConflicts:e.allOfPropertyConflicts,description:e.description,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName,additionalProperties:e.additionalProperties,availability:e.availability,source:e.source,inline:e.inline});case"array":return Ov.array({description:e.description,availability:e.availability,value:bA(e.value),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName,inline:e.inline});case"enum":return Ov.enum({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,values:e.values,default:e.default,namespace:e.namespace,groupName:e.groupName,source:e.source,inline:e.inline});case"literal":return Ov.literal({description:e.description,availability:e.availability,value:e.value,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName});case"nullable":return Ov.nullable({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:bA(e.value),namespace:e.namespace,groupName:e.groupName,inline:e.inline});case"optional":return Ov.optional({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:bA(e.value),namespace:e.namespace,groupName:e.groupName,inline:e.inline});case"primitive":return Ov.primitive({description:e.description,availability:e.availability,schema:a1_(e.schema),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,namespace:e.namespace,groupName:e.groupName});case"map":return Ov.map({description:e.description,availability:e.availability,key:Ov.primitive({description:e.key.description,availability:e.key.availability,schema:a1_(e.key.schema),generatedName:e.key.generatedName,title:e.key.title,nameOverride:e.key.nameOverride,namespace:e.namespace,groupName:e.groupName}),value:bA(e.value),generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,inline:e.inline});case"reference":return Ov.reference({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schema:e.schema,namespace:e.namespace,groupName:e.groupName,source:e.source});case"oneOf":return Ov.oneOf(EIE(e.value));case"unknown":return Ov.unknown({nameOverride:e.nameOverride,generatedName:e.generatedName});default:Ao(e)}}function EIE(e){switch(e.type){case"discriminated":return Mmi.discriminated({commonProperties:e.commonProperties.map(t=>({key:t.key,schema:bA(t.schema)})),description:e.description,availability:e.availability,discriminantProperty:e.discriminantProperty,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schemas:Object.fromEntries(Object.entries(e.schemas).map(([t,r])=>[t,bA(r)])),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:e.inline});case"undiscriminated":return Mmi.undiscriminated({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schemas:e.schemas.map(t=>bA(t)),namespace:e.namespace,groupName:e.groupName,encoding:e.encoding,source:e.source,inline:e.inline});default:Ao(e)}}function a1_(e){switch(e.type){case"string":return xw.string(e);case"base64":return xw.base64();case"boolean":return xw.boolean(e);case"date":return xw.date();case"datetime":return xw.datetime();case"double":return xw.double(e);case"float":return xw.float();case"int":return xw.int(e);case"int64":return xw.int64(e);case"uint":return xw.uint();case"uint64":return xw.uint64();default:Ao(e)}}function MIE(e){return{conflict:e.conflict,generatedName:e.generatedName,key:e.key,schema:bA(e.schema),audiences:e.audiences,nameOverride:e.nameOverride,availability:e.availability,readonly:e.readonly,writeonly:e.writeonly}}function lau(e,t){return Cue(bA(e),bA(t))}function o1_({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,properties:n,description:a,required:u,wrapAsNullable:c,allOf:d,context:s,propertiesToExclude:o,namespace:l,groupName:v,fullExamples:g,additionalProperties:O,availability:m,source:P}){let D=[...u??[]],A={...n},M=[],E=[];for(let R of d)if(!s.options.inlineAllOfSchemas&&ep(R)){let U=s.resolveSchemaReference(R);if(U.discriminator!=null&&U.discriminator.mapping!=null)continue;if(U.oneOf!=null||U.anyOf!=null){let J=U.oneOf??U.anyOf;if(J!=null){for(let X of J){let ae=ep(X)?s.resolveSchemaReference(X):X,pe=n0(ae,!1,s.DUMMY,i,P,l);pe.type==="object"&&M.push(...pe.properties.map(de=>de.schema.type!=="optional"&&de.schema.type!=="nullable"?{...de,schema:zl.optional({nameOverride:void 0,generatedName:"",title:void 0,value:de.schema,description:void 0,availability:de.availability,namespace:void 0,groupName:void 0,inline:void 0})}:de))}continue}}let Y=g3i(R);if(Y==null)continue;E.push({schemaId:Y,convertedSchema:lDc(R,[Y],P,s.options.preserveSchemaIds),properties:u1_({schema:R,context:s,breadcrumbs:i,source:P,namespace:l})}),s.markSchemaAsReferencedByNonRequest(Y)}else if(ep(R)){let U=s.resolveSchemaReference(R),Y=n0(U,!1,s,i,P,l);Y.type==="object"&&M.push(...Y.properties)}else{let U=R.required??[];M=M.map(J=>(J.schema.type==="optional"||J.schema.type==="nullable")&&U.includes(J.key)?{...J,schema:J.schema.value}:J);let Y=n0(R,!1,s,i,P,l);Y.type==="object"&&M.push(...Y.properties)}let T={};for(let R of E)for(let[U,Y]of Object.entries(R.properties)){let J=T[U];J!=null?(J.schemaIds.push(R.schemaId),J.schemas.some(ae=>lau(ae,Y))||J.schemas.push(Y)):T[U]={schemaIds:[R.schemaId],schemas:[Y]}}let z=[];for(let[R,U]of Object.entries(T))U.schemaIds.length>1&&z.push({propertyKey:R,allOfSchemaIds:U.schemaIds,conflictingTypeSignatures:U.schemas.length>1});let G=Object.fromEntries(Object.entries(A).filter(([R,U])=>!(!ep(U)&&U.type==="null"))),I=Object.entries(G).map(([R,U])=>{let Y=hf(U,ad.AUDIENCES)??[],J=IK(U),X=ep(U)?!1:U.readOnly,ae=ep(U)?!1:U.writeOnly,pe=D.includes(R)&&!X,de=hf(U,ad.FERN_PROPERTY_NAME),me=[...i,R],Le=cDc(me),yt=pe?n0(U,!1,s,me,P,l):zl.optional({nameOverride:e,generatedName:Le,title:r,description:void 0,availability:J,value:n0(U,!1,s,me,P,l),namespace:l,groupName:v,inline:void 0}),De={};for(let Ae of E){let Ct=Ae.properties[R];Ct!=null&&!lau(yt,Ct)?De[Ae.schemaId]={differentSchema:!0}:Ct!=null&&(De[Ae.schemaId]={differentSchema:!1})}return{key:R,schema:yt,nameOverride:de,audiences:Y,conflict:De,generatedName:cDc([...i,R]),availability:J,readonly:X,writeonly:ae}});return I.push(...M.map(R=>{let U=R.conflict;for(let Y of E){let J=Y.properties[R.key];J!=null&&!lau(R.schema,J)?U[Y.schemaId]={differentSchema:!0}:J!=null&&(U[Y.schemaId]={differentSchema:!1})}return{...R,conflict:U}})),AIE({nameOverride:e,generatedName:t,title:r,wrapAsNullable:c,properties:I.filter(R=>!o.has(R.key)),description:a,allOf:E.map(R=>R.convertedSchema),allOfPropertyConflicts:z,namespace:l,groupName:v,fullExamples:g,additionalProperties:O,availability:m,source:P,context:s})}function AIE({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,properties:n,description:a,allOf:u,allOfPropertyConflicts:c,namespace:d,groupName:s,fullExamples:o,additionalProperties:l,availability:v,source:g,context:O}){return i?zl.nullable({nameOverride:e,generatedName:t,title:r,value:zl.object({description:a,properties:n,nameOverride:e,generatedName:t,title:r,allOf:u,allOfPropertyConflicts:c,namespace:d,groupName:s,fullExamples:o,additionalProperties:RJn(l,O.options),availability:void 0,source:g,inline:void 0}),description:a,availability:v,namespace:d,groupName:s,inline:void 0}):zl.object({description:a,properties:n,nameOverride:e,generatedName:t,title:r,allOf:u,allOfPropertyConflicts:c,namespace:d,groupName:s,fullExamples:o,additionalProperties:RJn(l,O.options),availability:v,source:g,inline:void 0})}function u1_({schema:e,context:t,breadcrumbs:r,source:i,namespace:n}){let a={},[u,c]=ep(e)?[t.resolveSchemaReference(e),cau(e.$ref)]:[e,r];for(let d of u.allOf??[])a={...a,...u1_({schema:d,context:t,breadcrumbs:c,source:i,namespace:n})};for(let[d,s]of Object.entries(u.properties??{})){let o=n0(s,!1,t,[...c,d],i,n);a[d]=o}return a}function O3i({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,description:n,availability:a,wrapAsNullable:u,context:c,subtypes:d,namespace:s,groupName:o,encoding:l,source:v,subtypePrefixOverrides:g}){let O=CIE({schemas:d}),m=d.flatMap((D,A)=>{if(!ep(D)&&D.enum!=null&&c.options.coerceEnumsToLiterals&&D.type==="string")return D.enum.map(E=>zl.literal({nameOverride:void 0,generatedName:g5([t,E],c.options.preserveSchemaIds),title:void 0,value:px.string(String(E)),namespace:s,groupName:void 0,description:void 0,availability:E.availability}));let M=O[A];if(g!=null){let E=g[A];E!=null&&"name"in E&&(M=E.name)}return[n0(D,!1,c,[...i,M??`${A}`],v,s)]}),P=qIE(m);return TIE({uniqueSubtypes:P,nameOverride:e,generatedName:t,title:r,wrapAsNullable:u,description:n,availability:a,namespace:s,groupName:o,context:c,encoding:l,source:v})}function qIE(e){let t=[];for(let r=0;r<e.length;++r){let i=e[r],n=!1;for(let a=r+1;a<e.length;++a){let u=e[a];if(i!=null&&u!=null&&Cue(i,u)){n=!0;break}}i!=null&&!n&&t.push(i)}return t}function TIE({uniqueSubtypes:e,nameOverride:t,generatedName:r,title:i,wrapAsNullable:n,description:a,availability:u,namespace:c,groupName:d,context:s,encoding:o,source:l}){if(Object.entries(e).every(([g,O])=>O.type==="literal")){let g={},O=[];return Object.entries(e).forEach(([m,P])=>{P.type==="literal"&&P.value.type==="string"&&(O.push(P.value.value),P.description!=null&&(g[P.value.value]={description:P.description}))}),b3i({nameOverride:t,generatedName:r,title:i,wrapAsNullable:n,description:a,availability:u,fernEnum:g,enumVarNames:void 0,enumValues:O,_default:void 0,namespace:c,groupName:d,context:s,source:l,inline:void 0})}return e.length===1&&e[0]!=null&&!s.options.preserveSingleSchemaOneOf?e[0]:s1_({nameOverride:t,generatedName:r,title:i,wrapAsNullable:n,description:a,availability:u,subtypes:e,namespace:c,groupName:d,encoding:o,source:l})}function fDc({nameOverride:e,generatedName:t,title:r,description:i,availability:n,wrapAsNullable:a,context:u,namespace:c,groupName:d,discriminator:s,encoding:o,source:l}){let v=Object.entries(s.mapping??{}).map(([m,P],D)=>{let A={$ref:P},M=Cmi(A,!1,u,[P],o,l,c);return u.markSchemaWithDiscriminantValue(A,s.propertyName,m),M.type==="object"&&(M.properties={[s.propertyName]:zl.literal({nameOverride:void 0,generatedName:g5([t,m],u.options.preserveSchemaIds),title:void 0,value:px.string(m),namespace:void 0,groupName:void 0,description:void 0,availability:void 0}),...M.properties.filter(E=>E.key!==s.propertyName)}),M}),g=[];for(let m=0;m<v.length;++m){let P=v[m],D=!1;for(let A=m+1;A<v.length;++A){let M=v[A];if(P!=null&&M!=null&&Cue(P,M)){D=!0;break}}P!=null&&!D&&g.push(P)}if(Object.entries(g).every(([m,P])=>P.type==="literal")){let m={},P=[];return Object.entries(g).forEach(([D,A])=>{A.type==="literal"&&A.value.type==="string"&&(P.push(A.value.value),A.description!=null&&(m[A.value.value]={description:A.description}))}),b3i({nameOverride:e,generatedName:t,title:r,wrapAsNullable:a,description:i,availability:n,fernEnum:m,enumVarNames:void 0,enumValues:P,_default:void 0,namespace:c,groupName:d,context:u,source:l,inline:void 0})}return g.length===1&&g[0]!=null&&!u.options.preserveSingleSchemaOneOf?g[0]:s1_({nameOverride:e,generatedName:t,title:r,wrapAsNullable:a,description:i,availability:n,subtypes:g,namespace:c,groupName:d,encoding:o,source:l})}function CIE({schemas:e}){let t={},r=0;for(let a of e){if(!ep(a)){if(a.properties!=null&&Object.entries(a.properties).length>0){let u=Object.keys(a.properties),c={},d=u;for(let[s,o]of Object.entries(t)){let l=uAo(o,u);d=uAo(d,o),c[s]=l}c[r]=d,t=c}}r++}let i=[],n=0;for(let a of e){let u=t[n];if(u!=null&&u.length>0){let c=u.sort();if(c[0]!=null){i.push(c[0]),++n;continue}}ep(a)?i.push(h3i(n)??`${n}`):a.type==="array"||a.type==="boolean"||a.type==="integer"||a.type==="number"||a.type==="string"?i.push(""):i.push(h3i(n)??`${n}`),++n}return i}function s1_({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,description:n,availability:a,subtypes:u,namespace:c,groupName:d,encoding:s,source:o}){return i?zl.nullable({nameOverride:e,generatedName:t,title:r,value:zl.oneOf(Tee.undiscriminated({description:n,availability:a,nameOverride:e,generatedName:t,title:r,schemas:u,namespace:c,groupName:d,encoding:s,source:o,inline:void 0})),description:n,availability:a,namespace:c,groupName:d,inline:void 0}):zl.oneOf(Tee.undiscriminated({description:n,availability:a,nameOverride:e,generatedName:t,title:r,schemas:u,namespace:c,groupName:d,encoding:s,source:o,inline:void 0}))}function FJn(e){if(e.default!=null&&typeof e.default=="string")return e.default}function fau({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="number")return e.example;let i=gnn(e);for(let n of i??[])if(typeof n=="number")return n;if(r&&typeof r=="number")return r}function c1_({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="boolean")return e.example;let i=gnn(e);for(let n of i??[])if(typeof n=="boolean")return n;if(r&&typeof r=="boolean")return r}function nor({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="string")return e.example;let i=gnn(e);for(let n of i??[])if(typeof n=="string")return n;if(r&&typeof r=="string")return r}function l1_({schema:e,logger:t,fallback:r}){if(e.example!=null&&Array.isArray(e.example))return e.example;let i=gnn(e);for(let n of i??[])if(Array.isArray(n))return n;if(r&&Array.isArray(r))return r}var mnn="#/components/schemas/";function n0(e,t,r,i,n,a,u=!1,c=new Set,d){let s=Yw_(e)??n,o=LIE({schema:e,logger:r.logger});if(ep(e)){let l=g3i(e);return l!=null?(u?r.markSchemaAsReferencedByRequest(l):r.markSchemaAsReferencedByNonRequest(l),Cmi(e,t,r,i,o,s,a)):NJn(r.resolveSchemaReference(e),t,r,cau(e.$ref),o,s,a,c,u,d)}return NJn(e,t,r,i,o,s,a,c,u,d)}function Cmi(e,t,r,i,n,a,u){let c=e.$ref.includes("properties")?NJn(r.resolveSchemaReference(e),t,r,i,n,a,u,new Set):zl.reference(lDc(e,i,a,r.options.preserveSchemaIds));return t?zl.nullable({title:void 0,nameOverride:void 0,generatedName:g5(i,r.options.preserveSchemaIds),value:c,description:void 0,availability:void 0,namespace:void 0,groupName:void 0,inline:void 0}):c}function BIE(e){if(e!=null&&!e.includes(" ")&&/^[a-zA-Z]+$/.test(e))return e}function NJn(e,t,r,i,n,a,u,c=new Set,d=!1,s){typeof e=="string"&&(e={type:e});let o=hf(e,ad.TYPE_NAME)??(r.options.useTitlesAsName?BIE(e.title):void 0),l=hf(e,ad.SDK_GROUP_NAME)??hf(e,O$.TAGS)?.[0],v=(typeof l=="string"?[l]:l)??[];v=r.resolveGroupName(v);let g=g5(i,r.options.preserveSchemaIds),O=e.title,m=e.description,P=IK(e),D=[];e.example!=null&&D.push({name:void 0,value:e.example,description:void 0});let A=hf(e,O$.EXAMPLES);A!=null&&Object.keys(A).length>0&&D.push(...Object.entries(A).map(([T,z])=>({name:z?.summary??T,value:z.value,description:z.description})));let M=gnn(e);M!=null&&Object.keys(M).length>0&&D.push(...M.map(T=>({name:void 0,value:T,description:void 0})));let E=Kw_({schema:e,description:m,title:O,nameOverride:o,generatedName:g,availability:P});if(E!=null)return E;try{if(Array.isArray(e.type)){let z=e.type.indexOf("null"),G=z!==-1;if(e.type.length===1)e.type=e.type[0];else if(e.type.length===2&&G)e.type.splice(z,1),e.type=e.type[0],e.nullable=!0;else if(G&&(e.type.splice(z,1),e.nullable=!0),e.oneOf==null)e.oneOf=[...new Set(e.type)];else{let I=new Set([...e.oneOf,...e.type]);e.oneOf=[...I]}}if(!t&&e.nullable===!0)return NJn(e,!0,r,i,n,a,u,c,d,s);if("const"in e&&(e.enum=[e.const]),e.enum!=null&&(e.type==="string"||e.type==null||e.type==="enum")){if(!_au(e.enum))return b5({nameOverride:o,generatedName:g,title:O,primitive:vp.string({default:FJn(e),minLength:e.minLength,maxLength:e.maxLength,pattern:e.pattern,format:e.format,example:nor({schema:e,logger:r.logger,fallback:s})}),namespace:u,groupName:v,wrapAsNullable:t,description:m,availability:P});let z=Jw_(e);return e.enum.length===1&&e.enum[0]!=null&&z==null?n1_({nameOverride:o,generatedName:g,title:O,wrapAsNullable:t,value:e.enum[0],description:m,availability:P,namespace:u,groupName:v}):b3i({nameOverride:o,generatedName:g,title:O,fernEnum:z,enumVarNames:hf(e,[O$.ENUM_VAR_NAMES]),enumValues:e.enum,_default:e.default,description:m,availability:P,wrapAsNullable:t,namespace:u,groupName:v,context:r,source:a,inline:void 0})}if(_au(e.type)&&e.type.length>1){let z=e.type.includes("null"),G=e.type.filter(I=>I!=="null").map(I=>({type:I,nullable:z}));return O3i({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:P,wrapAsNullable:t,context:r,subtypes:G,namespace:u,groupName:v,encoding:n,source:a})}if(e.type==="boolean"){let z=hf(e,ad.BOOLEAN_LITERAL);return z!=null?f1_({nameOverride:o,generatedName:g,title:O,literal:px.boolean(z),wrapAsNullable:t,description:m,availability:P,namespace:u,groupName:v}):b5({nameOverride:o,generatedName:g,title:O,primitive:vp.boolean({default:IIE(e.default),example:c1_({schema:e,logger:r.logger,fallback:s})}),wrapAsNullable:t,description:m,availability:P,namespace:u,groupName:v})}if(e.type==="number")return sDc({nameOverride:o,generatedName:g,title:O,format:e.format,_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:Onn(e.exclusiveMinimum),exclusiveMaximum:Onn(e.exclusiveMaximum),multipleOf:e.multipleOf,description:m,availability:P,wrapAsNullable:t,example:fau({schema:e,logger:r.logger,fallback:s}),namespace:u,groupName:v});if(e.type==="integer")return r1_({nameOverride:o,generatedName:g,title:O,format:e.format,_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:Onn(e.exclusiveMinimum),exclusiveMaximum:Onn(e.exclusiveMaximum),multipleOf:e.multipleOf,description:m,availability:P,wrapAsNullable:t,example:fau({schema:e,logger:r.logger,fallback:s}),namespace:u,groupName:v});if(e.type==="float")return sDc({nameOverride:o,generatedName:g,title:O,format:"float",_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:Onn(e.exclusiveMinimum),exclusiveMaximum:Onn(e.exclusiveMaximum),multipleOf:e.multipleOf,description:m,availability:P,wrapAsNullable:t,example:fau({schema:e,logger:r.logger,fallback:s}),namespace:u,groupName:v});if(e.type==="string"){if(e.format==="date-time")return b5({nameOverride:o,generatedName:g,title:O,primitive:vp.datetime({example:nor({schema:e,logger:r.logger,fallback:s})}),wrapAsNullable:t,description:m,availability:P,namespace:u,groupName:v});if(e.format==="date"&&r.options.typeDatesAsStrings===!1)return b5({nameOverride:o,generatedName:g,title:O,primitive:vp.date({example:nor({schema:e,logger:r.logger,fallback:s})}),wrapAsNullable:t,description:m,availability:P,namespace:u,groupName:v});if(e.format==="json-string")return zl.unknown({nameOverride:o,generatedName:g,title:O,description:m,availability:P,namespace:u,groupName:v,example:void 0});let z=_1_(e,"const");return z!=null?f1_({nameOverride:o,generatedName:g,title:O,literal:px.string(z),wrapAsNullable:t,description:m,availability:P,namespace:u,groupName:v}):b5({nameOverride:o,generatedName:g,title:O,primitive:vp.string({default:FJn(e),pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:nor({schema:e,logger:r.logger,fallback:s})}),namespace:u,groupName:v,wrapAsNullable:t,description:m,availability:P})}if(e.type==="array")return kw_({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,item:e.items,description:m,availability:P,wrapAsNullable:t,context:r,namespace:u,groupName:v,example:l1_({schema:e,logger:r.logger,fallback:s}),source:a});if(e.additionalProperties!=null&&e.additionalProperties!==!1&&dau(e))return Xw_({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,additionalProperties:e.additionalProperties,description:m,availability:P,wrapAsNullable:t,context:r,namespace:u,groupName:v,encoding:n,example:e.example,source:a});if(e.oneOf!=null&&e.oneOf.length>0&&hf(e,ad.IS_DISCRIMINATED)===!1)return O3i({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:P,wrapAsNullable:t,context:r,subtypes:e.oneOf,namespace:u,groupName:v,encoding:n,source:a});if(e.type==="object"&&e.discriminator!=null&&e.discriminator.mapping!=null)return r.options.discriminatedUnionV2?fDc({nameOverride:o,generatedName:g,title:O,description:m,availability:P,wrapAsNullable:t,context:r,namespace:u,groupName:v,discriminator:e.discriminator,encoding:n,source:a}):oDc({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:P,discriminator:e.discriminator,properties:e.properties??{},required:e.required,wrapAsNullable:t,context:r,namespace:u,groupName:v,encoding:n,source:a});if(e.oneOf!=null&&e.oneOf.length>0){let z=hf(e,ad.IS_UNDISCRIMINATED);if(e.discriminator!=null&&e.discriminator.mapping!=null&&Object.keys(e.discriminator.mapping).length>0)return r.options.discriminatedUnionV2||z?fDc({nameOverride:o,generatedName:g,title:O,description:m,availability:P,wrapAsNullable:t,context:r,namespace:u,groupName:v,discriminator:e.discriminator,encoding:n,source:a}):oDc({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:P,discriminator:e.discriminator,properties:e.properties??{},required:e.required,wrapAsNullable:t,context:r,namespace:u,groupName:v,encoding:n,source:a});if(e.oneOf.length===1&&e.oneOf[0]!=null){if(r.options.preserveSingleSchemaOneOf)return O3i({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:P,wrapAsNullable:t,context:r,subtypes:e.oneOf.filter(I=>ep(I)||I.type!=="null"),encoding:n,namespace:u,groupName:v,source:a});let G=n0(e.oneOf[0],t,r,i,a,u,d);return LJn(G,m,u,v)}else if(e.oneOf.length>1){if(e.oneOf.length===2&&e.oneOf[0]!=null&&e.oneOf[1]!=null){let U=e.oneOf[0],Y=e.oneOf[1];if(!ep(U)&&U.type==="null")return n0(Y,!0,r,i,a,u);if(!ep(Y)&&Y.type==="null")return n0(U,!0,r,i,a,u)}let G=RIE({schemas:e.oneOf});if(G!=null)return b3i({nameOverride:o,generatedName:g,title:O,fernEnum:void 0,enumVarNames:void 0,enumValues:G,_default:e.default,description:m,availability:P,wrapAsNullable:t,namespace:u,groupName:v,context:r,source:a,inline:void 0});let I=d1_({schemas:e.oneOf,context:r});if(I!=null&&!r.options.discriminatedUnionV2&&!z)return uDc({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,properties:e.properties??{},required:e.required,description:m,availability:P,wrapAsNullable:t,discriminant:I.discriminant,variants:I.schemas,context:r,namespace:u,groupName:v,encoding:n,source:a});let R=e.oneOf.filter(U=>!ep(U)&&U.type==="null").length>0;return O3i({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:P,wrapAsNullable:t||R,context:r,subtypes:e.oneOf.filter(U=>ep(U)||U.type!=="null"),encoding:n,namespace:u,groupName:v,source:a})}}if(e.anyOf!=null&&e.anyOf.length>0){if(e.anyOf.length===1&&e.anyOf[0]!=null){let I=n0(e.anyOf[0],t,r,i,a,u,d);return LJn(I,m,u,v)}if(e.anyOf.length===2){let[I,R]=e.anyOf;if(I!=null&&R!=null){if(!ep(I)&&I.type==="null"){let U=n0(R,!0,r,i,a,u);return LJn(U,m,u,v)}else if(!ep(R)&&R.type==="null"){let U=n0(I,!0,r,i,a,u);return LJn(U,m,u,v)}}}let z=d1_({schemas:e.anyOf,context:r});if(z!=null&&!r.options.discriminatedUnionV2)return uDc({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,properties:e.properties??{},required:e.required,description:m,availability:P,wrapAsNullable:t,discriminant:z.discriminant,variants:z.schemas,context:r,namespace:u,groupName:v,encoding:n,source:a});let G=e.anyOf.filter(I=>!ep(I)&&I.type==="null").length>0;return O3i({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:P,wrapAsNullable:t||G,context:r,subtypes:e.anyOf.filter(I=>ep(I)||I.type!=="null"),encoding:n,namespace:u,groupName:v,source:a})}if(e.allOf!=null||e.properties!=null){let z=[];for(let I of e.allOf??[])(ep(I)||Object.keys(I).length>0)&&z.push(I);if((e.properties==null||dau(e))&&z.length===1&&z[0]!=null){let I=n0(z[0],t,r,i,a,u,d);return LJn(I,m,u,v)}let G=z.filter(I=>{let R=pau(I);return R||r.logger.warn(`Skipping non-object allOf element: ${JSON.stringify(I)}`),R});if((e.properties==null||dau(e))&&G.length===1&&G[0]!=null){let I=n0(G[0],t,r,i,a,u,d);return LJn(I,m,u,v)}return o1_({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,properties:e.properties??{},description:m,required:e.required,wrapAsNullable:t,allOf:G,context:r,propertiesToExclude:c,namespace:u,groupName:v,fullExamples:D,additionalProperties:e.additionalProperties,availability:P,encoding:n,source:a})}if(e.type==="object"&&zIE(e)&&xIE(e)&&dau(e))return sau({nameOverride:o,generatedName:g,title:O,description:m,availability:P,wrapAsNullable:t,keySchema:{nameOverride:void 0,generatedName:`${g}Key`,title:void 0,description:void 0,availability:void 0,schema:vp.string({default:FJn(e),pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:nor({schema:e,logger:r.logger,fallback:s})}),namespace:u,groupName:v},valueSchema:zl.unknown({nameOverride:void 0,generatedName:`${g}Value`,title:void 0,description:void 0,availability:void 0,example:void 0,namespace:u,groupName:v}),namespace:u,groupName:v,encoding:n,example:e.example});e.type!=null&&r.logger.warn(`Failed to parse an OpenAPI schema at the following location: ${i.join("->")}. Coercing to unknown.`);let T=e.example??e.default;return zl.unknown({nameOverride:o,generatedName:g,title:O,description:m,availability:P,namespace:u,groupName:v,example:T})}catch(T){return r.logger.debug(`Error converting schema: ${T.message}
|
|
@@ -2328,7 +2328,7 @@ ${a}]`:`[${e.join(u)}]`},U_u=(e,t,r)=>`let ${e} = ${F3c(t,r)}`,F3c=(e,t,r)=>{swi
|
|
|
2328
2328
|
`)},e.heapify=function(t,r){var i=new e(r);return i.heapArray=t,i.init(),i},e.heappop=function(t,r){var i=new e(r);return i.heapArray=t,i.pop()},e.heappush=function(t,r,i){var n=new e(i);n.heapArray=t,n.push(r)},e.heappushpop=function(t,r,i){var n=new e(i);return n.heapArray=t,n.pushpop(r)},e.heapreplace=function(t,r,i){var n=new e(i);return n.heapArray=t,n.replace(r)},e.heaptop=function(t,r,i){r===void 0&&(r=1);var n=new e(i);return n.heapArray=t,n.top(r)},e.heapbottom=function(t,r,i){r===void 0&&(r=1);var n=new e(i);return n.heapArray=t,n.bottom(r)},e.nlargest=function(t,r,i){var n=new e(i);return n.heapArray=Qee([],z$(r),!1),n.init(),n.top(t)},e.nsmallest=function(t,r,i){var n=new e(i);return n.heapArray=Qee([],z$(r),!1),n.init(),n.bottom(t)},e.prototype.add=function(t){return this._sortNodeUp(this.heapArray.push(t)-1),this._applyLimit(),!0},e.prototype.addAll=function(t){var r,i=this.length;(r=this.heapArray).push.apply(r,Qee([],z$(t),!1));for(var n=this.length;i<n;++i)this._sortNodeUp(i);return this._applyLimit(),!0},e.prototype.bottom=function(t){return t===void 0&&(t=1),this.heapArray.length===0||t<=0?[]:this.heapArray.length===1?[this.heapArray[0]]:t>=this.heapArray.length?Qee([],z$(this.heapArray),!1):this._bottomN_push(~~t)},e.prototype.check=function(){var t=this;return this.heapArray.find(function(r,i){return!!t.getChildrenOf(i).find(function(n){return t.compare(r,n)>0})})},e.prototype.clear=function(){this.heapArray=[]},e.prototype.clone=function(){var t=new e(this.comparator());return t.heapArray=this.toArray(),t._limit=this._limit,t},e.prototype.comparator=function(){return this.compare},e.prototype.contains=function(t,r){return r===void 0&&(r=e.defaultIsEqual),this.indexOf(t,r)!==-1},e.prototype.init=function(t){t&&(this.heapArray=Qee([],z$(t),!1));for(var r=Math.floor(this.heapArray.length);r>=0;--r)this._sortNodeDown(r);this._applyLimit()},e.prototype.isEmpty=function(){return this.length===0},e.prototype.indexOf=function(t,r){if(r===void 0&&(r=e.defaultIsEqual),this.heapArray.length===0)return-1;for(var i=[],n=0;n<this.heapArray.length;){var a=this.heapArray[n];if(r(a,t))return n;this.compare(a,t)<=0&&i.push.apply(i,Qee([],z$(e.getChildrenIndexOf(n)),!1)),n=i.shift()||this.heapArray.length}return-1},e.prototype.indexOfEvery=function(t,r){if(r===void 0&&(r=e.defaultIsEqual),this.heapArray.length===0)return[];for(var i=[],n=[],a=0;a<this.heapArray.length;){var u=this.heapArray[a];r(u,t)?(n.push(a),i.push.apply(i,Qee([],z$(e.getChildrenIndexOf(a)),!1))):this.compare(u,t)<=0&&i.push.apply(i,Qee([],z$(e.getChildrenIndexOf(a)),!1)),a=i.shift()||this.heapArray.length}return n},e.prototype.leafs=function(){if(this.heapArray.length===0)return[];var t=e.getParentIndexOf(this.heapArray.length-1);return this.heapArray.slice(t+1)},Object.defineProperty(e.prototype,"length",{get:function(){return this.heapArray.length},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"limit",{get:function(){return this._limit},set:function(t){t<0||isNaN(t)?this._limit=0:this._limit=~~t,this._applyLimit()},enumerable:!1,configurable:!0}),e.prototype.setLimit=function(t){return this.limit=t,t<0||isNaN(t)?NaN:this._limit},e.prototype.peek=function(){return this.heapArray[0]},e.prototype.pop=function(){var t=this.heapArray.pop();return this.length>0&&t!==void 0?this.replace(t):t},e.prototype.push=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return t.length<1?!1:t.length===1?this.add(t[0]):this.addAll(t)},e.prototype.pushpop=function(t){var r;return this.compare(this.heapArray[0],t)<0&&(r=z$([this.heapArray[0],t],2),t=r[0],this.heapArray[0]=r[1],this._sortNodeDown(0)),t},e.prototype.remove=function(t,r){var i=this;if(r===void 0&&(r=e.defaultIsEqual),!this.heapArray.length)return!1;if(t===void 0)return this.pop(),!0;for(var n=[0];n.length;){var a=n.shift();if(r(this.heapArray[a],t))return a===0?this.pop():a===this.heapArray.length-1?this.heapArray.pop():(this.heapArray.splice(a,1,this.heapArray.pop()),this._sortNodeUp(a),this._sortNodeDown(a)),!0;if(this.compare(this.heapArray[a],t)<=0){var u=e.getChildrenIndexOf(a).filter(function(c){return c<i.heapArray.length});n.push.apply(n,Qee([],z$(u),!1))}}return!1},e.prototype.replace=function(t){var r=this.heapArray[0];return this.heapArray[0]=t,this._sortNodeDown(0),r},e.prototype.size=function(){return this.length},e.prototype.top=function(t){return t===void 0&&(t=1),this.heapArray.length===0||t<=0?[]:this.heapArray.length===1||t===1?[this.heapArray[0]]:t>=this.heapArray.length?Qee([],z$(this.heapArray),!1):this._topN_push(~~t)},e.prototype.toArray=function(){return Qee([],z$(this.heapArray),!1)},e.prototype.toString=function(){return this.heapArray.toString()},e.prototype.get=function(t){return this.heapArray[t]},e.prototype.getChildrenOf=function(t){var r=this;return e.getChildrenIndexOf(t).map(function(i){return r.heapArray[i]}).filter(function(i){return i!==void 0})},e.prototype.getParentOf=function(t){var r=e.getParentIndexOf(t);return this.heapArray[r]},e.prototype[Symbol.iterator]=function(){return VgM(this,function(t){switch(t.label){case 0:return this.length?[4,this.pop()]:[3,2];case 1:return t.sent(),[3,0];case 2:return[2]}})},e.prototype.iterator=function(){return this.toArray()},e.prototype._applyLimit=function(){if(this._limit>0&&this._limit<this.heapArray.length)for(var t=this.heapArray.length-this._limit;t;)this.heapArray.pop(),--t},e.prototype._bottomN_push=function(t){var r=new e(this.compare);r.limit=t,r.heapArray=this.heapArray.slice(-t),r.init();for(var i=this.heapArray.length-1-t,n=e.getParentIndexOf(i),a=[],u=i;u>n;--u)a.push(u);for(var c=this.heapArray;a.length;){var u=a.shift();this.compare(c[u],r.peek())>0&&(r.replace(c[u]),u%2&&a.push(e.getParentIndexOf(u)))}return r.toArray()},e.prototype._moveNode=function(t,r){var i;i=z$([this.heapArray[r],this.heapArray[t]],2),this.heapArray[t]=i[0],this.heapArray[r]=i[1]},e.prototype._sortNodeDown=function(t){for(var r=this.heapArray.length;;){var i=2*t+1,n=i+1,a=t;if(i<r&&this.compare(this.heapArray[i],this.heapArray[a])<0&&(a=i),n<r&&this.compare(this.heapArray[n],this.heapArray[a])<0&&(a=n),a===t)break;this._moveNode(t,a),t=a}},e.prototype._sortNodeUp=function(t){for(;t>0;){var r=e.getParentIndexOf(t);if(this.compare(this.heapArray[t],this.heapArray[r])<0)this._moveNode(t,r),t=r;else break}},e.prototype._topN_push=function(t){var r=new e(this._invertedCompare);r.limit=t;for(var i=[0],n=this.heapArray;i.length;){var a=i.shift();a<n.length&&(r.length<t?(r.push(n[a]),i.push.apply(i,Qee([],z$(e.getChildrenIndexOf(a)),!1))):this.compare(n[a],r.peek())<0&&(r.replace(n[a]),i.push.apply(i,Qee([],z$(e.getChildrenIndexOf(a)),!1))))}return r.toArray()},e.prototype._topN_fill=function(t){var r=this.heapArray,i=new e(this._invertedCompare);i.limit=t,i.heapArray=r.slice(0,t),i.init();for(var n=e.getParentIndexOf(t-1)+1,a=[],u=n;u<t;++u)a.push.apply(a,Qee([],z$(e.getChildrenIndexOf(u).filter(function(c){return c<r.length})),!1));for((t-1)%2&&a.push(t);a.length;){var u=a.shift();u<r.length&&this.compare(r[u],i.peek())<0&&(i.replace(r[u]),a.push.apply(a,Qee([],z$(e.getChildrenIndexOf(u)),!1)))}return i.toArray()},e.prototype._topN_heap=function(t){for(var r=this.clone(),i=[],n=0;n<t;++n)i.push(r.pop());return i},e.prototype._topIdxOf=function(t){if(!t.length)return-1;for(var r=0,i=t[r],n=1;n<t.length;++n){var a=this.compare(t[n],i);a<0&&(r=n,i=t[n])}return r},e.prototype._topOf=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];var i=new e(this.compare);return i.init(t),i.peek()},e})();function _X_(e,t,r,i,n){if(r<=0)return[];let a=i??(c=>c),u=new dX_(WgM);for(let c of t){let d=pX_.default.get(a(e),a(c));n!=null&&d>n||(u.push({neighbor:c,distance:d}),u.size()>r&&u.pop())}return HgM(u).reverse().map(c=>c.neighbor)}function WgM(e,t){return e.distance!==t.distance?t.distance-e.distance:t.neighbor.localeCompare(e.neighbor)}function HgM(e){let t=[];for(;e.size()>0;){let r=e.pop();r&&t.push(r)}return t}var $gM=3,GgM=5;function u7i(e,t){let r=_X_(e,t,$gM,QgM,GgM),i=Array.from(t),n=`Failed to locate API section ${e}.`;switch(r.length){case 0:return n=`${n} No similar API sections found. Available API sections:`,i.length===0?`${n} []`:`${n} [
|
|
2329
2329
|
${i.map(a=>` ${a}`).join(`,
|
|
2330
2330
|
`)}
|
|
2331
|
-
]`;case 1:return`${n} Did you mean ${r[0]}?`;case 2:return`${n} Did you mean ${r[0]} or ${r[1]}?`;default:return`${n} Did you mean ${r[0]}, ${r[1]}, or ${r[2]}?`}}function Son(e){return`API section ${e} is specified multiple times, however will be only rendered once.`}function QgM(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}function BXn({children:e,findEndpointById:t,stringifyEndpointPathParts:r,disableEndpointPairs:i,apiDefinitionId:n}){if(i)return e;let a=[],u=new Map;return e.forEach(c=>{if(c.type!=="endpoint"){a.push(c);return}let d=t(c.endpointId);if(d==null)throw new Error(`Endpoint ${c.endpointId} not found`);let s=`${d.method} ${r(d)}`,o=u.get(s);if(u.set(s,c),o==null||o.isResponseStream===c.isResponseStream){a.push(c);return}let l=a.indexOf(o),v=c.isResponseStream?c:o,g=c.isResponseStream?o:c,O={id:Do.V1.NodeId(`${n}:${g.endpointId}+${v.endpointId}`),type:"endpointPair",stream:v,nonStream:g};a[l]=O}),a}function Khu({left:e,right:t,findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}){return BXn({children:[...e,...t],findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}).filter(u=>u.type==="apiPackage"?u.children.length>0:!0)}function kor(e,t){if(t!=null)return BT(e.absoluteFilePath,t)}function Yhu({docsWorkspace:e,page:t,parentSlug:r,idgen:i,markdownFilesToFullSlugs:n,markdownFilesToNoIndex:a,hideChildren:u}){let c=Do.V1.PageId(kor(e,t.absolutePath)),d=r.apply({fullSlug:n.get(t.absolutePath)?.split("/"),urlSlug:t.slug??TT(t.title)});return{id:i.get(c),type:"page",pageId:c,title:t.title,slug:d.get(),icon:t.icon,hidden:u||t.hidden,noindex:t.noindex||a.get(t.absolutePath),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,availability:t.availability}}var Xhu=class{apiSection;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;markdownFilesToTags;workspace;hideChildren;apiDefinitionId;#e;#t=new Set;#r=new Set;#n=new Set;#i=new Set;#a=new Set;#o=new Map;#s=[];#f;#u;#c;disableEndpointPairs;constructor(t,r,i,n,a,u,c,d,s,o,l){this.apiSection=t,this.docsWorkspace=n,this.taskContext=a,this.markdownFilesToFullSlugs=u,this.markdownFilesToNoIndex=c,this.markdownFilesToTags=d,this.workspace=o,this.hideChildren=l,this.disableEndpointPairs=n.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=Do.V1.ApiDefinitionId(r.id),this.#e=o7i.create(r,a),this.#c=s,this.#f=this.apiSection.overviewAbsolutePath!=null?Do.V1.PageId(kor(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let v=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#u=i.apply({fullSlug:v?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??TT(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#s=this.#l(this.apiSection.navigation,this.#e.api.rootPackage,this.#u)),this.#s=this.#y(this.#s.map(g=>this.#j(g)),this.#w(this.#e.api.rootPackage,this.#u))}get(){let t=Do.V1.followRedirects(this.#s),r=new UPi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,this.workspace?.changelog?.files.map(i=>i.absoluteFilepath),this.docsWorkspace,this.#c).orUndefined();return{id:this.#c.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#f,paginated:this.apiSection.paginated,slug:this.#u.get(),icon:this.apiSection.icon,hidden:this.hideChildren||this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#u,viewers:void 0,hidden:this.hideChildren}),children:this.#s,availability:this.apiSection.availability,pointsTo:t,noindex:void 0,playground:this.#g(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}#l(t,r,i){r=this.#e.resolveSubpackage(r);let n=r!=null?o7i.getSubpackageId(r):void 0;return t.map(a=>lVa(a)._visit({link:u=>({id:this.#c.get(u.url),type:"link",title:u.text,icon:u.icon,url:Do.Url(u.url)}),page:u=>this.#p(u,i),package:u=>this.#_(u,i),section:u=>this.#h(u,i),item:({value:u})=>this.#v(u,n,i),endpoint:u=>this.#O(u,n,i)})).filter(yy)}#p(t,r){return Yhu({page:t,parentSlug:r,docsWorkspace:this.docsWorkspace,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex,idgen:this.#c,hideChildren:this.hideChildren})}#_(t,r){let i=t.overviewAbsolutePath!=null?Do.V1.PageId(kor(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#e.getSubpackageByIdOrLocator(t.package);if(a!=null){let u=o7i.getSubpackageId(a),c=this.#c.get(i??`${this.apiDefinitionId}:${u}`);this.#a.has(u)&&this.taskContext.logger.warn(Son(t.package)),this.#a.add(u),this.#o.set(c,[u]);let d=t.slug??(Zor(a)?a.urlSlug:this.apiSection.slug??TT(this.apiSection.title)),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#l(t.contents,a,s);return{id:c,type:"apiPackage",children:o,title:t.title??(Zor(a)?a.displayName??nJt(a.name):this.apiSection.title),slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}else{this.taskContext.logger.warn(u7i(t.package,this.#e.subpackageLocators));let u=t.slug??TT(t.package),c=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),d=this.#l(t.contents,void 0,c);return{id:this.#c.get(i??`${this.apiDefinitionId}:${TT(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:c.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}#h(t,r){let i=t.overviewAbsolutePath!=null?Do.V1.PageId(kor(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=t.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(t.overviewAbsolutePath):void 0,u=this.#c.get(i??n??r.get()),c=t.referencedSubpackages.map(l=>{let v=this.#e.getSubpackageByIdOrLocator(l),g=v!=null?o7i.getSubpackageId(v):void 0;if(g===void 0){this.taskContext.logger.error(u7i(l,this.#e.subpackageLocators));return}return{subpackageId:g,locator:l}}).filter(l=>l!=null).filter(yy);this.#o.set(u,c.map(l=>l.subpackageId)),c.forEach(l=>{this.#a.has(l.subpackageId)&&this.taskContext.logger.error(Son(l.locator)),this.#a.add(l.subpackageId)});let d=t.slug??TT(t.title),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#l(t.contents,void 0,s);return{id:u,type:"apiPackage",children:o,title:t.title,slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:a,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}#v(t,r,i){t=t.trim();let n=this.#e.getSubpackageByIdOrLocator(t)??this.#e.getSubpackageByIdOrLocator(R_(t));if(n!=null){let a=o7i.getSubpackageId(n),u=this.#c.get(`${this.apiDefinitionId}:${a}`);this.#a.has(a)&&this.taskContext.logger.error(Son(t)),this.#a.add(a),this.#o.set(u,[a]);let c=Zor(n)?n.urlSlug:"",d=i.apply({urlSlug:c});return{id:u,type:"apiPackage",children:[],title:Zor(n)?n.displayName??nJt(n.name):this.apiSection.title,slug:d.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}return this.#O({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,i)}#O(t,r,i){let n=(r!=null?this.#e.subpackages.get(h2.SubpackageId(r))?.endpoints.get(h2.EndpointId(t.endpoint)):void 0)??this.#e.endpointsByLocator.get(t.endpoint);if(n!=null){let c=this.#e.getEndpointId(n);if(c==null)this.taskContext.logger.error(`Expected Endpoint ID for ${n.id} at path: ${won(n.method,n.path.parts)}. Got undefined.`);else{this.#t.has(c)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${c}`),this.#t.add(c);let d=t.slug!=null?i.append(t.slug):i.apply(n);return{id:this.#c.get(`${this.apiDefinitionId}:${c}`),type:"endpoint",method:n.method,endpointId:c,apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:t.title??n.name??mB(n.path.parts),slug:d.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}let a=(r!=null?this.#e.subpackages.get(h2.SubpackageId(r))?.webSockets.get(h2.WebSocketId(t.endpoint)):void 0)??this.#e.webSocketsByLocator.get(t.endpoint);if(a!=null){let c=this.#e.getWebSocketId(a);if(c==null)this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);else return this.#r.has(c)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${c}`),this.#r.add(c),{id:this.#c.get(`${this.apiDefinitionId}:${c}`),type:"webSocket",webSocketId:c,title:t.title??a.name??mB(a.path.parts),slug:(t.slug!=null?i.append(t.slug):i.apply(a)).get(),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(a.availability),playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let u=(r!=null?this.#e.subpackages.get(h2.SubpackageId(r))?.webhooks.get(h2.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(Do.V1.WebhookId(t.endpoint));if(u!=null){let c=this.#e.getWebhookId(u);if(c==null)this.taskContext.logger.error(`Expected Webhook ID for ${u.id}. Got undefined.`);else return this.#n.has(c)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${c}`),this.#n.add(c),{id:this.#c.get(`${this.apiDefinitionId}:${c}`),type:"webhook",webhookId:c,method:u.method,title:t.title??u.name??Fb("/",...u.path),slug:(t.slug!=null?i.append(t.slug):i.apply(u)).get(),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#y(t,r){return Khu({left:t,right:r,findEndpointById:i=>this.#e.endpoints.get(i),stringifyEndpointPathParts:i=>mB(i.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#j(t){return fVa({child:t,nodeIdToSubpackageId:this.#o,convertApiDefinitionPackageId:(r,i)=>this.#m(r,i),mergeAndFilterChildren:this.#y.bind(this)})}#w(t,r){let i=[];return t.endpoints.forEach(n=>{if(n.protocol?.type==="grpc"){let a=this.#e.getGrpcId(n);if(a==null){this.taskContext.logger.error(`Expected Grpc ID for ${n.id} at path: ${won(n.method,n.path.parts)}. Got undefined.`);return}if(this.#i.has(a))return;let u=r.apply(n);i.push({id:Do.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"grpc",grpcId:a,title:n.name??mB(n.path.parts),method:n.protocol?.methodType??"UNARY",apiDefinitionId:this.apiDefinitionId,availability:void 0,slug:u.get(),icon:void 0,hidden:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}else{let a=this.#e.getEndpointId(n);if(a==null){this.taskContext.logger.error(`Expected Endpoint ID for ${n.id} at path: ${won(n.method,n.path.parts)}. Got undefined.`);return}if(this.#t.has(a))return;let u=r.apply(n);i.push({id:Do.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"endpoint",method:n.method,endpointId:a,apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:n.name??mB(n.path.parts),slug:u.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}}),t.websockets.forEach(n=>{let a=this.#e.getWebSocketId(n);if(a==null){this.taskContext.logger.error(`Expected WebSocket ID for ${n.id}. Got undefined.`);return}this.#r.has(a)||i.push({id:Do.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webSocket",webSocketId:a,title:n.name??mB(n.path.parts),slug:r.apply(n).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(n.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.webhooks.forEach(n=>{let a=this.#e.getWebhookId(n);if(a==null){this.taskContext.logger.error(`Expected Webhook ID for ${n.id}. Got undefined.`);return}this.#n.has(a)||i.push({id:Do.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webhook",webhookId:a,method:n.method,title:n.name??nJt(n.id),slug:r.apply(n).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.subpackages.forEach(n=>{if(this.#a.has(n))return;let a=this.#e.getSubpackageByIdOrLocator(n);if(a==null){this.taskContext.logger.error(`Subpackage ${n} not found in ${this.apiDefinitionId}`);return}let u=Zor(a)?r.apply(a):r,c=this.#m(n,u);c.length>0&&i.push({id:Do.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"apiPackage",children:c,title:Zor(a)?a.displayName??nJt(a.name):this.apiSection.title,slug:u.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&(i=i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,c=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(c)})),i}#m(t,r){let i=t!=null?this.#e.resolveSubpackage(this.#e.getSubpackageByIdOrLocator(t)):void 0;return i==null?(this.taskContext.logger.error(u7i(t||"unknown",[])),[]):this.#w(i,r)}#g(t){return Jhu(t)}mergeEndpointPairs(t){return BXn({children:t,findEndpointById:r=>this.#e.endpoints.get(r),stringifyEndpointPathParts:r=>mB(r.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var Zhu=class{#e={};#t={};#r={};#n={};constructor(t){for(let[r,i]of Object.entries(t.subpackages))this.#e[R_(r).toLowerCase()]=i,this.#e[`subpackage_${R_(r).toLowerCase()}`]=i;for(let[r,i]of Object.entries(t.endpoints)){this.#r[r]=i,this.#r[r.replace("endpoint_","")]=i,this.#r[r.replace("endpoint_","subpackage_")]=i;for(let n of[i.method,"STREAM"])i.environments?.forEach(a=>{this.#r[`${n} ${Fb(a.baseUrl,mB(i.path))}`]=i,this.#r[`${n} ${Fb(a.baseUrl,Y6e(i.path))}`]=i;let u=Qhu(a);u!=null&&(this.#r[`${n} ${Fb(u,mB(i.path))}`]=i,this.#r[`${n} ${Fb(u,Y6e(i.path))}`]=i)}),this.#r[`${i.method} ${mB(i.path)}`]=i,this.#r[`${i.method} ${Y6e(i.path)}`]=i}for(let[r,i]of Object.entries(t.webhooks))this.#t[r]=i,this.#t[r.replace("webhook_","")]=i,this.#t[r.replace("webhook_","subpackage_")]=i,this.#t[`${i.method} ${i.path.join("/")}`]=i;for(let[r,i]of Object.entries(t.websockets))this.#n[r]=i,this.#n[r.replace("websocket_","")]=i,this.#n[r.replace("websocket_","subpackage_")]=i,this.#n[`STREAM ${mB(i.path)}`]=i,this.#n[`STREAM ${Y6e(i.path)}`]=i}getSubpackageByLocator(t){if(["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS","CONNECT","TRACE"].some(i=>t.includes(i)))return;let r=t.replace(".yml","").replace(".yaml","");return this.#e[r]}getWebhookByLocator(t,r){return this.#t[t]??this.#t[`${r}.${t}`]??this.#t[`webhook_${r}.${t}`]}getEndpointByLocator(t,r){return this.#r[t]??this.#r[`${r}.${t}`]??this.#r[`endpoint_${r}.${t}`]}getWebSocketByLocator(t,r){return this.#n[t]??this.#n[`${r}.${t}`]??this.#n[`websocket_${r}.${t}`]}get subpackageLocators(){return new Set(Object.keys(this.#e))}};function pVa({item:e,parentSlug:t}){return t.apply({urlSlug:TT(e.id.split(".").pop()??"")}).get()}var _Va=class{apiSection;workspace;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;markdownFilesToTags;hideChildren;apiDefinitionId;#e;#t;#r=new Set;#n=new Set;#i=new Set;#a=new Set;#o=new Map;#s=[];#f;#u;#c;#l=new Map;disableEndpointPairs;constructor(t,r,i,n,a,u,c,d,s,o,l){this.apiSection=t,this.workspace=n,this.docsWorkspace=a,this.taskContext=u,this.markdownFilesToFullSlugs=c,this.markdownFilesToNoIndex=d,this.markdownFilesToTags=s,this.hideChildren=l,this.#e=r,this.#t=new Zhu(r),this.disableEndpointPairs=a.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=Do.V1.ApiDefinitionId(r.id),this.#c=o,this.#f=this.apiSection.overviewAbsolutePath!=null?Do.V1.PageId(kor(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let v=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#u=i.apply({fullSlug:v?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??TT(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#s=this.#p(this.apiSection.navigation,void 0,this.#u)),this.#s=this.#j(this.#s.map(g=>this.#w(g)),this.#m(this.#e,this.#u))}get(){let t=Do.V1.followRedirects(this.#s),r=new UPi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,this.workspace?.changelog?.files.map(i=>i.absoluteFilepath),this.docsWorkspace,this.#c).orUndefined();return{id:this.#c.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#f,paginated:this.apiSection.paginated,slug:this.#u.get(),icon:this.apiSection.icon,hidden:this.hideChildren||this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#u,viewers:void 0,hidden:this.hideChildren}),children:this.#s,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#S(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}#p(t,r,i){return t.map(n=>lVa(n)._visit({link:a=>({id:this.#c.get(a.url),type:"link",title:a.text,icon:a.icon,url:Do.Url(a.url)}),page:a=>this.#_(a,i),package:a=>this.#h(a,i),section:a=>this.#v(a,i),item:({value:a})=>this.#O(a,r,i),endpoint:a=>this.#y(a,r,i)})).filter(yy)}#_(t,r){return Yhu({docsWorkspace:this.docsWorkspace,page:t,parentSlug:r,idgen:this.#c,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex})}#h(t,r){let i=t.overviewAbsolutePath!=null?Do.V1.PageId(kor(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#t.getSubpackageByLocator(t.package);if(a!=null){let u=this.#c.get(i??`${this.apiDefinitionId}:${a.id}`);this.#a.has(a.id)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${a.id}`),this.#a.add(a.id),this.#o.set(u,[a.id]);let c=t.slug??TT(a.name),d=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:c}),s=this.#p(t.contents,a.id,d),o={id:u,type:"apiPackage",children:s,title:t.title??a.displayName??nJt(a.name),slug:d.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return this.#l.set(a.id,o),o}else{this.taskContext.logger.warn(u7i(t.package,this.#t.subpackageLocators));let u=t.slug??TT(t.package),c=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),d=this.#p(t.contents,t.package,c),s={id:this.#c.get(i??`${this.apiDefinitionId}:${TT(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:c.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return this.#l.set(t.package,s),s}}#v(t,r){let i=t.overviewAbsolutePath!=null?Do.V1.PageId(kor(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#c.get(i??n??r.get()),u=t.referencedSubpackages.map(v=>{let g=this.#t.getSubpackageByLocator(v);if(g==null){this.taskContext.logger.error(u7i(v,this.#t.subpackageLocators));return}return{subpackageId:g.id,locator:v}}).filter(v=>v!=null).filter(yy),c=u.map(v=>v.subpackageId);this.#o.set(a,c),u.forEach(v=>{this.#a.has(v.subpackageId)&&this.taskContext.logger.error(Son(v.locator)),this.#a.add(v.subpackageId)});let d=t.slug??TT(t.title),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#p(t.contents,t.title,s),l={id:a,type:"apiPackage",children:o,title:t.title,slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return c.forEach(v=>{this.#l.set(v,l)}),l}#O(t,r,i){t=t.trim();let n=this.#t.getSubpackageByLocator(t);if(n!=null){let a=n.id,u=this.#c.get(`${this.apiDefinitionId}:${a}`);this.#a.has(a)&&this.taskContext.logger.warn(Son(t)),this.#a.add(a),this.#o.set(u,[a]);let c=TT(n.name),d=i.apply({urlSlug:c}),s={id:u,type:"apiPackage",children:[],title:n.displayName??nJt(n.name),slug:d.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};return this.#l.set(a,s),s}return this.#y({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,i)}#y(t,r,i){let n=this.#t.getEndpointByLocator(t.endpoint,r);if(n!=null)if(this.#r.has(n.id)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${n.id}`),n.id==null)this.taskContext.logger.error(`Expected Endpoint ID for ${n.id} at path: ${won(n.method,n.path)}. Got undefined.`);else{this.#r.add(n.id);let c=t.slug!=null?i.append(t.slug).get():pVa({item:n,parentSlug:i});return{id:this.#c.get(`${this.apiDefinitionId}:${n.id}`),type:"endpoint",method:n.method,endpointId:n.id,apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(n.availability),isResponseStream:n.responses?.[0]?.body.type==="stream",title:t.title??n.displayName??mB(n.path),slug:c,icon:t.icon,hidden:this.hideChildren||t.hidden,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let a=this.#t.getWebSocketByLocator(t.endpoint,r);if(a!=null)if(this.#n.has(a.id)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${a.id}`),a.id==null){this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return}else return this.#n.add(a.id),{id:this.#c.get(`${this.apiDefinitionId}:${a.id}`),type:"webSocket",webSocketId:a.id,title:t.title??a.displayName??mB(a.path),slug:t.slug!=null?i.append(t.slug).get():pVa({item:a,parentSlug:i}),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(a.availability),playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};let u=this.#t.getWebhookByLocator(t.endpoint,r);if(u!=null)if(this.#i.has(u.id)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${u.id}`),u.id==null)this.taskContext.logger.error(`Expected Webhook ID for ${u.id}. Got undefined.`);else return this.#i.add(u.id),{id:this.#c.get(`${this.apiDefinitionId}:${u.id}`),type:"webhook",webhookId:u.id,method:u.method,title:t.title??u.displayName??Fb("/",...u.path),slug:t.slug!=null?i.append(t.slug).get():pVa({item:u,parentSlug:i}),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#j(t,r){return Khu({left:t,right:r,findEndpointById:i=>this.#t.getEndpointByLocator(i,void 0),stringifyEndpointPathParts:i=>mB(i.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#w(t){return fVa({child:t,nodeIdToSubpackageId:this.#o,convertApiDefinitionPackageId:(r,i)=>this.#E(r,i),mergeAndFilterChildren:this.#j.bind(this)})}#m(t,r){let i=[];return Object.entries(t.subpackages).forEach(([n,a])=>{if(!this.#a.has(n)){let u=this.#g(n,a,r);u!=null&&i.push(u)}}),Object.entries(t.endpoints).forEach(([n,a])=>{if(n==null){this.taskContext.logger.error(`Expected Endpoint ID for ${a.id} at path: ${won(a.method,a.path)}. Got undefined.`);return}!this.#r.has(Wq.EndpointId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#P(n,a,r,i)}),Object.entries(t.websockets).forEach(([n,a])=>{if(n==null){this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return}!this.#n.has(Wq.WebSocketId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#A(n,a,r,i)}),Object.entries(t.webhooks).forEach(([n,a])=>{if(n==null){this.taskContext.logger.error(`Expected Webhook ID for ${a.id}. Got undefined.`);return}!this.#i.has(Wq.WebhookId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#d(n,a,r,i)}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,c=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(c)}),i}#g(t,r,i){let n=Do.V1.SlugGenerator.init(i.get()).apply({urlSlug:TT(r.name)}),a=this.#E(t,n),u={id:Do.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"apiPackage",children:a,title:r.displayName??nJt(r.name),slug:n.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};return this.#l.set(t,u),a.length>0?u:void 0}#D(t,r,i,n){r.slug=pVa({item:t,parentSlug:i}),n.push(r)}#P(t,r,i,n){let a={id:Do.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"endpoint",method:r.method,endpointId:Wq.EndpointId(t),apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(r.availability),isResponseStream:r.responses?.[0]?.body.type==="stream",title:r.displayName??mB(r.path),slug:i.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#D(r,a,i,n)}#A(t,r,i,n){let a={id:Do.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"webSocket",webSocketId:Wq.WebSocketId(t),title:r.displayName??mB(r.path),slug:i.get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(r.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#D(r,a,i,n)}#d(t,r,i,n){let a={id:Do.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"webhook",webhookId:Wq.WebhookId(t),method:r.method,title:r.displayName??nJt(r.id),slug:i.get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#D(r,a,i,n)}#T(t){let r=Object.fromEntries(Object.entries(this.#e?.subpackages??{}).filter(([u,c])=>t===this.#e.id?c.id.split(".").length===1:c.id!=null&&c.id.includes(t)&&c.id!==t&&c.id.split(".").length===t.split(".").length+1)),i=Object.fromEntries(Object.entries(this.#e?.endpoints??{}).filter(([u,c])=>c.namespace!=null&&c.namespace.join(".")===Wq.api.v1.SubpackageId(t))),n=Object.fromEntries(Object.entries(this.#e?.websockets??{}).filter(([u,c])=>c.namespace!=null&&c.namespace.join(".")===Wq.api.v1.SubpackageId(t))),a=Object.fromEntries(Object.entries(this.#e?.webhooks??{}).filter(([u,c])=>c.namespace!=null&&c.namespace.join(".")===Wq.api.v1.SubpackageId(t)));return{id:Wq.ApiDefinitionId(t),endpoints:i,websockets:n,webhooks:a,types:{},subpackages:r,auths:{},globalHeaders:void 0,snippetsConfiguration:void 0}}#E(t,r){let i=t!=null?this.#T(t):void 0;return i==null?(this.taskContext.logger.error(u7i(t||"unknown",[])),[]):this.#m(i,r)}#S(t){return Jhu(t)}mergeEndpointPairs(t){return BXn({children:t,findEndpointById:r=>this.#e?.endpoints[r],stringifyEndpointPathParts:r=>mB(r.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var hX_=ui(require("crypto"),1);function JgM(e){return hX_.default.createHash("sha256").update(e).digest("hex")}var khu=class e{static init(){return new e}constructor(){}#e=new Map;#t=new Set;#r(t){let r=this.#e.get(t)??0;return this.#e.set(t,r+1),JgM(r===0?t:`${t}-${r}`)}#n(t){let r=this.#r(t),i=0;for(;this.#t.has(r);)if(r=this.#r(t),i++,i>100)throw new Error(`Infinite loop detected for id: ${t}`);return r}get(t){return Do.V1.NodeId(this.#n(t))}};function eyu(e){return e==null?{}:{pythonSdk:e.python!=null?{package:typeof e.python=="string"?e.python:e.python.package,version:typeof e.python=="string"?void 0:e.python.version}:void 0,typescriptSdk:e.typescript!=null?{package:typeof e.typescript=="string"?e.typescript:e.typescript.package,version:typeof e.typescript=="string"?void 0:e.typescript.version}:void 0,goSdk:e.go!=null?{githubRepo:typeof e.go=="string"?e.go:e.go.package,version:typeof e.go=="string"?void 0:e.go.version}:void 0,javaSdk:e.java!=null?{coordinate:typeof e.java=="string"?e.java:e.java.package,version:typeof e.java=="string"?void 0:e.java.version}:void 0,rubySdk:e.ruby!=null?{gem:typeof e.ruby=="string"?e.ruby:e.ruby.package,version:typeof e.ruby=="string"?void 0:e.ruby.version}:void 0,csharpSdk:e.csharp!=null?{package:typeof e.csharp=="string"?e.csharp:e.csharp.package,version:typeof e.csharp=="string"?void 0:e.csharp.version}:void 0}}var tyu=ui(RAe(),1);var Q6c=ui(RAe(),1);function yX_({auth:e,ir:t,playgroundConfig:r,context:i}){if(e.schemes.length>0&&e.schemes[0]!=null){let n=e.schemes[0];switch(n.type){case"basic":return{type:"basicAuth",passwordName:n.password.originalName,usernameName:n.username.originalName,description:e.docs};case"bearer":return{type:"bearerAuth",tokenName:n.token.originalName,description:e.docs};case"header":return{type:"header",headerWireValue:n.name.wireValue,nameOverride:n.name.name.originalName,prefix:n.prefix,description:e.docs};case"oauth":{let a=n.configuration.tokenEndpoint.responseProperties.accessToken.propertyPath?.map(u=>u.originalName).join(".")||"$.body.access_token";return r?.oauth?{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:Q6c.FernRegistry.EndpointId(n.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:Q6c.FernRegistry.JqString(a),headerName:n.configuration.tokenHeader,tokenPrefix:n.configuration.tokenPrefix,description:e.docs}}}:{type:"bearerAuth",tokenName:"token",description:e.docs}}case"inferred":{n.tokenEndpoint.authenticatedRequestHeaders.length>1&&i.logger.warn("Inferred auth scheme has multiple authenticated request headers. Only the `Authentication` or first header will be pushed to FDR.");let a=n.tokenEndpoint.authenticatedRequestHeaders.find(c=>c.headerName.toLowerCase()==="authorization");if(a)return a.responseProperty.propertyPath!=null&&a.responseProperty.propertyPath.length>0&&i.logger.warn("Inferred Authentication header has a property path. The property wirevalue will be pushed to FDR without property path."),{type:"bearerAuth",tokenName:a.responseProperty.property.name.wireValue,description:e.docs};let u=n.tokenEndpoint.authenticatedRequestHeaders[0];return u?{type:"header",headerWireValue:u.headerName,prefix:u.valuePrefix,nameOverride:void 0,description:e.docs}:{type:"bearerAuth",tokenName:"token",description:e.docs}}default:Ao(n)}}}var Hm=ui(RAe(),1);var s7i=ui(RAe(),1);function bX_(e){return e._visit({alias:t=>({type:"alias",value:hM(t.aliasOf)}),enum:t=>({type:"enum",default:t.default!=null?t.default.name.wireValue:void 0,values:t.values.map(r=>({description:r.docs??void 0,value:r.name.wireValue,availability:g2(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>s7i.FernRegistry.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:s7i.FernRegistry.PropertyKey(r.name.wireValue),valueType:hM(r.valueType),availability:g2(r.availability),propertyAccess:r.propertyAccess})),extraProperties:XgM(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(i=>({key:s7i.FernRegistry.PropertyKey(i.name.wireValue),valueType:hM(i.valueType),availability:g2(i.availability),description:i.docs,propertyAccess:i.propertyAccess}));return{type:"discriminatedUnion",discriminant:t.discriminant.wireValue,variants:t.types.map(i=>({description:i.docs??void 0,discriminantValue:i.discriminantValue.wireValue,displayName:i.displayName,availability:i.availability!=null?g2(i.availability):void 0,additionalProperties:Hs.types.SingleUnionTypeProperties._visit(i.shape,{samePropertiesAsObject:n=>({extends:[s7i.FernRegistry.TypeId(n.typeId)],properties:r,extraProperties:void 0}),singleProperty:n=>({extends:[],properties:[{key:s7i.FernRegistry.PropertyKey(n.name.wireValue),valueType:hM(n.type),description:void 0,availability:void 0,propertyAccess:void 0},...r],extraProperties:void 0}),noProperties:()=>({extends:[],properties:r,extraProperties:void 0}),_other:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+i.shape.propertiesType)}})}))}},undiscriminatedUnion:t=>({type:"undiscriminatedUnion",variants:t.members.map(r=>({typeName:r.type.type==="named"?r.type.name.originalName:void 0,description:r.docs??void 0,type:hM(r.type),availability:void 0,displayName:r.type.type==="named"?r.type.displayName:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function hM(e){return e._visit({container:t=>Hs.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:hM(r)}),map:({keyType:r,valueType:i})=>({type:"map",keyType:hM(r),valueType:hM(i)}),optional:r=>({type:"optional",itemType:hM(r),defaultValue:void 0}),nullable:r=>({type:"nullable",itemType:hM(r)}),set:r=>({type:"set",itemType:hM(r)}),literal:r=>Hs.types.Literal._visit(r,{boolean:i=>({type:"literal",value:{type:"booleanLiteral",value:i}}),string:i=>({type:"literal",value:{type:"stringLiteral",value:i}}),_other:()=>{throw new Error("Unknown literal type: "+r.type)}}),_other:()=>{throw new Error("Unknown container reference: "+t.type)}}),named:t=>({type:"id",value:s7i.FernRegistry.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:Hs.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>YgM(t.v2),float:()=>vX_(t.v2),double:()=>vX_(t.v2),string:()=>KgM(t.v2),long:()=>({type:"long",default:t.v2?.type==="long"?t.v2.default:void 0,minimum:void 0,maximum:void 0}),boolean:()=>({type:"boolean",default:t.v2?.type==="boolean"?t.v2.default:void 0}),dateTime:()=>({type:"datetime",default:void 0}),date:()=>({type:"date",default:void 0}),uuid:()=>({type:"uuid",default:void 0}),base64:()=>({type:"base64",mimeType:void 0,default:void 0}),bigInteger:()=>({type:"bigInteger",default:t.v2?.type==="bigInteger"?t.v2.default:void 0}),uint:()=>({type:"uint"}),uint64:()=>({type:"uint64"}),_other:()=>{throw new Error("Unknown primitive: "+t.v1)}})}),unknown:()=>({type:"unknown"}),_other:()=>{throw new Error("Unknown Type reference: "+e.type)}})}function KgM(e){let t=e!=null&&e.type==="string"?e.validation:void 0;return{type:"string",format:t?.format,regex:t?.pattern,minLength:t?.minLength,maxLength:t?.maxLength,default:e!=null&&e.type==="string"?e.default:void 0}}function YgM(e){let t=e!=null&&e.type==="integer"?e.validation:void 0;return{type:"integer",minimum:t?.min,maximum:t?.max,default:e!=null&&e.type==="integer"?e.default:void 0}}function vX_(e){let t=e!=null&&e.type==="double"?e.validation:void 0;return{type:"double",minimum:t?.min,maximum:t?.max,default:e!=null&&e.type==="double"?e.default:void 0}}function XgM(e){return typeof e=="boolean"?e?ol.unknown():void 0:typeof e=="string"?{type:"id",value:s7i.FernRegistry.TypeId(e),default:void 0}:hM(e)}function K6c(e,t){let r=e.service!=null?t.services[e.service]:void 0,i=e.webhooks!=null?t.webhookGroups[e.webhooks]:void 0,n=e.websocket!=null&&t.websocketChannels!=null?t.websocketChannels[e.websocket]:void 0;return{endpoints:r!=null?kgM(r,t):[],webhooks:i!=null?ZgM(i):[],websockets:n!=null?[eOM(n,t)]:[],types:e.types.map(a=>Hm.FernRegistry.TypeId(a)),subpackages:e.subpackages.map(a=>Hm.FernRegistry.api.v1.SubpackageId(a)),pointsTo:e.navigationConfig!=null?Hm.FernRegistry.api.v1.SubpackageId(e.navigationConfig.pointsTo):void 0}}function ZgM(e){return e.map(t=>{let r=[];return t.v2Examples!=null?(r.push(...Object.values(t.v2Examples.userSpecifiedExamples)),r.push(...Object.values(t.v2Examples.autogeneratedExamples))):r.push(...t.examples?.map(i=>({payload:i.payload.jsonExample}))??[]),{description:t.docs??void 0,id:Hm.FernRegistry.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??fZi(t.name.originalName),headers:t.headers.map(i=>({description:i.docs??void 0,key:i.name.wireValue,type:hM(i.valueType),availability:g2(i.availability)})),payload:oOM(t.payload),examples:r}})}function kgM(e,t){let r=[];for(let i of e.endpoints){let n=i.autogeneratedExamples[0],a=[];if(i.v2Examples!=null){let c,d=i.v2Examples.userSpecifiedExamples,s=i.v2Examples.autogeneratedExamples,o=Object.values(d).map(v=>v.response?.statusCode).filter((v,g,O)=>O.indexOf(v)!==g).length>0;for(let[v,g]of Object.entries(d))c=mX_({shouldUseExampleName:o,exampleName:g.displayName??v,example:g,irEndpoint:i}),c!=null&&a.push(c);let l=Object.values(s).map(v=>v.response?.statusCode).filter((v,g,O)=>O.indexOf(v)!==g).length>0;for(let[v,g]of Object.entries(s))c=mX_({shouldUseExampleName:l,exampleName:g.displayName??v,example:g,irEndpoint:i}),c!=null&&a.push(c)}else if(i.userSpecifiedExamples.length>0)a.push(...i.userSpecifiedExamples.map(c=>J6c({userSpecifiedExample:c,...n!=null&&{autogeneratedExample:n},irEndpoint:i,ir:t})).filter(yy));else if(n!=null){let c=J6c({autogeneratedExample:n,irEndpoint:i,ir:t});c!=null&&a.push(c)}else if(i.response?.body?.type==="fileDownload"){let c=jQn({ir:t,service:e,endpoint:{...i,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(c.type==="success"){let d=J6c({autogeneratedExample:c,irEndpoint:i,ir:t});if(d!=null){let s={...d,responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(s)}}}let u={slug:void 0,availability:g2(i.availability??e.availability),auth:i.auth,description:i.docs??void 0,method:nOM(i.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?Hm.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?tOM({environmentsConfig:t.environments,endpoint:i}):void 0,id:Hm.FernRegistry.EndpointId(i.name.originalName),originalEndpointId:i.id,name:i.displayName??fZi(i.name.originalName),path:i.basePath!=null?{pathParameters:i.pathParameters.map(c=>({description:c.docs??void 0,key:Hm.FernRegistry.PropertyKey(c.name.originalName),type:hM(c.valueType),availability:void 0})),parts:[...IXn(i.basePath),...IXn(i.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...i.pathParameters].map(c=>({description:c.docs??void 0,key:Hm.FernRegistry.PropertyKey(c.name.originalName),type:hM(c.valueType),availability:void 0})),parts:[...t.basePath!=null?IXn(t.basePath):[],...IXn(e.basePath),...IXn(i.path)]},queryParameters:i.queryParameters.map(c=>({description:c.docs??void 0,key:c.name.wireValue,type:hM(c.valueType),availability:g2(c.availability)})),headers:[...e.headers,...i.headers].map(c=>({description:c.docs??void 0,key:c.name.wireValue,type:hM(c.valueType),availability:g2(c.availability)})),request:i.requestBody!=null?gX_(i.requestBody):void 0,requestsV2:{requests:i.v2RequestBodies?.requestBodies?.map(gX_).filter(yy)},response:i.response!=null?OX_(i.response):void 0,responsesV2:{responses:i.v2Responses?.responses?.map(OX_).filter(yy)},errors:void 0,errorsV2:aOM(i.errors,t),examples:a,protocol:i.source?._visit({openapi:()=>({type:"rest"}),openrpc:()=>({type:"openrpc",methodName:i.id}),proto:c=>({type:"grpc",methodName:i.id,methodType:c.methodType}),_other:()=>{}})};r.push(u)}return r}function eOM(e,t){let r=[];if(e.v2Examples!=null&&(Object.keys(e.v2Examples.userSpecifiedExamples).length>0||Object.keys(e.v2Examples.autogeneratedExamples).length>0)){let i=Object.values(e.v2Examples.userSpecifiedExamples),n=Object.values(e.v2Examples.autogeneratedExamples),a=i.length>0?i[0]:n[0];a!=null&&r.push({name:"",description:"",path:a.baseUrl??"",pathParameters:a.pathParameters??{},queryParameters:a.queryParameters??{},headers:a.headers??{},messages:a.messages?.map(u=>({type:Hm.FernRegistry.api.v1.WebSocketMessageId(u.type),body:u.body}))??[]})}else r=e.examples.map(i=>({name:i.name?.originalName,description:i.docs,path:i.url,pathParameters:i.pathParameters.reduce((n,a)=>(n[Hm.FernRegistry.PropertyKey(a.name.originalName)]=a.value.jsonExample,n),{}),queryParameters:i.queryParameters.reduce((n,a)=>(n[a.name.wireValue]=a.value.jsonExample,n),{}),headers:i.headers.reduce((n,a)=>(n[a.name.wireValue]=a.value.jsonExample,n),{}),messages:i.messages.map(n=>({type:Hm.FernRegistry.api.v1.WebSocketMessageId(n.type),body:n.body.jsonExample}))}));return{auth:e.auth,availability:g2(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?Hm.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?rOM({environmentsConfig:t.environments,channel:e}):[],id:Hm.FernRegistry.WebSocketId(e.name.originalName),name:e.displayName??fZi(e.name.originalName),path:{pathParameters:e.pathParameters.map(i=>({description:i.docs??void 0,key:Hm.FernRegistry.PropertyKey(i.name.originalName),type:hM(i.valueType),availability:void 0})),parts:IXn(e.path)},headers:e.headers.map(i=>({key:i.name.wireValue,type:hM(i.valueType),description:i.docs,availability:g2(i.availability)})),queryParameters:e.queryParameters.map(i=>({description:i.docs??void 0,key:i.name.wireValue,type:hM(i.valueType),availability:g2(i.availability)})),messages:e.messages.map(i=>({type:Hm.FernRegistry.api.v1.WebSocketMessageId(i.type),displayName:i.displayName,origin:i.origin,body:uOM(i.body),description:i.docs,availability:g2(i.availability)})),examples:r}}function g2(e){if(e!=null)switch(e.status){case"DEPRECATED":return Hm.FernRegistry.Availability.Deprecated;case"PRE_RELEASE":return Hm.FernRegistry.Availability.Beta;case"GENERAL_AVAILABILITY":return Hm.FernRegistry.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return Hm.FernRegistry.Availability.Beta;default:Ao(e.status)}}function tOM({environmentsConfig:e,endpoint:t}){let r=e.environments,i=t.baseUrl,n=t.v2BaseUrls;switch(r.type){case"singleBaseUrl":return r.environments.map(a=>({id:Hm.FernRegistry.EnvironmentId(a.id),baseUrl:a.url}));case"multipleBaseUrls":if(n!=null)return n.flatMap(u=>r.environments.map(c=>{let d=c.urls[u];if(d==null)throw new Error(`Expected environment ${c.id} to contain url for ${u}`);return{id:Hm.FernRegistry.EnvironmentId(u),baseUrl:d}})).filter((u,c,d)=>c===d.findIndex(s=>s.id===u.id&&s.baseUrl===u.baseUrl));if(i==null)throw new Error(`Expected endpoint ${t.name.originalName} to have base url.`);return r.environments.map(a=>{let u=a.urls[i];if(u==null)throw new Error(`Expected environment ${a.id} to contain url for ${i}`);return{id:Hm.FernRegistry.EnvironmentId(a.id),baseUrl:u}});default:Ao(r)}}function rOM({environmentsConfig:e,channel:t}){let r=e.environments,i=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:Hm.FernRegistry.EnvironmentId(n.id),baseUrl:iOM(n.url,"wss")}));case"multipleBaseUrls":if(i==null)throw new Error(`Expected channel ${t.name.originalName} to have base url.`);return r.environments.map(n=>{let a=n.urls[i];if(a==null)throw new Error(`Expected environment ${n.id} to contain url for ${i}`);return{id:Hm.FernRegistry.EnvironmentId(n.id),baseUrl:a}});default:Ao(r)}}function iOM(e,t){return e.replace(/^[^:]+/,t)}function nOM(e){return Hs.http.HttpMethod._visit(e,{get:()=>Hm.FernRegistry.HttpMethod.Get,post:()=>Hm.FernRegistry.HttpMethod.Post,put:()=>Hm.FernRegistry.HttpMethod.Put,patch:()=>Hm.FernRegistry.HttpMethod.Patch,delete:()=>Hm.FernRegistry.HttpMethod.Delete,head:()=>Hm.FernRegistry.HttpMethod.Head,_other:()=>{throw new Error("Unknown http method: "+e)}})}function IXn(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:Hm.FernRegistry.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function gX_(e){let t=Hs.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??Bq.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(i=>Hm.FernRegistry.TypeId(i.typeId)),properties:r.properties.map(i=>({description:i.docs??void 0,key:Hm.FernRegistry.PropertyKey(i.name.wireValue),valueType:hM(i.valueType),availability:g2(i.availability),propertyAccess:i.propertyAccess})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??Bq.APPLICATION_JSON,shape:{type:"reference",value:hM(r.requestBodyType)},description:r.docs??void 0}),fileUpload:r=>({type:"fileUpload",value:{name:r.name.originalName,description:void 0,availability:void 0,properties:r.properties.map(i=>i._visit({file:n=>{let a=n._visit({file:u=>({type:"file",key:Hm.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:u.docs??void 0,availability:void 0}),fileArray:u=>({type:"fileArray",key:Hm.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:u.docs??void 0,availability:void 0}),_other:()=>{}});if(a!=null)return{type:"file",value:a}},bodyProperty:n=>({type:"bodyProperty",key:Hm.FernRegistry.PropertyKey(n.name.wireValue),valueType:hM(n.valueType),contentType:n.contentType,description:n.docs??void 0,availability:g2(n.availability),exploded:n.style==="exploded",propertyAccess:void 0}),_other:()=>{}})).filter(yy)},contentType:r.contentType,description:r.docs??void 0}),bytes:r=>({type:"bytes",description:r.docs??void 0,availability:void 0,isOptional:r.isOptional,contentType:r.contentType}),_other:()=>{throw new Error("Unknown HttpRequestBody: "+e.type)}});return t!=null?{type:t,description:e.docs}:void 0}function OX_(e){if(e.body==null)return;let t,r=Hs.http.HttpResponseBody._visit(e.body,{fileDownload:i=>(t=i.docs,{type:"fileDownload",contentType:void 0}),json:i=>(t=i.docs,{type:"reference",value:hM(i.responseBodyType)}),text:()=>{},bytes:()=>{},streamParameter:()=>{},streaming:i=>{if(i.type==="text")return t=i.docs,{type:"streamingText"};if(i.type==="json")return t=i.docs,{type:"stream",shape:{type:"reference",value:hM(i.payload)},terminator:i.terminator};if(i.type==="sse")return t=i.docs,{type:"stream",shape:{type:"reference",value:hM(i.payload)},terminator:i.terminator}},_other:()=>{throw new Error("Unknown HttpResponse: "+e.body)}});return r!=null?{type:r,statusCode:e.statusCode,description:t}:e.statusCode!=null?{statusCode:e.statusCode,description:t,type:{type:"object",extends:[],properties:[],extraProperties:void 0}}:void 0}function aOM(e,t){let r=[];if(t.errorDiscriminationStrategy.type==="statusCode")for(let i of e){let n=t.errors[i.error.errorId];n&&r.push({type:n.type==null?void 0:{type:"alias",value:hM(n.type)},statusCode:n.statusCode,description:n.docs??void 0,name:n.displayName??n.name.name.originalName,availability:void 0,examples:sOM(n)})}else for(let i of e){let n=t.errors[i.error.errorId];if(n){let a=[{key:Hm.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.discriminant.wireValue),valueType:{type:"literal",value:{type:"stringLiteral",value:n.discriminantValue.name.originalName}},description:n.docs,availability:void 0,propertyAccess:void 0}];n.type!=null&&a.push({key:Hm.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.contentProperty.wireValue),valueType:hM(n.type),description:n.docs,availability:void 0,propertyAccess:void 0}),r.push({type:n.type==null?void 0:{type:"object",extends:[],properties:a,extraProperties:void 0},statusCode:n.statusCode,description:n.docs??void 0,availability:void 0,name:n.displayName??n.name.name.originalName,examples:n.examples.map(u=>({name:u.name?.originalName,responseBody:{type:"json",value:u.jsonExample},description:u.docs}))})}}return r}function mX_({shouldUseExampleName:e,exampleName:t,example:r,irEndpoint:i}){if(r==null)return;let n=r.response?.body!=null?r.response.body.value:void 0;return{name:e?t:void 0,description:"",path:r.request?.endpoint.path??"",pathParameters:r.request?.pathParameters??{},queryParameters:r.request?.queryParameters??{},headers:r.request?.headers??{},requestBody:r.request?.requestBody,requestBodyV3:i.requestBody?._visit({inlinedRequestBody:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,reference:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,fileUpload:a=>{if(r.request==null)return;let u={};if(Tw(r.request.requestBody)){let c=r.request.requestBody;for(let d of a.properties)d._visit({file:s=>{let o=c[s.key.wireValue];if(s.type==="file")u[s.key.wireValue]={type:"filename",value:typeof o=="string"?o:"<file1>"};else if(s.type==="fileArray"){let l=(Array.isArray(o)?o:[o]).filter(v=>typeof v=="string");u[s.key.wireValue]={type:"filenames",value:l}}},bodyProperty:s=>{if(s.style==="exploded"){let o=c[s.name.wireValue];u[s.name.wireValue]={type:"exploded",value:Array.isArray(o)?o:[o]}}else u[s.name.wireValue]={type:"json",value:c[s.name.wireValue]}},_other:P3e})}return{type:"form",value:u}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??i.response?.statusCode??200,responseBody:n??void 0,responseBodyV3:n!=null?r.response?.body?._visit({json:a=>({type:"json",value:a}),stream:a=>({type:"stream",value:a.map(u=>({type:"json",value:u}))}),error:()=>{},_other:()=>{throw new Error("Unknown ExampleResponseBody: "+r.response?.body?.type)}}):void 0,codeSamples:r.codeSamples?.map(a=>({name:a.name,description:a.docs??void 0,install:void 0,language:a.language,code:a.code})).filter(yy)}}function J6c({userSpecifiedExample:e,autogeneratedExample:t,irEndpoint:r,ir:i}){let n=i.headers.map(c=>{let d=c.valueType.type==="container"&&c.valueType.container.type==="literal"?c.valueType.container.literal._visit({boolean:s=>`${s}`,string:s=>s,_other:()=>{}}):void 0;if(d!=null)return{name:c.name,value:{jsonExample:d,shape:Hs.ExampleTypeReferenceShape.primitive(Hs.ExamplePrimitive.string({original:d}))}}}).filter(yy),a=e?.example??t?.example;if(a==null)return;let{codeSamples:u}=e??{codeSamples:[]};return{name:a.name?.originalName,description:a.docs,path:a.url,pathParameters:[...a.rootPathParameters,...a.servicePathParameters,...a.endpointPathParameters].reduce((c,d)=>(c[Hm.FernRegistry.PropertyKey(d.name.originalName)]=d.value.jsonExample,c),{}),queryParameters:a.queryParameters.reduce((c,d)=>(c[d.name.wireValue]=d.value.jsonExample,c),{}),headers:[...n,...a.serviceHeaders,...a.endpointHeaders].reduce((c,d)=>(c[d.name.wireValue]=d.value.jsonExample,c),{}),requestBody:a.request?.jsonExample,requestBodyV3:r.requestBody?._visit({inlinedRequestBody:()=>a.request!=null?{type:"json",value:a.request.jsonExample}:void 0,reference:()=>a.request!=null?{type:"json",value:a.request.jsonExample}:void 0,fileUpload:c=>{if(a.request==null)return;let d={};if(Tw(a.request.jsonExample)){let s=a.request.jsonExample;for(let o of c.properties)o._visit({file:l=>{let v=s[l.key.wireValue];if(l.type==="file")d[l.key.wireValue]={type:"filename",value:typeof v=="string"?v:"<file1>"};else if(l.type==="fileArray"){let g=(Array.isArray(v)?v:[v]).filter(O=>typeof O=="string");d[l.key.wireValue]={type:"filenames",value:g}}},bodyProperty:l=>{if(l.style==="exploded"){let v=s[l.name.wireValue];d[l.name.wireValue]={type:"exploded",value:Array.isArray(v)?v:[v]}}else d[l.name.wireValue]={type:"json",value:s[l.name.wireValue]}},_other:P3e})}return{type:"form",value:d}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??Hs.http.ExampleResponse._visit(a.response,{ok:c=>c._visit({body:d=>d!=null?200:204,stream:d=>d.length>0?200:204,sse:d=>d.length>0?200:204,_other:()=>{throw new Error("Unknown ExampleResponseBody: "+c.type)}}),error:({error:c})=>{let d=i.errors[c.errorId];if(d==null)throw new Error("Cannot find error "+c.errorId);return d.statusCode},_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),responseBody:a.response._visit({ok:c=>c._visit({body:d=>d?.jsonExample,stream:()=>{},sse:()=>{},_other:()=>{}}),error:c=>c.body?.jsonExample,_other:()=>{}}),responseBodyV3:a.response._visit({ok:c=>c._visit({body:d=>d!=null?{type:"json",value:d.jsonExample}:void 0,stream:d=>({type:"stream",value:d.map(s=>s.jsonExample)}),sse:d=>({type:"sse",value:d.map(({event:s,data:o})=>({event:s,data:o.jsonExample}))}),_other:()=>{throw new Error("Unknown ExampleResponseBody: "+c.type)}}),error:c=>c.body!=null?{type:"json",value:c.body.jsonExample}:void 0,_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),codeSamples:u?.map(c=>FAe._visit(c,{language:d=>({language:d.language,code:d.code,name:d.name?.originalName,description:d.docs??void 0,install:d.install}),sdk:d=>({language:d.sdk,code:d.code,name:d.name?.originalName,description:d.docs??void 0,install:void 0}),_other:()=>{}})).filter(yy)}}function oOM(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>Hm.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:Hm.FernRegistry.PropertyKey(t.name.wireValue),valueType:hM(t.valueType),availability:g2(t.availability),propertyAccess:void 0})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:hM(e.payloadType)},description:e.docs};default:Ao(e)}}function uOM(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>Hm.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:Hm.FernRegistry.PropertyKey(t.name.wireValue),valueType:hM(t.valueType),availability:g2(t.availability),propertyAccess:void 0})),extraProperties:void 0};case"reference":return{type:"reference",value:hM(e.bodyType)};default:Ao(e)}}function sOM(e){let t=e.v2Examples?.userSpecifiedExamples,r=e.v2Examples?.autogeneratedExamples,i=e.examples;return t!=null&&Object.keys(t).length>0?Object.entries(t).map(([n,a])=>({name:n,responseBody:{type:"json",value:a},description:void 0})):r!=null&&Object.keys(r).length>0?Object.entries(r).map(([n,a])=>({name:n,responseBody:{type:"json",value:a},description:void 0})):i.length>0?i.map(n=>({name:n.name?.originalName,responseBody:{type:"json",value:n.jsonExample},description:n.docs})):[]}function Jee({ir:e,snippetsConfig:t,playgroundConfig:r,context:i}){let n={types:{},subpackages:{},rootPackage:K6c(e.rootPackage,e),auth:yX_({auth:e.auth,ir:e,playgroundConfig:r,context:i}),snippetsConfiguration:t,globalHeaders:e.headers.map(a=>({availability:g2(a.availability),description:a.docs??void 0,key:a.name.wireValue,type:hM(a.valueType)})),navigation:void 0};for(let[a,u]of Object.entries(e.types))n.types[tyu.FernRegistry.TypeId(a)]={description:u.docs??void 0,name:u.name.name.originalName,shape:bX_(u.shape),availability:g2(u.availability),displayName:u.name.displayName};for(let[a,u]of Object.entries(e.subpackages)){let c=u.service!=null?e.services[u.service]:void 0;n.subpackages[tyu.FernRegistry.api.v1.SubpackageId(a)]={subpackageId:tyu.FernRegistry.api.v1.SubpackageId(a),displayName:c?.displayName??u.displayName,name:u.name.originalName,description:u.docs??void 0,...K6c(u,e)}}return n}var Y6c=ui(RAe(),1);async function X6c({organization:e,workspace:t,context:r,token:i,audiences:n,snippetsConfig:a,playgroundConfig:u}){let c=bx({workspace:t,audiences:n,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1},readme:void 0,version:void 0,packageName:void 0,context:r,sourceResolver:new yx(r,t)}),d=Fen({token:i.value}),s=Jee({ir:c,snippetsConfig:a,playgroundConfig:u,context:r}),o=await d.api.v1.register.registerApiDefinition({orgId:Y6c.FernRegistry.OrgId(e),apiId:Y6c.FernRegistry.ApiId(c.apiName.originalName),definition:s});if(o.ok)return r.logger.debug(`Registered API Definition ${o.body.apiDefinitionId}`),{id:o.body.apiDefinitionId,ir:c};switch(o.error.error){case"UnauthorizedError":case"UserNotInOrgError":return r.failAndThrow("You do not have permissions to register the docs. Reach out to support@buildwithfern.com");default:return r.failAndThrow("Failed to register API",o.error)}}var cOM=new pon({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function hVa({ir:e,apiDefinitionId:t,playgroundConfig:r,context:i}){return xUa(BUa(Jee({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0},playgroundConfig:r,context:i}),h2.ApiDefinitionId(t),cOM))}var Bh={};Na(Bh,{AlgoliaSearchIndex:()=>PX_,ApiDefinitionId:()=>WX_,ApiId:()=>QX_,Availability:()=>sZ_,DocsConfigId:()=>JX_,EndpointId:()=>YX_,EndpointPathLiteral:()=>oZ_,EnvironmentId:()=>KX_,FileId:()=>tZ_,HttpMethod:()=>uZ_,IndexSegmentId:()=>jX_,JqString:()=>iZ_,OrgId:()=>$X_,PageId:()=>eZ_,PayloadLocation:()=>zZ_,PropertyKey:()=>nZ_,PullRequestState:()=>qZ_,RoleId:()=>aZ_,TokenId:()=>GX_,TypeId:()=>kX_,Url:()=>rZ_,VersionId:()=>HX_,WebSocketId:()=>XX_,WebhookId:()=>ZX_,algolia:()=>Z6c,api:()=>sFc,commons:()=>cFc,diff:()=>cZ_,docs:()=>bFc,generators:()=>OFc,git:()=>mFc,navigation:()=>wFc,sdks:()=>DFc,snippets:()=>BZ_,snippetsFactory:()=>IZ_,templates:()=>EFc,tokens:()=>xZ_});var Z6c={};Na(Z6c,{AlgoliaSearchIndex:()=>PX_,IndexSegmentId:()=>jX_});function PX_(e){return e}function jX_(e){return e}var sFc={};Na(sFc,{latest:()=>tFc,v1:()=>uFc});var tFc={};Na(tFc,{AuthSchemeId:()=>wX_,WebhookHttpMethod:()=>MX_,auth:()=>k6c,commons:()=>SX_,endpoint:()=>DX_,type_:()=>EX_,webhook:()=>eFc,websocket:()=>AX_});var k6c={};Na(k6c,{AuthSchemeId:()=>wX_});function wX_(e){return e}var SX_={};var DX_={};var EX_={};var eFc={};Na(eFc,{WebhookHttpMethod:()=>MX_});var MX_={Get:"GET",Post:"POST"};var AX_={};var uFc={};Na(uFc,{SubpackageId:()=>FX_,WebSocketMessageId:()=>LX_,WebSocketMessageOrigin:()=>UX_,WebhookHttpMethod:()=>VX_,commons:()=>oFc,db:()=>rFc,read:()=>nFc,register:()=>aFc});var rFc={};Na(rFc,{endpoint:()=>qX_});var qX_={};var nFc={};Na(nFc,{SupportedLanguage:()=>TX_,endpoint:()=>iFc,type_:()=>CX_,webhook:()=>BX_,websocket:()=>IX_});var iFc={};Na(iFc,{SupportedLanguage:()=>TX_});var TX_={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby",Csharp:"csharp"};var CX_={};var BX_={};var IX_={};var aFc={};Na(aFc,{SourceId:()=>lOM,endpoint:()=>zX_,type_:()=>xX_,webhook:()=>RX_,websocket:()=>NX_});var zX_={};var xX_={};var RX_={};var NX_={};function lOM(e){return e}var oFc={};Na(oFc,{SubpackageId:()=>FX_,WebSocketMessageId:()=>LX_,WebSocketMessageOrigin:()=>UX_,WebhookHttpMethod:()=>VX_});function FX_(e){return e}function LX_(e){return e}var UX_={Client:"client",Server:"server"};var VX_={Get:"GET",Post:"POST"};var cFc={};Na(cFc,{ApiDefinitionId:()=>WX_,ApiId:()=>QX_,Availability:()=>sZ_,DocsConfigId:()=>JX_,EndpointId:()=>YX_,EndpointPathLiteral:()=>oZ_,EnvironmentId:()=>KX_,FileId:()=>tZ_,HttpMethod:()=>uZ_,JqString:()=>iZ_,OrgId:()=>$X_,PageId:()=>eZ_,PropertyKey:()=>nZ_,RoleId:()=>aZ_,TokenId:()=>GX_,TypeId:()=>kX_,Url:()=>rZ_,VersionId:()=>HX_,WebSocketId:()=>XX_,WebhookId:()=>ZX_});function WX_(e){return e}function HX_(e){return e}function $X_(e){return e}function GX_(e){return e}function QX_(e){return e}function JX_(e){return e}function KX_(e){return e}function YX_(e){return e}function XX_(e){return e}function ZX_(e){return e}function kX_(e){return e}function eZ_(e){return e}function tZ_(e){return e}function rZ_(e){return e}function iZ_(e){return e}function nZ_(e){return e}function aZ_(e){return e}function oZ_(e){return e}var uZ_={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var sZ_={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var cZ_={};var bFc={};Na(bFc,{latest:()=>dFc,v1:()=>yFc,v2:()=>vFc});var dFc={};Na(dFc,{Layout:()=>fZ_,MdxEngine:()=>fOM,TwitterCardSetting:()=>dZ_,commons:()=>lZ_,frontmatter:()=>lFc,seo:()=>fFc});var fOM={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var lZ_={};var lFc={};Na(lFc,{Layout:()=>fZ_});var fZ_={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var fFc={};Na(fFc,{TwitterCardSetting:()=>dZ_});var dZ_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var yFc={};Na(yFc,{commons:()=>hFc,db:()=>pZ_,read:()=>_Z_,write:()=>pFc});var pZ_={};var _Z_={};var pFc={};Na(pFc,{DocsRegistrationId:()=>pOM,FilePath:()=>dOM});function dOM(e){return e}function pOM(e){return e}var hFc={};Na(hFc,{ContentAlignment:()=>bZ_,FontDisplay:()=>jZ_,FontStyle:()=>PZ_,HeaderPosition:()=>gZ_,JsScriptStrategy:()=>mZ_,ProgrammingLanguage:()=>hZ_,SearchbarPlacement:()=>yZ_,TabsPlacement:()=>vZ_,TwitterCardSetting:()=>OZ_,commons:()=>_Fc});var _Fc={};Na(_Fc,{ContentAlignment:()=>bZ_,FontDisplay:()=>jZ_,FontStyle:()=>PZ_,HeaderPosition:()=>gZ_,JsScriptStrategy:()=>mZ_,ProgrammingLanguage:()=>hZ_,SearchbarPlacement:()=>yZ_,TabsPlacement:()=>vZ_,TwitterCardSetting:()=>OZ_});var hZ_={Typescript:"typescript",Javascript:"javascript",Python:"python",Java:"java",Go:"go",Ruby:"ruby",Csharp:"csharp",Nodets:"nodets",Nodejs:"nodejs",Dotnet:"dotnet",Curl:"curl",Jvm:"jvm",Ts:"ts",Js:"js"};var yZ_={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var vZ_={Header:"HEADER",Sidebar:"SIDEBAR"};var bZ_={Center:"CENTER",Left:"LEFT"};var gZ_={Fixed:"FIXED",Absolute:"ABSOLUTE"};var OZ_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var mZ_={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var PZ_={Normal:"normal",Italic:"italic"};var jZ_={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var vFc={};Na(vFc,{read:()=>wZ_,write:()=>SZ_});var wZ_={};var SZ_={};var OFc={};Na(OFc,{ChangelogEntryType:()=>EZ_,GeneratorId:()=>_OM,GeneratorLanguage:()=>hOM,ReleaseType:()=>MZ_,cli:()=>DZ_,commons:()=>gFc,versions:()=>AZ_});var DZ_={};var gFc={};Na(gFc,{ChangelogEntryType:()=>EZ_,ReleaseType:()=>MZ_});var EZ_={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var MZ_={Ga:"GA",Rc:"RC"};var AZ_={};function _OM(e){return e}var hOM={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var mFc={};Na(mFc,{PullRequestState:()=>qZ_});var qZ_={Open:"open",Closed:"closed",Merged:"merged"};var wFc={};Na(wFc,{latest:()=>PFc,v1:()=>jFc});var PFc={};Na(PFc,{NodeId:()=>bOM,ProductId:()=>gOM,Slug:()=>yOM,TabId:()=>vOM});function yOM(e){return e}function vOM(e){return e}function bOM(e){return e}function gOM(e){return e}var jFc={};Na(jFc,{NavigationV1Availability:()=>wOM,NodeId:()=>POM,ProductId:()=>jOM,Slug:()=>OOM,TabId:()=>mOM});function OOM(e){return e}function mOM(e){return e}function POM(e){return e}function jOM(e){return e}var wOM={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var DFc={};Na(DFc,{Language:()=>TZ_,VersionBump:()=>CZ_,versions:()=>SFc});var SFc={};Na(SFc,{Language:()=>TZ_,VersionBump:()=>CZ_});var TZ_={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var CZ_={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var BZ_={};var IZ_={};var EFc={};Na(EFc,{PayloadLocation:()=>zZ_});var zZ_={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var xZ_={};var zXn=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};function sp(e){return e!=null}var NZ_=ui(e8n(),1);var RZ_=["PII","PHI","PCI","GDPR","CCPA","HIPAA","COPPA","FERPA","GLBA","SOX","FISMA","NIST","CIS","ISO","IEC","ITAR","EAR","CMMC","CUI","CDI","FTC","FCC","SEC","FINRA","XSS","CSRF","SSRF","XSRF","TLS","SSL","SSH","API","OAuth","OAuth1","OAuth1.0","OAuth2","OAuth2.0","SAML","OpenID","OpenID Connect","CAPTCHA","reCAPTCHA","2FA","MFA","OTP","TOTP","HOTP","U2F","FIDO","FIDO2","PKI","HMAC","AES","RSA","SHA","MD5","BCrypt","PBKDF2","Argon2","SCrypt","JWT","JWE","JWS","JWK","JWA","JOSE","SKU","SKUs","UPC","EAN","ISBN","ASIN","MPN","MSRP","MAP","RRP","MSRP","AM","PM","UTC","GMT","PST","PDT","EST","EDT","CST","CDT","MST","MDT","USA","UK","EU","UAE","APAC","EMEA","LATAM","ANZ","SEA","MEA","MENA","NATO","NA","SA","CA","EU","AU","NZ","JP","KR","CN","HK","TW","SG","MY","TH","ID","PH","VN","IN","PK","BD","LK","NP","MM","KH","LA","MM","BT","MV","USD","EUR","GBP","JPY","CNY","RUB","INR","AUD","CAD","CHF","SGD","MYR","THB","IDR","KRW","PHP","VND","HKD","TWD","MXN","BRL","ARS","CLP","COP","PEN","ZAR","NGN","EGP","AED","SAR","ILS","TRY","SEK","NOK","DKK","ISK","HUF","PLN","CZK","RON","BGN","API","APIs","SDK","SDKs","AI","OCR","REST","SOAP","JSON","XML","HTTP","HTTPS","URI","URL","CRUD","RESTful","KYB","KYC","AML","HTML","CSS","JS","SQL","DB","UI","UX","SaaS","PaaS","IaaS","IP","TCP","UDP","DNS","FTP","SMTP","IMAP","POP3","CSV","MVC","MVP","MVVM","DOM","SPA","SSR","CSR","DDoS","CDN","IoT","ML","DL","NLP","CLI","GUI","BI","ETL","RDBMS","NoSQL","IDE","CMS","CCPA","POSIX","ABI","API","AST","COBOL","DDL","DML","NN","CNN","RNN","LSTM","GRU","ANN","GAN","RL","DL","ML","NLP","NLG","NLU","BERT","GPT","SVM","PCA","AI","CV","TF","TTS","ASR","HMM","DNN","MLP","RBM","CRF","PDF","PDFs","RTF","TXT","XLS","XLSX","PPT","JPG","JPEG","PNG","GIF","GIFs","SVG","TIFF","BMP","ICO","PSD","WebP","AVIF","HEIF","HEIC","EPS","MP3","WAV","AIFF","FLAC","WMA","AAC","OGG","AVI","WMV","MOV","M4V","MP4","MPG","MPEG","FLV","SWF","MKV","WebM","GCP","AWS","VM","VPC","S3","EC2","DynamoDB","CosmosDB","BigQuery","CI/CD","SOC1","SOC2","SOC3","PCI DSS","WAF","IAM","SDN","MPLS","BGP","Vue.js","Node.js",".NET"];function eur(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,NZ_.default)(e,{special:RZ_}).replace(/V\s(\d)/g,"V$1")}function ryu({endpoints:e,webhookEndpoints:t}){let r={};return Object.values({...e,...t}).forEach(i=>{let n=[];i.namespace?.forEach(a=>{let u=[...n,a],c=Bh.api.v1.SubpackageId(u.join("."));r[c]={id:c,name:a,displayName:eur(a)},n.push(a)})}),r}var iyu=class{errors=new zXn},xXn=class{input;context;constructor(t,r){this.input=t,this.context=r}errors(){return this.context.errors.errors}warnings(){return this.context.errors.warnings}};function FZ_(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var nyu=class extends iyu{},A_=class extends xXn{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){if(super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,n!=null){let a=Array.isArray(this.pathId)?this.pathId:[this.pathId];a.every((u,c)=>u===this.accessPath[this.accessPath.length-a.length+c])||this.accessPath.push(...a)}r.logger.debug(`Processing ${FZ_(this.accessPath)}`)}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}},Y6=class extends A_{},ese=class extends Y6{seenSchemas;constructor(t){super(t),this.seenSchemas=new Set(t.seenSchemas)}};var LZ_="x-fern-base-path",UZ_="x-fern-availability",ayu="x-fern-sdk-group-name",VZ_="x-fern-global-headers",WZ_="x-fern-sdk-method-name";var HZ_="x-fern-webhook",$Z_="x-fern-access-token-locator",GZ_="x-fern-basic",QZ_="x-fern-username-variable-name",JZ_="x-fern-password-variable-name",KZ_="x-fern-bearer",YZ_="x-fern-token-variable-name",XZ_="x-fern-header",ZZ_="x-fern-header-variable-name",kZ_="x-fern-server-name",ek_="x-fern-examples";var oyu=class extends A_{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[kZ_]}convert(){if(this.serverName!=null)return this.serverName}};var uyu=class extends A_{url;serverName;constructor(t){super(t),this.safeParse()}parse(){this.url=Object.entries(this.input.variables??{}).reduce((t,[r,i])=>t.replace(`{${r}}`,i.default),this.input.url)??this.input.url,this.serverName=new oyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.serverName?.convert()??this.url;if(!(this.url==null||t==null))return{id:Bh.EnvironmentId(t),baseUrl:this.url}}};function tur(e,t,r,i){let n=e??[],a=new Set(n.map(c=>c.url)),u=(t??[]).filter(c=>!a.has(c.url)).map((c,d)=>new uyu({input:c,context:r,accessPath:i,pathId:["servers",`${d}`]}));return[...n,...u]}function AD(e){return typeof e=="object"&&sp(e)&&"$ref"in e&&typeof e.$ref=="string"}function x$(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(AD(n)&&(n=x$(n,t,r)),n)}function syu(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return AD(r)?x$(r,t,void 0):r}var Ok_=ui(vx());var cyu=class extends A_{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[GZ_];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var lyu=class extends A_{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[JZ_]}convert(){return this.passwordVariableName}};var fyu=class extends A_{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[QZ_]}convert(){return this.usernameVariableName}};var dyu=class extends A_{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[KZ_];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var pyu=class extends A_{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[YZ_]}convert(){return this.tokenVariableName}};function tk_(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var rk_="x-bearer-format",ik_="x-code-samples",nk_="x-codeSamples";var _yu=class extends A_{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[rk_]}convert(){return this.bearerFormat}};var hyu=class extends A_{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[XZ_];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var yyu=class extends A_{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[ZZ_]}convert(){return this.headerVariableName}};function ak_(e){return e.type==="apiKey"}var RXn=class extends A_{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){ak_(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new hyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new yyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new _yu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.headerAuthNode?.convert();if(t!=null)return{type:"header",nameOverride:t?.name,headerWireValue:this.headerName??"Authorization",prefix:t?.prefix??this.headerBearerFormatNode?.convert()}}};function vyu(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function byu(e){return typeof e=="string"||typeof e=="symbol"?e:Object.is(e?.valueOf?.(),-0)?"-0":String(e)}function gyu(e){let t=[],r=e.length;if(r===0)return t;let i=0,n="",a="",u=!1;for(e.charCodeAt(0)===46&&(t.push(""),i++);i<r;){let c=e[i];a?c==="\\"&&i+1<r?(i++,n+=e[i]):c===a?a="":n+=c:u?c==='"'||c==="'"?a=c:c==="]"?(u=!1,t.push(n),n=""):n+=c:c==="["?(u=!0,n&&(t.push(n),n="")):c==="."?n&&(t.push(n),n=""):n+=c,i++}return n&&t.push(n),t}function yVa(e,t,r){if(e==null)return r;switch(typeof t){case"string":{if(kpu(t))return r;let i=e[t];return i===void 0?vyu(t)?yVa(e,gyu(t),r):r:i}case"number":case"symbol":{typeof t=="number"&&(t=byu(t));let i=e[t];return i===void 0?r:i}default:{if(Array.isArray(t))return SOM(e,t,r);if(Object.is(t?.valueOf(),-0)?t="-0":t=String(t),kpu(t))return r;let i=e[t];return i===void 0?r:i}}}function SOM(e,t,r){if(t.length===0)return r;let i=e;for(let n=0;n<t.length;n++){if(i==null||kpu(t[n]))return r;i=i[t[n]]}return i===void 0?r:i}function ok_(e){return function(t){return yVa(t,e)}}function uk_(e){return e!==null&&(typeof e=="object"||typeof e=="function")}function MFc(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function sk_(e,t,r){return typeof r!="function"?NXn(e,t):AFc(e,t,function i(n,a,u,c,d,s){let o=r(n,a,u,c,d,s);return o!==void 0?!!o:AFc(n,a,i,s)},new Map)}function AFc(e,t,r,i){if(t===e)return!0;switch(typeof t){case"object":return DOM(e,t,r,i);case"function":return Object.keys(t).length>0?AFc(e,{...t},r,i):MFc(e,t);default:return uk_(e)?typeof t=="string"?t==="":!0:MFc(e,t)}}function DOM(e,t,r,i){if(t==null)return!0;if(Array.isArray(t))return ck_(e,t,r,i);if(t instanceof Map)return EOM(e,t,r,i);if(t instanceof Set)return MOM(e,t,r,i);let n=Object.keys(t);if(e==null)return n.length===0;if(n.length===0)return!0;if(i&&i.has(t))return i.get(t)===e;i&&i.set(t,e);try{for(let a=0;a<n.length;a++){let u=n[a];if(!Qpu(e)&&!(u in e)||t[u]===void 0&&e[u]!==void 0||t[u]===null&&e[u]!==null||!r(e[u],t[u],u,e,t,i))return!1}return!0}finally{i&&i.delete(t)}}function EOM(e,t,r,i){if(t.size===0)return!0;if(!(e instanceof Map))return!1;for(let[n,a]of t.entries()){let u=e.get(n);if(r(u,a,n,e,t,i)===!1)return!1}return!0}function ck_(e,t,r,i){if(t.length===0)return!0;if(!Array.isArray(e))return!1;let n=new Set;for(let a=0;a<t.length;a++){let u=t[a],c=!1;for(let d=0;d<e.length;d++){if(n.has(d))continue;let s=e[d],o=!1;if(r(s,u,a,e,t,i)&&(o=!0),o){n.add(d),c=!0;break}}if(!c)return!1}return!0}function MOM(e,t,r,i){return t.size===0?!0:e instanceof Set?ck_([...e],[...t],r,i):!1}function NXn(e,t){return sk_(e,t,()=>{})}function lk_(e){return e=xV_(e),t=>NXn(t,e)}function fk_(e,t){return zV_(e,(r,i,n,a)=>{let u=t?.(r,i,n,a);if(u!==void 0)return u;if(typeof e=="object")switch(Object.prototype.toString.call(e)){case Ypu:case Kpu:case Xpu:{let c=new e.constructor(e?.valueOf());return GNi(c,e),c}case Zpu:{let c={};return GNi(c,e),c.length=e.length,c[Symbol.iterator]=e[Symbol.iterator],c}default:return}})}function dk_(e){return fk_(e)}var AOM=/^(?:0|[1-9]\d*)$/;function pk_(e,t=Number.MAX_SAFE_INTEGER){switch(typeof e){case"number":return Number.isInteger(e)&&e>=0&&e<t;case"symbol":return!1;case"string":return AOM.test(e)}}function _k_(e){return e!==null&&typeof e=="object"&&Jpu(e)==="[object Arguments]"}function hk_(e,t){let r;if(Array.isArray(t)?r=t:typeof t=="string"&&vyu(t)&&e?.[t]==null?r=gyu(t):r=[t],r.length===0)return!1;let i=e;for(let n=0;n<r.length;n++){let a=r[n];if((i==null||!Object.hasOwn(i,a))&&!((Array.isArray(i)||_k_(i))&&pk_(a)&&a<i.length))return!1;i=i[a]}return!0}function yk_(e,t){switch(typeof e){case"object":{Object.is(e?.valueOf(),-0)&&(e="-0");break}case"number":{e=byu(e);break}}return t=dk_(t),function(r){let i=yVa(r,e);return i===void 0?hk_(r,e):t===void 0?i===void 0:NXn(i,t)}}function vk_(e){if(e==null)return fhu;switch(typeof e){case"function":return e;case"object":return Array.isArray(e)&&e.length===2?yk_(e[0],e[1]):lk_(e);case"string":case"symbol":case"number":return ok_(e)}}function qFc(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e))return e.map(qFc).join(",");let t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function Oyu(e,t=fhu){return e==null?{}:B$(e,vk_(t))}function bk_(e){return typeof e!="string"&&(e=qFc(e)),e.replace(/['\u2019]/g,"")}function aJt(e){return NV_(bk_(e))}function dq(e){if(e!=null)return Array.isArray(e)?e:[e]}function myu({namespace:e,path:t,method:r,sdkMethodName:i,operationId:n,displayName:a,isWebhook:u}){if(t==null)return;let c=r!=null&&t!=null?`${r}_${t.split("/").join("_")}`:r??t.split("/").join("_");if(!(i==null&&n==null&&a==null&&c==null))return`${qOM(u)}${TOM(e)}.${COM(i,n,a,c)}`}function qOM(e){return e?"webhook_":"endpoint_"}function TOM(e){return e!=null?dq(e)?.map(t=>aJt(t)).join("/"):""}function COM(e,t,r,i){return e||t||aJt(r??"")||aJt(i??"")}function gk_(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var Pyu=class extends A_{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[$Z_],this.accessTokenLocator!=null&&(gk_(this.accessTokenLocator)||(this.context.errors.error({message:"Invalid access token locator, must be a valid jq path",path:this.accessPath}),this.accessTokenLocator=void 0))}convert(){return this.accessTokenLocator}};var jyu=class extends A_{authorizationUrl;headerAuthNode;accessTokenLocatorNode;constructor(t){super(t),this.safeParse()}parse(){if(this.input.flows.clientCredentials!=null){let t=this.input.flows.clientCredentials;this.authorizationUrl=t.tokenUrl,this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.headerAuthNode=new RXn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new Pyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.accessTokenLocatorNode?.accessTokenLocator==null&&this.context.errors.error({message:"Expected 'x-fern-access-token-locator' property to be specified",path:this.accessPath})}}convert(){let t=this.accessTokenLocatorNode?.convert();if(t==null||this.authorizationUrl==null)return{type:"bearerAuth",tokenName:void 0};let r=myu({namespace:void 0,path:this.authorizationUrl,method:"POST",sdkMethodName:void 0,operationId:void 0,displayName:void 0,isWebhook:void 0});if(r!=null)return{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:Bh.EndpointId(r),accessTokenLocator:Bh.JqString(t),headerName:this.headerAuthNode?.convert()?.headerWireValue,tokenPrefix:this.headerAuthNode?.convert()?.prefix}}}}};var FXn=class extends A_{authScheme;headerAuthNode;bearerTokenNode;bearerTokenVariableNameNode;basicAuthNode;basicUsernameVariableNameNode;basicPasswordVariableNameNode;oauth2Node;constructor(t){super(t),this.safeParse()}parse(){switch(this.input.type){case"http":switch(this.input.scheme){case"basic":{this.authScheme="basic",this.basicAuthNode=new cyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicUsernameVariableNameNode=new fyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new lyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),(this.basicAuthNode==null||this.basicAuthNode.username==null&&this.basicUsernameVariableNameNode?.usernameVariableName==null||this.basicAuthNode.password==null&&this.basicPasswordVariableNameNode?.passwordVariableName==null)&&this.context.errors.warning({message:"Basic auth should specify either a username or a username variable name",path:this.accessPath});break}case"bearer":{this.authScheme="bearer",this.bearerTokenNode=new dyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new pyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}default:{this.context.errors.warning({message:`Unsupported HTTP auth scheme: ${this.input.scheme}`,path:this.accessPath});break}}break;case"apiKey":{tk_(this.input)?(this.authScheme="header",this.headerAuthNode=new RXn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})):this.context.errors.error({message:`Unsupported API key location: ${this.input.in}`,path:this.accessPath});break}case"oauth2":{this.authScheme="oauth",this.oauth2Node=new jyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}case"openIdConnect":{this.authScheme="bearer";break}}}convert(){switch(this.authScheme){case"basic":{let t=this.basicAuthNode?.convert();return{type:"basicAuth",usernameName:t?.username?.name??this.basicUsernameVariableNameNode?.convert(),passwordName:t?.password?.name??this.basicPasswordVariableNameNode?.convert()}}case"bearer":return{type:"bearerAuth",tokenName:this.bearerTokenNode?.convert()?.tokenVariableName??this.bearerTokenVariableNameNode?.convert()};case"header":return this.headerAuthNode?.convert();case"oauth":return this.oauth2Node?.convert();case void 0:return;default:new Ok_.UnreachableCaseError(this.authScheme);return}}};var LXn=class extends A_{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(i=>{let n=syu(i,this.context.document);if(n==null){this.context.errors.warning({message:`No auth scheme found for ${i}. Inline security schemes are not supported.`,path:this.accessPath});return}let a=new FXn({input:n,context:this.context,accessPath:this.accessPath,pathId:["security",`${r}`]});a.convert()!=null?(this.authNodesMap??={},this.authNodesMap[i]=a):this.context.errors.warning({message:`No auth scheme found for ${i}`,path:this.accessPath})}))}convert(){return Object.fromEntries(Object.entries(this.authNodesMap??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[t,i]}).filter(sp))}};var wyu=class extends A_{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[LZ_],this.basePath!=null?(this.basePath.startsWith("/")&&(this.basePath=this.basePath.slice(1)),this.basePath.endsWith("/")&&(this.basePath=this.basePath.slice(0,-1))):this.basePath=void 0}convert(){return this.basePath}};function mk_(e){return"required"in e&&typeof e.required=="boolean"?e.required:!1}function Pk_(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function UXn(e,t){return e==null?void 0:Object.entries(e).map(([i,n])=>dq(n.convert())?.map(u=>((t!=null&&!t.includes(i)||t==null&&!mk_(n))&&(u=Pk_(u,u.type==="enum"?u.default:void 0)),{key:Bh.PropertyKey(i),valueShape:u,description:n.description,availability:n.availability?.convert()})).filter(sp)).filter(sp).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(u=>[...a,u]):[[...a]]),[[]])}function Syu(e,t){return AD(e)?x$(e,t,void 0):e}function c7i(e,t){return e!=null&&e!==""?e:t!=null&&t!==""?t:void 0}function jk_(e,t){let r={...e};for(let[i,n]of Object.entries(t??{}))r[i]=[...r[i]??[],...n];return Object.keys(r).length>0?r:void 0}function wk_(e,t){if(e==null)return t;if(t==null)return e;let r=[];for(let i of e)for(let n of t)r.push({path:i.path??n.path,responseStatusCode:i.responseStatusCode??n.responseStatusCode,name:i.name??n.name,description:i.description??n.description,pathParameters:i.pathParameters??n.pathParameters,queryParameters:i.queryParameters??n.queryParameters,headers:i.headers??n.headers,requestBody:i.requestBody??n.requestBody,responseBody:i.responseBody??n.responseBody,snippets:{...n.snippets,...i.snippets}});return r}var Sk_=ui(vx());var TFc=["decimal","decimal128","double-int","double","float","sf-decimal"],CFc=["int16","int32","int64","int8","sf-integer","uint8"],BFc=["base64url","binary","byte","char","commonmark","date-time","date","decimal","decimal128","duration","email","hostname","html","http-date","idn-email","idn-hostname","int64","ipv4","ipv6","iri-reference","iri","json-pointer","media-range","password","regex","relative-json-pointer","sf-binary","sf-boolean","sf-string","sf-token","time","uri-reference","uri-template","uri","uuid"],IFc=["beta","pre-release","in-development","generally-available","deprecated"];function X6(e,t){return AD(e)?x$(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var Z6e=class extends A_{availability;constructor(t){super(t),this.safeParse()}parse(){if(X6(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[UZ_];r!=null&&(IFc.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${IFc.join(", ")}. Received: ${r}`,path:this.accessPath}),this.availability=void 0))}}convert(){switch(this.availability){case"beta":case"pre-release":return Bh.Availability.Beta;case"in-development":return Bh.Availability.InDevelopment;case"generally-available":return Bh.Availability.GenerallyAvailable;case"deprecated":return Bh.Availability.Deprecated;case void 0:return;default:new Sk_.UnreachableCaseError(this.availability);return}}};var Eyu=ui(vx());function Dk_(e){return typeof e=="object"&&e!=null&&"language"in e}function Ek_(e){return typeof e=="object"&&e!=null&&"sdk"in e}function Mk_(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function Ak_(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function Dyu(e){return typeof e=="object"&&e!=null&&"event"in e}function zFc(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(Dyu)}function l7i(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function qk_(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var Myu=class extends A_{path;successResponseStatusCode;requestBodyByContentType;responseBodies;examples;constructor(t,r,i,n,a){super(t),this.path=r,this.successResponseStatusCode=i,this.requestBodyByContentType=n,this.responseBodies=a,this.safeParse()}parse(){this.examples=this.input[ek_]}convertFormDataExampleRequest(t,r){if(t.fields!=null)switch(t.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(t.fields).map(([n,a])=>{let u=typeof r=="object"?r[n]:void 0;switch(a.multipartType){case"file":return l7i(u)?[n,{type:"filenameWithData",filename:u.filename,data:Bh.FileId(u.data)}]:u!=null?[n,{type:"filename",value:u}]:void 0;case"files":{if(Array.isArray(u)){if(u.every(c=>l7i(c)))return[n,{type:"filenamesWithData",value:u.map(c=>({filename:c.filename,data:Bh.FileId(c.data)}))}];if(u.every(c=>typeof c=="string"))return[n,{type:"filenames",value:u}]}return}case"property":return[n,{type:"json",value:u}];case void 0:return;default:new Eyu.UnreachableCaseError(a.multipartType);return}}).filter(sp))};case"json":return{type:"json",value:r};case"bytes":return typeof r=="string"?{type:"bytes",value:{type:"base64",value:r}}:void 0;default:return}}convert(){if(this.examples==null)return;this.requestBodyByContentType!=null&&Object.keys(this.requestBodyByContentType).length>1&&this.context.logger.warn(`Multiple request bodies found for #/${[this.accessPath,this.pathId,"x-fern-examples"].join("/")}. Coercing to first request body until supported.`);let t=Object.keys(this.requestBodyByContentType??{})[0];return this.examples.flatMap(r=>(this.responseBodies??[]).map(i=>{let n=t!=null?this.requestBodyByContentType?.[t]:void 0,a;if(n!=null)switch(n.contentType){case"form-data":a=qk_(r.request)?this.convertFormDataExampleRequest(n,r.request):void 0;break;case"json":a=r.request!=null?{type:"json",value:r.request}:void 0;break;case"bytes":a=typeof r.request=="string"&&r.request!=null?{type:"bytes",value:{type:"base64",value:r.request}}:void 0;break;case void 0:break;default:new Eyu.UnreachableCaseError(n.contentType);break}let u;switch(i.contentType){case"application/json":{Mk_(r.response)&&(u={type:"json",value:r.response.body});break}case"text/event-stream":{zFc(r.response)&&(u={type:"sse",value:r.response.stream.map(l=>({event:l.event,data:l.data}))});break}case"application/octet-stream":!zFc(r.response)&&Ak_(r.response)&&(u={type:"stream",value:r.response.stream});break;case void 0:break;default:new Eyu.UnreachableCaseError(i.contentType);break}let c={};r["code-samples"]?.forEach(l=>{Dk_(l)?l.language!=null&&(c[l.language]??=[],c[l.language]?.push({name:l.name,language:l.language,install:l.install,code:l.code,generated:!1,description:l.docs})):Ek_(l)&&l.sdk!=null&&(c[l.sdk]??=[],c[l.sdk]?.push({name:l.name,language:l.sdk,install:void 0,code:l.code,generated:!1,description:l.docs}))});let d=Object.fromEntries(Object.entries(r["path-parameters"]??{}).map(([l,v])=>[Bh.PropertyKey(l),v])),s=Object.fromEntries(Object.entries(r["query-parameters"]??{}).map(([l,v])=>[Bh.PropertyKey(l),v])),o=Object.fromEntries(Object.entries(r.headers??{}).map(([l,v])=>[Bh.PropertyKey(l),v]));return{path:this.path,responseStatusCode:this.successResponseStatusCode,name:r.name,description:r.docs,pathParameters:Object.keys(d).length>0?d:void 0,queryParameters:Object.keys(s).length>0?s:void 0,headers:Object.keys(o).length>0?o:void 0,requestBody:a,responseBody:u,snippets:c}}))}};var vVa=class extends A_{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[ayu]}convert(){if(this.groupName==null)return;let t;return Array.isArray(this.groupName)?t=this.groupName:t=[this.groupName],t.map(r=>Bh.api.v1.SubpackageId(aJt(r)))}};var Ayu=class extends A_{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[WZ_]}convert(){return this.sdkMethodName}};var qyu=class extends A_{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[HZ_]}convert(){return this.isWebhook}};var Tyu=class extends A_{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[ik_]??[],...this.input[nk_]??[]],this.codeSamples.forEach(t=>{[...Object.values(Bh.api.v1.read.SupportedLanguage),"Kotlin","Swift","PHP"].map(r=>r.toLowerCase()).includes(t.lang.toLowerCase())||this.context.errors.warning({message:`Unsupported language: ${t.lang}. This may not render correctly.`,path:this.accessPath})})}convert(){let t={};if(this.codeSamples?.forEach(r=>{t[r.lang.toLowerCase()]??=[],t[r.lang.toLowerCase()]?.push({name:r.label,language:r.lang,code:r.source,install:void 0,generated:!1,description:void 0})}),Object.keys(t).length!==0)return t}};var Don=ui(vx());function xFc(e,t){return AD(e)?x$(e,t,void 0):e}function Tk_(e,t){return e.replace(/{(\w+)}/g,(r,i)=>t[i]!=null&&typeof t[i]=="string"||typeof t[i]=="number"||typeof t[i]=="boolean"?`${t[i]}`:r)}var xU="",rur=class extends A_{path;responseStatusCode;name;shapes;resolvedRequestInput;resolvedResponseInput;summary;constructor(t,r,i,n,a){super(t),this.path=r,this.responseStatusCode=i,this.name=n,this.shapes=a,this.safeParse()}validateFormDataRequestExample(){return typeof this.resolvedRequestInput?.value!="object"?!1:Object.entries(this.shapes.requestBody?.fields??{}).reduce((t,[r,i])=>{let n=this.resolvedRequestInput?.value[r];switch(i.multipartType){case"file":return t&&(l7i(n)||typeof n=="string");case"files":return t&&Array.isArray(n)&&n.every(a=>l7i(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new Don.UnreachableCaseError(i.multipartType),t}},!0)}parse(){let t=this.shapes.requestBody?.schema?.example({includeOptionals:!1,override:void 0});this.resolvedRequestInput=xFc(this.input?.requestExample,this.context.document)??(t!=null?{value:t}:void 0);let r=this.shapes.responseBody?.schema?.example({includeOptionals:!1,override:void 0});if(this.resolvedResponseInput=xFc(this.input?.responseExample,this.context.document)??(r!=null?{value:r}:void 0),this.summary=this.input?.requestExample?.summary??this.input?.responseExample?.summary,this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody?.contentType){case"json":{if(typeof this.resolvedRequestInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break}case"bytes":{if(typeof this.resolvedRequestInput.value!="string"){this.context.errors.error({message:"Invalid example, expected string for bytes",path:this.accessPath});return}break}case"form-data":{if(!this.validateFormDataRequestExample()){this.context.errors.error({message:"Invalid example, expected valid form-data",path:this.accessPath});return}break}case void 0:break;default:new Don.UnreachableCaseError(this.shapes.requestBody?.contentType),this.context.errors.error({message:"Invalid example, unsupported content type",path:this.accessPath});return}if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody?.contentType){case"application/json":if(this.resolvedResponseInput!=null&&typeof this.resolvedResponseInput!="object"||this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break;case"text/event-stream":if(this.resolvedResponseInput.value!=null&&!Array.isArray(this.resolvedResponseInput.value)&&!this.resolvedResponseInput.value.every(Dyu)){this.context.errors.error({message:"Invalid example, expected array of SSE events for event-stream",path:this.accessPath});return}break;case"application/octet-stream":if(this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="string"&&!Array.isArray(this.resolvedResponseInput.value)){this.context.errors.error({message:"Invalid example, expected string or array for octet-stream",path:this.accessPath});return}break;case void 0:break;default:new Don.UnreachableCaseError(this.shapes.responseBody?.contentType);return}}convertFormDataExampleRequest(){if(!(this.resolvedRequestInput==null||this.shapes.requestBody?.fields==null))switch(this.shapes.requestBody?.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(this.shapes.requestBody.fields).map(([r,i])=>{let n=this.resolvedRequestInput?.value?.[r];switch(i.multipartType){case"file":return l7i(n)?[r,{type:"filenameWithData",filename:n.filename,data:Bh.FileId(n.data)}]:[r,{type:"filename",value:n}];case"files":{if(Array.isArray(n)){if(n.every(a=>l7i(a)))return[r,{type:"filenamesWithData",value:n.map(a=>({filename:a.filename,data:Bh.FileId(a.data)}))}];if(n.every(a=>typeof a=="string"))return[r,{type:"filenames",value:n}]}return}case"property":return[r,{type:"json",value:n}];case void 0:return;default:new Don.UnreachableCaseError(i.multipartType);return}}).filter(sp))};case"json":return{type:"json",value:this.resolvedRequestInput.value};case"bytes":return typeof this.resolvedRequestInput.value=="string"?{type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}}:void 0;default:return}}convertDescription(){if(this.resolvedRequestInput!=null&&this.resolvedResponseInput!=null)return this.resolvedResponseInput.description;if(this.resolvedRequestInput!=null)return this.resolvedRequestInput.description;if(this.resolvedResponseInput!=null)return this.resolvedResponseInput.description}convert(){let t;if(this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody.contentType){case"form-data":t=this.convertFormDataExampleRequest();break;case"json":t={type:"json",value:this.resolvedRequestInput.value};break;case"bytes":t={type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}};break;case void 0:break;default:new Don.UnreachableCaseError(this.shapes.requestBody?.contentType);break}let r;if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody.contentType){case"application/json":{r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break}case"text/event-stream":r={type:"sse",value:this.resolvedResponseInput?.value};break;case"application/octet-stream":r={type:typeof this.resolvedResponseInput?.value=="string"?"filename":"stream",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;case void 0:r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;default:new Don.UnreachableCaseError(this.shapes.responseBody?.contentType);break}let i=Object.fromEntries(Object.entries(this.shapes.pathParameters??{}).map(([u,c])=>[u,c.example({includeOptionals:!1,override:u})]));i=Object.keys(i).length>0?i:void 0;let n=Object.fromEntries(Object.entries(this.shapes.queryParameters??{}).map(([u,c])=>c.required||c.inputExample!=null?[u,c.example({includeOptionals:!1,override:u})]:void 0).filter(sp));n=Object.keys(n).length>0?n:void 0;let a=Object.fromEntries(Object.entries(this.shapes.requestHeaders??{}).map(([u,c])=>c.required||c.inputExample!=null?[u,c.example({includeOptionals:!1,override:u})]:void 0).filter(sp));if(a=Object.keys(a).length>0?a:void 0,!(this.path==null&&t==null&&r==null&&a==null&&n==null&&i==null))return{path:Tk_(this.path,i??{}),responseStatusCode:this.responseStatusCode,name:this.name!=null?eur(this.name):this.summary!=null?eur(this.summary):void 0,description:this.convertDescription(),pathParameters:i,queryParameters:n,headers:a,requestBody:t,responseBody:r,snippets:void 0}}};function Ck_(e,t){return AD(e)?x$(e,t,void 0):e}var $k_=ui(vx());var Bk_="#/components/schemas/";function VXn(e){if(e.$ref.startsWith(Bk_))return e.$ref.replace(Bk_,"")}function WPi(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}function f7i(e){return typeof e.type=="string"&&e.type==="array"}function Ik_(e){return e.type==="boolean"}function zk_(e){return e.type==="integer"}function d7i(e){return!Array.isArray(e.type)&&!f7i(e)}function xk_(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||d7i(t)||f7i(t))}function Rk_(e){return"nullable"in e&&typeof e.nullable=="boolean"}function Nk_(e){return e.type==="null"}function Fk_(e){return e.type==="number"}function RFc(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function Lk_(e){return e.type==="string"}var Cyu=class extends ese{item;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.item=new HT({input:this.input.items,context:this.context,accessPath:this.accessPath,pathId:"items",seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}),this.input.items==null&&this.context.errors.error({message:"Expected 'items' property to be specified",path:this.accessPath})}convert(){return dq(this.item?.convert())?.map(r=>({type:"alias",value:{type:"list",itemShape:r}}))}example(t){return this.input.example??this.input.examples?.[0]??[this.item?.example(t)]}};var Byu=class extends Y6{constValue;description;availability;constructor(t){super(t),this.safeParse()}parse(){this.input.const!=null&&(typeof this.input.const=="string"||typeof this.input.const=="number"||typeof this.input.const=="boolean")?this.constValue=this.input.const.toString():this.context.errors.warning({message:`Unsupported const type: ${typeof this.input}`,path:this.accessPath}),this.description=this.input.description,this.availability=new Z6e({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"})}convert(){if(this.constValue!=null)return{type:"enum",default:this.constValue,values:[{value:this.constValue,description:this.description,availability:this.availability?.convert()}]}}example(){return this.input.example??this.input.examples?.[0]??this.constValue}};var Iyu=class extends ese{typeNodes;nullable;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.parse()}parse(){this.typeNodes=this.input.map(t=>{if(t.type==="null")this.nullable=!0;else return new HT({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName})}).filter(sp)}convert(){if(this.typeNodes==null)return;let i=this.typeNodes.map(n=>dq(n.convert())?.map(u=>({displayName:n.name,shape:u,description:n.description,availability:n.availability?.convert()}))).filter(sp).reduce((n,a)=>n.flatMap(u=>a.length>0?a.map(c=>[...u,c]):[[...u]]),[[]]).map(n=>({type:"undiscriminatedUnion",variants:n}));return this.nullable?i.map(WPi).filter(sp):i}example(t){return this.nullable?null:this.typeNodes?.[0]?.example(t)}};function zyu(e){return e!=null&&e.length>0?e:[void 0]}var WXn=class extends ese{description;extends=[];properties;extraProperties;requiredProperties;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.extends=[],this.requiredProperties=this.input.required,this.properties=Object.fromEntries(Object.entries(this.input.properties??{}).map(([t,r])=>[t,new HT({input:r,context:this.context,accessPath:this.accessPath,pathId:["properties",t],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})])),this.extraProperties=this.input.additionalProperties!=null?typeof this.input.additionalProperties=="boolean"?this.input.additionalProperties?this.input.title:void 0:new HT({input:this.input.additionalProperties,context:this.context,accessPath:this.accessPath,pathId:["additionalProperties"],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0,this.input.allOf!=null&&(this.extends=this.extends.concat(this.input.allOf.map((t,r)=>{if(AD(t))return VXn(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([i,n])=>[i,new HT({input:n,context:this.context,accessPath:this.accessPath,pathId:["allOf",r.toString(),"properties",i],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))}}).filter(sp))),this.description=this.input.description}convertProperties(){if(this.properties!=null)return UXn(this.properties,this.requiredProperties)}convertExtraProperties(){return this.extraProperties==null?void 0:typeof this.extraProperties=="string"?[{type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:{type:"alias",value:{type:"unknown",displayName:this.extraProperties}}}]:dq(this.extraProperties.convert())?.map(r=>({type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:r})).filter(sp)}convert(){let t=this.convertProperties();if(t==null)return;let r=this.convertExtraProperties();return t.flatMap(i=>zyu(r).map(n=>(this.extends==null||this.extends.length===0)&&i.length===0&&n!=null?{type:"alias",value:n}:{type:"object",extends:this.extends.map(a=>Bh.TypeId(a)),properties:i,extraProperties:n}))}example({includeOptionals:t}){let r={...this.properties};return this.input.allOf?.forEach(i=>{let n=X6(i,this.context.document);n!=null&&(r={...r,...Object.fromEntries(Object.entries(n.properties??{}).map(([a,u])=>[a,new HT({input:u,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))})}),this.input.example??this.input.examples?.[0]??(!t&&this.requiredProperties!=null&&this.requiredProperties.length>0?this.requiredProperties?.reduce((i,n)=>{let a=r?.[n];return i[n]=a?.example({includeOptionals:t,override:n}),i},{}):Object.entries(r).reduce((i,[n,a])=>(i[n]=a?.example({includeOptionals:t,override:n}),i),{}))}};var xyu=class extends ese{isNullable;discriminated;discriminant;discriminatedMapping;undiscriminatedMapping;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.input.oneOf!=null||this.input.anyOf!=null)if(this.isNullable=(this.input.oneOf??this.input.anyOf)?.some(t=>X6(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>X6(t,this.context.document)?.type!=="null"?new HT({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0).filter(sp);else{let t=this.input.discriminator.mapping;if(t!=null){this.discriminated=!0,this.discriminant=this.input.discriminator.propertyName,this.discriminatedMapping={};let r=this.discriminatedMapping;Object.entries(t).map(([i,n])=>{let a=X6({$ref:n},this.context.document);if(a==null){this.context.errors.warning({message:`Expected schema reference. Received undefined reference: ${n}`,path:[...this.accessPath,"discriminator","mapping",i]});return}r[i]=new HT({input:a,context:this.context,accessPath:[...this.accessPath,"discriminator","mapping",i],pathId:i,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})})}}}convert(){if(!this.discriminated&&this.undiscriminatedMapping?.length===1){let n=this.undiscriminatedMapping?.flatMap(a=>a.convert()).filter(sp);return this.isNullable&&n!=null?n.map(WPi).filter(sp):n}let t=0,r=this.discriminated&&this.discriminant!=null&&this.discriminatedMapping!=null?{type:"discriminatedUnion",discriminant:Bh.PropertyKey(this.discriminant),variants:Object.entries(this.discriminatedMapping).flatMap(([n,a])=>dq(a.convert())?.map(c=>{if(!(c==null||c.type!=="object"))return{discriminantValue:n,displayName:a.name??eur(n),availability:a.availability?.convert(),description:a.description,...c}}).filter(sp)).filter(sp)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(n=>dq(n.convert())?.map(u=>{if(u==null)return;t+=1;let c=u.type==="object"?eur(`${this.schemaName??"Variant"} ${t}`):void 0;return{displayName:n.name??(u.type==="alias"&&u.value.type==="id"?eur(u.value.id):c),shape:u,description:n.description,availability:n.availability?.convert()}}).filter(sp)).filter(sp)}:void 0,i=this.isNullable?WPi(r):r;return i!=null?[i]:void 0}example(t){return this.input.example??this.input.examples?.[0]??this.undiscriminatedMapping?.[0]?.example(t)??Object.values(this.discriminatedMapping??{})[0]?.example(t)}};var Ryu=class extends Y6{default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.input.default!=null&&typeof this.input.default!="boolean"&&this.context.errors.warning({message:`Expected default value to be a boolean. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default}convert(){return{type:"alias",value:{type:"primitive",value:{type:"boolean",default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:!1)}};var p7i=class extends Y6{default;values=[];nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){if(this.input.enum!=null){let t=!0;this.values=this.input.enum.map((r,i)=>{if(t){if(AD(r)){let n=X6(r,this.context.document);r=typeof n=="string"?n:typeof n?.default=="string"?n?.default:typeof n?.example=="string"?n.example:void 0}if(typeof r!="string"){this.context.errors.error({message:`Expected enum values to be strings. Received ${r}`,path:[...this.accessPath,`enum[${i}]`]}),t=!1;return}return r}}).filter(sp),this.values=Array.from(new Set(this.values))}this.default=this.input.default}convert(){return{type:"enum",values:this.values.map(t=>({value:t,description:void 0,availability:void 0})),default:this.default}}example(){return this.input.example??this.input.examples?.[0]??this.default??this.values[0]??(this.nullable?null:void 0)}};var Uk_=ui(vx());function BOM(e){return CFc.includes(e)}var Nyu=class extends Y6{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be an integer. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(BOM(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${CFc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="integer";if(this.format!=null)switch(this.format){case"int64":t="long";break;case"int8":case"int16":case"int32":case"uint8":case"sf-integer":case void 0:t="integer";break;default:new Uk_.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var Fyu=class extends Y6{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return WPi({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var Vk_=ui(vx());function IOM(e){return TFc.includes(e)}var Lyu=class extends Y6{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be a number. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(IOM(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${TFc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="double";if(this.format!=null)switch(this.format){case"decimal":case"decimal128":case"double-int":case"double":case"float":case"sf-decimal":case void 0:t="double";break;default:new Vk_.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var Wk_=ui(vx());function zOM(e){return BFc.includes(e)}var Uyu=class extends Y6{format;regex;default;minLength;maxLength;enum;mimeType;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}mapToFdrType(t){switch(t){case"base64url":case"binary":case"byte":case"sf-binary":return"base64";case"date-time":return"datetime";case"int64":return"bigInteger";case"date":return"date";case"uuid":return"uuid";case"char":case"commonmark":case"decimal":case"decimal128":case"duration":case"email":case"hostname":case"html":case"http-date":case"idn-email":case"idn-hostname":case"ipv4":case"ipv6":case"iri-reference":case"iri":case"json-pointer":case"media-range":case"password":case"regex":case"relative-json-pointer":case"sf-boolean":case"sf-string":case"sf-token":case"time":case"uri-reference":case"uri-template":case"uri":case void 0:return"string";default:return new Wk_.UnreachableCaseError(t),"string"}}parse(){this.regex=this.input.pattern,this.minLength=this.input.minLength,this.maxLength=this.input.maxLength,this.mimeType=this.input.contentMediaType,this.input.default!=null&&typeof this.input.default!="string"&&this.context.errors.warning({message:`Expected default value to be a string. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(zOM(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${BFc.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new p7i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"enum",nullable:this.nullable}))}convert(){if(this.enum!=null)return this.enum.convert();let t="string";return this.format!=null&&(t=this.mapToFdrType(this.format)),{type:"alias",value:{type:"primitive",value:t==="base64"?{type:t,mimeType:this.mimeType,default:this.default}:{type:t,format:t==="string"?this.format:void 0,regex:this.regex,minLength:this.minLength,maxLength:this.maxLength,default:this.default}}}}example({override:t}){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:t??"string")}};var Hk_=ui(vx());var Vyu=class extends Y6{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,Hk_.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var Eon=class extends ese{description;availability;schemaId;maybeEnumConverterNode;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.description=t.description,this.availability=t.availability,this.safeParse()}parse(){this.schemaId=VXn(this.input);let t=X6(this.input,this.context.document);t?.enum!=null&&d7i(t)&&(this.maybeEnumConverterNode=new p7i({input:t,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",nullable:this.nullable})),this.schemaId==null&&this.context.errors.error({message:`Unprocessable reference: ${this.input.$ref}`,path:this.accessPath})}convert(){if(this.schemaId!=null)return{type:"alias",value:{type:"id",id:Bh.TypeId(this.schemaId),default:this.maybeEnumConverterNode?.default!=null?{type:"enum",value:this.maybeEnumConverterNode.default}:void 0}}}example(t){let r=X6(this.input,this.context.document);if(r!=null)return new HT({input:r,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName}).example(t)}};var HT=class e extends ese{typeShapeNode;description;name;examples;availability;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.description=this.input.description,this.availability=new Z6e({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),d7i(this.input)&&Rk_(this.input)&&(this.nullable=this.input.nullable!=null?this.input.nullable:this.nullable),AD(this.input)){let t=VXn(this.input);if(t==null){this.context.errors.error({message:"Reference object does not have a valid schema ID",path:this.accessPath});return}if(this.seenSchemas.has(t)){this.context.errors.warning({message:"Circular or deeply nested schema found, terminating",path:this.accessPath});return}this.seenSchemas.add(t),this.typeShapeNode=new Eon({input:this.input,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName,description:this.description,availability:this.availability})}else if(this.name=this.input.title,this.examples=this.input.example,this.input.const!=null)this.typeShapeNode=new Byu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(xk_(this.input))this.typeShapeNode=new Iyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(d7i(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new xyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(RFc(this.input)&&this.input.allOf!=null)this.typeShapeNode=new WXn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(d7i(this.input)&&this.input.enum!=null)this.typeShapeNode=new p7i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable});else if(typeof this.input.type=="string"||Array.isArray(this.input.type)&&this.input.type.length===1){if(this.input.type=Array.isArray(this.input.type)?this.input.type[0]:this.input.type,!Array.isArray(this.input.type))switch(this.input.type){case"object":RFc(this.input)&&(this.typeShapeNode=new WXn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"array":f7i(this.input)&&(this.typeShapeNode=new Cyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"boolean":Ik_(this.input)&&(this.typeShapeNode=new Ryu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"integer":zk_(this.input)&&(this.typeShapeNode=new Nyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"number":Fk_(this.input)&&(this.typeShapeNode=new Lyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"string":Lk_(this.input)&&(this.typeShapeNode=new Uyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"null":Nk_(this.input)&&(this.typeShapeNode=new Fyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case void 0:break;default:new $k_.UnreachableCaseError(this.input.type);break}}else if(Array.isArray(this.input.type)&&this.input.type.includes("null")&&this.input.type.length===2){let t=this.input.type.filter(r=>r!=="null")[0];t!=="array"&&(this.typeShapeNode=new e({input:{...this.input,type:t},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:!0,schemaName:this.schemaName}))}else this.input.properties!=null&&(this.typeShapeNode=new WXn({input:{...this.input,type:"object"},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));this.typeShapeNode==null&&(this.typeShapeNode=new Vyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),!AD(this.input)&&(!f7i(this.input)&&this.input==null||f7i(this.input)&&this.input.items==null)&&this.context.errors.error({message:"Expected type declaration. Received: null",path:this.accessPath}))}convert(){let t=this.typeShapeNode?.convert();if(t==null)return;let r=dq(t)?.map(i=>this.nullable?WPi(i):i).filter(sp);return Array.isArray(t)&&t.length>1?r:r?.[0]}example(t){return this.availability?.availability!=="deprecated"?this.typeShapeNode?.example(t):void 0}};function _7i(e){if(e!=null)return UXn(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(sp))}var iur=class extends Y6{availability;required;schema;description;inputExample;constructor(t){super(t),this.safeParse(t.parameterName)}parse(t){this.description=this.input.description;let r;AD(this.input)?r=this.input:this.input.schema!=null?(r=this.input.schema,this.required=this.input.required):(r={type:"string"},this.required=!1),this.availability=new Z6e({input:r,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new HT({input:r,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:t});let i=Ck_(this.input,this.context.document);this.inputExample=i?.example??Object.values(i?.examples??{})[0]}convert(){return this.schema?.convert()}example(t){return this.inputExample??this.schema?.example(t)}};function Gk_(e,t){return AD(e)?x$(e,t,void 0):e}var NFc=ui(vx());function Wyu(e){let{uniqueId:t,type:r,contextTypes:i,description:n,availability:a}=e;i[Bh.TypeId(t)]={name:t,shape:r,description:n,availability:a}}var Qk_=ui(pHs(),1),HXn=class e{type;subtype;essence;parameters;mimeType;input;constructor(t,r,i,n,a,u){this.type=t,this.subtype=r,this.essence=i,this.parameters=n,this.mimeType=a,this.input=u}static APPLICATION_JSON="application/json";static APPLICATION_OCTET_STREAM="application/octet-stream";static MULTIPART_FORM_DATA="multipart/form-data";static parse(t){if(t==null)return null;let r=Qk_.default.parse(t);return r==null?null:new e(r.type,r.subtype,r.essence,r.parameters,r,t)}toString(){return this.input}isText(){return this.type==="text"}isImage(){return this.type==="image"}isAudio(){return this.type==="audio"}isVideo(){return this.type==="video"}isFont(){return this.type==="font"}isMultipart(){return this.type==="multipart"}isApplication(){return this.type==="application"}isMessage(){return this.type==="message"}isModel(){return this.type==="model"}isCSS(){return this.isText()&&this.subtype==="css"}isCSV(){return this.isText()&&this.subtype==="csv"}isMarkdown(){return this.isText()&&this.subtype==="markdown"}isPlainText(){return this.isText()&&this.subtype==="plain"}isEventStream(){return this.isText()&&this.subtype==="event-stream"}isMultiPartFormData(){return this.isMultipart()&&this.subtype==="form-data"}isJSON(){return this.isApplication()&&this.subtype==="json"}containsJSON(){return this.isApplication()&&this.subtype.includes("json")}isURLEncoded(){return this.isApplication()&&this.subtype==="x-www-form-urlencoded"}isOctetStream(){return this.isApplication()&&this.subtype==="octet-stream"}isPDF(){return this.isApplication()&&this.subtype==="pdf"}isZip(){return this.isApplication()&&this.subtype==="zip"}isGzip(){return this.isApplication()&&this.subtype==="gzip"}isTar(){return this.isApplication()&&this.subtype==="tar"}isBrotli(){return this.isApplication()&&this.subtype==="br"}isDeflate(){return this.isApplication()&&this.subtype==="deflate"}isProtobuf(){return this.isApplication()&&this.subtype==="protobuf"}isAvif(){return this.isImage()&&this.subtype==="avif"}isWebP(){return this.isImage()&&this.subtype==="webp"}isSVG(){return this.isImage()&&this.subtype==="svg+xml"}isPNG(){return this.isImage()&&this.subtype==="png"}isJPEG(){return this.isImage()&&this.subtype==="jpeg"}isGIF(){return this.isImage()&&this.subtype==="gif"}isMPEG(){return this.isAudio()&&this.subtype==="mpeg"}isWAV(){return this.isAudio()&&this.subtype==="wav"}isHTML(){return this.mimeType.isHTML()}isXML(){return this.mimeType.isXML()}isJavaScript(){return this.mimeType.isJavaScript()}};function xOM(e){return typeof e.securitySchemes=="object"&&e.securitySchemes!=null}var $Xn=class extends A_{typeSchemas;securitySchemes;constructor(t){super(t),this.safeParse()}parse(){this.input.schemas!=null&&(this.typeSchemas=Object.fromEntries(Object.entries(this.input.schemas).map(([t,r])=>[t,new HT({input:r,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:new Set,nullable:void 0,schemaName:t})]))),xOM(this.input)&&this.input.securitySchemes!=null&&(this.securitySchemes=Object.fromEntries(Object.entries(this.input.securitySchemes??{}).map(([t,r],i)=>{let n;if(AD(r)?n=syu(r.$ref,this.context.document):n=r,n!=null)return[t,new FXn({input:n,context:this.context,accessPath:this.accessPath,pathId:["securitySchemes",`${i}`]})]}).filter(sp)))}convert(){return{auths:this.securitySchemes!=null?Object.fromEntries(Object.entries(this.securitySchemes??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[Bh.api.latest.AuthSchemeId(t),i]}).filter(sp)):void 0,types:this.typeSchemas!=null?Object.fromEntries(Object.entries(this.typeSchemas).map(([t,r])=>{let i=r.name??t,n=dq(r.convert());return n==null?[t,void 0]:[Bh.TypeId(t),{name:i,shape:n[0],description:r.description,availability:void 0}]}).filter(([t,r])=>sp(r))):void 0}}};var Hyu=class extends HT{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=X6(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${AD(this.input)?`Received undefined reference: ${this.input.$ref}`:""}`,path:this.accessPath});return}if(t.type==="string"&&t.format==="binary")this.multipartType="file",this.contentType=t.contentMediaType;else if(t.type==="array"){let r=X6(t.items,this.context.document);r?.type==="string"&&r?.format==="binary"?(this.multipartType="files",this.contentType=r?.contentMediaType):(this.context.errors.warning({message:"Expected multipart form data files definition with array type with internal string type and binary format.",path:this.accessPath}),this.multipartType=void 0,this.contentType=void 0)}else this.multipartType="property",this.contentType=t.contentMediaType}};var $yu=class extends A_{description;method;path;schema;isOptional;contentType;availability;requiredFields;fields;examples;constructor(t){super(t),this.method=t.method,this.path=t.path,this.safeParse(t)}parse({contentType:t}){if(this.input.schema!=null){let i=X6(this.input.schema,this.context.document);this.availability=new Z6e({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=AD(this.input.schema)?new Eon({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:!1,schemaName:"Request Body",description:this.input.schema.description,availability:this.availability}):void 0;let n=HXn.parse(t);n?.containsJSON()?(this.contentType="json",this.schema=this.schema??new HT({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:"Request Body"})):n?.isOctetStream()?(this.contentType="bytes",this.isOptional=i?.required==null):n?.isMultiPartFormData()?(this.contentType="form-data",this.requiredFields=i?.required,this.fields=Object.fromEntries(Object.entries(i?.properties??{}).map(([a,u])=>{if(u!=null)return[a,new Hyu({input:u,context:this.context,accessPath:this.accessPath,pathId:`schema.${a}`,seenSchemas:new Set,nullable:void 0,schemaName:a})]}).filter(sp))):this.context.errors.warning({message:`Expected request body of reference or object with json, streaming or form-data content types. Received: ${t}`,path:this.accessPath})}let r=this.schema?.example({includeOptionals:!0,override:void 0});this.examples={...this.input.example!=null?{[xU]:{value:this.input.example}}:{},...this.input.examples},r!=null&&Object.keys(this.examples).length===0&&(this.examples={[xU]:{value:r}})}convertJsonLike(){let t=this.schema?.convert();return t==null?void 0:dq(t)?.map(i=>{let n=i.type;switch(n){case"object":case"alias":return i;case"enum":case"undiscriminatedUnion":case"discriminatedUnion":{let a=aJt([this.method,this.path,this.contentType,"request"].join("_"));return Wyu({uniqueId:a,type:i,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:Bh.TypeId(a),default:i.type==="enum"&&i.default!=null?{type:"enum",value:i.default}:void 0}}}case void 0:return;default:new NFc.UnreachableCaseError(n);return}}).filter(sp)}convert(){if(this.schema instanceof Eon)return this.schema.convert();switch(this.contentType){case"json":return this.convertJsonLike();case"bytes":return{type:"bytes",isOptional:this.isOptional??!1,contentType:this.contentType};case"form-data":return Object.entries(this.fields??{}).map(([i,n])=>{switch(n.multipartType){case"file":return[{type:n.multipartType,key:Bh.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"files":return[{type:n.multipartType,key:Bh.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"property":{let a=dq(n.convert()),u=n.multipartType;return a?.map(c=>({type:u,key:Bh.PropertyKey(i),contentType:n.contentType,exploded:void 0,valueShape:c,description:n.description,availability:n.availability?.convert()}))}case void 0:return[];default:return new NFc.UnreachableCaseError(n.multipartType),[]}}).filter(sp).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(u=>[...a,u]):[[...a]]),[[]]).map(i=>({type:"formData",fields:i,availability:this.availability?.convert(),description:this.description}));case void 0:return this.convertJsonLike();default:return}}};var Gyu=class extends A_{description;requestBodiesByContentType;constructor(t){super(t),this.safeParse(t)}parse({method:t,path:r}){let i=Gk_(this.input,this.context.document);if(i==null){this.context.errors.error({message:"Expected request body. Received: null",path:this.accessPath});return}Object.entries(i.content).forEach(([n,a])=>{this.requestBodiesByContentType??={},this.requestBodiesByContentType[n]=new $yu({input:a,context:this.context,accessPath:this.accessPath,pathId:"content",contentType:n,method:t,path:r})})}convert(){return Object.entries(this.requestBodiesByContentType??{}).flatMap(([t,r])=>dq(r.convert())?.map(n=>({description:this.description,contentType:t,body:n}))).filter(sp)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>dq(t.convert())?.map(i=>{if(!(i.type!=="alias"&&i.type!=="object"))return{description:this.description,shape:i}})).filter(sp)}webhookExample(){return{payload:this.requestBodiesByContentType?.["application/json"]?.schema?.example({includeOptionals:!0,override:void 0})}}};var Jk_={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};function Kk_(e,t){if(AD(e)){let r=x$(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var Qyu=ui(vx());var Yk_="application/json";var Xk_="application/octet-stream";function Zk_(e,t){return e===t||t===xU||e===xU}var bVa=class extends A_{streamingFormat;path;method;statusCode;requests;shapes;schema;contentType;unsupportedContentType;contentSubtype;examples;empty;constructor(t,r,i,n,a,u,c,d){super(t),this.streamingFormat=i,this.path=n,this.method=a,this.statusCode=u,this.requests=c,this.shapes=d,this.safeParse(r)}matchRequestResponseExamplesByName(t,r,i){for(let n of t)for(let[a,u]of Object.entries(n?.examples??{}))for(let[c,d]of Object.entries(r))for(let s of d)Zk_(c,a)&&(i.add(c),this.examples?.push(new rur({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,c7i(a,c),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}matchExamplesByIndex(t,r){let i=0;for(let n of t){let a=0;for(let[u,c]of r){if(a===i){let[d,s,o]=n??[void 0,void 0,void 0];this.examples?.push(...c.map(l=>new rur({input:{requestExample:o,responseExample:l},context:this.context,accessPath:this.accessPath,pathId:s!=null&&s!==""?["examples",s]:"examples"},this.path,this.statusCode,c7i(s,u),{requestBody:d,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}a++}i++}if(t.length>r.length)for(let n of t.slice(r.length)){let[a,u]=r[r.length-1]??[void 0,void 0],[c,d,s]=n??[void 0,void 0,void 0];this.examples?.push(...(u??[void 0]).map(o=>new rur({input:{requestExample:s,responseExample:o},context:this.context,accessPath:this.accessPath,pathId:d!=null&&d!==""?["examples",d]:"examples"},this.path,this.statusCode,c7i(d,a),{requestBody:c,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}if(r.length>t.length){let[n,a,u]=t[t.length-1]??[void 0,void 0,void 0];for(let[c,d]of r.slice(t.length))this.examples?.push(...d.map(s=>new rur({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,c7i(a,c),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}}pushResponseExample(t,r,i,n){let a=t[xU];if(a!=null)for(let u of a)this.examples?.push(new rur({input:{requestExample:n,responseExample:u},context:this.context,accessPath:this.accessPath,pathId:i!=null&&i!==""?["examples",i]:"examples"},this.path,this.statusCode,c7i(i,void 0),{requestBody:r,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders}))}addGlobalFallbackExample(t,r){if(t==null||t.length===0)this.pushResponseExample(r,void 0,void 0,void 0);else for(let i of t)if(Object.keys(i.examples??{}).length===0)this.pushResponseExample(r,i,void 0,void 0);else for(let[n,a]of Object.entries(i.examples??{}))this.pushResponseExample(r,i,n,a)}parse(t){if(t==="empty")this.empty=!0;else{let c=HXn.parse(t);if(c?.isJSON()||c?.isEventStream())this.contentType=Yk_,this.input.schema==null?(this.streamingFormat==null||this.streamingFormat==="json")&&this.context.errors.error({message:"Expected schema for JSON response body. Received null",path:this.accessPath}):this.schema=new HT({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"type",seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"});else if(c?.isOctetStream())this.contentType=Xk_,this.contentSubtype=X6(this.input.schema,this.context.document)?.contentMediaType;else if(this.unsupportedContentType=t,this.input.schema==null){this.context.errors.error({message:"Expected schema for plain text response body. Received null",path:this.accessPath});return}else this.schema=new HT({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"})}let r={};this.input.examples!=null&&(r=Oyu(this.input.examples,c=>[c])),this.input.example!=null&&Object.keys(r).length===0&&(r[xU]??=[],r[xU]=[{value:this.input.example}]);let i=X6(this.input.schema,this.context.document);if(i!=null&&(i.examples!=null&&Object.keys(r).length===0&&(r=Oyu(i.examples,c=>[c])),i.example!=null&&Object.keys(r).length===0&&(r[xU]??=[],r[xU]?.push({value:i.example}))),Object.keys(r).length===0){let c=this.schema?.example({includeOptionals:!0,override:void 0});r[xU]??=[],r[xU]?.push(c!=null?{value:c}:void 0)}this.examples??=[];let n=new Set;this.matchRequestResponseExamplesByName(this.requests,r,n);let a=[];for(let c of this.requests)a.push(...Object.entries(c.examples??{}).filter(([d])=>!n.has(d)&&d!==xU).map(([d,s])=>[c,d,s]));let u=Object.entries(r).filter(([c,d])=>!n.has(c)&&sp(d)&&c!==xU);Object.keys(r).every(c=>c===xU)||this.matchExamplesByIndex(a,u),!n.has(xU)&&this.examples.length===0&&this.addGlobalFallbackExample(this.requests,r),this.examples.length===0&&(this.examples=void 0)}convertStreamingFormat(){switch(this.streamingFormat){case"json":return dq(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new Qyu.UnreachableCaseError(this.streamingFormat);return}}convertJsonLike(){return dq(this.schema?.convert())?.map(r=>{let i=r.type;switch(i){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":{let n=aJt([this.method,this.path,this.statusCode,"response"].join("_"));return Wyu({uniqueId:n,type:r,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:Bh.TypeId(n),default:r.type==="enum"&&r.default!=null?{type:"enum",value:r.default}:void 0}}}case"object":return r;default:new Qyu.UnreachableCaseError(i);return}}).filter(sp)}convert(){if(this.empty)return{type:"empty"};if(this.contentType!=null)switch(this.contentType){case"application/json":return this.streamingFormat==null?this.convertJsonLike():this.convertStreamingFormat();case"application/octet-stream":return{type:"fileDownload",contentType:this.contentSubtype};case"text/event-stream":return this.convertStreamingFormat();case void 0:return;default:new Qyu.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?this.convertJsonLike():void 0}};var gVa=class extends A_{path;method;statusCode;requests;shapes;headers;responses;description;constructor(t,r,i,n,a,u){super(t),this.path=r,this.method=i,this.statusCode=n,this.requests=a,this.shapes=u,this.safeParse()}parse(t){this.description=this.input.description;let r=Kk_(this.input,this.context.document);if(r==null){this.context.errors.error({message:AD(this.input)?`Undefined reference: ${this.input.$ref}`:"Expected response, received null",path:this.accessPath});return}Object.entries(r.headers??{}).forEach(([i,n])=>{this.headers??={},this.headers[i]=new iur({input:n,context:this.context,accessPath:this.accessPath,pathId:"headers",parameterName:i})}),r.content==null?(this.responses??=[],this.responses.push(new bVa({input:{},context:this.context,accessPath:this.accessPath,pathId:["content"]},"empty",t,this.path,this.method,this.statusCode,this.requests,this.shapes))):Object.entries(r.content??{}).forEach(([i,n])=>{this.responses??=[],this.responses.push(new bVa({input:n,context:this.context,accessPath:this.accessPath,pathId:["content",i]},i,t,this.path,this.method,this.statusCode,this.requests,this.shapes))})}convert(){return this.responses?.flatMap(t=>t.convert()).filter(sp)}};var Jyu=class extends A_{path;method;requests;shapes;responsesByStatusCode;errorsByStatusCode;constructor(t,r,i,n,a){super(t),this.path=r,this.method=i,this.requests=n,this.shapes=a,this.safeParse()}parse(){let t=this.input.default;Object.entries(this.input).forEach(([r,i])=>{r!=="default"&&(parseInt(r)>=400?(this.errorsByStatusCode??={},this.errorsByStatusCode[r]=new gVa({input:{...t,...i},context:this.context,accessPath:this.accessPath,pathId:"errors"},this.path,this.method,parseInt(r),[],this.shapes)):(this.responsesByStatusCode??={},this.responsesByStatusCode[r]=new gVa({input:i,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,parseInt(r),this.requests,this.shapes)))})}convertResponseObjectToHttpResponses(){return Object.entries(this.responsesByStatusCode??{}).flatMap(([t,r])=>{let i=r.convert();if(i!=null)return zyu(_7i(r.headers)).flatMap(n=>i?.map(a=>({headers:n,response:{statusCode:parseInt(t),body:a,description:r.description},examples:(r.responses??[]).flatMap(u=>(u.examples??[]).map(c=>c.convert()).filter(sp))})))}).filter(sp)}convertResponseObjectToErrors(){return Object.entries(this.errorsByStatusCode??{}).flatMap(([t,r])=>r.responses?.flatMap(i=>{let n=i.schema,a=dq(n?.convert());if(n!=null)return a?.map(u=>({statusCode:parseInt(t),shape:u,description:r.description??n.description,availability:n.availability?.convert(),name:n.name??Jk_[parseInt(t)]??"UNKNOWN ERROR",examples:i.examples?.map(c=>{let d=c.convert();if(d!=null&&d.responseBody?.type==="json")return{name:d.name,description:d.description,responseBody:d.responseBody}}).filter(sp)})).filter(sp)})).filter(sp)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var h7i=class extends A_{servers;globalAuth;path;method;basePath;isWebhook;endpointIds;description;displayName;operationId;pathParameters;queryParameters;requestHeaders;requests;responses;availability;auth;namespaces;xFernExamplesNode;redocExamplesNode;emptyResponseExamples;constructor(t){super(t),this.servers=t.servers,this.globalAuth=t.globalAuth,this.path=t.path,this.method=t.method,this.basePath=t.basePath,this.isWebhook=t.isWebhook,this.safeParse()}pushEmptyResponseExample(t,r,i){this.emptyResponseExamples??=[],this.emptyResponseExamples.push(new rur({input:{requestExample:t,responseExample:void 0},context:this.context,accessPath:this.accessPath,pathId:"examples"},this.path,200,c7i(i,void 0),{requestBody:r,pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}))}parse(){if(this.isWebhook&&this.method!=="POST"&&this.method!=="GET"){this.context.errors.error({message:`Webhook method must be POST or GET. Received: ${this.method}`,path:this.accessPath});return}this.description=this.input.description,this.displayName=this.input.summary,this.operationId=this.input.operationId,this.availability=new Z6e({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=tur(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new qyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((i,n)=>{if(AD(i)){let a=Syu(i,this.context.document);if(a!=null)i=a;else{this.context.errors.warning({message:`Expected parameter reference to resolve to an object. Received undefined reference: ${i.$ref}`,path:[...this.accessPath,`parameters[${n}]`]});return}}i.in==="path"?i.schema!=null&&(this.pathParameters??={},this.pathParameters[i.name]=new iur({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="query"?i.schema!=null&&(this.queryParameters??={},this.queryParameters[i.name]=new iur({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="header"&&i.schema!=null&&(this.requestHeaders??={},this.requestHeaders[i.name]=new iur({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name}))});for(let i of this.extractPathParameterIds()??[])this.pathParameters?.[i]==null&&this.context.errors.warning({message:`Path parameter not defined: ${i}`,path:[...this.accessPath,"parameters"]});if(this.redocExamplesNode=new Tyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new Gyu({input:this.input.requestBody,context:this.context,accessPath:this.accessPath,pathId:"requestBody",method:this.method,path:this.path}):void 0,this.responses=this.input.responses!=null?new Jyu({input:this.input.responses,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,Object.values(this.requests?.requestBodiesByContentType??{}),{pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}):void 0,this.responses==null){let i=this.requests?.requestBodiesByContentType;i==null||Object.keys(i).length===0?this.pushEmptyResponseExample(void 0,void 0,void 0):Object.values(i).forEach(n=>{if(Object.keys(n.examples??{}).length===0){let a=n.schema?.example({includeOptionals:!1,override:void 0});a!=null&&this.pushEmptyResponseExample({value:a},n,void 0)}else Object.entries(n.examples??{}).forEach(([a,u])=>{this.pushEmptyResponseExample(u,n,a)})})}let t=200;this.responses?.responsesByStatusCode!=null&&(t=Number(Object.keys(this.responses.responsesByStatusCode)?.filter(i=>Number(i)>=200&&Number(i)<300)[0])),this.globalAuth!=null&&(this.auth=this.globalAuth),this.input.security!=null&&(this.auth=new LXn({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespaces=[new vVa({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-group-name"})],this.namespaces?.every(i=>i.groupName==null)&&this.input.tags!=null&&(this.namespaces=this.input.tags.slice(0,1).map((i,n)=>new vVa({input:{[ayu]:i},context:this.context,accessPath:this.accessPath,pathId:["tags",`${n}`]})));let r=new Ayu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointIds=this.namespaces.map(i=>myu({namespace:dq(i?.groupName),path:this.path,method:this.method,sdkMethodName:r.sdkMethodName,operationId:this.input.operationId,displayName:this.displayName,isWebhook:this.isWebhook})).filter(sp),this.xFernExamplesNode=new Myu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-examples"},this.path,t,this.requests?.requestBodiesByContentType,this.responses?.responsesByStatusCode?.[t]?.responses)}extractPathParameterIds(){if(this.path!=null)return this.path.split("/").map(t=>{if(t.startsWith("{")&&t.endsWith("}"))return t.slice(1,-1).trim()}).filter(sp)}convertPathToPathParts(){if(this.path===void 0)return;let t=this.path.startsWith("/")?this.path.slice(1):this.path,r=this.basePath?.convert();return(r?[r,...t.split("/")]:t.split("/")).reduce((n,a)=>(n.push({type:"literal",value:"/"}),a.startsWith("{")&&a.endsWith("}")?n.push({type:"pathParameter",value:Bh.PropertyKey(a.slice(1,-1).trim())}):n.push({type:"literal",value:a}),n),[])}convert(){if(this.path==null||this.endpointIds==null)return;let{responses:t,errors:r}=this.responses?.convert()??{responses:void 0,errors:void 0},i=this.emptyResponseExamples?.map(o=>o.convert()).filter(sp),n=wk_(this.xFernExamplesNode?.convert(),[...i??[],...t?.flatMap(o=>o.examples)??[]])?.map(o=>({...o,snippets:jk_(o.snippets,this.redocExamplesNode?.convert())}));if(this.isWebhook)return this.endpointIds.map((o,l)=>{if(!(this.method!=="POST"&&this.method!=="GET"))return{id:Bh.WebhookId(o),description:this.description,availability:this.availability?.convert(),displayName:this.displayName,operationId:this.operationId,namespace:this.namespaces?.[l]?.convert(),method:this.method,path:this.convertPathToPathParts()?.map(v=>v.value.toString())??[],queryParameters:_7i(this.queryParameters)?.flat(),headers:_7i(this.requestHeaders)?.flat(),payloads:this.requests?.convertToWebhookPayload(),examples:[this.requests?.webhookExample()].filter(sp)}}).filter(sp);let a=this.servers?.map(o=>o.convert()).filter(sp),u=this.convertPathToPathParts();if(u==null)return;let c,d=this.auth?.convert();d!=null&&(c=Object.keys(d));let s=t?.flatMap(o=>o.headers).filter(sp);return this.endpointIds.map((o,l)=>({id:Bh.EndpointId(o),description:this.description,availability:this.availability?.convert(),namespace:this.namespaces?.[l]?.convert()?.map(v=>Bh.api.v1.SubpackageId(v)),displayName:this.displayName,operationId:this.operationId,method:this.method,path:u,auth:c?.map(v=>Bh.api.latest.AuthSchemeId(v)),defaultEnvironment:a?.[0]?.id,environments:a,pathParameters:_7i(this.pathParameters)?.flat(),queryParameters:_7i(this.queryParameters)?.flat(),requestHeaders:_7i(this.requestHeaders)?.flat(),responseHeaders:s!=null&&s.length>0?s:void 0,requests:this.requests?.convert(),responses:t?.map(v=>v.response),errors:r,examples:n,snippetTemplates:void 0,protocol:{type:"rest"}}))}};var GXn=class extends A_{description;get;post;put;patch;delete;path;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i,isWebhook:n}){this.description=this.input.description;let a=tur(t,this.input.servers,this.context,this.accessPath),u=Array.isArray(this.pathId)?this.pathId.join("/"):this.pathId;this.input.get!=null&&(this.get=new h7i({input:this.input.get,context:this.context,accessPath:this.accessPath,pathId:"get",servers:a,globalAuth:r,path:u,method:"GET",basePath:i,isWebhook:n})),this.input.post!=null&&(this.post=new h7i({input:this.input.post,context:this.context,accessPath:this.accessPath,pathId:"post",servers:a,globalAuth:r,path:u,method:"POST",basePath:i,isWebhook:n})),this.input.put!=null&&(this.put=new h7i({input:this.input.put,context:this.context,accessPath:this.accessPath,pathId:"put",servers:a,globalAuth:r,path:u,method:"PUT",basePath:i,isWebhook:!1})),this.input.patch!=null&&(this.patch=new h7i({input:this.input.patch,context:this.context,accessPath:this.accessPath,pathId:"patch",servers:a,globalAuth:r,path:u,method:"PATCH",basePath:i,isWebhook:!1})),this.input.delete!=null&&(this.delete=new h7i({input:this.input.delete,context:this.context,accessPath:this.accessPath,pathId:"delete",servers:a,globalAuth:r,path:u,method:"DELETE",basePath:i,isWebhook:!1}))}convert(){return[...this.get?.convert()??[],...this.post?.convert()??[],...this.put?.convert()??[],...this.patch?.convert()??[],...this.delete?.convert()??[]].filter(sp)}};function Kyu(e){return"payloads"in e}var Yyu=class extends A_{paths;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.paths=Object.entries(this.input).map(([n,a])=>{if(a!=null)return new GXn({input:a,context:this.context,accessPath:this.accessPath,pathId:n,servers:tur(t,a.servers,this.context,this.accessPath),globalAuth:r,basePath:i,isWebhook:void 0})}).filter(sp)}convert(){if(this.paths==null)return;let t={},r={};return this.paths.forEach(i=>{let n=i.convert();n?.forEach(a=>{Kyu(a)?r[Bh.WebhookId(a.id)]=a:t[Bh.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var Xyu=class extends A_{globalHeaders;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[VZ_]?.map(r=>{let{header:i,...n}=r;return(n.optional!=null&&!n.optional||Syu(n,this.context.document)?.required)&&(this.requiredProperties??=[],this.requiredProperties?.push(i)),[i,new iur({input:n,context:this.context,accessPath:this.accessPath,pathId:this.pathId,parameterName:i})]});t!=null&&(this.globalHeaders=Object.fromEntries(t))}convert(){return UXn(this.globalHeaders,this.requiredProperties)?.flat()}};function kk_(e,t){if(AD(e)){let r=x$(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var Zyu=class extends A_{webhooks;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.webhooks=Object.entries(this.input??{}).map(([n,a])=>{let u=kk_(a,this.context.document);if(u!=null)return new GXn({input:u,context:this.context,accessPath:this.accessPath,pathId:n,servers:t,globalAuth:r,basePath:i,isWebhook:!0})}).filter(sp)}convert(){return this.webhooks?.reduce((t,r)=>(r.convert()?.forEach(i=>{Kyu(i)&&(t[Bh.WebhookId(i.id)]=i)}),t),{})}};var kyu=class extends A_{paths;webhooks;components;auth;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){let t=tur(void 0,this.input.servers,this.context,this.accessPath);this.input.security!=null&&(this.auth=new LXn({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"}));let r=new wyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});this.input.paths==null&&this.input.webhooks==null&&this.context.errors.warning({message:"Expected 'paths' or 'webhooks' property to be specified",path:this.accessPath}),this.input.paths!=null&&(this.paths=new Yyu({input:this.input.paths,context:this.context,accessPath:this.accessPath,pathId:"paths",basePath:r,servers:t,globalAuth:this.auth})),this.input.webhooks!=null&&(this.webhooks=new Zyu({input:this.input.webhooks,context:this.context,accessPath:this.accessPath,pathId:"webhooks",basePath:r,servers:t,globalAuth:this.auth})),this.input.components!=null&&(this.components=new $Xn({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"})),this.globalHeaders=new Xyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=_ue(),{webhookEndpoints:r,endpoints:i}=this.paths?.convert()??{},n={...this.webhooks?.convert()??{},...r??{}},a=ryu({endpoints:i,webhookEndpoints:n}),{types:u,auths:c}=this.components?.convert()??{};return{id:Bh.ApiDefinitionId(t),endpoints:i??{},websockets:{},webhooks:n,types:{...u,...this.context.generatedTypes},subpackages:a,auths:{...c,...this.auth?.convert()??{}},globalHeaders:this.globalHeaders?.convert(),snippetsConfiguration:void 0}}};var QXn=class extends xXn{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,this.pathId&&this.pathId!==this.accessPath[this.accessPath.length-1]&&(this.accessPath.push(this.pathId),r.logger.debug(`Processing #/${this.accessPath.join("/")}`))}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}};function k6e(e){return typeof e=="object"&&sp(e)&&"$ref"in e&&typeof e.$ref=="string"}function oJt(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(k6e(n)&&(n=oJt(n,t,r)),n)}function eeh(e,t){return k6e(e)?oJt(e,t,{name:"",params:[],result:{name:"",schema:{type:"object"}}}):e}var neh=ui(vx());function HPi(e){if(typeof e=="boolean")return e;if(e.enum!=null&&e.enum.length>0)return e.enum[0];if(e.const!=null)return e.const;if(e.examples!=null&&e.examples.length>0)return e.examples[0];if(e.type==="object"){let t={};if(e.properties!=null)for(let[r,i]of Object.entries(e.properties))t[r]=HPi(i);return t}if(e.type==="array")return e.items==null?[]:Array.isArray(e.items)?e.items.map(t=>HPi(t)):[HPi(e.items)];if(e.type==="string")return e.default??"string";if(e.type==="number"||e.type==="integer")return e.default??0;if(e.type==="boolean")return e.default??!1;if(e.type==="null")return null;if(e.oneOf?.[0]!=null)return HPi(e.oneOf[0]);if(e.anyOf?.[0]!=null)return HPi(e.anyOf[0]);if(e.allOf!=null&&e.allOf.length>0){let t={};for(let r of e.allOf)r!=null&&Object.assign(t,HPi(r));return t}}function OVa(e,t){return k6e(e)?oJt(e,t,{name:"",schema:{type:"object"}}):e}function teh(e,t){return k6e(e)?oJt(e,t,void 0):e}function reh(e,t){return k6e(e)?oJt(e,t,void 0):e}function ieh(e,t){return k6e(e)?oJt(e,t,void 0):e}var ROM={key:Bh.PropertyKey("apiKey"),description:void 0,availability:void 0,valueShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}}},evu=class extends QXn{method;servers=[];constructor(t,r){super(t),this.method=t.input,this.servers=r,this.safeParse()}parse(){}convert(){try{let t=this.method.result?OVa(this.method.result,this.context.openrpc):void 0,r=t?new HT({input:t.schema,context:this.context,accessPath:this.accessPath,pathId:"result",seenSchemas:new Set,nullable:void 0,schemaName:"Result"}).convert():void 0,n=this.method.params?.map(c=>OVa(c,this.context.openrpc)).filter(sp)?.map(c=>{let d=new HT({input:c.schema,context:this.context,accessPath:this.accessPath,pathId:["params",c.name],seenSchemas:new Set,nullable:void 0,schemaName:c.name}).convert();if(!d)return;let s=Array.isArray(d)?d[0]:d;if(s)return{key:Bh.PropertyKey(c.name),valueShape:c.required?s:{type:"alias",value:{type:"optional",shape:s,default:void 0}},description:c.description,availability:void 0}}).filter(sp),a=n.length>0?{contentType:"application/json",body:{type:"object",extends:[],properties:n,extraProperties:void 0},description:void 0}:void 0,u=this.method.examples?.map(c=>{let d=reh(c,this.context.openrpc);if(d)return{name:d.name??"Example",path:"",description:void 0,snippets:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:d.params.length>0?{type:"json",value:Object.fromEntries(d.params.map(s=>{let o=teh(s,this.context.openrpc);if(o)return[o.name??"",o.value]}).filter(sp))}:void 0,responseStatusCode:200,responseBody:d.result?{type:"json",value:d.result}:void 0}}).filter(sp)??[];if(u.length<=0){let c=HPi({type:"object",properties:Object.fromEntries(this.method.params?.map(s=>{let o=OVa(s,this.context.openrpc);return[o?.name??"",o?.schema??{}]})??[])}),d={name:"Example",path:"",pathParameters:{},queryParameters:{},headers:{},requestBody:{type:"json",value:c},responseStatusCode:200,responseBody:{type:"json",value:HPi(OVa(this.method.result,this.context.openrpc)?.schema??{})},snippets:void 0,description:void 0};u.push(d)}return{protocol:{type:"openrpc",methodName:this.input.name},id:Bh.EndpointId(this.input.name),displayName:this.input.name,method:"POST",path:[{type:"pathParameter",value:Bh.PropertyKey("apiKey")}],auth:void 0,pathParameters:[ROM],queryParameters:[],requests:a!=null?[a]:void 0,responses:r!=null?[this.convertToHttpResponse(r,this.input.description)].filter(sp):[],errors:[],examples:u,description:this.input.description??this.input.summary,operationId:this.input.name,defaultEnvironment:void 0,environments:this.servers.map(c=>c.convert()).filter(sp),availability:this.method.deprecated?"Deprecated":void 0,requestHeaders:[],responseHeaders:[],snippetTemplates:void 0,namespace:this.getNamespace()}}catch{this.context.errors.error({message:"Failed to convert method",path:this.accessPath});return}}getNamespace(){if(this.method.tags?.[0]==null)return;let t=ieh(this.method.tags[0],this.context.openrpc);if(t?.name!=null)return[Bh.api.v1.SubpackageId(t.name)]}convertToHttpResponse(t,r){if(t==null)return;let n=dq(t)?.map(a=>{let u=a.type;switch(u){case"alias":return a;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":return;case"object":return a;default:new neh.UnreachableCaseError(u);return}}).filter(sp)[0];if(n)return{statusCode:200,body:n,description:r}}};var mVa=class extends QXn{servers=[];methods=[];components;constructor(t){super(t),this.safeParse()}parse(){if(this.context.openrpc.servers!=null&&(this.servers=tur(this.servers,this.input.servers,this.context,this.accessPath)),this.input.methods!=null)for(let t of this.input.methods){let r=eeh(t,this.context.openrpc);r!=null&&this.methods.push(new evu({input:r,context:this.context,accessPath:this.accessPath,pathId:"methods"},this.servers))}this.context.openrpc.components!=null&&(this.components=new $Xn({input:this.context.openrpc.components,context:this.context,accessPath:this.accessPath,pathId:"components"}))}convert(){let t=_ue(),{types:r}=this.components?.convert()??{},i=this.methods?.map(u=>u.convert()).filter(sp),n=Object.fromEntries(i?.map(u=>[u.id,u])??[]),a=ryu({endpoints:n});return{id:Bh.ApiDefinitionId(t),types:r??{},endpoints:n,websockets:{},webhooks:{},subpackages:a,auths:{},globalHeaders:[],snippetsConfiguration:void 0}}};var PVa=class extends nyu{openrpc;logger;generatedTypes;constructor(t){super(),this.openrpc=t.openrpc,this.logger=t.logger,this.generatedTypes={}}get document(){return{openapi:"3.1.0",info:{title:"Mock API",version:"1.0.0"},paths:{},components:this.openrpc.components}}};async function jVa(e,t){if(e instanceof wor){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof D3))return;let r=new GQt(e.absoluteFilePath),i=await W6e({context:t,specs:e.specs}),n=await r.loadDocuments({context:t,specs:i}),a;for(let u of n){if(u.type!=="openapi")continue;let c={document:u.value,logger:t.logger,errors:new zXn,generatedTypes:{}},d=new kyu({input:u.value,context:c,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=AHs(a,d.convert())}return a}var aeh=require("fs/promises");async function oeh(e,t){let r=await(0,aeh.readFile)(e,"utf-8"),i=JSON.parse(r),n=new PVa({openrpc:i,logger:t.logger});return new mVa({input:i,context:n,accessPath:[],pathId:"openrpc"}).convert()}function NOM(e){return e.startsWith(".")||e.includes("/")||e.includes("\\")||e.includes(":")}function FOM(e){return/^(https?:)?\/\//.test(e)}async function LOM({pathToImage:e,absolutePathToFernFolder:t}){if(e==null||FOM(e))return;let r=$v(t,za.of(e));if(await Cf(r))return r}async function JXn({iconPath:e,filepaths:t,docsWorkspace:r}){if(NOM(e)){let i=await LOM({pathToImage:e,absolutePathToFernFolder:r.absoluteFilePath});i&&t.add(i)}}async function ueh({parsedDocsConfig:e,docsWorkspace:t}){let r=new Set;return e.logo?.dark!=null&&r.add(e.logo.dark),e.logo?.light!=null&&r.add(e.logo.light),e.favicon!=null&&r.add(e.favicon),e.backgroundImage?.dark!=null&&r.add(e.backgroundImage.dark),e.backgroundImage?.light!=null&&r.add(e.backgroundImage.light),e.metadata?.["og:image"]!=null&&e.metadata["og:image"].type==="filepath"&&r.add(e.metadata["og:image"].value),e.metadata?.["og:logo"]!=null&&e.metadata["og:logo"].type==="filepath"&&r.add(e.metadata["og:logo"].value),e.metadata?.["twitter:image"]!=null&&e.metadata["twitter:image"].type==="filepath"&&r.add(e.metadata["twitter:image"].value),e.typography?.bodyFont!=null&&e.typography.bodyFont.variants.forEach(n=>{r.add(n.absolutePath)}),e.typography?.headingsFont!=null&&e.typography.headingsFont.variants.forEach(n=>{r.add(n.absolutePath)}),e.typography?.codeFont!=null&&e.typography.codeFont.variants.forEach(n=>{r.add(n.absolutePath)}),e.navigation.type==="productgroup"&&e.navigation.products.forEach(n=>{n.image!=null&&r.add(n.image)}),(await FFc({navigation:e.navigation,docsWorkspace:t})).forEach(n=>{r.add(n)}),e.js!=null&&e.js.files.forEach(n=>{r.add(n.absolutePath)}),r}async function FFc({navigation:e,docsWorkspace:t}){let r=new Set;switch(e.type){case"untabbed":await Promise.all(e.items.map(i=>wVa({item:i,filepaths:r,docsWorkspace:t})));break;case"tabbed":await Promise.all(e.items.map(async i=>{i.icon!=null&&await JXn({iconPath:i.icon,filepaths:r,docsWorkspace:t}),i.child.type==="layout"&&i.child.layout!=null&&await Promise.all(i.child.layout.map(n=>wVa({item:n,filepaths:r,docsWorkspace:t})))}));break;case"versioned":await Promise.all(e.versions.map(async i=>{i.landingPage!=null&&await wVa({item:i.landingPage,filepaths:r,docsWorkspace:t}),(await FFc({navigation:i.navigation,docsWorkspace:t})).forEach(a=>r.add(a))}));break;case"productgroup":await Promise.all(e.products.map(async i=>{i.landingPage!=null&&await wVa({item:i.landingPage,filepaths:r,docsWorkspace:t}),(await FFc({navigation:i.navigation,docsWorkspace:t})).forEach(a=>r.add(a))}));break}return r}async function wVa({item:e,filepaths:t,docsWorkspace:r}){switch(e.type){case"page":e.icon!=null&&await JXn({iconPath:e.icon,filepaths:t,docsWorkspace:r});break;case"section":e.icon!=null&&await JXn({iconPath:e.icon,filepaths:t,docsWorkspace:r}),await Promise.all(e.contents.map(i=>wVa({item:i,filepaths:t,docsWorkspace:r})));break;case"apiSection":e.icon!=null&&await JXn({iconPath:e.icon,filepaths:t,docsWorkspace:r});break;case"link":e.icon!=null&&await JXn({iconPath:e.icon,filepaths:t,docsWorkspace:r});break;case"changelog":e.icon!=null&&await JXn({iconPath:e.icon,filepaths:t,docsWorkspace:r});break}}async function seh({navigation:e,apiWorkspaces:t,visitor:r,context:i}){VOM(e)?await Promise.all(e.map(async n=>{n.layout!=null&&await Promise.all(n.layout.map(async a=>{await LFc({navigationItem:a,visitor:r,apiWorkspaces:t,context:i})}))})):await Promise.all(e.map(async n=>{await LFc({navigationItem:n,visitor:r,apiWorkspaces:t,context:i})}))}async function LFc({navigationItem:e,visitor:t,apiWorkspaces:r,context:i}){if(await Ver(e,{alphabetized:$o,api:$o,apiName:$o,audiences:$o,displayErrors:$o,snippets:$o,summary:$o,title:$o,layout:$o,icon:$o,slug:$o,hidden:$o,skipSlug:$o,paginated:$o,playground:$o,flattened:$o,path:$o,page:$o,featureFlag:$o,openrpc:$o,contents:async n=>{n!=null&&await Promise.all(n.map(async a=>{await LFc({navigationItem:a,visitor:t,apiWorkspaces:r,context:i})}))},viewers:$o,orphaned:$o,availability:$o}),UOM(e)){let n=r.find(a=>a.workspaceName===e.apiName);n!=null&&await t.apiSection?.({config:e,workspace:n,context:i})}}function UOM(e){return e.api!=null}function VOM(e){return e[0]?.tab!=null}function Kee(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}ceh.default.extend(leh.default);var WOM=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),rvu=0,HOM=async({ir:e})=>(rvu++,`${e.apiName.snakeCase.unsafeName}-${rvu}`),$OM=async({api:e})=>(rvu++,`${e.id}-${rvu}`),uJt=class{domain;docsWorkspace;ossWorkspaces;apiWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;registerApiV2;constructor(t,r,i,n,a,u,c=WOM,d=HOM,s=$OM){this.domain=t,this.docsWorkspace=r,this.ossWorkspaces=i,this.apiWorkspaces=n,this.taskContext=a,this.editThisPage=u,this.uploadFiles=c,this.registerApi=d,this.registerApiV2=s}#e=khu.init();_parsedDocsConfig;get parsedDocsConfig(){if(this._parsedDocsConfig==null)throw new Error("parsedDocsConfig is not set");return this._parsedDocsConfig}collectedFileIds=new Map;markdownFilesToFullSlugs=new Map;markdownFilesToNoIndex=new Map;markdownFilesToTags=new Map;rawMarkdownFiles={};async resolve(){this._parsedDocsConfig=await WZs({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig});for(let[o,l]of Object.entries(this.parsedDocsConfig.pages))this.rawMarkdownFiles[za.of(o)]=l;let t=this.parsedDocsConfig.experimental?.openapiParserV3,r=t!=null&&!t;this.docsWorkspace.config.navigation!=null&&r&&await seh({navigation:this.docsWorkspace.config.navigation,visitor:{apiSection:async({workspace:o})=>{(await o.toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,preserveSchemaIds:!0,objectQueryParameters:!0,respectReadonlySchemas:!0})).changelog?.files.forEach(v=>{let g=BT(this.docsWorkspace.absoluteFilePath,v.absoluteFilepath);this.parsedDocsConfig.pages[g]=v.contents,this.rawMarkdownFiles[za.of(g)]=v.contents})}},apiWorkspaces:this.apiWorkspaces,context:this.taskContext}),this.markdownFilesToFullSlugs=await this.getMarkdownFilesToFullSlugs(this.parsedDocsConfig.pages),this.markdownFilesToNoIndex=await this.getMarkdownFilesToNoIndex(this.parsedDocsConfig.pages),this.markdownFilesToTags=await this.getMarkdownFilesToTags(this.parsedDocsConfig.pages);for(let[o,l]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[za.of(o)]=await pRc({markdown:l,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(o),context:this.taskContext});for(let[o,l]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[za.of(o)]=await dRc({markdown:l,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(o),context:this.taskContext});let i=await ueh({parsedDocsConfig:this.parsedDocsConfig,docsWorkspace:this.docsWorkspace});for(let[o,l]of Object.entries(this.parsedDocsConfig.pages))try{let{filepaths:v,markdown:g}=Ean(l,{absolutePathToMarkdownFile:this.resolveFilepath(o),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath});this.parsedDocsConfig.pages[za.of(o)]=g;for(let O of v)i.add(O)}catch(v){throw this.taskContext.logger.error(`Failed to parse ${o}: ${v instanceof Error?v.message:String(v)}`),v}let n=Array.from(i).map(o=>({absoluteFilePath:o,relativeFilePath:this.toRelativeFilepath(o)}));(await this.uploadFiles(n)).forEach(o=>{this.collectedFileIds.set(o.absoluteFilePath,o.fileId)});let u=await this.getMarkdownFilesToFullyQualifiedPathNames();for(let[o,l]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[za.of(o)]=fRc(l,this.collectedFileIds,u,{absolutePathToMarkdownFile:this.resolveFilepath(o),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);let c={};Object.entries(this.parsedDocsConfig.pages).forEach(([o,l])=>{let v=GOM(this.editThisPage,o),g=this.rawMarkdownFiles[za.of(o)];c[ZQt.PageId(o)]={markdown:l,editThisPageUrl:v?ZQt.Url(v):void 0,rawMarkdown:g}});let d=await this.convertDocsConfiguration(),s={};if(this._parsedDocsConfig.experimental?.mdxComponents!=null){let o=new Set;await Promise.all(this._parsedDocsConfig.experimental.mdxComponents.map(async l=>{let v=$v(this.docsWorkspace.absoluteFilePath,l);(await(0,ivu.stat)(v)).isDirectory()?(await Wae(v,"{js,ts,jsx,tsx,md,mdx}")).forEach(m=>{o.add(m)}):v.match(/\.(js|ts|jsx|tsx|md|mdx)$/)!=null&&o.add(v)})),s=Object.fromEntries(await Promise.all([...o].map(async l=>{let v=this.toRelativeFilepath(l),g=(await(0,ivu.readFile)(l)).toString();return[v,g]})))}return{config:d,pages:c,jsFiles:s}}resolveFilepath(t){if(t!=null)return $v(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return BT(this.docsWorkspace.absoluteFilePath,t)}async getMarkdownFilesToFullSlugs(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,tvu.default)(n).data.slug;typeof u=="string"&&u.trim().length>0&&r.set(this.resolveFilepath(i),u.trim())}return r}async getMarkdownFilesToNoIndex(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,tvu.default)(n).data.noindex;typeof u=="boolean"&&r.set(this.resolveFilepath(i),u)}return r}async getMarkdownFilesToTags(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,tvu.default)(n).data.tags;typeof u=="string"?r.set(this.resolveFilepath(i),u.split(",").map(c=>c.trim()).filter(c=>c.length>0)):Array.isArray(u)&&r.set(this.resolveFilepath(i),u)}return r}async getMarkdownFilesToFullyQualifiedPathNames(){let t={},r=Do.migrate.FernNavigationV1ToLatest.create().root(await this.toRootNode());return Do.NodeCollector.collect(r).slugMap.forEach((n,a)=>{if(n==null||!Do.isPage(n))return;let u=Do.getPageId(n);if(u==null)return;let c=Bu(this.docsWorkspace.absoluteFilePath,za.of(u));t[c]=a}),t}getDocsBasePath(){return new URL(Kee(this.domain)).pathname}async convertDocsConfiguration(){let t=await this.toRootNode();return{aiChatConfig:this.parsedDocsConfig.aiChatConfig!=null?{model:this.parsedDocsConfig.aiChatConfig.model,systemPrompt:this.parsedDocsConfig.aiChatConfig.systemPrompt}:void 0,hideNavLinks:void 0,title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?ZQt.Url(this.parsedDocsConfig.logo?.href):void 0,favicon:this.getFileId(this.parsedDocsConfig.favicon),navigation:void 0,root:t,colorsV3:this.convertColorConfigImageReferences(),navbarLinks:this.parsedDocsConfig.navbarLinks?.map(i=>({...i,url:ZQt.Url(i.url)})),typographyV2:this.convertDocsTypographyConfiguration(),layout:this.parsedDocsConfig.layout,css:this.parsedDocsConfig.css,js:this.convertJavascriptConfiguration(),metadata:this.convertMetadata(),redirects:this.parsedDocsConfig.redirects,integrations:this.parsedDocsConfig.integrations,footerLinks:this.parsedDocsConfig.footerLinks?.map(i=>({...i,value:ZQt.Url(i.value)})),defaultLanguage:this.parsedDocsConfig.defaultLanguage,analyticsConfig:{...this.parsedDocsConfig.analyticsConfig,segment:this.parsedDocsConfig.analyticsConfig?.segment,fullstory:this.parsedDocsConfig.analyticsConfig?.fullstory,intercom:this.parsedDocsConfig.analyticsConfig?.intercom?{appId:this.parsedDocsConfig.analyticsConfig.intercom.appId,apiBase:this.parsedDocsConfig.analyticsConfig.intercom.apiBase}:void 0,posthog:this.parsedDocsConfig.analyticsConfig?.posthog?{apiKey:this.parsedDocsConfig.analyticsConfig.posthog.apiKey,endpoint:this.parsedDocsConfig.analyticsConfig.posthog.endpoint}:void 0,gtm:this.parsedDocsConfig.analyticsConfig?.gtm?{containerId:this.parsedDocsConfig.analyticsConfig.gtm.containerId}:void 0,ga4:this.parsedDocsConfig.analyticsConfig?.ga4?{measurementId:this.parsedDocsConfig.analyticsConfig.ga4.measurementId}:void 0,amplitude:void 0,mixpanel:void 0,hotjar:void 0,koala:void 0,logrocket:void 0,pirsch:void 0,plausible:void 0,fathom:void 0,clearbit:void 0,heap:void 0},announcement:this.parsedDocsConfig.announcement!=null?{text:this.parsedDocsConfig.announcement.message}:void 0,logo:void 0,logoV2:void 0,colors:void 0,colorsV2:void 0,typography:void 0,backgroundImage:void 0}}getFernWorkspaceForApiSection(t){if(t.apiName!=null){let i=this.apiWorkspaces.find(n=>n.workspaceName===t.apiName);if(i!=null)return i}else if(this.apiWorkspaces.length===1&&this.apiWorkspaces[0]!=null)return this.apiWorkspaces[0];let r=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs`:"Failed to load API Definition referenced in docs";throw new Error(r)}getOpenApiWorkspaceForApiSection(t){if(t.apiName!=null){let i=this.ossWorkspaces.find(n=>n.workspaceName===t.apiName);if(i!=null)return i}else if(this.ossWorkspaces.length===1&&this.ossWorkspaces[0]!=null)return this.ossWorkspaces[0];let r=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs`:"Failed to load API Definition referenced in docs";throw new Error(r)}async toRootNode(){let t=Do.V1.SlugGenerator.init(Do.slugjoin(this.getDocsBasePath())),r=this.#e.get("root"),i=await this.toRootChild(t);return{type:"root",version:"v1",id:r,child:i,slug:t.get(),title:this.parsedDocsConfig.title??"Documentation",hidden:!1,icon:void 0,pointsTo:void 0,authed:void 0,viewers:void 0,orphaned:void 0,roles:this.parsedDocsConfig.roles?.map(n=>Do.RoleId(n)),featureFlags:void 0}}async toRootChild(t){return y8n(this.parsedDocsConfig.navigation)._visit({untabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),tabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),versioned:r=>this.toVersionedNode(r,t),productgroup:r=>this.toProductGroupNode({landingPageConfig:this.parsedDocsConfig.landingPage,productGroup:r,parentSlug:t})})}toLandingPageNode(t,r){let i=Do.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??TT(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{type:"landingPage",id:this.#e.get(i),title:t.title,slug:n.get(),icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toUnversionedNode({landingPage:t,navigationConfig:r,parentSlug:i}){let n=this.#e.get("unversioned"),a=t!=null?this.toLandingPageNode(t,i):void 0,u=r.type==="tabbed"?await this.convertTabbedNavigation(n,r.items,i):await this.toSidebarRootNode(n,r.items,i);return{type:"unversioned",id:n,landingPage:a,child:u}}async toVersionedNode(t,r){return{id:this.#e.get("versioned"),type:"versioned",children:await Promise.all(t.versions.map((n,a)=>this.toVersionNode(n,r,a===0)))}}async toProductGroupNode({productGroup:t,landingPageConfig:r,parentSlug:i}){let n=this.#e.get("productgroup"),a=r!=null?this.toLandingPageNode(r,i):void 0;return{id:n,type:"productgroup",landingPage:a,children:await Promise.all(t.products.map(u=>this.toProductNode(u,i)))}}async toProductNode(t,r){let i=r.setProductSlug(t.slug??TT(t.product)),n;switch(t.navigation.type){case"tabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.convertTabbedNavigation(this.#e.get(t.product),t.navigation.items,i)};break;case"untabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.toSidebarRootNode(this.#e.get(t.product),t.navigation.items,i)};break;case"versioned":n=await this.toVersionedNode(t.navigation,i);break;default:Ao(t.navigation)}return{type:"product",id:this.#e.get(t.product),productId:Do.V1.ProductId(t.product),title:t.product,subtitle:t.subtitle??"",slug:i.get(),child:n,default:!1,hidden:void 0,authed:void 0,icon:t.icon,image:t.image!=null?this.getFileId(t.image):void 0,pointsTo:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}async toVersionNode(t,r,i){let n=this.#e.get(t.version),a=r.setVersionSlug(t.slug??TT(t.version)),u=t.navigation.type==="tabbed"?await this.convertTabbedNavigation(n,t.navigation.items,a):await this.toSidebarRootNode(n,t.navigation.items,a);return{type:"version",id:n,versionId:Do.VersionId(t.version),title:t.version,slug:a.get(),child:u,default:i,availability:t.availability!=null?QOM(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,a):void 0,hidden:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,icon:void 0,pointsTo:void 0,featureFlags:t.featureFlags}}async toSidebarRootNode(t,r,i){let n=this.#e.get(`${t}/root`),a=await Promise.all(r.map(c=>this.toNavigationChild(n,c,i))),u=[];return a.forEach(c=>{if(c.type==="apiReference"){u.push(c);return}if(c.type==="section"&&!c.collapsed){u.push(c);return}let d=u.length>0?u[u.length-1]:void 0,s;d?.type==="sidebarGroup"?s=d:(s={id:this.#e.get(`${n}/group`),type:"sidebarGroup",children:[]},u.push(s)),s.children.push(c)}),{type:"sidebarRoot",id:n,children:u}}async toNavigationChild(t,r,i,n){return y8n(r)._visit({page:async a=>this.toPageNode(a,i,n),apiSection:async a=>this.toApiSectionNode(a,i,n),section:async a=>this.toSectionNode(t,a,i,n),link:async a=>this.toLinkNode(a),changelog:async a=>this.toChangelogNode(a,i,n)})}async toApiSectionNode(t,r,i){if(t.openrpc!=null){let v=$v(this.docsWorkspace.absoluteFilePath,za.of(t.openrpc));if(!await Cf(v))throw new Error(`OpenRPC file does not exist at path: ${v}`);let g=await oeh(v,this.taskContext);if(g==null)throw new Error("Failed to generate API Definition from OpenRPC document");return await this.registerApiV2({api:g,apiName:t.apiName,snippetsConfig:eyu(t.snippetsConfiguration)}),new _Va(t,g,r,void 0,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,this.#e,i).get()}if(this.parsedDocsConfig.experimental?.openapiParserV2){let v=this.getOpenApiWorkspaceForApiSection(t),g=eyu(t.snippetsConfiguration),O=await jVa(v,this.taskContext);if(O==null)throw new Error("Failed to generate API Definition from OpenAPI workspace");return await this.registerApiV2({api:O,snippetsConfig:g,apiName:t.apiName}),new _Va(t,O,r,v,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,this.#e,i).get()}let n=eyu(t.snippetsConfiguration),a,u=await this.getFernWorkspaceForApiSection(t).toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,objectQueryParameters:!0,preserveSchemaIds:!0}),c=this.parsedDocsConfig.experimental?.openapiParserV3;if(c==null||c)try{a=await this.getOpenApiWorkspaceForApiSection(t).getIntermediateRepresentation({context:this.taskContext,audiences:t.audiences,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1})}catch{}a==null&&(a=bx({workspace:u,audiences:t.audiences,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!0},readme:void 0,version:void 0,packageName:void 0,context:this.taskContext,sourceResolver:new yx(this.taskContext,u)}));let s=await this.registerApi({ir:a,snippetsConfig:n,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName,workspace:u}),o=hVa({ir:a,apiDefinitionId:s,playgroundConfig:{oauth:t.playground?.oauth},context:this.taskContext});return new Xhu(t,o,r,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,this.#e,u,i).get()}async toChangelogNode(t,r,i){return new UPi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:t.icon,viewers:t.viewers,hidden:i||t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:Do.V1.Url(t.url),icon:t.icon}}async toPageNode(t,r,i){let n=Do.PageId(this.toRelativeFilepath(t.absolutePath)),a=r.apply({urlSlug:t.slug??TT(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(n),type:"page",slug:a.get(),title:t.title,icon:t.icon,hidden:i||t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:n,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags,availability:t.availability}}async toSectionNode(t,r,i,n){let a=this.toRelativeFilepath(r.overviewAbsolutePath),u=a?Do.PageId(a):void 0,c=this.#e.get(u??`${t}/section`),d=i.apply({urlSlug:r.slug??TT(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug}),s=r.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(r.overviewAbsolutePath):void 0,o=n||r.hidden;return{id:c,type:"section",overviewPageId:u,slug:d.get(),title:r.title,icon:r.icon,collapsed:r.collapsed,hidden:o,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(l=>this.toNavigationChild(c,l,d,o))),authed:void 0,pointsTo:void 0,noindex:s,featureFlags:r.featureFlags,availability:r.availability}}async convertTabbedNavigation(t,r,i){let n=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:n,children:await Promise.all(r.map(a=>this.toTabChild(n,a,i)))}}async toTabChild(t,r,i){return y8n(r.child)._visit({link:({href:n})=>this.toTabLinkNode(r,n),layout:({layout:n})=>this.toTabNode(t,r,n,i),changelog:({changelog:n})=>this.toTabChangelogNode(r,n,i)})}async toTabChangelogNode(t,r,i){return new UPi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:i,title:t.title,icon:t.icon,viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r){return{type:"link",id:this.#e.get(r),title:t.title,url:Do.V1.Url(r),icon:t.icon}}async toTabNode(t,r,i,n){let a=this.#e.get(`${t}/tab`),u=n.apply({urlSlug:r.slug??TT(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:u.get(),icon:r.icon,hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNode(a,i,u),featureFlags:r.featureFlags}}getFileId(t){if(t==null)return;let r=this.collectedFileIds.get(t);return r==null?this.taskContext.failAndThrow("Failed to locate file after uploading: "+t):ZQt.FileId(r)}convertColorConfigImageReferences(){let{colors:t}=this.parsedDocsConfig;if(t!=null)return t.type==="dark"?{...t,...this.convertLogoAndBackgroundImage({theme:"dark"})}:t.type==="light"?{...t,...this.convertLogoAndBackgroundImage({theme:"light"}),type:"light"}:{...t,dark:{...t.dark,...this.convertLogoAndBackgroundImage({theme:"dark"})},light:{...t.light,...this.convertLogoAndBackgroundImage({theme:"light"})}}}convertLogoAndBackgroundImage({theme:t}){let{logo:r,backgroundImage:i}=this.parsedDocsConfig,n=r?.[t],a=i?.[t];return{logo:this.getFileId(n),backgroundImage:this.getFileId(a)}}convertDocsTypographyConfiguration(){if(this.parsedDocsConfig.typography!=null)return{headingsFont:this.convertFont(this.parsedDocsConfig.typography.headingsFont,"headings"),bodyFont:this.convertFont(this.parsedDocsConfig.typography.bodyFont,"body"),codeFont:this.convertFont(this.parsedDocsConfig.typography.codeFont,"code")}}convertFont(t,r){if(t==null||t.variants[0]==null)return;let i=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${i}`,variants:t.variants.map(n=>({fontFile:this.getFileId(n.absolutePath),weight:n.weight,style:n.style!=null?[n.style]:void 0})),display:t.display,fallback:t.fallback,fontVariationSettings:t.fontVariationSettings}}convertJavascriptConfiguration(){if(this.parsedDocsConfig.js!=null)return{files:this.parsedDocsConfig.js.files.map(({absolutePath:t,strategy:r})=>({fileId:this.getFileId(t),strategy:r})).filter(yy),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:ZQt.Url(t.url)})),inline:void 0}}convertMetadata(){if(this.parsedDocsConfig.metadata==null)return;let{"og:image":t,"og:logo":r,"twitter:image":i,...n}=this.parsedDocsConfig.metadata;return{...n,"og:image":this.convertFileIdOrUrl(t),"og:logo":this.convertFileIdOrUrl(r),"twitter:image":this.convertFileIdOrUrl(i)}}convertFileIdOrUrl(t){if(t!=null)return y8n(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:ZQt.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function GOM(e,t){if(e?.github==null)return;let{owner:r,repo:i,branch:n="main",host:a="https://github.com"}=e.github;return`${Kee(a)}/${r}/${i}/blob/${n}/fern/${t}?plain=1`}function QOM(e){switch(e){case"beta":return Do.V1.NavigationV1Availability.Beta;case"deprecated":return Do.V1.NavigationV1Availability.Deprecated;case"ga":return Do.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return Do.V1.NavigationV1Availability.Stable;default:Ao(e)}}async function R$(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof D3?t:null))).filter(yy)}async function UFc(e,t,r){if(e instanceof wor){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof D3))return;let i=await e.getIntermediateRepresentation({context:t,audiences:r,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1});return Jee({ir:i,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0},playgroundConfig:{oauth:!0},context:t})}var wlh=ui(HFc(),1),Slh=ui(Ivu(),1),Dlh=ui(require("http"),1),Elh=ui(require("path"),1);var Lnh=require("events"),Fvu=ui(require("fs"),1),xon=ui(require("path"),1);var Pnh=ui(require("os"),1),jnh=300,m7i=20,GVa=1e7,wnh=Pnh.default.platform();var qEM=wnh==="darwin",L4c=wnh==="win32",P7i=qEM||L4c,Snh=3e3,Dnh=2e4,U4c=1250;var uur;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(uur||(uur={}));var zon;(function(e){e.CHANGE="change",e.RENAME="rename"})(zon||(zon={}));var QVa;(function(e){e.CHANGE="change",e.ERROR="error"})(QVa||(QVa={}));var F0;(function(e){e.ADD="add",e.ADD_DIR="addDir",e.CHANGE="change",e.RENAME="rename",e.RENAME_DIR="renameDir",e.UNLINK="unlink",e.UNLINK_DIR="unlinkDir"})(F0||(F0={}));var Zee;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(Zee||(Zee={}));var TEM=(e,t=1,r)=>{t=Math.max(1,t);let i=r?.leading??!1,n=r?.trailing??!0,a=Math.max(r?.maxWait??1/0,t),u,c,d=0,s=0,o=()=>{let E=Date.now(),T=E-d,z=E-s,G=T>=t||z>=a;return[E,G]},l=E=>{if(s=E,!u)return;let T=u;u=void 0,e.apply(void 0,T)},v=()=>{A(0)},g=()=>{c&&(v(),l(Date.now()))},O=E=>{if(s=E,i)return l(E)},m=E=>{if(n&&u)return l(E);u=void 0},P=()=>{c=void 0;let[E,T]=o();return T?m(E):D(E)},D=E=>{let T=E-d,z=E-s,G=t-T,I=a-z,R=Math.min(G,I);return A(R)},A=E=>{c&&clearTimeout(c),!(E<=0)&&(c=setTimeout(P,E))},M=(...E)=>{let[T,z]=o(),G=!!c;if(u=E,d=T,(z||!c)&&A(t),z)return G?l(T):O(T)};return M.cancel=v,M.flush=g,M},zvu=TEM;var $4c=ui(require("fs"),1),Rvu=ui(require("path"),1);var LM=ui(require("fs"),1),N$=require("util");var $Pi=(e,t)=>function(...i){return e.apply(void 0,i).catch(t)},sur=(e,t)=>function(...i){try{return e.apply(void 0,i)}catch(n){return t(n)}};var V4c=ui(require("process"),1),Enh=V4c.default.getuid?!V4c.default.getuid():!1,Mnh=1e4,ise=()=>{};var JVa={isChangeErrorOk:e=>{if(!JVa.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!Enh&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!JVa.isNodeError(e))return!1;let{code:t}=e;return t==="EMFILE"||t==="ENFILE"||t==="EAGAIN"||t==="EBUSY"||t==="EACCESS"||t==="EACCES"||t==="EACCS"||t==="EPERM"},onChangeError:e=>{if(!JVa.isNodeError(e))throw e;if(!JVa.isChangeErrorOk(e))throw e}},Z6=JVa;var W4c=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=Mnh,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(i),i=()=>t(r);this.add(i)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},Anh=new W4c;var GPi=(e,t)=>function(i){return function n(...a){return Anh.schedule().then(u=>{let c=s=>(u(),s),d=s=>{if(u(),Date.now()>=i)throw s;if(t(s)){let o=Math.round(100*Math.random());return new Promise(v=>setTimeout(v,o)).then(()=>n.apply(void 0,a))}throw s};return e.apply(void 0,a).then(c,d)})}},QPi=(e,t)=>function(i){return function n(...a){try{return e.apply(void 0,a)}catch(u){if(Date.now()>i)throw u;if(t(u))return n.apply(void 0,a);throw u}}};var CEM={attempt:{chmod:$Pi((0,N$.promisify)(LM.default.chmod),Z6.onChangeError),chown:$Pi((0,N$.promisify)(LM.default.chown),Z6.onChangeError),close:$Pi((0,N$.promisify)(LM.default.close),ise),fsync:$Pi((0,N$.promisify)(LM.default.fsync),ise),mkdir:$Pi((0,N$.promisify)(LM.default.mkdir),ise),realpath:$Pi((0,N$.promisify)(LM.default.realpath),ise),stat:$Pi((0,N$.promisify)(LM.default.stat),ise),unlink:$Pi((0,N$.promisify)(LM.default.unlink),ise),chmodSync:sur(LM.default.chmodSync,Z6.onChangeError),chownSync:sur(LM.default.chownSync,Z6.onChangeError),closeSync:sur(LM.default.closeSync,ise),existsSync:sur(LM.default.existsSync,ise),fsyncSync:sur(LM.default.fsync,ise),mkdirSync:sur(LM.default.mkdirSync,ise),realpathSync:sur(LM.default.realpathSync,ise),statSync:sur(LM.default.statSync,ise),unlinkSync:sur(LM.default.unlinkSync,ise)},retry:{close:GPi((0,N$.promisify)(LM.default.close),Z6.isRetriableError),fsync:GPi((0,N$.promisify)(LM.default.fsync),Z6.isRetriableError),open:GPi((0,N$.promisify)(LM.default.open),Z6.isRetriableError),readFile:GPi((0,N$.promisify)(LM.default.readFile),Z6.isRetriableError),rename:GPi((0,N$.promisify)(LM.default.rename),Z6.isRetriableError),stat:GPi((0,N$.promisify)(LM.default.stat),Z6.isRetriableError),write:GPi((0,N$.promisify)(LM.default.write),Z6.isRetriableError),writeFile:GPi((0,N$.promisify)(LM.default.writeFile),Z6.isRetriableError),closeSync:QPi(LM.default.closeSync,Z6.isRetriableError),fsyncSync:QPi(LM.default.fsyncSync,Z6.isRetriableError),openSync:QPi(LM.default.openSync,Z6.isRetriableError),readFileSync:QPi(LM.default.readFileSync,Z6.isRetriableError),renameSync:QPi(LM.default.renameSync,Z6.isRetriableError),statSync:QPi(LM.default.statSync,Z6.isRetriableError),writeSync:QPi(LM.default.writeSync,Z6.isRetriableError),writeFileSync:QPi(LM.default.writeFileSync,Z6.isRetriableError)}},qnh=CEM;var xvu=ui(require("fs"),1),KVa=ui(require("path"),1);var H4c=()=>{};var BEM=()=>{let e=H4c,t=H4c,r=!1,i=!1;return{promise:new Promise((d,s)=>{e=o=>(r=!0,d(o)),t=o=>(i=!0,s(o))}),resolve:e,reject:t,isPending:()=>!r&&!i,isResolved:()=>r,isRejected:()=>i}},Tnh=BEM;var IEM=()=>{let{promise:e,resolve:t,isPending:r}=Tnh(),i=0,n=()=>{i+=1},a=()=>{i-=1,!i&&t()};return(()=>{n(),queueMicrotask(a)})(),{promise:e,isPending:r,increment:n,decrement:a}},Cnh=IEM;var Bnh={then:e=>{e()}};var Inh=e=>Array.isArray(e)?e:[e],znh=e=>typeof e=="function";var zEM=(e,t)=>{let r=t?.followSymlinks??!1,i=t?.depth??1/0,n=t?.limit??1/0,a=t?.ignore??[],u=Inh(a).map(De=>znh(De)?De:Ae=>De.test(Ae)),c=De=>u.some(Ae=>Ae(De)),d=t?.signal??{aborted:!1},s=t?.onDirents||(()=>{}),o=[],l=new Set,v={},g=[],O=new Set,m={},P=[],D=new Set,A={},M={},E=new Set,T={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},z={directories:o,directoriesNames:l,directoriesNamesToPaths:v,files:g,filesNames:O,filesNamesToPaths:m,symlinks:P,symlinksNames:D,symlinksNamesToPaths:A,map:M},{promise:G,increment:I,decrement:R}=Cnh(),U=0,Y=(De,Ae,Ct,Pe)=>{E.has(Ae)||U>=n||(U+=1,De.directories.push(Ae),De.directoriesNames.add(Ct),o.push(Ae),l.add(Ct),v.propertyIsEnumerable(Ct)||(v[Ct]=[]),v[Ct].push(Ae),E.add(Ae),!(Pe>=i)&&(U>=n||me(Ae,Pe+1)))},J=(De,Ae,Ct)=>{E.has(Ae)||U>=n||(U+=1,De.files.push(Ae),De.filesNames.add(Ct),g.push(Ae),O.add(Ct),m.propertyIsEnumerable(Ct)||(m[Ct]=[]),m[Ct].push(Ae),E.add(Ae))},X=(De,Ae,Ct,Pe)=>{E.has(Ae)||U>=n||(U+=1,De.symlinks.push(Ae),De.symlinksNames.add(Ct),P.push(Ae),D.add(Ct),A.propertyIsEnumerable(Ct)||(A[Ct]=[]),A[Ct].push(Ae),E.add(Ae),r&&(Pe>=i||U>=n||Le(Ae,Pe+1)))},ae=(De,Ae,Ct,Pe,St)=>{d.aborted||c(Ae)||(Pe.isDirectory()?Y(De,Ae,Ct,St):Pe.isFile()?J(De,Ae,Ct):Pe.isSymbolicLink()&&X(De,Ae,Ct,St))},pe=(De,Ae,Ct,Pe)=>{if(d.aborted)return;let St=Ae===KVa.default.sep?"":KVa.default.sep,at=Ct.name,Oe=`${Ae}${St}${at}`;c(Oe)||(Ct.isDirectory()?Y(De,Oe,at,Pe):Ct.isFile()?J(De,Oe,at):Ct.isSymbolicLink()&&X(De,Oe,at,Pe))},de=(De,Ae,Ct,Pe)=>{for(let St=0,at=Ct.length;St<at;St++)pe(De,Ae,Ct[St],Pe)},me=(De,Ae)=>{d.aborted||Ae>i||U>=n||(I(),xvu.default.readdir(De,{withFileTypes:!0},(Ct,Pe)=>{if(Ct||d.aborted||!Pe.length)return R();(s(Pe)||Bnh).then(()=>{let at=M[De]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};de(at,De,Pe,Ae),R()})}))},Le=(De,Ae)=>{I(),xvu.default.realpath(De,(Ct,Pe)=>{if(Ct||d.aborted)return R();xvu.default.stat(Pe,(St,at)=>{if(St||d.aborted)return R();let Oe=KVa.default.basename(Pe),je=M[De]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};ae(je,Pe,Oe,at,Ae),R()})})};return(async(De,Ae=1)=>(De=KVa.default.normalize(De),E.add(De),me(De,Ae),await G,d.aborted?T:z))(e)},xnh=zEM;var cur={lang:{debounce:zvu,attempt:e=>{try{return e()}catch(t){return cur.lang.castError(t)}},castArray:e=>cur.lang.isArray(e)?e:[e],castError:e=>cur.lang.isError(e)?e:cur.lang.isString(e)?new Error(e):new Error("Unknown error"),defer:e=>setTimeout(e,0),isArray:e=>Array.isArray(e),isError:e=>e instanceof Error,isFunction:e=>typeof e=="function",isNaN:e=>Number.isNaN(e),isNumber:e=>typeof e=="number",isPrimitive:e=>{if(e===null)return!0;let t=typeof e;return t!=="object"&&t!=="function"},isShallowEqual:(e,t)=>{if(e===t)return!0;if(cur.lang.isNaN(e))return cur.lang.isNaN(t);if(cur.lang.isPrimitive(e)||cur.lang.isPrimitive(t))return e===t;for(let r in e)if(!(r in t))return!1;for(let r in t)if(e[r]!==t[r])return!1;return!0},isSet:e=>e instanceof Set,isString:e=>typeof e=="string",isUndefined:e=>e===void 0,noop:()=>{},uniq:e=>e.length<2?e:Array.from(new Set(e))},fs:{getDepth:e=>Math.max(0,e.split(Rvu.default.sep).length-1),getRealPath:(e,t)=>{try{return t?$4c.default.realpathSync.native(e):$4c.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===Rvu.default.sep&&t.length-e.length>Rvu.default.sep.length,poll:(e,t=Dnh)=>qnh.retry.stat(t)(e,{bigint:!0}).catch(cur.lang.noop),readdir:async(e,t,r=1/0,i=1/0,n,a)=>{if(a&&r===1&&e in a){let u=a[e];return[u.directories,u.files]}else{let u=await xnh(e,{depth:r,limit:i,ignore:t,signal:n});return[u.directories,u.files]}}}},sP=cur;var Nvu=ui(require("path"),1);var G4c=class{constructor(t,r,i){this.base=i,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||sP.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=jnh){return(()=>{let r=this.watcher._readyWait,i=[],n=new Set,a=async(c,d)=>{let s=this.options.ignoreInitial?[]:c,o=await this.eventsPopulate([...d]),l=this.eventsDeduplicate([...s,...o]);this.onTargetEvents(l)},u=sP.lang.debounce(()=>{this.watcher.isClosed()||(r=a(i,n),i=[],n=new Set)},t);return async(c,d="",s=!1)=>{s?await this.eventsPopulate([d],i,!0):n.add(d),r.then(u)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((i,n)=>{let[a,u]=n,c=r[u];return a===c||a===F0.CHANGE&&c===F0.ADD||(r[u]=a,i.push(n)),i},[])}async eventsPopulate(t,r=[],i=!1){return await Promise.all(t.map(async n=>{let a=await this.watcher._poller.update(n,this.options.pollingTimeout);await Promise.all(a.map(async u=>{r.push([u,n]),u===F0.ADD_DIR?await this.eventsPopulateAddDir(t,n,r,i):u===F0.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,n,r,i)}))})),r}async eventsPopulateAddDir(t,r,i=[],n=!1){if(n)return i;let a=this.options.recursive?this.options.depth??m7i:Math.min(1,this.options.depth??m7i),u=this.options.limit??GVa,[c,d]=await sP.fs.readdir(r,this.options.ignore,a,u,this.watcher._closeSignal),s=[...c,...d];return await Promise.all(s.map(o=>{if(!this.watcher.isIgnored(o,this.options.ignore)&&!t.includes(o))return this.eventsPopulate([o],i,!0)})),i}async eventsPopulateUnlinkDir(t,r,i=[],n=!1){if(n)return i;for(let a of this.watcher._poller.stats.keys())sP.fs.isSubPath(r,a)&&(t.includes(a)||await this.eventsPopulate([a],i,!0));return i}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(F0.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!P7i&&this.options.native!==!1&&this.watcher.watchDirectory(t,this.options,this.handler,void 0,this.base||this),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAddDir(t,this.options.renameTimeout):this.watcher.event(F0.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(F0.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(Nvu.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(F0.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(Nvu.default.dirname(t),t,!1),this.watcher.watchersClose(t),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlinkDir(t,this.options.renameTimeout):this.watcher.event(F0.UNLINK_DIR,t))}onTargetEvent(t){let[r,i]=t;r===F0.ADD?this.onTargetAdd(i):r===F0.ADD_DIR?this.onTargetAddDir(i):r===F0.CHANGE?this.onTargetChange(i):r===F0.UNLINK?this.onTargetUnlink(i):r===F0.UNLINK_DIR&&this.onTargetUnlinkDir(i)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,i=!1){return this.handlerBatched(t,r,i)}onWatcherChange(t=zon.CHANGE,r){if(this.watcher.isClosed())return;let i=Nvu.default.resolve(this.folderPath,r||"");this.filePath&&i!==this.folderPath&&i!==this.filePath||this.watcher.isIgnored(i,this.options.ignore)||this.onWatcherEvent(t,i)}onWatcherError(t){L4c&&t.code==="EPERM"?this.onWatcherChange(zon.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(QVa.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(QVa.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(zon.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&P7i&&this.options.native!==!1?this.options.depth??m7i:Math.min(1,this.options.depth??m7i),i=this.options.limit??GVa,[n,a]=await sP.fs.readdir(this.folderPath,this.options.ignore,r,i,this.watcher._closeSignal,this.options.readdirMap),u=[this.folderPath,...n,...a];await Promise.all(u.map(c=>{if(!this.watcher._poller.stats.has(c)&&!this.watcher.isIgnored(c,this.options.ignore))return this.onWatcherEvent(zon.CHANGE,c,t)}))}}},Rnh=G4c;var kee={interval:100,intervalId:void 0,fns:new Map,init:()=>{kee.intervalId||(kee.intervalId=setInterval(kee.resolve,kee.interval))},reset:()=>{kee.intervalId&&(clearInterval(kee.intervalId),delete kee.intervalId)},add:(e,t)=>{kee.fns.set(e,Date.now()+t),kee.init()},remove:e=>{kee.fns.delete(e)},resolve:()=>{if(!kee.fns.size)return kee.reset();let e=Date.now();for(let[t,r]of kee.fns)r>=e||(kee.remove(t),t())}},YVa=kee;var XVa=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=U4c){let{ino:i,targetPath:n,events:a,locks:u}=t,c=()=>{let l=this._watcher._poller.paths.find(i||-1,v=>v!==n);if(l&&l!==n){if(sP.fs.getRealPath(n,!0)===l)return;this._watcher.event(a.rename,l,n)}else this._watcher.event(a.add,n)};if(!i)return c();let d=()=>{u.add.delete(i),YVa.remove(s)},s=()=>{d(),c()};YVa.add(s,r);let o=()=>{let l=u.unlink.get(i);if(!l)return;d();let v=l();n===v?a.change&&this._watcher._poller.stats.has(n)&&this._watcher.event(a.change,n):this._watcher.event(a.rename,v,n)};u.add.set(i,o),o()}getLockUnlink(t,r=U4c){let{ino:i,targetPath:n,events:a,locks:u}=t,c=()=>{this._watcher.event(a.unlink,n)};if(!i)return c();let d=()=>{u.unlink.delete(i),YVa.remove(s)},s=()=>{d(),c()};YVa.add(s,r);let o=()=>(d(),n);u.unlink.set(i,o),u.add.get(i)?.()}getLockTargetAdd(t,r){let i=this._watcher._poller.getIno(t,F0.ADD,uur.FILE);return this.getLockAdd({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let i=this._watcher._poller.getIno(t,F0.ADD_DIR,uur.DIR);return this.getLockAdd({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let i=this._watcher._poller.getIno(t,F0.UNLINK,uur.FILE);return this.getLockUnlink({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let i=this._watcher._poller.getIno(t,F0.UNLINK_DIR,uur.DIR);return this.getLockUnlink({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};XVa.DIR_EVENTS={add:F0.ADD_DIR,rename:F0.RENAME_DIR,unlink:F0.UNLINK_DIR};XVa.FILE_EVENTS={add:F0.ADD,change:F0.CHANGE,rename:F0.RENAME,unlink:F0.UNLINK};var Nnh=XVa;var Q4c=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(sP.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let i=this.map.get(t);if(sP.lang.isSet(i)){let n=i.delete(r);return i.size||this.map.delete(t),n}else if(i===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let i=this.map.get(t);if(sP.lang.isSet(i))return Array.from(i).find(r);if(r(i))return i}}get(t){return this.map.get(t)}has(t,r){if(sP.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let i=this.map.get(t);return sP.lang.isSet(i)?i.has(r):i===r}return!1}set(t,r){if(this.map.has(t)){let i=this.map.get(t);sP.lang.isSet(i)?i.add(r):i!==r&&this.map.set(t,new Set([i,r]))}else this.map.set(t,r);return this}},J4c=Q4c;var K4c=class{constructor(t){this.ino=t.ino<=Number.MAX_SAFE_INTEGER?Number(t.ino):t.ino,this.size=Number(t.size),this.atimeMs=Number(t.atimeMs),this.mtimeMs=Number(t.mtimeMs),this.ctimeMs=Number(t.ctimeMs),this.birthtimeMs=Number(t.birthtimeMs),this._isFile=t.isFile(),this._isDirectory=t.isDirectory(),this._isSymbolicLink=t.isSymbolicLink()}isFile(){return this._isFile}isDirectory(){return this._isDirectory}isSymbolicLink(){return this._isSymbolicLink}},Fnh=K4c;var Y4c=class{constructor(){this.inos={},this.paths=new J4c,this.stats=new Map}getIno(t,r,i){let n=this.inos[r];if(!n)return;let a=n[t];if(a&&!(i&&a[1]!==i))return a[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let i=await sP.fs.poll(t,r);if(!(!i||!(i.isFile()||i.isDirectory())))return new Fnh(i)}reset(){this.inos={},this.paths=new J4c,this.stats=new Map}async update(t,r){let i=this.getStats(t),n=await this.poll(t,r);if(this.updateStats(t,n),!i&&n){if(n.isFile())return this.updateIno(t,F0.ADD,n),[F0.ADD];if(n.isDirectory())return this.updateIno(t,F0.ADD_DIR,n),[F0.ADD_DIR]}else if(i&&!n){if(i.isFile())return this.updateIno(t,F0.UNLINK,i),[F0.UNLINK];if(i.isDirectory())return this.updateIno(t,F0.UNLINK_DIR,i),[F0.UNLINK_DIR]}else if(i&&n){if(i.isFile()){if(n.isFile())return i.ino===n.ino&&!i.size&&!n.size?[]:(this.updateIno(t,F0.CHANGE,n),[F0.CHANGE]);if(n.isDirectory())return this.updateIno(t,F0.UNLINK,i),this.updateIno(t,F0.ADD_DIR,n),[F0.UNLINK,F0.ADD_DIR]}else if(i.isDirectory()){if(n.isFile())return this.updateIno(t,F0.UNLINK_DIR,i),this.updateIno(t,F0.ADD,n),[F0.UNLINK_DIR,F0.ADD];if(n.isDirectory())return i.ino===n.ino?[]:(this.updateIno(t,F0.UNLINK_DIR,i),this.updateIno(t,F0.ADD_DIR,n),[F0.UNLINK_DIR,F0.ADD_DIR])}}return[]}updateIno(t,r,i){let n=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=i.isFile()?uur.FILE:uur.DIR;n[t]=[i.ino,a]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let i=this.stats.get(t)?.ino||-1;this.paths.delete(i,t),this.stats.delete(t)}}},X4c=Y4c;var Z4c=class e extends Lnh.EventEmitter{constructor(t,r,i){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(Zee.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(n=>this.on(Zee.CLOSE,n)),this._readyWait=new Promise(n=>this.on(Zee.READY,n)),this._locker=new Nnh(this),this._roots=new Set,this._poller=new X4c,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,i)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(sP.lang.isFunction(r)?!!r(t):r.test(t))}isReady(){return this._ready}close(){return this._locker.reset(),this._poller.reset(),this._roots.clear(),this.watchersClose(),this.isClosed()?!1:(this._closed=!0,this.emit(Zee.CLOSE))}error(t){if(this.isClosed())return!1;let r=sP.lang.castError(t);return this.emit(Zee.ERROR,r)}event(t,r,i){return this.isClosed()?!1:(this.emit(Zee.ALL,t,r,i),this.emit(t,r,i))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(Zee.READY))}pollerExists(t,r){for(let i of this._pollers)if(i.targetPath===t&&sP.lang.isShallowEqual(i.options,r))return!0;return!1}subwatcherExists(t,r){for(let i of this._subwatchers)if(i.targetPath===t&&sP.lang.isShallowEqual(i.options,r))return!0;return!1}watchersClose(t,r,i=!0){if(t){let n=this._watchers[t];if(n)for(let a of[...n])r&&a.filePath!==r||this.watcherClose(a);if(i)for(let a in this._watchers)sP.fs.isSubPath(t,a)&&this.watchersClose(a,r,!1)}else for(let n in this._watchers)this.watchersClose(n,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,i]of t)this.watchPath(r,i.options,i.handler)}async watcherAdd(t,r){let{folderPath:i}=t;(this._watchers[i]=this._watchers[i]||[]).push(t);let a=new Rnh(this,t,r);return await a.init(),a}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let a=r.indexOf(t);r.splice(a,1),r.length||delete this._watchers[t.folderPath]}let i=t.filePath||t.folderPath;this._roots.has(i)&&(this._watchersRestorable[i]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=sP.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,i,n){if(this._watchers[t]?.find(c=>c.handler===i&&(!c.filePath||c.filePath===n)&&c.options.ignore===r.ignore&&!!c.options.native==!!r.native&&(!r.recursive||c.options.recursive)))return!0;let u=xon.default.dirname(t);for(let c=1;c<1/0;c++){if(this._watchers[u]?.find(o=>(c===1||o.options.recursive&&c<=(o.options.depth??m7i))&&o.handler===i&&(!o.filePath||o.filePath===n)&&o.options.ignore===r.ignore&&!!o.options.native==!!r.native&&(!r.recursive||o.options.recursive&&P7i&&o.options.native!==!1)))return!0;if(!P7i)break;let s=xon.default.dirname(t);if(u===s)break;u=s}return!1}async watchDirectories(t,r,i,n,a){if(this.isClosed())return;t=sP.lang.uniq(t).sort();let u;for(let c of t)if(!this.isIgnored(c,r.ignore)&&!this.watcherExists(c,r,i,n))try{let d=!r.recursive||P7i&&r.native!==!1?r:{...r,recursive:!1},o={watcher:Fvu.default.watch(c,d),handler:i,options:r,folderPath:c,filePath:n},l=u=await this.watcherAdd(o,a);if(this._roots.has(n||c)){let g={...r,ignoreInitial:!0,recursive:!1},O=xon.default.dirname(c),m=c;await this.watchDirectories([O],g,i,m,l)}}catch(d){this.error(d)}return u}async watchDirectory(t,r,i,n,a){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||P7i&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,i,n,a));{r={...r,recursive:!0};let u=r.depth??m7i,c=r.limit??GVa,[d]=await sP.fs.readdir(t,r.ignore,u,c,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let s=await this.watchDirectories([t],r,i,n,a);if(d.length){let o=sP.fs.getDepth(t);for(let l of d){let v=sP.fs.getDepth(l),g=Math.max(0,u-(v-o)),O={...r,depth:g};await this.watchDirectories([l],O,i,n,a||s)}}})}}}async watchFileOnce(t,r,i){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let n={targetPath:t,options:r},a=(s,o)=>{o===t&&(d(),i())},u=new e(a),c=()=>{this._subwatchers.add(n),this.on(Zee.CLOSE,d),u.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(n),this.removeListener(Zee.CLOSE,d),u.close()};return c()}async watchFile(t,r,i){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let n=xon.default.dirname(t);return this.watchDirectory(n,r,i,t)}async watchPollingOnce(t,r,i){if(this.isClosed())return;let n=!1,a=new X4c,u=await this.watchPolling(t,r,async()=>{n||!(await a.update(t,r.pollingTimeout)).length||n||(n=!0,u(),i())})}async watchPolling(t,r,i){if(this.isClosed())return sP.lang.noop;if(this.pollerExists(t,r))return sP.lang.noop;let n={...r,interval:r.pollingInterval??Snh},a={targetPath:t,options:r},u=()=>{this._pollers.add(a),this.on(Zee.CLOSE,c),Fvu.default.watchFile(t,n,i)},c=()=>{this._pollers.delete(a),this.removeListener(Zee.CLOSE,c),Fvu.default.unwatchFile(t,i)};return sP.lang.attempt(u),()=>sP.lang.attempt(c)}async watchUnknownChild(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchFileOnce(t,r,n)}async watchUnknownTarget(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchPollingOnce(t,r,n)}async watchPaths(t,r,i){if(this.isClosed())return;if(t=sP.lang.uniq(t).sort(),t.every((a,u)=>t.every((c,d)=>d===u||!sP.fs.isSubPath(a,c))))await Promise.all(t.map(a=>this.watchPath(a,r,i)));else for(let a of t)await this.watchPath(a,r,i)}async watchPath(t,r,i){if(this.isClosed()||(t=xon.default.resolve(t),this.isIgnored(t,r.ignore)))return;let n=await sP.fs.poll(t,r.pollingTimeout);if(n){if(n.isFile())return this.watchFile(t,r,i);if(n.isDirectory())return this.watchDirectory(t,r,i);this.error(`"${t}" is not supported`)}else{let a=xon.default.dirname(t);return(await sP.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,i):this.watchUnknownTarget(t,r,i)}}async watch(t,r,i=sP.lang.noop){if(sP.lang.isFunction(t))return this.watch([],{},t);if(sP.lang.isUndefined(t))return this.watch([],r,i);if(sP.lang.isFunction(r))return this.watch(t,{},r);if(sP.lang.isUndefined(r))return this.watch(t,{},i);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let n=sP.lang.castArray(t);n.forEach(a=>this._roots.add(a)),await this.watchPaths(n,r,i),!this.isClosed()&&(i!==sP.lang.noop&&this.on(Zee.ALL,i),r.readdirMap=void 0,this.ready())}},Lvu=Z4c;var eAM=ui(zah(),1),tAM=ui(c2c(),1),rAM=ui(d2c(),1),oWa=ui(Zvu(),1),uWa=ui(Hah(),1);var alh=ui(Abu(),1),tte=require("fs/promises"),olh=require("os"),ulh=ui($k(),1),slh=ui(nlh(),1),Gbu=process.platform==="win32",_CM="etag",hCM="preview",yCM="app-preview",vCM="bundle",bCM=".next",gCM="standalone",OCM=".fern",mCM="packages/fern-docs/bundle/.next/server/instrumentation.js",PCM=".npmrc",jCM=".pnpmfile.cjs",wCM="pnpm-workspace.yaml",SCM='Cannot find matching keyid: {"signatures":';function DCM(){return Bu($c.of((0,olh.homedir)()),za.of(OCM))}function Qbu({app:e=!1}){return Bu(DCM(),za.of(e?yCM:hCM))}function q7i({app:e=!1}){return Bu(Qbu({app:e}),za.of(e?bCM:vCM))}function EWa({app:e=!1}){return Bu(q7i({app:e}),za.of(gCM))}function ECM({app:e=!1}){return Bu(EWa({app:e}),za.of(mCM))}function MCM({app:e=!1}){return Bu(EWa({app:e}),za.of(wCM))}function ACM({app:e=!1}){return Bu(EWa({app:e}),za.of(jCM))}function qCM({app:e=!1}){return Bu(EWa({app:e}),za.of(PCM))}function Qon(e){return new Error(`${e}. Please reach out to support@buildwithfern.com.`)}function TCM({app:e=!1}){return Bu(Qbu({app:e}),za.of(_CM))}var CCM=`packages:
|
|
2331
|
+
]`;case 1:return`${n} Did you mean ${r[0]}?`;case 2:return`${n} Did you mean ${r[0]} or ${r[1]}?`;default:return`${n} Did you mean ${r[0]}, ${r[1]}, or ${r[2]}?`}}function Son(e){return`API section ${e} is specified multiple times, however will be only rendered once.`}function QgM(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}function BXn({children:e,findEndpointById:t,stringifyEndpointPathParts:r,disableEndpointPairs:i,apiDefinitionId:n}){if(i)return e;let a=[],u=new Map;return e.forEach(c=>{if(c.type!=="endpoint"){a.push(c);return}let d=t(c.endpointId);if(d==null)throw new Error(`Endpoint ${c.endpointId} not found`);let s=`${d.method} ${r(d)}`,o=u.get(s);if(u.set(s,c),o==null||o.isResponseStream===c.isResponseStream){a.push(c);return}let l=a.indexOf(o),v=c.isResponseStream?c:o,g=c.isResponseStream?o:c,O={id:Do.V1.NodeId(`${n}:${g.endpointId}+${v.endpointId}`),type:"endpointPair",stream:v,nonStream:g};a[l]=O}),a}function Khu({left:e,right:t,findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}){return BXn({children:[...e,...t],findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}).filter(u=>u.type==="apiPackage"?u.children.length>0:!0)}function kor(e,t){if(t!=null)return BT(e.absoluteFilePath,t)}function Yhu({docsWorkspace:e,page:t,parentSlug:r,idgen:i,markdownFilesToFullSlugs:n,markdownFilesToNoIndex:a,hideChildren:u}){let c=Do.V1.PageId(kor(e,t.absolutePath)),d=r.apply({fullSlug:n.get(t.absolutePath)?.split("/"),urlSlug:t.slug??TT(t.title)});return{id:i.get(c),type:"page",pageId:c,title:t.title,slug:d.get(),icon:t.icon,hidden:u||t.hidden,noindex:t.noindex||a.get(t.absolutePath),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,availability:t.availability}}var Xhu=class{apiSection;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;markdownFilesToTags;workspace;hideChildren;parentAvailability;apiDefinitionId;#e;#t=new Set;#r=new Set;#n=new Set;#i=new Set;#a=new Set;#o=new Map;#s=[];#f;#u;#c;disableEndpointPairs;constructor(t,r,i,n,a,u,c,d,s,o,l,v){this.apiSection=t,this.docsWorkspace=n,this.taskContext=a,this.markdownFilesToFullSlugs=u,this.markdownFilesToNoIndex=c,this.markdownFilesToTags=d,this.workspace=o,this.hideChildren=l,this.parentAvailability=v,this.disableEndpointPairs=n.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=Do.V1.ApiDefinitionId(r.id),this.#e=o7i.create(r,a),this.#c=s,this.#f=this.apiSection.overviewAbsolutePath!=null?Do.V1.PageId(kor(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let g=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#u=i.apply({fullSlug:g?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??TT(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#s=this.#l(this.apiSection.navigation,this.#e.api.rootPackage,this.#u)),this.#s=this.#y(this.#s.map(O=>this.#j(O)),this.#w(this.#e.api.rootPackage,this.#u))}get(){let t=Do.V1.followRedirects(this.#s),r=new UPi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,this.workspace?.changelog?.files.map(i=>i.absoluteFilepath),this.docsWorkspace,this.#c).orUndefined();return{id:this.#c.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#f,paginated:this.apiSection.paginated,slug:this.#u.get(),icon:this.apiSection.icon,hidden:this.hideChildren||this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#u,viewers:void 0,hidden:this.hideChildren}),children:this.#s,availability:this.apiSection.availability??this.parentAvailability,pointsTo:t,noindex:void 0,playground:this.#g(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}#l(t,r,i){r=this.#e.resolveSubpackage(r);let n=r!=null?o7i.getSubpackageId(r):void 0;return t.map(a=>lVa(a)._visit({link:u=>({id:this.#c.get(u.url),type:"link",title:u.text,icon:u.icon,url:Do.Url(u.url)}),page:u=>this.#p(u,i),package:u=>this.#_(u,i),section:u=>this.#h(u,i),item:({value:u})=>this.#v(u,n,i),endpoint:u=>this.#O(u,n,i)})).filter(yy)}#p(t,r){return Yhu({page:t,parentSlug:r,docsWorkspace:this.docsWorkspace,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex,idgen:this.#c,hideChildren:this.hideChildren})}#_(t,r){let i=t.overviewAbsolutePath!=null?Do.V1.PageId(kor(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#e.getSubpackageByIdOrLocator(t.package);if(a!=null){let u=o7i.getSubpackageId(a),c=this.#c.get(i??`${this.apiDefinitionId}:${u}`);this.#a.has(u)&&this.taskContext.logger.warn(Son(t.package)),this.#a.add(u),this.#o.set(c,[u]);let d=t.slug??(Zor(a)?a.urlSlug:this.apiSection.slug??TT(this.apiSection.title)),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#l(t.contents,a,s);return{id:c,type:"apiPackage",children:o,title:t.title??(Zor(a)?a.displayName??nJt(a.name):this.apiSection.title),slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:this.parentAvailability,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}else{this.taskContext.logger.warn(u7i(t.package,this.#e.subpackageLocators));let u=t.slug??TT(t.package),c=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),d=this.#l(t.contents,void 0,c);return{id:this.#c.get(i??`${this.apiDefinitionId}:${TT(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:c.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:this.parentAvailability,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}#h(t,r){let i=t.overviewAbsolutePath!=null?Do.V1.PageId(kor(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=t.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(t.overviewAbsolutePath):void 0,u=this.#c.get(i??n??r.get()),c=t.referencedSubpackages.map(l=>{let v=this.#e.getSubpackageByIdOrLocator(l),g=v!=null?o7i.getSubpackageId(v):void 0;if(g===void 0){this.taskContext.logger.error(u7i(l,this.#e.subpackageLocators));return}return{subpackageId:g,locator:l}}).filter(l=>l!=null).filter(yy);this.#o.set(u,c.map(l=>l.subpackageId)),c.forEach(l=>{this.#a.has(l.subpackageId)&&this.taskContext.logger.error(Son(l.locator)),this.#a.add(l.subpackageId)});let d=t.slug??TT(t.title),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#l(t.contents,void 0,s);return{id:u,type:"apiPackage",children:o,title:t.title,slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:this.parentAvailability,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:a,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}#v(t,r,i){t=t.trim();let n=this.#e.getSubpackageByIdOrLocator(t)??this.#e.getSubpackageByIdOrLocator(R_(t));if(n!=null){let a=o7i.getSubpackageId(n),u=this.#c.get(`${this.apiDefinitionId}:${a}`);this.#a.has(a)&&this.taskContext.logger.error(Son(t)),this.#a.add(a),this.#o.set(u,[a]);let c=Zor(n)?n.urlSlug:"",d=i.apply({urlSlug:c});return{id:u,type:"apiPackage",children:[],title:Zor(n)?n.displayName??nJt(n.name):this.apiSection.title,slug:d.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:this.parentAvailability,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}return this.#O({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,i)}#O(t,r,i){let n=(r!=null?this.#e.subpackages.get(h2.SubpackageId(r))?.endpoints.get(h2.EndpointId(t.endpoint)):void 0)??this.#e.endpointsByLocator.get(t.endpoint);if(n!=null){let c=this.#e.getEndpointId(n);if(c==null)this.taskContext.logger.error(`Expected Endpoint ID for ${n.id} at path: ${won(n.method,n.path.parts)}. Got undefined.`);else{this.#t.has(c)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${c}`),this.#t.add(c);let d=t.slug!=null?i.append(t.slug):i.apply(n);return{id:this.#c.get(`${this.apiDefinitionId}:${c}`),type:"endpoint",method:n.method,endpointId:c,apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(n.availability)??this.parentAvailability,isResponseStream:n.response?.type.type==="stream",title:t.title??n.name??mB(n.path.parts),slug:d.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}let a=(r!=null?this.#e.subpackages.get(h2.SubpackageId(r))?.webSockets.get(h2.WebSocketId(t.endpoint)):void 0)??this.#e.webSocketsByLocator.get(t.endpoint);if(a!=null){let c=this.#e.getWebSocketId(a);if(c==null)this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);else return this.#r.has(c)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${c}`),this.#r.add(c),{id:this.#c.get(`${this.apiDefinitionId}:${c}`),type:"webSocket",webSocketId:c,title:t.title??a.name??mB(a.path.parts),slug:(t.slug!=null?i.append(t.slug):i.apply(a)).get(),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(a.availability)??this.parentAvailability,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let u=(r!=null?this.#e.subpackages.get(h2.SubpackageId(r))?.webhooks.get(h2.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(Do.V1.WebhookId(t.endpoint));if(u!=null){let c=this.#e.getWebhookId(u);if(c==null)this.taskContext.logger.error(`Expected Webhook ID for ${u.id}. Got undefined.`);else return this.#n.has(c)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${c}`),this.#n.add(c),{id:this.#c.get(`${this.apiDefinitionId}:${c}`),type:"webhook",webhookId:c,method:u.method,title:t.title??u.name??Fb("/",...u.path),slug:(t.slug!=null?i.append(t.slug):i.apply(u)).get(),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:this.parentAvailability,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#y(t,r){return Khu({left:t,right:r,findEndpointById:i=>this.#e.endpoints.get(i),stringifyEndpointPathParts:i=>mB(i.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#j(t){return fVa({child:t,nodeIdToSubpackageId:this.#o,convertApiDefinitionPackageId:(r,i)=>this.#m(r,i),mergeAndFilterChildren:this.#y.bind(this)})}#w(t,r){let i=[];return t.endpoints.forEach(n=>{if(n.protocol?.type==="grpc"){let a=this.#e.getGrpcId(n);if(a==null){this.taskContext.logger.error(`Expected Grpc ID for ${n.id} at path: ${won(n.method,n.path.parts)}. Got undefined.`);return}if(this.#i.has(a))return;let u=r.apply(n);i.push({id:Do.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"grpc",grpcId:a,title:n.name??mB(n.path.parts),method:n.protocol?.methodType??"UNARY",apiDefinitionId:this.apiDefinitionId,availability:this.parentAvailability,slug:u.get(),icon:void 0,hidden:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}else{let a=this.#e.getEndpointId(n);if(a==null){this.taskContext.logger.error(`Expected Endpoint ID for ${n.id} at path: ${won(n.method,n.path.parts)}. Got undefined.`);return}if(this.#t.has(a))return;let u=r.apply(n);i.push({id:Do.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"endpoint",method:n.method,endpointId:a,apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(n.availability)??this.parentAvailability,isResponseStream:n.response?.type.type==="stream",title:n.name??mB(n.path.parts),slug:u.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}}),t.websockets.forEach(n=>{let a=this.#e.getWebSocketId(n);if(a==null){this.taskContext.logger.error(`Expected WebSocket ID for ${n.id}. Got undefined.`);return}this.#r.has(a)||i.push({id:Do.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webSocket",webSocketId:a,title:n.name??mB(n.path.parts),slug:r.apply(n).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(n.availability)??this.parentAvailability,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.webhooks.forEach(n=>{let a=this.#e.getWebhookId(n);if(a==null){this.taskContext.logger.error(`Expected Webhook ID for ${n.id}. Got undefined.`);return}this.#n.has(a)||i.push({id:Do.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webhook",webhookId:a,method:n.method,title:n.name??nJt(n.id),slug:r.apply(n).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:this.parentAvailability,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.subpackages.forEach(n=>{if(this.#a.has(n))return;let a=this.#e.getSubpackageByIdOrLocator(n);if(a==null){this.taskContext.logger.error(`Subpackage ${n} not found in ${this.apiDefinitionId}`);return}let u=Zor(a)?r.apply(a):r,c=this.#m(n,u);c.length>0&&i.push({id:Do.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"apiPackage",children:c,title:Zor(a)?a.displayName??nJt(a.name):this.apiSection.title,slug:u.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:this.parentAvailability,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&(i=i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,c=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(c)})),i}#m(t,r){let i=t!=null?this.#e.resolveSubpackage(this.#e.getSubpackageByIdOrLocator(t)):void 0;return i==null?(this.taskContext.logger.error(u7i(t||"unknown",[])),[]):this.#w(i,r)}#g(t){return Jhu(t)}mergeEndpointPairs(t){return BXn({children:t,findEndpointById:r=>this.#e.endpoints.get(r),stringifyEndpointPathParts:r=>mB(r.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var Zhu=class{#e={};#t={};#r={};#n={};constructor(t){for(let[r,i]of Object.entries(t.subpackages))this.#e[R_(r).toLowerCase()]=i,this.#e[`subpackage_${R_(r).toLowerCase()}`]=i;for(let[r,i]of Object.entries(t.endpoints)){this.#r[r]=i,this.#r[r.replace("endpoint_","")]=i,this.#r[r.replace("endpoint_","subpackage_")]=i;for(let n of[i.method,"STREAM"])i.environments?.forEach(a=>{this.#r[`${n} ${Fb(a.baseUrl,mB(i.path))}`]=i,this.#r[`${n} ${Fb(a.baseUrl,Y6e(i.path))}`]=i;let u=Qhu(a);u!=null&&(this.#r[`${n} ${Fb(u,mB(i.path))}`]=i,this.#r[`${n} ${Fb(u,Y6e(i.path))}`]=i)}),this.#r[`${i.method} ${mB(i.path)}`]=i,this.#r[`${i.method} ${Y6e(i.path)}`]=i}for(let[r,i]of Object.entries(t.webhooks))this.#t[r]=i,this.#t[r.replace("webhook_","")]=i,this.#t[r.replace("webhook_","subpackage_")]=i,this.#t[`${i.method} ${i.path.join("/")}`]=i;for(let[r,i]of Object.entries(t.websockets))this.#n[r]=i,this.#n[r.replace("websocket_","")]=i,this.#n[r.replace("websocket_","subpackage_")]=i,this.#n[`STREAM ${mB(i.path)}`]=i,this.#n[`STREAM ${Y6e(i.path)}`]=i}getSubpackageByLocator(t){if(["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS","CONNECT","TRACE"].some(i=>t.includes(i)))return;let r=t.replace(".yml","").replace(".yaml","");return this.#e[r]}getWebhookByLocator(t,r){return this.#t[t]??this.#t[`${r}.${t}`]??this.#t[`webhook_${r}.${t}`]}getEndpointByLocator(t,r){return this.#r[t]??this.#r[`${r}.${t}`]??this.#r[`endpoint_${r}.${t}`]}getWebSocketByLocator(t,r){return this.#n[t]??this.#n[`${r}.${t}`]??this.#n[`websocket_${r}.${t}`]}get subpackageLocators(){return new Set(Object.keys(this.#e))}};function pVa({item:e,parentSlug:t}){return t.apply({urlSlug:TT(e.id.split(".").pop()??"")}).get()}var _Va=class{apiSection;workspace;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;markdownFilesToTags;hideChildren;parentAvailability;apiDefinitionId;#e;#t;#r=new Set;#n=new Set;#i=new Set;#a=new Set;#o=new Map;#s=[];#f;#u;#c;#l=new Map;disableEndpointPairs;constructor(t,r,i,n,a,u,c,d,s,o,l,v){this.apiSection=t,this.workspace=n,this.docsWorkspace=a,this.taskContext=u,this.markdownFilesToFullSlugs=c,this.markdownFilesToNoIndex=d,this.markdownFilesToTags=s,this.hideChildren=l,this.parentAvailability=v,this.#e=r,this.#t=new Zhu(r),this.disableEndpointPairs=a.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=Do.V1.ApiDefinitionId(r.id),this.#c=o,this.#f=this.apiSection.overviewAbsolutePath!=null?Do.V1.PageId(kor(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let g=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#u=i.apply({fullSlug:g?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??TT(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#s=this.#p(this.apiSection.navigation,void 0,this.#u)),this.#s=this.#j(this.#s.map(O=>this.#w(O)),this.#m(this.#e,this.#u))}get(){let t=Do.V1.followRedirects(this.#s),r=new UPi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,this.workspace?.changelog?.files.map(i=>i.absoluteFilepath),this.docsWorkspace,this.#c).orUndefined();return{id:this.#c.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#f,paginated:this.apiSection.paginated,slug:this.#u.get(),icon:this.apiSection.icon,hidden:this.hideChildren||this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#u,viewers:void 0,hidden:this.hideChildren}),children:this.#s,availability:this.parentAvailability,pointsTo:t,noindex:void 0,playground:this.#S(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}#p(t,r,i){return t.map(n=>lVa(n)._visit({link:a=>({id:this.#c.get(a.url),type:"link",title:a.text,icon:a.icon,url:Do.Url(a.url)}),page:a=>this.#_(a,i),package:a=>this.#h(a,i),section:a=>this.#v(a,i),item:({value:a})=>this.#O(a,r,i),endpoint:a=>this.#y(a,r,i)})).filter(yy)}#_(t,r){return Yhu({docsWorkspace:this.docsWorkspace,page:t,parentSlug:r,idgen:this.#c,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex})}#h(t,r){let i=t.overviewAbsolutePath!=null?Do.V1.PageId(kor(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#t.getSubpackageByLocator(t.package);if(a!=null){let u=this.#c.get(i??`${this.apiDefinitionId}:${a.id}`);this.#a.has(a.id)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${a.id}`),this.#a.add(a.id),this.#o.set(u,[a.id]);let c=t.slug??TT(a.name),d=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:c}),s=this.#p(t.contents,a.id,d),o={id:u,type:"apiPackage",children:s,title:t.title??a.displayName??nJt(a.name),slug:d.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:this.parentAvailability,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return this.#l.set(a.id,o),o}else{this.taskContext.logger.warn(u7i(t.package,this.#t.subpackageLocators));let u=t.slug??TT(t.package),c=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),d=this.#p(t.contents,t.package,c),s={id:this.#c.get(i??`${this.apiDefinitionId}:${TT(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:c.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:this.parentAvailability,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return this.#l.set(t.package,s),s}}#v(t,r){let i=t.overviewAbsolutePath!=null?Do.V1.PageId(kor(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#c.get(i??n??r.get()),u=t.referencedSubpackages.map(v=>{let g=this.#t.getSubpackageByLocator(v);if(g==null){this.taskContext.logger.error(u7i(v,this.#t.subpackageLocators));return}return{subpackageId:g.id,locator:v}}).filter(v=>v!=null).filter(yy),c=u.map(v=>v.subpackageId);this.#o.set(a,c),u.forEach(v=>{this.#a.has(v.subpackageId)&&this.taskContext.logger.error(Son(v.locator)),this.#a.add(v.subpackageId)});let d=t.slug??TT(t.title),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#p(t.contents,t.title,s),l={id:a,type:"apiPackage",children:o,title:t.title,slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:this.parentAvailability,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return c.forEach(v=>{this.#l.set(v,l)}),l}#O(t,r,i){t=t.trim();let n=this.#t.getSubpackageByLocator(t);if(n!=null){let a=n.id,u=this.#c.get(`${this.apiDefinitionId}:${a}`);this.#a.has(a)&&this.taskContext.logger.warn(Son(t)),this.#a.add(a),this.#o.set(u,[a]);let c=TT(n.name),d=i.apply({urlSlug:c}),s={id:u,type:"apiPackage",children:[],title:n.displayName??nJt(n.name),slug:d.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:this.parentAvailability,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};return this.#l.set(a,s),s}return this.#y({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,i)}#y(t,r,i){let n=this.#t.getEndpointByLocator(t.endpoint,r);if(n!=null)if(this.#r.has(n.id)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${n.id}`),n.id==null)this.taskContext.logger.error(`Expected Endpoint ID for ${n.id} at path: ${won(n.method,n.path)}. Got undefined.`);else{this.#r.add(n.id);let c=t.slug!=null?i.append(t.slug).get():pVa({item:n,parentSlug:i});return{id:this.#c.get(`${this.apiDefinitionId}:${n.id}`),type:"endpoint",method:n.method,endpointId:n.id,apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(n.availability)??this.parentAvailability,isResponseStream:n.responses?.[0]?.body.type==="stream",title:t.title??n.displayName??mB(n.path),slug:c,icon:t.icon,hidden:this.hideChildren||t.hidden,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let a=this.#t.getWebSocketByLocator(t.endpoint,r);if(a!=null)if(this.#n.has(a.id)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${a.id}`),a.id==null){this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return}else return this.#n.add(a.id),{id:this.#c.get(`${this.apiDefinitionId}:${a.id}`),type:"webSocket",webSocketId:a.id,title:t.title??a.displayName??mB(a.path),slug:t.slug!=null?i.append(t.slug).get():pVa({item:a,parentSlug:i}),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(a.availability)??this.parentAvailability,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};let u=this.#t.getWebhookByLocator(t.endpoint,r);if(u!=null)if(this.#i.has(u.id)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${u.id}`),u.id==null)this.taskContext.logger.error(`Expected Webhook ID for ${u.id}. Got undefined.`);else return this.#i.add(u.id),{id:this.#c.get(`${this.apiDefinitionId}:${u.id}`),type:"webhook",webhookId:u.id,method:u.method,title:t.title??u.displayName??Fb("/",...u.path),slug:t.slug!=null?i.append(t.slug).get():pVa({item:u,parentSlug:i}),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:this.parentAvailability,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#j(t,r){return Khu({left:t,right:r,findEndpointById:i=>this.#t.getEndpointByLocator(i,void 0),stringifyEndpointPathParts:i=>mB(i.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#w(t){return fVa({child:t,nodeIdToSubpackageId:this.#o,convertApiDefinitionPackageId:(r,i)=>this.#E(r,i),mergeAndFilterChildren:this.#j.bind(this)})}#m(t,r){let i=[];return Object.entries(t.subpackages).forEach(([n,a])=>{if(!this.#a.has(n)){let u=this.#g(n,a,r);u!=null&&i.push(u)}}),Object.entries(t.endpoints).forEach(([n,a])=>{if(n==null){this.taskContext.logger.error(`Expected Endpoint ID for ${a.id} at path: ${won(a.method,a.path)}. Got undefined.`);return}!this.#r.has(Wq.EndpointId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#P(n,a,r,i)}),Object.entries(t.websockets).forEach(([n,a])=>{if(n==null){this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return}!this.#n.has(Wq.WebSocketId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#A(n,a,r,i)}),Object.entries(t.webhooks).forEach(([n,a])=>{if(n==null){this.taskContext.logger.error(`Expected Webhook ID for ${a.id}. Got undefined.`);return}!this.#i.has(Wq.WebhookId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#d(n,a,r,i)}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,c=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(c)}),i}#g(t,r,i){let n=Do.V1.SlugGenerator.init(i.get()).apply({urlSlug:TT(r.name)}),a=this.#E(t,n),u={id:Do.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"apiPackage",children:a,title:r.displayName??nJt(r.name),slug:n.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:this.parentAvailability,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};return this.#l.set(t,u),a.length>0?u:void 0}#D(t,r,i,n){r.slug=pVa({item:t,parentSlug:i}),n.push(r)}#P(t,r,i,n){let a={id:Do.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"endpoint",method:r.method,endpointId:Wq.EndpointId(t),apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(r.availability)??this.parentAvailability,isResponseStream:r.responses?.[0]?.body.type==="stream",title:r.displayName??mB(r.path),slug:i.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#D(r,a,i,n)}#A(t,r,i,n){let a={id:Do.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"webSocket",webSocketId:Wq.WebSocketId(t),title:r.displayName??mB(r.path),slug:i.get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:Do.V1.convertAvailability(r.availability)??this.parentAvailability,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#D(r,a,i,n)}#d(t,r,i,n){let a={id:Do.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"webhook",webhookId:Wq.WebhookId(t),method:r.method,title:r.displayName??nJt(r.id),slug:i.get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:this.parentAvailability,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#D(r,a,i,n)}#T(t){let r=Object.fromEntries(Object.entries(this.#e?.subpackages??{}).filter(([u,c])=>t===this.#e.id?c.id.split(".").length===1:c.id!=null&&c.id.includes(t)&&c.id!==t&&c.id.split(".").length===t.split(".").length+1)),i=Object.fromEntries(Object.entries(this.#e?.endpoints??{}).filter(([u,c])=>c.namespace!=null&&c.namespace.join(".")===Wq.api.v1.SubpackageId(t))),n=Object.fromEntries(Object.entries(this.#e?.websockets??{}).filter(([u,c])=>c.namespace!=null&&c.namespace.join(".")===Wq.api.v1.SubpackageId(t))),a=Object.fromEntries(Object.entries(this.#e?.webhooks??{}).filter(([u,c])=>c.namespace!=null&&c.namespace.join(".")===Wq.api.v1.SubpackageId(t)));return{id:Wq.ApiDefinitionId(t),endpoints:i,websockets:n,webhooks:a,types:{},subpackages:r,auths:{},globalHeaders:void 0,snippetsConfiguration:void 0}}#E(t,r){let i=t!=null?this.#T(t):void 0;return i==null?(this.taskContext.logger.error(u7i(t||"unknown",[])),[]):this.#m(i,r)}#S(t){return Jhu(t)}mergeEndpointPairs(t){return BXn({children:t,findEndpointById:r=>this.#e?.endpoints[r],stringifyEndpointPathParts:r=>mB(r.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var hX_=ui(require("crypto"),1);function JgM(e){return hX_.default.createHash("sha256").update(e).digest("hex")}var khu=class e{static init(){return new e}constructor(){}#e=new Map;#t=new Set;#r(t){let r=this.#e.get(t)??0;return this.#e.set(t,r+1),JgM(r===0?t:`${t}-${r}`)}#n(t){let r=this.#r(t),i=0;for(;this.#t.has(r);)if(r=this.#r(t),i++,i>100)throw new Error(`Infinite loop detected for id: ${t}`);return r}get(t){return Do.V1.NodeId(this.#n(t))}};function eyu(e){return e==null?{}:{pythonSdk:e.python!=null?{package:typeof e.python=="string"?e.python:e.python.package,version:typeof e.python=="string"?void 0:e.python.version}:void 0,typescriptSdk:e.typescript!=null?{package:typeof e.typescript=="string"?e.typescript:e.typescript.package,version:typeof e.typescript=="string"?void 0:e.typescript.version}:void 0,goSdk:e.go!=null?{githubRepo:typeof e.go=="string"?e.go:e.go.package,version:typeof e.go=="string"?void 0:e.go.version}:void 0,javaSdk:e.java!=null?{coordinate:typeof e.java=="string"?e.java:e.java.package,version:typeof e.java=="string"?void 0:e.java.version}:void 0,rubySdk:e.ruby!=null?{gem:typeof e.ruby=="string"?e.ruby:e.ruby.package,version:typeof e.ruby=="string"?void 0:e.ruby.version}:void 0,csharpSdk:e.csharp!=null?{package:typeof e.csharp=="string"?e.csharp:e.csharp.package,version:typeof e.csharp=="string"?void 0:e.csharp.version}:void 0}}var tyu=ui(RAe(),1);var Q6c=ui(RAe(),1);function yX_({auth:e,ir:t,playgroundConfig:r,context:i}){if(e.schemes.length>0&&e.schemes[0]!=null){let n=e.schemes[0];switch(n.type){case"basic":return{type:"basicAuth",passwordName:n.password.originalName,usernameName:n.username.originalName,description:e.docs};case"bearer":return{type:"bearerAuth",tokenName:n.token.originalName,description:e.docs};case"header":return{type:"header",headerWireValue:n.name.wireValue,nameOverride:n.name.name.originalName,prefix:n.prefix,description:e.docs};case"oauth":{let a=n.configuration.tokenEndpoint.responseProperties.accessToken.propertyPath?.map(u=>u.originalName).join(".")||"$.body.access_token";return r?.oauth?{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:Q6c.FernRegistry.EndpointId(n.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:Q6c.FernRegistry.JqString(a),headerName:n.configuration.tokenHeader,tokenPrefix:n.configuration.tokenPrefix,description:e.docs}}}:{type:"bearerAuth",tokenName:"token",description:e.docs}}case"inferred":{n.tokenEndpoint.authenticatedRequestHeaders.length>1&&i.logger.warn("Inferred auth scheme has multiple authenticated request headers. Only the `Authentication` or first header will be pushed to FDR.");let a=n.tokenEndpoint.authenticatedRequestHeaders.find(c=>c.headerName.toLowerCase()==="authorization");if(a)return a.responseProperty.propertyPath!=null&&a.responseProperty.propertyPath.length>0&&i.logger.warn("Inferred Authentication header has a property path. The property wirevalue will be pushed to FDR without property path."),{type:"bearerAuth",tokenName:a.responseProperty.property.name.wireValue,description:e.docs};let u=n.tokenEndpoint.authenticatedRequestHeaders[0];return u?{type:"header",headerWireValue:u.headerName,prefix:u.valuePrefix,nameOverride:void 0,description:e.docs}:{type:"bearerAuth",tokenName:"token",description:e.docs}}default:Ao(n)}}}var Hm=ui(RAe(),1);var s7i=ui(RAe(),1);function bX_(e){return e._visit({alias:t=>({type:"alias",value:hM(t.aliasOf)}),enum:t=>({type:"enum",default:t.default!=null?t.default.name.wireValue:void 0,values:t.values.map(r=>({description:r.docs??void 0,value:r.name.wireValue,availability:g2(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>s7i.FernRegistry.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:s7i.FernRegistry.PropertyKey(r.name.wireValue),valueType:hM(r.valueType),availability:g2(r.availability),propertyAccess:r.propertyAccess})),extraProperties:XgM(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(i=>({key:s7i.FernRegistry.PropertyKey(i.name.wireValue),valueType:hM(i.valueType),availability:g2(i.availability),description:i.docs,propertyAccess:i.propertyAccess}));return{type:"discriminatedUnion",discriminant:t.discriminant.wireValue,variants:t.types.map(i=>({description:i.docs??void 0,discriminantValue:i.discriminantValue.wireValue,displayName:i.displayName,availability:i.availability!=null?g2(i.availability):void 0,additionalProperties:Hs.types.SingleUnionTypeProperties._visit(i.shape,{samePropertiesAsObject:n=>({extends:[s7i.FernRegistry.TypeId(n.typeId)],properties:r,extraProperties:void 0}),singleProperty:n=>({extends:[],properties:[{key:s7i.FernRegistry.PropertyKey(n.name.wireValue),valueType:hM(n.type),description:void 0,availability:void 0,propertyAccess:void 0},...r],extraProperties:void 0}),noProperties:()=>({extends:[],properties:r,extraProperties:void 0}),_other:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+i.shape.propertiesType)}})}))}},undiscriminatedUnion:t=>({type:"undiscriminatedUnion",variants:t.members.map(r=>({typeName:r.type.type==="named"?r.type.name.originalName:void 0,description:r.docs??void 0,type:hM(r.type),availability:void 0,displayName:r.type.type==="named"?r.type.displayName:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function hM(e){return e._visit({container:t=>Hs.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:hM(r)}),map:({keyType:r,valueType:i})=>({type:"map",keyType:hM(r),valueType:hM(i)}),optional:r=>({type:"optional",itemType:hM(r),defaultValue:void 0}),nullable:r=>({type:"nullable",itemType:hM(r)}),set:r=>({type:"set",itemType:hM(r)}),literal:r=>Hs.types.Literal._visit(r,{boolean:i=>({type:"literal",value:{type:"booleanLiteral",value:i}}),string:i=>({type:"literal",value:{type:"stringLiteral",value:i}}),_other:()=>{throw new Error("Unknown literal type: "+r.type)}}),_other:()=>{throw new Error("Unknown container reference: "+t.type)}}),named:t=>({type:"id",value:s7i.FernRegistry.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:Hs.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>YgM(t.v2),float:()=>vX_(t.v2),double:()=>vX_(t.v2),string:()=>KgM(t.v2),long:()=>({type:"long",default:t.v2?.type==="long"?t.v2.default:void 0,minimum:void 0,maximum:void 0}),boolean:()=>({type:"boolean",default:t.v2?.type==="boolean"?t.v2.default:void 0}),dateTime:()=>({type:"datetime",default:void 0}),date:()=>({type:"date",default:void 0}),uuid:()=>({type:"uuid",default:void 0}),base64:()=>({type:"base64",mimeType:void 0,default:void 0}),bigInteger:()=>({type:"bigInteger",default:t.v2?.type==="bigInteger"?t.v2.default:void 0}),uint:()=>({type:"uint"}),uint64:()=>({type:"uint64"}),_other:()=>{throw new Error("Unknown primitive: "+t.v1)}})}),unknown:()=>({type:"unknown"}),_other:()=>{throw new Error("Unknown Type reference: "+e.type)}})}function KgM(e){let t=e!=null&&e.type==="string"?e.validation:void 0;return{type:"string",format:t?.format,regex:t?.pattern,minLength:t?.minLength,maxLength:t?.maxLength,default:e!=null&&e.type==="string"?e.default:void 0}}function YgM(e){let t=e!=null&&e.type==="integer"?e.validation:void 0;return{type:"integer",minimum:t?.min,maximum:t?.max,default:e!=null&&e.type==="integer"?e.default:void 0}}function vX_(e){let t=e!=null&&e.type==="double"?e.validation:void 0;return{type:"double",minimum:t?.min,maximum:t?.max,default:e!=null&&e.type==="double"?e.default:void 0}}function XgM(e){return typeof e=="boolean"?e?ol.unknown():void 0:typeof e=="string"?{type:"id",value:s7i.FernRegistry.TypeId(e),default:void 0}:hM(e)}function K6c(e,t){let r=e.service!=null?t.services[e.service]:void 0,i=e.webhooks!=null?t.webhookGroups[e.webhooks]:void 0,n=e.websocket!=null&&t.websocketChannels!=null?t.websocketChannels[e.websocket]:void 0;return{endpoints:r!=null?kgM(r,t):[],webhooks:i!=null?ZgM(i):[],websockets:n!=null?[eOM(n,t)]:[],types:e.types.map(a=>Hm.FernRegistry.TypeId(a)),subpackages:e.subpackages.map(a=>Hm.FernRegistry.api.v1.SubpackageId(a)),pointsTo:e.navigationConfig!=null?Hm.FernRegistry.api.v1.SubpackageId(e.navigationConfig.pointsTo):void 0}}function ZgM(e){return e.map(t=>{let r=[];return t.v2Examples!=null?(r.push(...Object.values(t.v2Examples.userSpecifiedExamples)),r.push(...Object.values(t.v2Examples.autogeneratedExamples))):r.push(...t.examples?.map(i=>({payload:i.payload.jsonExample}))??[]),{description:t.docs??void 0,id:Hm.FernRegistry.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??fZi(t.name.originalName),headers:t.headers.map(i=>({description:i.docs??void 0,key:i.name.wireValue,type:hM(i.valueType),availability:g2(i.availability)})),payload:oOM(t.payload),examples:r}})}function kgM(e,t){let r=[];for(let i of e.endpoints){let n=i.autogeneratedExamples[0],a=[];if(i.v2Examples!=null){let c,d=i.v2Examples.userSpecifiedExamples,s=i.v2Examples.autogeneratedExamples,o=Object.values(d).map(v=>v.response?.statusCode).filter((v,g,O)=>O.indexOf(v)!==g).length>0;for(let[v,g]of Object.entries(d))c=mX_({shouldUseExampleName:o,exampleName:g.displayName??v,example:g,irEndpoint:i}),c!=null&&a.push(c);let l=Object.values(s).map(v=>v.response?.statusCode).filter((v,g,O)=>O.indexOf(v)!==g).length>0;for(let[v,g]of Object.entries(s))c=mX_({shouldUseExampleName:l,exampleName:g.displayName??v,example:g,irEndpoint:i}),c!=null&&a.push(c)}else if(i.userSpecifiedExamples.length>0)a.push(...i.userSpecifiedExamples.map(c=>J6c({userSpecifiedExample:c,...n!=null&&{autogeneratedExample:n},irEndpoint:i,ir:t})).filter(yy));else if(n!=null){let c=J6c({autogeneratedExample:n,irEndpoint:i,ir:t});c!=null&&a.push(c)}else if(i.response?.body?.type==="fileDownload"){let c=jQn({ir:t,service:e,endpoint:{...i,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(c.type==="success"){let d=J6c({autogeneratedExample:c,irEndpoint:i,ir:t});if(d!=null){let s={...d,responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(s)}}}let u={slug:void 0,availability:g2(i.availability??e.availability),auth:i.auth,description:i.docs??void 0,method:nOM(i.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?Hm.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?tOM({environmentsConfig:t.environments,endpoint:i}):void 0,id:Hm.FernRegistry.EndpointId(i.name.originalName),originalEndpointId:i.id,name:i.displayName??fZi(i.name.originalName),path:i.basePath!=null?{pathParameters:i.pathParameters.map(c=>({description:c.docs??void 0,key:Hm.FernRegistry.PropertyKey(c.name.originalName),type:hM(c.valueType),availability:void 0})),parts:[...IXn(i.basePath),...IXn(i.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...i.pathParameters].map(c=>({description:c.docs??void 0,key:Hm.FernRegistry.PropertyKey(c.name.originalName),type:hM(c.valueType),availability:void 0})),parts:[...t.basePath!=null?IXn(t.basePath):[],...IXn(e.basePath),...IXn(i.path)]},queryParameters:i.queryParameters.map(c=>({description:c.docs??void 0,key:c.name.wireValue,type:hM(c.valueType),availability:g2(c.availability)})),headers:[...e.headers,...i.headers].map(c=>({description:c.docs??void 0,key:c.name.wireValue,type:hM(c.valueType),availability:g2(c.availability)})),request:i.requestBody!=null?gX_(i.requestBody):void 0,requestsV2:{requests:i.v2RequestBodies?.requestBodies?.map(gX_).filter(yy)},response:i.response!=null?OX_(i.response):void 0,responsesV2:{responses:i.v2Responses?.responses?.map(OX_).filter(yy)},errors:void 0,errorsV2:aOM(i.errors,t),examples:a,protocol:i.source?._visit({openapi:()=>({type:"rest"}),openrpc:()=>({type:"openrpc",methodName:i.id}),proto:c=>({type:"grpc",methodName:i.id,methodType:c.methodType}),_other:()=>{}})};r.push(u)}return r}function eOM(e,t){let r=[];if(e.v2Examples!=null&&(Object.keys(e.v2Examples.userSpecifiedExamples).length>0||Object.keys(e.v2Examples.autogeneratedExamples).length>0)){let i=Object.values(e.v2Examples.userSpecifiedExamples),n=Object.values(e.v2Examples.autogeneratedExamples),a=i.length>0?i[0]:n[0];a!=null&&r.push({name:"",description:"",path:a.baseUrl??"",pathParameters:a.pathParameters??{},queryParameters:a.queryParameters??{},headers:a.headers??{},messages:a.messages?.map(u=>({type:Hm.FernRegistry.api.v1.WebSocketMessageId(u.type),body:u.body}))??[]})}else r=e.examples.map(i=>({name:i.name?.originalName,description:i.docs,path:i.url,pathParameters:i.pathParameters.reduce((n,a)=>(n[Hm.FernRegistry.PropertyKey(a.name.originalName)]=a.value.jsonExample,n),{}),queryParameters:i.queryParameters.reduce((n,a)=>(n[a.name.wireValue]=a.value.jsonExample,n),{}),headers:i.headers.reduce((n,a)=>(n[a.name.wireValue]=a.value.jsonExample,n),{}),messages:i.messages.map(n=>({type:Hm.FernRegistry.api.v1.WebSocketMessageId(n.type),body:n.body.jsonExample}))}));return{auth:e.auth,availability:g2(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?Hm.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?rOM({environmentsConfig:t.environments,channel:e}):[],id:Hm.FernRegistry.WebSocketId(e.name.originalName),name:e.displayName??fZi(e.name.originalName),path:{pathParameters:e.pathParameters.map(i=>({description:i.docs??void 0,key:Hm.FernRegistry.PropertyKey(i.name.originalName),type:hM(i.valueType),availability:void 0})),parts:IXn(e.path)},headers:e.headers.map(i=>({key:i.name.wireValue,type:hM(i.valueType),description:i.docs,availability:g2(i.availability)})),queryParameters:e.queryParameters.map(i=>({description:i.docs??void 0,key:i.name.wireValue,type:hM(i.valueType),availability:g2(i.availability)})),messages:e.messages.map(i=>({type:Hm.FernRegistry.api.v1.WebSocketMessageId(i.type),displayName:i.displayName,origin:i.origin,body:uOM(i.body),description:i.docs,availability:g2(i.availability)})),examples:r}}function g2(e){if(e!=null)switch(e.status){case"DEPRECATED":return Hm.FernRegistry.Availability.Deprecated;case"PRE_RELEASE":return Hm.FernRegistry.Availability.Beta;case"GENERAL_AVAILABILITY":return Hm.FernRegistry.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return Hm.FernRegistry.Availability.Beta;default:Ao(e.status)}}function tOM({environmentsConfig:e,endpoint:t}){let r=e.environments,i=t.baseUrl,n=t.v2BaseUrls;switch(r.type){case"singleBaseUrl":return r.environments.map(a=>({id:Hm.FernRegistry.EnvironmentId(a.id),baseUrl:a.url}));case"multipleBaseUrls":if(n!=null)return n.flatMap(u=>r.environments.map(c=>{let d=c.urls[u];if(d==null)throw new Error(`Expected environment ${c.id} to contain url for ${u}`);return{id:Hm.FernRegistry.EnvironmentId(u),baseUrl:d}})).filter((u,c,d)=>c===d.findIndex(s=>s.id===u.id&&s.baseUrl===u.baseUrl));if(i==null)throw new Error(`Expected endpoint ${t.name.originalName} to have base url.`);return r.environments.map(a=>{let u=a.urls[i];if(u==null)throw new Error(`Expected environment ${a.id} to contain url for ${i}`);return{id:Hm.FernRegistry.EnvironmentId(a.id),baseUrl:u}});default:Ao(r)}}function rOM({environmentsConfig:e,channel:t}){let r=e.environments,i=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:Hm.FernRegistry.EnvironmentId(n.id),baseUrl:iOM(n.url,"wss")}));case"multipleBaseUrls":if(i==null)throw new Error(`Expected channel ${t.name.originalName} to have base url.`);return r.environments.map(n=>{let a=n.urls[i];if(a==null)throw new Error(`Expected environment ${n.id} to contain url for ${i}`);return{id:Hm.FernRegistry.EnvironmentId(n.id),baseUrl:a}});default:Ao(r)}}function iOM(e,t){return e.replace(/^[^:]+/,t)}function nOM(e){return Hs.http.HttpMethod._visit(e,{get:()=>Hm.FernRegistry.HttpMethod.Get,post:()=>Hm.FernRegistry.HttpMethod.Post,put:()=>Hm.FernRegistry.HttpMethod.Put,patch:()=>Hm.FernRegistry.HttpMethod.Patch,delete:()=>Hm.FernRegistry.HttpMethod.Delete,head:()=>Hm.FernRegistry.HttpMethod.Head,_other:()=>{throw new Error("Unknown http method: "+e)}})}function IXn(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:Hm.FernRegistry.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function gX_(e){let t=Hs.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??Bq.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(i=>Hm.FernRegistry.TypeId(i.typeId)),properties:r.properties.map(i=>({description:i.docs??void 0,key:Hm.FernRegistry.PropertyKey(i.name.wireValue),valueType:hM(i.valueType),availability:g2(i.availability),propertyAccess:i.propertyAccess})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??Bq.APPLICATION_JSON,shape:{type:"reference",value:hM(r.requestBodyType)},description:r.docs??void 0}),fileUpload:r=>({type:"fileUpload",value:{name:r.name.originalName,description:void 0,availability:void 0,properties:r.properties.map(i=>i._visit({file:n=>{let a=n._visit({file:u=>({type:"file",key:Hm.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:u.docs??void 0,availability:void 0}),fileArray:u=>({type:"fileArray",key:Hm.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:u.docs??void 0,availability:void 0}),_other:()=>{}});if(a!=null)return{type:"file",value:a}},bodyProperty:n=>({type:"bodyProperty",key:Hm.FernRegistry.PropertyKey(n.name.wireValue),valueType:hM(n.valueType),contentType:n.contentType,description:n.docs??void 0,availability:g2(n.availability),exploded:n.style==="exploded",propertyAccess:void 0}),_other:()=>{}})).filter(yy)},contentType:r.contentType,description:r.docs??void 0}),bytes:r=>({type:"bytes",description:r.docs??void 0,availability:void 0,isOptional:r.isOptional,contentType:r.contentType}),_other:()=>{throw new Error("Unknown HttpRequestBody: "+e.type)}});return t!=null?{type:t,description:e.docs}:void 0}function OX_(e){if(e.body==null)return;let t,r=Hs.http.HttpResponseBody._visit(e.body,{fileDownload:i=>(t=i.docs,{type:"fileDownload",contentType:void 0}),json:i=>(t=i.docs,{type:"reference",value:hM(i.responseBodyType)}),text:()=>{},bytes:()=>{},streamParameter:()=>{},streaming:i=>{if(i.type==="text")return t=i.docs,{type:"streamingText"};if(i.type==="json")return t=i.docs,{type:"stream",shape:{type:"reference",value:hM(i.payload)},terminator:i.terminator};if(i.type==="sse")return t=i.docs,{type:"stream",shape:{type:"reference",value:hM(i.payload)},terminator:i.terminator}},_other:()=>{throw new Error("Unknown HttpResponse: "+e.body)}});return r!=null?{type:r,statusCode:e.statusCode,description:t}:e.statusCode!=null?{statusCode:e.statusCode,description:t,type:{type:"object",extends:[],properties:[],extraProperties:void 0}}:void 0}function aOM(e,t){let r=[];if(t.errorDiscriminationStrategy.type==="statusCode")for(let i of e){let n=t.errors[i.error.errorId];n&&r.push({type:n.type==null?void 0:{type:"alias",value:hM(n.type)},statusCode:n.statusCode,description:n.docs??void 0,name:n.displayName??n.name.name.originalName,availability:void 0,examples:sOM(n)})}else for(let i of e){let n=t.errors[i.error.errorId];if(n){let a=[{key:Hm.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.discriminant.wireValue),valueType:{type:"literal",value:{type:"stringLiteral",value:n.discriminantValue.name.originalName}},description:n.docs,availability:void 0,propertyAccess:void 0}];n.type!=null&&a.push({key:Hm.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.contentProperty.wireValue),valueType:hM(n.type),description:n.docs,availability:void 0,propertyAccess:void 0}),r.push({type:n.type==null?void 0:{type:"object",extends:[],properties:a,extraProperties:void 0},statusCode:n.statusCode,description:n.docs??void 0,availability:void 0,name:n.displayName??n.name.name.originalName,examples:n.examples.map(u=>({name:u.name?.originalName,responseBody:{type:"json",value:u.jsonExample},description:u.docs}))})}}return r}function mX_({shouldUseExampleName:e,exampleName:t,example:r,irEndpoint:i}){if(r==null)return;let n=r.response?.body!=null?r.response.body.value:void 0;return{name:e?t:void 0,description:"",path:r.request?.endpoint.path??"",pathParameters:r.request?.pathParameters??{},queryParameters:r.request?.queryParameters??{},headers:r.request?.headers??{},requestBody:r.request?.requestBody,requestBodyV3:i.requestBody?._visit({inlinedRequestBody:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,reference:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,fileUpload:a=>{if(r.request==null)return;let u={};if(Tw(r.request.requestBody)){let c=r.request.requestBody;for(let d of a.properties)d._visit({file:s=>{let o=c[s.key.wireValue];if(s.type==="file")u[s.key.wireValue]={type:"filename",value:typeof o=="string"?o:"<file1>"};else if(s.type==="fileArray"){let l=(Array.isArray(o)?o:[o]).filter(v=>typeof v=="string");u[s.key.wireValue]={type:"filenames",value:l}}},bodyProperty:s=>{if(s.style==="exploded"){let o=c[s.name.wireValue];u[s.name.wireValue]={type:"exploded",value:Array.isArray(o)?o:[o]}}else u[s.name.wireValue]={type:"json",value:c[s.name.wireValue]}},_other:P3e})}return{type:"form",value:u}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??i.response?.statusCode??200,responseBody:n??void 0,responseBodyV3:n!=null?r.response?.body?._visit({json:a=>({type:"json",value:a}),stream:a=>({type:"stream",value:a.map(u=>({type:"json",value:u}))}),error:()=>{},_other:()=>{throw new Error("Unknown ExampleResponseBody: "+r.response?.body?.type)}}):void 0,codeSamples:r.codeSamples?.map(a=>({name:a.name,description:a.docs??void 0,install:void 0,language:a.language,code:a.code})).filter(yy)}}function J6c({userSpecifiedExample:e,autogeneratedExample:t,irEndpoint:r,ir:i}){let n=i.headers.map(c=>{let d=c.valueType.type==="container"&&c.valueType.container.type==="literal"?c.valueType.container.literal._visit({boolean:s=>`${s}`,string:s=>s,_other:()=>{}}):void 0;if(d!=null)return{name:c.name,value:{jsonExample:d,shape:Hs.ExampleTypeReferenceShape.primitive(Hs.ExamplePrimitive.string({original:d}))}}}).filter(yy),a=e?.example??t?.example;if(a==null)return;let{codeSamples:u}=e??{codeSamples:[]};return{name:a.name?.originalName,description:a.docs,path:a.url,pathParameters:[...a.rootPathParameters,...a.servicePathParameters,...a.endpointPathParameters].reduce((c,d)=>(c[Hm.FernRegistry.PropertyKey(d.name.originalName)]=d.value.jsonExample,c),{}),queryParameters:a.queryParameters.reduce((c,d)=>(c[d.name.wireValue]=d.value.jsonExample,c),{}),headers:[...n,...a.serviceHeaders,...a.endpointHeaders].reduce((c,d)=>(c[d.name.wireValue]=d.value.jsonExample,c),{}),requestBody:a.request?.jsonExample,requestBodyV3:r.requestBody?._visit({inlinedRequestBody:()=>a.request!=null?{type:"json",value:a.request.jsonExample}:void 0,reference:()=>a.request!=null?{type:"json",value:a.request.jsonExample}:void 0,fileUpload:c=>{if(a.request==null)return;let d={};if(Tw(a.request.jsonExample)){let s=a.request.jsonExample;for(let o of c.properties)o._visit({file:l=>{let v=s[l.key.wireValue];if(l.type==="file")d[l.key.wireValue]={type:"filename",value:typeof v=="string"?v:"<file1>"};else if(l.type==="fileArray"){let g=(Array.isArray(v)?v:[v]).filter(O=>typeof O=="string");d[l.key.wireValue]={type:"filenames",value:g}}},bodyProperty:l=>{if(l.style==="exploded"){let v=s[l.name.wireValue];d[l.name.wireValue]={type:"exploded",value:Array.isArray(v)?v:[v]}}else d[l.name.wireValue]={type:"json",value:s[l.name.wireValue]}},_other:P3e})}return{type:"form",value:d}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??Hs.http.ExampleResponse._visit(a.response,{ok:c=>c._visit({body:d=>d!=null?200:204,stream:d=>d.length>0?200:204,sse:d=>d.length>0?200:204,_other:()=>{throw new Error("Unknown ExampleResponseBody: "+c.type)}}),error:({error:c})=>{let d=i.errors[c.errorId];if(d==null)throw new Error("Cannot find error "+c.errorId);return d.statusCode},_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),responseBody:a.response._visit({ok:c=>c._visit({body:d=>d?.jsonExample,stream:()=>{},sse:()=>{},_other:()=>{}}),error:c=>c.body?.jsonExample,_other:()=>{}}),responseBodyV3:a.response._visit({ok:c=>c._visit({body:d=>d!=null?{type:"json",value:d.jsonExample}:void 0,stream:d=>({type:"stream",value:d.map(s=>s.jsonExample)}),sse:d=>({type:"sse",value:d.map(({event:s,data:o})=>({event:s,data:o.jsonExample}))}),_other:()=>{throw new Error("Unknown ExampleResponseBody: "+c.type)}}),error:c=>c.body!=null?{type:"json",value:c.body.jsonExample}:void 0,_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),codeSamples:u?.map(c=>FAe._visit(c,{language:d=>({language:d.language,code:d.code,name:d.name?.originalName,description:d.docs??void 0,install:d.install}),sdk:d=>({language:d.sdk,code:d.code,name:d.name?.originalName,description:d.docs??void 0,install:void 0}),_other:()=>{}})).filter(yy)}}function oOM(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>Hm.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:Hm.FernRegistry.PropertyKey(t.name.wireValue),valueType:hM(t.valueType),availability:g2(t.availability),propertyAccess:void 0})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:hM(e.payloadType)},description:e.docs};default:Ao(e)}}function uOM(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>Hm.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:Hm.FernRegistry.PropertyKey(t.name.wireValue),valueType:hM(t.valueType),availability:g2(t.availability),propertyAccess:void 0})),extraProperties:void 0};case"reference":return{type:"reference",value:hM(e.bodyType)};default:Ao(e)}}function sOM(e){let t=e.v2Examples?.userSpecifiedExamples,r=e.v2Examples?.autogeneratedExamples,i=e.examples;return t!=null&&Object.keys(t).length>0?Object.entries(t).map(([n,a])=>({name:n,responseBody:{type:"json",value:a},description:void 0})):r!=null&&Object.keys(r).length>0?Object.entries(r).map(([n,a])=>({name:n,responseBody:{type:"json",value:a},description:void 0})):i.length>0?i.map(n=>({name:n.name?.originalName,responseBody:{type:"json",value:n.jsonExample},description:n.docs})):[]}function Jee({ir:e,snippetsConfig:t,playgroundConfig:r,context:i}){let n={types:{},subpackages:{},rootPackage:K6c(e.rootPackage,e),auth:yX_({auth:e.auth,ir:e,playgroundConfig:r,context:i}),snippetsConfiguration:t,globalHeaders:e.headers.map(a=>({availability:g2(a.availability),description:a.docs??void 0,key:a.name.wireValue,type:hM(a.valueType)})),navigation:void 0};for(let[a,u]of Object.entries(e.types))n.types[tyu.FernRegistry.TypeId(a)]={description:u.docs??void 0,name:u.name.name.originalName,shape:bX_(u.shape),availability:g2(u.availability),displayName:u.name.displayName};for(let[a,u]of Object.entries(e.subpackages)){let c=u.service!=null?e.services[u.service]:void 0;n.subpackages[tyu.FernRegistry.api.v1.SubpackageId(a)]={subpackageId:tyu.FernRegistry.api.v1.SubpackageId(a),displayName:c?.displayName??u.displayName,name:u.name.originalName,description:u.docs??void 0,...K6c(u,e)}}return n}var Y6c=ui(RAe(),1);async function X6c({organization:e,workspace:t,context:r,token:i,audiences:n,snippetsConfig:a,playgroundConfig:u}){let c=bx({workspace:t,audiences:n,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1},readme:void 0,version:void 0,packageName:void 0,context:r,sourceResolver:new yx(r,t)}),d=Fen({token:i.value}),s=Jee({ir:c,snippetsConfig:a,playgroundConfig:u,context:r}),o=await d.api.v1.register.registerApiDefinition({orgId:Y6c.FernRegistry.OrgId(e),apiId:Y6c.FernRegistry.ApiId(c.apiName.originalName),definition:s});if(o.ok)return r.logger.debug(`Registered API Definition ${o.body.apiDefinitionId}`),{id:o.body.apiDefinitionId,ir:c};switch(o.error.error){case"UnauthorizedError":case"UserNotInOrgError":return r.failAndThrow("You do not have permissions to register the docs. Reach out to support@buildwithfern.com");default:return r.failAndThrow("Failed to register API",o.error)}}var cOM=new pon({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function hVa({ir:e,apiDefinitionId:t,playgroundConfig:r,context:i}){return xUa(BUa(Jee({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0},playgroundConfig:r,context:i}),h2.ApiDefinitionId(t),cOM))}var Bh={};Na(Bh,{AlgoliaSearchIndex:()=>PX_,ApiDefinitionId:()=>WX_,ApiId:()=>QX_,Availability:()=>sZ_,DocsConfigId:()=>JX_,EndpointId:()=>YX_,EndpointPathLiteral:()=>oZ_,EnvironmentId:()=>KX_,FileId:()=>tZ_,HttpMethod:()=>uZ_,IndexSegmentId:()=>jX_,JqString:()=>iZ_,OrgId:()=>$X_,PageId:()=>eZ_,PayloadLocation:()=>zZ_,PropertyKey:()=>nZ_,PullRequestState:()=>qZ_,RoleId:()=>aZ_,TokenId:()=>GX_,TypeId:()=>kX_,Url:()=>rZ_,VersionId:()=>HX_,WebSocketId:()=>XX_,WebhookId:()=>ZX_,algolia:()=>Z6c,api:()=>sFc,commons:()=>cFc,diff:()=>cZ_,docs:()=>bFc,generators:()=>OFc,git:()=>mFc,navigation:()=>wFc,sdks:()=>DFc,snippets:()=>BZ_,snippetsFactory:()=>IZ_,templates:()=>EFc,tokens:()=>xZ_});var Z6c={};Na(Z6c,{AlgoliaSearchIndex:()=>PX_,IndexSegmentId:()=>jX_});function PX_(e){return e}function jX_(e){return e}var sFc={};Na(sFc,{latest:()=>tFc,v1:()=>uFc});var tFc={};Na(tFc,{AuthSchemeId:()=>wX_,WebhookHttpMethod:()=>MX_,auth:()=>k6c,commons:()=>SX_,endpoint:()=>DX_,type_:()=>EX_,webhook:()=>eFc,websocket:()=>AX_});var k6c={};Na(k6c,{AuthSchemeId:()=>wX_});function wX_(e){return e}var SX_={};var DX_={};var EX_={};var eFc={};Na(eFc,{WebhookHttpMethod:()=>MX_});var MX_={Get:"GET",Post:"POST"};var AX_={};var uFc={};Na(uFc,{SubpackageId:()=>FX_,WebSocketMessageId:()=>LX_,WebSocketMessageOrigin:()=>UX_,WebhookHttpMethod:()=>VX_,commons:()=>oFc,db:()=>rFc,read:()=>nFc,register:()=>aFc});var rFc={};Na(rFc,{endpoint:()=>qX_});var qX_={};var nFc={};Na(nFc,{SupportedLanguage:()=>TX_,endpoint:()=>iFc,type_:()=>CX_,webhook:()=>BX_,websocket:()=>IX_});var iFc={};Na(iFc,{SupportedLanguage:()=>TX_});var TX_={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby",Csharp:"csharp"};var CX_={};var BX_={};var IX_={};var aFc={};Na(aFc,{SourceId:()=>lOM,endpoint:()=>zX_,type_:()=>xX_,webhook:()=>RX_,websocket:()=>NX_});var zX_={};var xX_={};var RX_={};var NX_={};function lOM(e){return e}var oFc={};Na(oFc,{SubpackageId:()=>FX_,WebSocketMessageId:()=>LX_,WebSocketMessageOrigin:()=>UX_,WebhookHttpMethod:()=>VX_});function FX_(e){return e}function LX_(e){return e}var UX_={Client:"client",Server:"server"};var VX_={Get:"GET",Post:"POST"};var cFc={};Na(cFc,{ApiDefinitionId:()=>WX_,ApiId:()=>QX_,Availability:()=>sZ_,DocsConfigId:()=>JX_,EndpointId:()=>YX_,EndpointPathLiteral:()=>oZ_,EnvironmentId:()=>KX_,FileId:()=>tZ_,HttpMethod:()=>uZ_,JqString:()=>iZ_,OrgId:()=>$X_,PageId:()=>eZ_,PropertyKey:()=>nZ_,RoleId:()=>aZ_,TokenId:()=>GX_,TypeId:()=>kX_,Url:()=>rZ_,VersionId:()=>HX_,WebSocketId:()=>XX_,WebhookId:()=>ZX_});function WX_(e){return e}function HX_(e){return e}function $X_(e){return e}function GX_(e){return e}function QX_(e){return e}function JX_(e){return e}function KX_(e){return e}function YX_(e){return e}function XX_(e){return e}function ZX_(e){return e}function kX_(e){return e}function eZ_(e){return e}function tZ_(e){return e}function rZ_(e){return e}function iZ_(e){return e}function nZ_(e){return e}function aZ_(e){return e}function oZ_(e){return e}var uZ_={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var sZ_={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var cZ_={};var bFc={};Na(bFc,{latest:()=>dFc,v1:()=>yFc,v2:()=>vFc});var dFc={};Na(dFc,{Layout:()=>fZ_,MdxEngine:()=>fOM,TwitterCardSetting:()=>dZ_,commons:()=>lZ_,frontmatter:()=>lFc,seo:()=>fFc});var fOM={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var lZ_={};var lFc={};Na(lFc,{Layout:()=>fZ_});var fZ_={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var fFc={};Na(fFc,{TwitterCardSetting:()=>dZ_});var dZ_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var yFc={};Na(yFc,{commons:()=>hFc,db:()=>pZ_,read:()=>_Z_,write:()=>pFc});var pZ_={};var _Z_={};var pFc={};Na(pFc,{DocsRegistrationId:()=>pOM,FilePath:()=>dOM});function dOM(e){return e}function pOM(e){return e}var hFc={};Na(hFc,{ContentAlignment:()=>bZ_,FontDisplay:()=>jZ_,FontStyle:()=>PZ_,HeaderPosition:()=>gZ_,JsScriptStrategy:()=>mZ_,ProgrammingLanguage:()=>hZ_,SearchbarPlacement:()=>yZ_,TabsPlacement:()=>vZ_,TwitterCardSetting:()=>OZ_,commons:()=>_Fc});var _Fc={};Na(_Fc,{ContentAlignment:()=>bZ_,FontDisplay:()=>jZ_,FontStyle:()=>PZ_,HeaderPosition:()=>gZ_,JsScriptStrategy:()=>mZ_,ProgrammingLanguage:()=>hZ_,SearchbarPlacement:()=>yZ_,TabsPlacement:()=>vZ_,TwitterCardSetting:()=>OZ_});var hZ_={Typescript:"typescript",Javascript:"javascript",Python:"python",Java:"java",Go:"go",Ruby:"ruby",Csharp:"csharp",Nodets:"nodets",Nodejs:"nodejs",Dotnet:"dotnet",Curl:"curl",Jvm:"jvm",Ts:"ts",Js:"js"};var yZ_={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var vZ_={Header:"HEADER",Sidebar:"SIDEBAR"};var bZ_={Center:"CENTER",Left:"LEFT"};var gZ_={Fixed:"FIXED",Absolute:"ABSOLUTE"};var OZ_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var mZ_={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var PZ_={Normal:"normal",Italic:"italic"};var jZ_={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var vFc={};Na(vFc,{read:()=>wZ_,write:()=>SZ_});var wZ_={};var SZ_={};var OFc={};Na(OFc,{ChangelogEntryType:()=>EZ_,GeneratorId:()=>_OM,GeneratorLanguage:()=>hOM,ReleaseType:()=>MZ_,cli:()=>DZ_,commons:()=>gFc,versions:()=>AZ_});var DZ_={};var gFc={};Na(gFc,{ChangelogEntryType:()=>EZ_,ReleaseType:()=>MZ_});var EZ_={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var MZ_={Ga:"GA",Rc:"RC"};var AZ_={};function _OM(e){return e}var hOM={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var mFc={};Na(mFc,{PullRequestState:()=>qZ_});var qZ_={Open:"open",Closed:"closed",Merged:"merged"};var wFc={};Na(wFc,{latest:()=>PFc,v1:()=>jFc});var PFc={};Na(PFc,{NodeId:()=>bOM,ProductId:()=>gOM,Slug:()=>yOM,TabId:()=>vOM});function yOM(e){return e}function vOM(e){return e}function bOM(e){return e}function gOM(e){return e}var jFc={};Na(jFc,{NavigationV1Availability:()=>wOM,NodeId:()=>POM,ProductId:()=>jOM,Slug:()=>OOM,TabId:()=>mOM});function OOM(e){return e}function mOM(e){return e}function POM(e){return e}function jOM(e){return e}var wOM={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var DFc={};Na(DFc,{Language:()=>TZ_,VersionBump:()=>CZ_,versions:()=>SFc});var SFc={};Na(SFc,{Language:()=>TZ_,VersionBump:()=>CZ_});var TZ_={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var CZ_={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var BZ_={};var IZ_={};var EFc={};Na(EFc,{PayloadLocation:()=>zZ_});var zZ_={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var xZ_={};var zXn=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};function sp(e){return e!=null}var NZ_=ui(e8n(),1);var RZ_=["PII","PHI","PCI","GDPR","CCPA","HIPAA","COPPA","FERPA","GLBA","SOX","FISMA","NIST","CIS","ISO","IEC","ITAR","EAR","CMMC","CUI","CDI","FTC","FCC","SEC","FINRA","XSS","CSRF","SSRF","XSRF","TLS","SSL","SSH","API","OAuth","OAuth1","OAuth1.0","OAuth2","OAuth2.0","SAML","OpenID","OpenID Connect","CAPTCHA","reCAPTCHA","2FA","MFA","OTP","TOTP","HOTP","U2F","FIDO","FIDO2","PKI","HMAC","AES","RSA","SHA","MD5","BCrypt","PBKDF2","Argon2","SCrypt","JWT","JWE","JWS","JWK","JWA","JOSE","SKU","SKUs","UPC","EAN","ISBN","ASIN","MPN","MSRP","MAP","RRP","MSRP","AM","PM","UTC","GMT","PST","PDT","EST","EDT","CST","CDT","MST","MDT","USA","UK","EU","UAE","APAC","EMEA","LATAM","ANZ","SEA","MEA","MENA","NATO","NA","SA","CA","EU","AU","NZ","JP","KR","CN","HK","TW","SG","MY","TH","ID","PH","VN","IN","PK","BD","LK","NP","MM","KH","LA","MM","BT","MV","USD","EUR","GBP","JPY","CNY","RUB","INR","AUD","CAD","CHF","SGD","MYR","THB","IDR","KRW","PHP","VND","HKD","TWD","MXN","BRL","ARS","CLP","COP","PEN","ZAR","NGN","EGP","AED","SAR","ILS","TRY","SEK","NOK","DKK","ISK","HUF","PLN","CZK","RON","BGN","API","APIs","SDK","SDKs","AI","OCR","REST","SOAP","JSON","XML","HTTP","HTTPS","URI","URL","CRUD","RESTful","KYB","KYC","AML","HTML","CSS","JS","SQL","DB","UI","UX","SaaS","PaaS","IaaS","IP","TCP","UDP","DNS","FTP","SMTP","IMAP","POP3","CSV","MVC","MVP","MVVM","DOM","SPA","SSR","CSR","DDoS","CDN","IoT","ML","DL","NLP","CLI","GUI","BI","ETL","RDBMS","NoSQL","IDE","CMS","CCPA","POSIX","ABI","API","AST","COBOL","DDL","DML","NN","CNN","RNN","LSTM","GRU","ANN","GAN","RL","DL","ML","NLP","NLG","NLU","BERT","GPT","SVM","PCA","AI","CV","TF","TTS","ASR","HMM","DNN","MLP","RBM","CRF","PDF","PDFs","RTF","TXT","XLS","XLSX","PPT","JPG","JPEG","PNG","GIF","GIFs","SVG","TIFF","BMP","ICO","PSD","WebP","AVIF","HEIF","HEIC","EPS","MP3","WAV","AIFF","FLAC","WMA","AAC","OGG","AVI","WMV","MOV","M4V","MP4","MPG","MPEG","FLV","SWF","MKV","WebM","GCP","AWS","VM","VPC","S3","EC2","DynamoDB","CosmosDB","BigQuery","CI/CD","SOC1","SOC2","SOC3","PCI DSS","WAF","IAM","SDN","MPLS","BGP","Vue.js","Node.js",".NET"];function eur(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,NZ_.default)(e,{special:RZ_}).replace(/V\s(\d)/g,"V$1")}function ryu({endpoints:e,webhookEndpoints:t}){let r={};return Object.values({...e,...t}).forEach(i=>{let n=[];i.namespace?.forEach(a=>{let u=[...n,a],c=Bh.api.v1.SubpackageId(u.join("."));r[c]={id:c,name:a,displayName:eur(a)},n.push(a)})}),r}var iyu=class{errors=new zXn},xXn=class{input;context;constructor(t,r){this.input=t,this.context=r}errors(){return this.context.errors.errors}warnings(){return this.context.errors.warnings}};function FZ_(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var nyu=class extends iyu{},A_=class extends xXn{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){if(super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,n!=null){let a=Array.isArray(this.pathId)?this.pathId:[this.pathId];a.every((u,c)=>u===this.accessPath[this.accessPath.length-a.length+c])||this.accessPath.push(...a)}r.logger.debug(`Processing ${FZ_(this.accessPath)}`)}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}},Y6=class extends A_{},ese=class extends Y6{seenSchemas;constructor(t){super(t),this.seenSchemas=new Set(t.seenSchemas)}};var LZ_="x-fern-base-path",UZ_="x-fern-availability",ayu="x-fern-sdk-group-name",VZ_="x-fern-global-headers",WZ_="x-fern-sdk-method-name";var HZ_="x-fern-webhook",$Z_="x-fern-access-token-locator",GZ_="x-fern-basic",QZ_="x-fern-username-variable-name",JZ_="x-fern-password-variable-name",KZ_="x-fern-bearer",YZ_="x-fern-token-variable-name",XZ_="x-fern-header",ZZ_="x-fern-header-variable-name",kZ_="x-fern-server-name",ek_="x-fern-examples";var oyu=class extends A_{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[kZ_]}convert(){if(this.serverName!=null)return this.serverName}};var uyu=class extends A_{url;serverName;constructor(t){super(t),this.safeParse()}parse(){this.url=Object.entries(this.input.variables??{}).reduce((t,[r,i])=>t.replace(`{${r}}`,i.default),this.input.url)??this.input.url,this.serverName=new oyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.serverName?.convert()??this.url;if(!(this.url==null||t==null))return{id:Bh.EnvironmentId(t),baseUrl:this.url}}};function tur(e,t,r,i){let n=e??[],a=new Set(n.map(c=>c.url)),u=(t??[]).filter(c=>!a.has(c.url)).map((c,d)=>new uyu({input:c,context:r,accessPath:i,pathId:["servers",`${d}`]}));return[...n,...u]}function AD(e){return typeof e=="object"&&sp(e)&&"$ref"in e&&typeof e.$ref=="string"}function x$(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(AD(n)&&(n=x$(n,t,r)),n)}function syu(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return AD(r)?x$(r,t,void 0):r}var Ok_=ui(vx());var cyu=class extends A_{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[GZ_];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var lyu=class extends A_{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[JZ_]}convert(){return this.passwordVariableName}};var fyu=class extends A_{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[QZ_]}convert(){return this.usernameVariableName}};var dyu=class extends A_{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[KZ_];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var pyu=class extends A_{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[YZ_]}convert(){return this.tokenVariableName}};function tk_(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var rk_="x-bearer-format",ik_="x-code-samples",nk_="x-codeSamples";var _yu=class extends A_{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[rk_]}convert(){return this.bearerFormat}};var hyu=class extends A_{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[XZ_];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var yyu=class extends A_{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[ZZ_]}convert(){return this.headerVariableName}};function ak_(e){return e.type==="apiKey"}var RXn=class extends A_{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){ak_(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new hyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new yyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new _yu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.headerAuthNode?.convert();if(t!=null)return{type:"header",nameOverride:t?.name,headerWireValue:this.headerName??"Authorization",prefix:t?.prefix??this.headerBearerFormatNode?.convert()}}};function vyu(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function byu(e){return typeof e=="string"||typeof e=="symbol"?e:Object.is(e?.valueOf?.(),-0)?"-0":String(e)}function gyu(e){let t=[],r=e.length;if(r===0)return t;let i=0,n="",a="",u=!1;for(e.charCodeAt(0)===46&&(t.push(""),i++);i<r;){let c=e[i];a?c==="\\"&&i+1<r?(i++,n+=e[i]):c===a?a="":n+=c:u?c==='"'||c==="'"?a=c:c==="]"?(u=!1,t.push(n),n=""):n+=c:c==="["?(u=!0,n&&(t.push(n),n="")):c==="."?n&&(t.push(n),n=""):n+=c,i++}return n&&t.push(n),t}function yVa(e,t,r){if(e==null)return r;switch(typeof t){case"string":{if(kpu(t))return r;let i=e[t];return i===void 0?vyu(t)?yVa(e,gyu(t),r):r:i}case"number":case"symbol":{typeof t=="number"&&(t=byu(t));let i=e[t];return i===void 0?r:i}default:{if(Array.isArray(t))return SOM(e,t,r);if(Object.is(t?.valueOf(),-0)?t="-0":t=String(t),kpu(t))return r;let i=e[t];return i===void 0?r:i}}}function SOM(e,t,r){if(t.length===0)return r;let i=e;for(let n=0;n<t.length;n++){if(i==null||kpu(t[n]))return r;i=i[t[n]]}return i===void 0?r:i}function ok_(e){return function(t){return yVa(t,e)}}function uk_(e){return e!==null&&(typeof e=="object"||typeof e=="function")}function MFc(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function sk_(e,t,r){return typeof r!="function"?NXn(e,t):AFc(e,t,function i(n,a,u,c,d,s){let o=r(n,a,u,c,d,s);return o!==void 0?!!o:AFc(n,a,i,s)},new Map)}function AFc(e,t,r,i){if(t===e)return!0;switch(typeof t){case"object":return DOM(e,t,r,i);case"function":return Object.keys(t).length>0?AFc(e,{...t},r,i):MFc(e,t);default:return uk_(e)?typeof t=="string"?t==="":!0:MFc(e,t)}}function DOM(e,t,r,i){if(t==null)return!0;if(Array.isArray(t))return ck_(e,t,r,i);if(t instanceof Map)return EOM(e,t,r,i);if(t instanceof Set)return MOM(e,t,r,i);let n=Object.keys(t);if(e==null)return n.length===0;if(n.length===0)return!0;if(i&&i.has(t))return i.get(t)===e;i&&i.set(t,e);try{for(let a=0;a<n.length;a++){let u=n[a];if(!Qpu(e)&&!(u in e)||t[u]===void 0&&e[u]!==void 0||t[u]===null&&e[u]!==null||!r(e[u],t[u],u,e,t,i))return!1}return!0}finally{i&&i.delete(t)}}function EOM(e,t,r,i){if(t.size===0)return!0;if(!(e instanceof Map))return!1;for(let[n,a]of t.entries()){let u=e.get(n);if(r(u,a,n,e,t,i)===!1)return!1}return!0}function ck_(e,t,r,i){if(t.length===0)return!0;if(!Array.isArray(e))return!1;let n=new Set;for(let a=0;a<t.length;a++){let u=t[a],c=!1;for(let d=0;d<e.length;d++){if(n.has(d))continue;let s=e[d],o=!1;if(r(s,u,a,e,t,i)&&(o=!0),o){n.add(d),c=!0;break}}if(!c)return!1}return!0}function MOM(e,t,r,i){return t.size===0?!0:e instanceof Set?ck_([...e],[...t],r,i):!1}function NXn(e,t){return sk_(e,t,()=>{})}function lk_(e){return e=xV_(e),t=>NXn(t,e)}function fk_(e,t){return zV_(e,(r,i,n,a)=>{let u=t?.(r,i,n,a);if(u!==void 0)return u;if(typeof e=="object")switch(Object.prototype.toString.call(e)){case Ypu:case Kpu:case Xpu:{let c=new e.constructor(e?.valueOf());return GNi(c,e),c}case Zpu:{let c={};return GNi(c,e),c.length=e.length,c[Symbol.iterator]=e[Symbol.iterator],c}default:return}})}function dk_(e){return fk_(e)}var AOM=/^(?:0|[1-9]\d*)$/;function pk_(e,t=Number.MAX_SAFE_INTEGER){switch(typeof e){case"number":return Number.isInteger(e)&&e>=0&&e<t;case"symbol":return!1;case"string":return AOM.test(e)}}function _k_(e){return e!==null&&typeof e=="object"&&Jpu(e)==="[object Arguments]"}function hk_(e,t){let r;if(Array.isArray(t)?r=t:typeof t=="string"&&vyu(t)&&e?.[t]==null?r=gyu(t):r=[t],r.length===0)return!1;let i=e;for(let n=0;n<r.length;n++){let a=r[n];if((i==null||!Object.hasOwn(i,a))&&!((Array.isArray(i)||_k_(i))&&pk_(a)&&a<i.length))return!1;i=i[a]}return!0}function yk_(e,t){switch(typeof e){case"object":{Object.is(e?.valueOf(),-0)&&(e="-0");break}case"number":{e=byu(e);break}}return t=dk_(t),function(r){let i=yVa(r,e);return i===void 0?hk_(r,e):t===void 0?i===void 0:NXn(i,t)}}function vk_(e){if(e==null)return fhu;switch(typeof e){case"function":return e;case"object":return Array.isArray(e)&&e.length===2?yk_(e[0],e[1]):lk_(e);case"string":case"symbol":case"number":return ok_(e)}}function qFc(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e))return e.map(qFc).join(",");let t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function Oyu(e,t=fhu){return e==null?{}:B$(e,vk_(t))}function bk_(e){return typeof e!="string"&&(e=qFc(e)),e.replace(/['\u2019]/g,"")}function aJt(e){return NV_(bk_(e))}function dq(e){if(e!=null)return Array.isArray(e)?e:[e]}function myu({namespace:e,path:t,method:r,sdkMethodName:i,operationId:n,displayName:a,isWebhook:u}){if(t==null)return;let c=r!=null&&t!=null?`${r}_${t.split("/").join("_")}`:r??t.split("/").join("_");if(!(i==null&&n==null&&a==null&&c==null))return`${qOM(u)}${TOM(e)}.${COM(i,n,a,c)}`}function qOM(e){return e?"webhook_":"endpoint_"}function TOM(e){return e!=null?dq(e)?.map(t=>aJt(t)).join("/"):""}function COM(e,t,r,i){return e||t||aJt(r??"")||aJt(i??"")}function gk_(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var Pyu=class extends A_{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[$Z_],this.accessTokenLocator!=null&&(gk_(this.accessTokenLocator)||(this.context.errors.error({message:"Invalid access token locator, must be a valid jq path",path:this.accessPath}),this.accessTokenLocator=void 0))}convert(){return this.accessTokenLocator}};var jyu=class extends A_{authorizationUrl;headerAuthNode;accessTokenLocatorNode;constructor(t){super(t),this.safeParse()}parse(){if(this.input.flows.clientCredentials!=null){let t=this.input.flows.clientCredentials;this.authorizationUrl=t.tokenUrl,this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.headerAuthNode=new RXn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new Pyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.accessTokenLocatorNode?.accessTokenLocator==null&&this.context.errors.error({message:"Expected 'x-fern-access-token-locator' property to be specified",path:this.accessPath})}}convert(){let t=this.accessTokenLocatorNode?.convert();if(t==null||this.authorizationUrl==null)return{type:"bearerAuth",tokenName:void 0};let r=myu({namespace:void 0,path:this.authorizationUrl,method:"POST",sdkMethodName:void 0,operationId:void 0,displayName:void 0,isWebhook:void 0});if(r!=null)return{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:Bh.EndpointId(r),accessTokenLocator:Bh.JqString(t),headerName:this.headerAuthNode?.convert()?.headerWireValue,tokenPrefix:this.headerAuthNode?.convert()?.prefix}}}}};var FXn=class extends A_{authScheme;headerAuthNode;bearerTokenNode;bearerTokenVariableNameNode;basicAuthNode;basicUsernameVariableNameNode;basicPasswordVariableNameNode;oauth2Node;constructor(t){super(t),this.safeParse()}parse(){switch(this.input.type){case"http":switch(this.input.scheme){case"basic":{this.authScheme="basic",this.basicAuthNode=new cyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicUsernameVariableNameNode=new fyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new lyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),(this.basicAuthNode==null||this.basicAuthNode.username==null&&this.basicUsernameVariableNameNode?.usernameVariableName==null||this.basicAuthNode.password==null&&this.basicPasswordVariableNameNode?.passwordVariableName==null)&&this.context.errors.warning({message:"Basic auth should specify either a username or a username variable name",path:this.accessPath});break}case"bearer":{this.authScheme="bearer",this.bearerTokenNode=new dyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new pyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}default:{this.context.errors.warning({message:`Unsupported HTTP auth scheme: ${this.input.scheme}`,path:this.accessPath});break}}break;case"apiKey":{tk_(this.input)?(this.authScheme="header",this.headerAuthNode=new RXn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})):this.context.errors.error({message:`Unsupported API key location: ${this.input.in}`,path:this.accessPath});break}case"oauth2":{this.authScheme="oauth",this.oauth2Node=new jyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}case"openIdConnect":{this.authScheme="bearer";break}}}convert(){switch(this.authScheme){case"basic":{let t=this.basicAuthNode?.convert();return{type:"basicAuth",usernameName:t?.username?.name??this.basicUsernameVariableNameNode?.convert(),passwordName:t?.password?.name??this.basicPasswordVariableNameNode?.convert()}}case"bearer":return{type:"bearerAuth",tokenName:this.bearerTokenNode?.convert()?.tokenVariableName??this.bearerTokenVariableNameNode?.convert()};case"header":return this.headerAuthNode?.convert();case"oauth":return this.oauth2Node?.convert();case void 0:return;default:new Ok_.UnreachableCaseError(this.authScheme);return}}};var LXn=class extends A_{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(i=>{let n=syu(i,this.context.document);if(n==null){this.context.errors.warning({message:`No auth scheme found for ${i}. Inline security schemes are not supported.`,path:this.accessPath});return}let a=new FXn({input:n,context:this.context,accessPath:this.accessPath,pathId:["security",`${r}`]});a.convert()!=null?(this.authNodesMap??={},this.authNodesMap[i]=a):this.context.errors.warning({message:`No auth scheme found for ${i}`,path:this.accessPath})}))}convert(){return Object.fromEntries(Object.entries(this.authNodesMap??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[t,i]}).filter(sp))}};var wyu=class extends A_{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[LZ_],this.basePath!=null?(this.basePath.startsWith("/")&&(this.basePath=this.basePath.slice(1)),this.basePath.endsWith("/")&&(this.basePath=this.basePath.slice(0,-1))):this.basePath=void 0}convert(){return this.basePath}};function mk_(e){return"required"in e&&typeof e.required=="boolean"?e.required:!1}function Pk_(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function UXn(e,t){return e==null?void 0:Object.entries(e).map(([i,n])=>dq(n.convert())?.map(u=>((t!=null&&!t.includes(i)||t==null&&!mk_(n))&&(u=Pk_(u,u.type==="enum"?u.default:void 0)),{key:Bh.PropertyKey(i),valueShape:u,description:n.description,availability:n.availability?.convert()})).filter(sp)).filter(sp).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(u=>[...a,u]):[[...a]]),[[]])}function Syu(e,t){return AD(e)?x$(e,t,void 0):e}function c7i(e,t){return e!=null&&e!==""?e:t!=null&&t!==""?t:void 0}function jk_(e,t){let r={...e};for(let[i,n]of Object.entries(t??{}))r[i]=[...r[i]??[],...n];return Object.keys(r).length>0?r:void 0}function wk_(e,t){if(e==null)return t;if(t==null)return e;let r=[];for(let i of e)for(let n of t)r.push({path:i.path??n.path,responseStatusCode:i.responseStatusCode??n.responseStatusCode,name:i.name??n.name,description:i.description??n.description,pathParameters:i.pathParameters??n.pathParameters,queryParameters:i.queryParameters??n.queryParameters,headers:i.headers??n.headers,requestBody:i.requestBody??n.requestBody,responseBody:i.responseBody??n.responseBody,snippets:{...n.snippets,...i.snippets}});return r}var Sk_=ui(vx());var TFc=["decimal","decimal128","double-int","double","float","sf-decimal"],CFc=["int16","int32","int64","int8","sf-integer","uint8"],BFc=["base64url","binary","byte","char","commonmark","date-time","date","decimal","decimal128","duration","email","hostname","html","http-date","idn-email","idn-hostname","int64","ipv4","ipv6","iri-reference","iri","json-pointer","media-range","password","regex","relative-json-pointer","sf-binary","sf-boolean","sf-string","sf-token","time","uri-reference","uri-template","uri","uuid"],IFc=["beta","pre-release","in-development","generally-available","deprecated"];function X6(e,t){return AD(e)?x$(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var Z6e=class extends A_{availability;constructor(t){super(t),this.safeParse()}parse(){if(X6(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[UZ_];r!=null&&(IFc.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${IFc.join(", ")}. Received: ${r}`,path:this.accessPath}),this.availability=void 0))}}convert(){switch(this.availability){case"beta":case"pre-release":return Bh.Availability.Beta;case"in-development":return Bh.Availability.InDevelopment;case"generally-available":return Bh.Availability.GenerallyAvailable;case"deprecated":return Bh.Availability.Deprecated;case void 0:return;default:new Sk_.UnreachableCaseError(this.availability);return}}};var Eyu=ui(vx());function Dk_(e){return typeof e=="object"&&e!=null&&"language"in e}function Ek_(e){return typeof e=="object"&&e!=null&&"sdk"in e}function Mk_(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function Ak_(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function Dyu(e){return typeof e=="object"&&e!=null&&"event"in e}function zFc(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(Dyu)}function l7i(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function qk_(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var Myu=class extends A_{path;successResponseStatusCode;requestBodyByContentType;responseBodies;examples;constructor(t,r,i,n,a){super(t),this.path=r,this.successResponseStatusCode=i,this.requestBodyByContentType=n,this.responseBodies=a,this.safeParse()}parse(){this.examples=this.input[ek_]}convertFormDataExampleRequest(t,r){if(t.fields!=null)switch(t.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(t.fields).map(([n,a])=>{let u=typeof r=="object"?r[n]:void 0;switch(a.multipartType){case"file":return l7i(u)?[n,{type:"filenameWithData",filename:u.filename,data:Bh.FileId(u.data)}]:u!=null?[n,{type:"filename",value:u}]:void 0;case"files":{if(Array.isArray(u)){if(u.every(c=>l7i(c)))return[n,{type:"filenamesWithData",value:u.map(c=>({filename:c.filename,data:Bh.FileId(c.data)}))}];if(u.every(c=>typeof c=="string"))return[n,{type:"filenames",value:u}]}return}case"property":return[n,{type:"json",value:u}];case void 0:return;default:new Eyu.UnreachableCaseError(a.multipartType);return}}).filter(sp))};case"json":return{type:"json",value:r};case"bytes":return typeof r=="string"?{type:"bytes",value:{type:"base64",value:r}}:void 0;default:return}}convert(){if(this.examples==null)return;this.requestBodyByContentType!=null&&Object.keys(this.requestBodyByContentType).length>1&&this.context.logger.warn(`Multiple request bodies found for #/${[this.accessPath,this.pathId,"x-fern-examples"].join("/")}. Coercing to first request body until supported.`);let t=Object.keys(this.requestBodyByContentType??{})[0];return this.examples.flatMap(r=>(this.responseBodies??[]).map(i=>{let n=t!=null?this.requestBodyByContentType?.[t]:void 0,a;if(n!=null)switch(n.contentType){case"form-data":a=qk_(r.request)?this.convertFormDataExampleRequest(n,r.request):void 0;break;case"json":a=r.request!=null?{type:"json",value:r.request}:void 0;break;case"bytes":a=typeof r.request=="string"&&r.request!=null?{type:"bytes",value:{type:"base64",value:r.request}}:void 0;break;case void 0:break;default:new Eyu.UnreachableCaseError(n.contentType);break}let u;switch(i.contentType){case"application/json":{Mk_(r.response)&&(u={type:"json",value:r.response.body});break}case"text/event-stream":{zFc(r.response)&&(u={type:"sse",value:r.response.stream.map(l=>({event:l.event,data:l.data}))});break}case"application/octet-stream":!zFc(r.response)&&Ak_(r.response)&&(u={type:"stream",value:r.response.stream});break;case void 0:break;default:new Eyu.UnreachableCaseError(i.contentType);break}let c={};r["code-samples"]?.forEach(l=>{Dk_(l)?l.language!=null&&(c[l.language]??=[],c[l.language]?.push({name:l.name,language:l.language,install:l.install,code:l.code,generated:!1,description:l.docs})):Ek_(l)&&l.sdk!=null&&(c[l.sdk]??=[],c[l.sdk]?.push({name:l.name,language:l.sdk,install:void 0,code:l.code,generated:!1,description:l.docs}))});let d=Object.fromEntries(Object.entries(r["path-parameters"]??{}).map(([l,v])=>[Bh.PropertyKey(l),v])),s=Object.fromEntries(Object.entries(r["query-parameters"]??{}).map(([l,v])=>[Bh.PropertyKey(l),v])),o=Object.fromEntries(Object.entries(r.headers??{}).map(([l,v])=>[Bh.PropertyKey(l),v]));return{path:this.path,responseStatusCode:this.successResponseStatusCode,name:r.name,description:r.docs,pathParameters:Object.keys(d).length>0?d:void 0,queryParameters:Object.keys(s).length>0?s:void 0,headers:Object.keys(o).length>0?o:void 0,requestBody:a,responseBody:u,snippets:c}}))}};var vVa=class extends A_{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[ayu]}convert(){if(this.groupName==null)return;let t;return Array.isArray(this.groupName)?t=this.groupName:t=[this.groupName],t.map(r=>Bh.api.v1.SubpackageId(aJt(r)))}};var Ayu=class extends A_{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[WZ_]}convert(){return this.sdkMethodName}};var qyu=class extends A_{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[HZ_]}convert(){return this.isWebhook}};var Tyu=class extends A_{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[ik_]??[],...this.input[nk_]??[]],this.codeSamples.forEach(t=>{[...Object.values(Bh.api.v1.read.SupportedLanguage),"Kotlin","Swift","PHP"].map(r=>r.toLowerCase()).includes(t.lang.toLowerCase())||this.context.errors.warning({message:`Unsupported language: ${t.lang}. This may not render correctly.`,path:this.accessPath})})}convert(){let t={};if(this.codeSamples?.forEach(r=>{t[r.lang.toLowerCase()]??=[],t[r.lang.toLowerCase()]?.push({name:r.label,language:r.lang,code:r.source,install:void 0,generated:!1,description:void 0})}),Object.keys(t).length!==0)return t}};var Don=ui(vx());function xFc(e,t){return AD(e)?x$(e,t,void 0):e}function Tk_(e,t){return e.replace(/{(\w+)}/g,(r,i)=>t[i]!=null&&typeof t[i]=="string"||typeof t[i]=="number"||typeof t[i]=="boolean"?`${t[i]}`:r)}var xU="",rur=class extends A_{path;responseStatusCode;name;shapes;resolvedRequestInput;resolvedResponseInput;summary;constructor(t,r,i,n,a){super(t),this.path=r,this.responseStatusCode=i,this.name=n,this.shapes=a,this.safeParse()}validateFormDataRequestExample(){return typeof this.resolvedRequestInput?.value!="object"?!1:Object.entries(this.shapes.requestBody?.fields??{}).reduce((t,[r,i])=>{let n=this.resolvedRequestInput?.value[r];switch(i.multipartType){case"file":return t&&(l7i(n)||typeof n=="string");case"files":return t&&Array.isArray(n)&&n.every(a=>l7i(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new Don.UnreachableCaseError(i.multipartType),t}},!0)}parse(){let t=this.shapes.requestBody?.schema?.example({includeOptionals:!1,override:void 0});this.resolvedRequestInput=xFc(this.input?.requestExample,this.context.document)??(t!=null?{value:t}:void 0);let r=this.shapes.responseBody?.schema?.example({includeOptionals:!1,override:void 0});if(this.resolvedResponseInput=xFc(this.input?.responseExample,this.context.document)??(r!=null?{value:r}:void 0),this.summary=this.input?.requestExample?.summary??this.input?.responseExample?.summary,this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody?.contentType){case"json":{if(typeof this.resolvedRequestInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break}case"bytes":{if(typeof this.resolvedRequestInput.value!="string"){this.context.errors.error({message:"Invalid example, expected string for bytes",path:this.accessPath});return}break}case"form-data":{if(!this.validateFormDataRequestExample()){this.context.errors.error({message:"Invalid example, expected valid form-data",path:this.accessPath});return}break}case void 0:break;default:new Don.UnreachableCaseError(this.shapes.requestBody?.contentType),this.context.errors.error({message:"Invalid example, unsupported content type",path:this.accessPath});return}if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody?.contentType){case"application/json":if(this.resolvedResponseInput!=null&&typeof this.resolvedResponseInput!="object"||this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break;case"text/event-stream":if(this.resolvedResponseInput.value!=null&&!Array.isArray(this.resolvedResponseInput.value)&&!this.resolvedResponseInput.value.every(Dyu)){this.context.errors.error({message:"Invalid example, expected array of SSE events for event-stream",path:this.accessPath});return}break;case"application/octet-stream":if(this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="string"&&!Array.isArray(this.resolvedResponseInput.value)){this.context.errors.error({message:"Invalid example, expected string or array for octet-stream",path:this.accessPath});return}break;case void 0:break;default:new Don.UnreachableCaseError(this.shapes.responseBody?.contentType);return}}convertFormDataExampleRequest(){if(!(this.resolvedRequestInput==null||this.shapes.requestBody?.fields==null))switch(this.shapes.requestBody?.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(this.shapes.requestBody.fields).map(([r,i])=>{let n=this.resolvedRequestInput?.value?.[r];switch(i.multipartType){case"file":return l7i(n)?[r,{type:"filenameWithData",filename:n.filename,data:Bh.FileId(n.data)}]:[r,{type:"filename",value:n}];case"files":{if(Array.isArray(n)){if(n.every(a=>l7i(a)))return[r,{type:"filenamesWithData",value:n.map(a=>({filename:a.filename,data:Bh.FileId(a.data)}))}];if(n.every(a=>typeof a=="string"))return[r,{type:"filenames",value:n}]}return}case"property":return[r,{type:"json",value:n}];case void 0:return;default:new Don.UnreachableCaseError(i.multipartType);return}}).filter(sp))};case"json":return{type:"json",value:this.resolvedRequestInput.value};case"bytes":return typeof this.resolvedRequestInput.value=="string"?{type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}}:void 0;default:return}}convertDescription(){if(this.resolvedRequestInput!=null&&this.resolvedResponseInput!=null)return this.resolvedResponseInput.description;if(this.resolvedRequestInput!=null)return this.resolvedRequestInput.description;if(this.resolvedResponseInput!=null)return this.resolvedResponseInput.description}convert(){let t;if(this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody.contentType){case"form-data":t=this.convertFormDataExampleRequest();break;case"json":t={type:"json",value:this.resolvedRequestInput.value};break;case"bytes":t={type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}};break;case void 0:break;default:new Don.UnreachableCaseError(this.shapes.requestBody?.contentType);break}let r;if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody.contentType){case"application/json":{r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break}case"text/event-stream":r={type:"sse",value:this.resolvedResponseInput?.value};break;case"application/octet-stream":r={type:typeof this.resolvedResponseInput?.value=="string"?"filename":"stream",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;case void 0:r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;default:new Don.UnreachableCaseError(this.shapes.responseBody?.contentType);break}let i=Object.fromEntries(Object.entries(this.shapes.pathParameters??{}).map(([u,c])=>[u,c.example({includeOptionals:!1,override:u})]));i=Object.keys(i).length>0?i:void 0;let n=Object.fromEntries(Object.entries(this.shapes.queryParameters??{}).map(([u,c])=>c.required||c.inputExample!=null?[u,c.example({includeOptionals:!1,override:u})]:void 0).filter(sp));n=Object.keys(n).length>0?n:void 0;let a=Object.fromEntries(Object.entries(this.shapes.requestHeaders??{}).map(([u,c])=>c.required||c.inputExample!=null?[u,c.example({includeOptionals:!1,override:u})]:void 0).filter(sp));if(a=Object.keys(a).length>0?a:void 0,!(this.path==null&&t==null&&r==null&&a==null&&n==null&&i==null))return{path:Tk_(this.path,i??{}),responseStatusCode:this.responseStatusCode,name:this.name!=null?eur(this.name):this.summary!=null?eur(this.summary):void 0,description:this.convertDescription(),pathParameters:i,queryParameters:n,headers:a,requestBody:t,responseBody:r,snippets:void 0}}};function Ck_(e,t){return AD(e)?x$(e,t,void 0):e}var $k_=ui(vx());var Bk_="#/components/schemas/";function VXn(e){if(e.$ref.startsWith(Bk_))return e.$ref.replace(Bk_,"")}function WPi(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}function f7i(e){return typeof e.type=="string"&&e.type==="array"}function Ik_(e){return e.type==="boolean"}function zk_(e){return e.type==="integer"}function d7i(e){return!Array.isArray(e.type)&&!f7i(e)}function xk_(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||d7i(t)||f7i(t))}function Rk_(e){return"nullable"in e&&typeof e.nullable=="boolean"}function Nk_(e){return e.type==="null"}function Fk_(e){return e.type==="number"}function RFc(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function Lk_(e){return e.type==="string"}var Cyu=class extends ese{item;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.item=new HT({input:this.input.items,context:this.context,accessPath:this.accessPath,pathId:"items",seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}),this.input.items==null&&this.context.errors.error({message:"Expected 'items' property to be specified",path:this.accessPath})}convert(){return dq(this.item?.convert())?.map(r=>({type:"alias",value:{type:"list",itemShape:r}}))}example(t){return this.input.example??this.input.examples?.[0]??[this.item?.example(t)]}};var Byu=class extends Y6{constValue;description;availability;constructor(t){super(t),this.safeParse()}parse(){this.input.const!=null&&(typeof this.input.const=="string"||typeof this.input.const=="number"||typeof this.input.const=="boolean")?this.constValue=this.input.const.toString():this.context.errors.warning({message:`Unsupported const type: ${typeof this.input}`,path:this.accessPath}),this.description=this.input.description,this.availability=new Z6e({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"})}convert(){if(this.constValue!=null)return{type:"enum",default:this.constValue,values:[{value:this.constValue,description:this.description,availability:this.availability?.convert()}]}}example(){return this.input.example??this.input.examples?.[0]??this.constValue}};var Iyu=class extends ese{typeNodes;nullable;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.parse()}parse(){this.typeNodes=this.input.map(t=>{if(t.type==="null")this.nullable=!0;else return new HT({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName})}).filter(sp)}convert(){if(this.typeNodes==null)return;let i=this.typeNodes.map(n=>dq(n.convert())?.map(u=>({displayName:n.name,shape:u,description:n.description,availability:n.availability?.convert()}))).filter(sp).reduce((n,a)=>n.flatMap(u=>a.length>0?a.map(c=>[...u,c]):[[...u]]),[[]]).map(n=>({type:"undiscriminatedUnion",variants:n}));return this.nullable?i.map(WPi).filter(sp):i}example(t){return this.nullable?null:this.typeNodes?.[0]?.example(t)}};function zyu(e){return e!=null&&e.length>0?e:[void 0]}var WXn=class extends ese{description;extends=[];properties;extraProperties;requiredProperties;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.extends=[],this.requiredProperties=this.input.required,this.properties=Object.fromEntries(Object.entries(this.input.properties??{}).map(([t,r])=>[t,new HT({input:r,context:this.context,accessPath:this.accessPath,pathId:["properties",t],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})])),this.extraProperties=this.input.additionalProperties!=null?typeof this.input.additionalProperties=="boolean"?this.input.additionalProperties?this.input.title:void 0:new HT({input:this.input.additionalProperties,context:this.context,accessPath:this.accessPath,pathId:["additionalProperties"],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0,this.input.allOf!=null&&(this.extends=this.extends.concat(this.input.allOf.map((t,r)=>{if(AD(t))return VXn(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([i,n])=>[i,new HT({input:n,context:this.context,accessPath:this.accessPath,pathId:["allOf",r.toString(),"properties",i],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))}}).filter(sp))),this.description=this.input.description}convertProperties(){if(this.properties!=null)return UXn(this.properties,this.requiredProperties)}convertExtraProperties(){return this.extraProperties==null?void 0:typeof this.extraProperties=="string"?[{type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:{type:"alias",value:{type:"unknown",displayName:this.extraProperties}}}]:dq(this.extraProperties.convert())?.map(r=>({type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:r})).filter(sp)}convert(){let t=this.convertProperties();if(t==null)return;let r=this.convertExtraProperties();return t.flatMap(i=>zyu(r).map(n=>(this.extends==null||this.extends.length===0)&&i.length===0&&n!=null?{type:"alias",value:n}:{type:"object",extends:this.extends.map(a=>Bh.TypeId(a)),properties:i,extraProperties:n}))}example({includeOptionals:t}){let r={...this.properties};return this.input.allOf?.forEach(i=>{let n=X6(i,this.context.document);n!=null&&(r={...r,...Object.fromEntries(Object.entries(n.properties??{}).map(([a,u])=>[a,new HT({input:u,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))})}),this.input.example??this.input.examples?.[0]??(!t&&this.requiredProperties!=null&&this.requiredProperties.length>0?this.requiredProperties?.reduce((i,n)=>{let a=r?.[n];return i[n]=a?.example({includeOptionals:t,override:n}),i},{}):Object.entries(r).reduce((i,[n,a])=>(i[n]=a?.example({includeOptionals:t,override:n}),i),{}))}};var xyu=class extends ese{isNullable;discriminated;discriminant;discriminatedMapping;undiscriminatedMapping;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.input.oneOf!=null||this.input.anyOf!=null)if(this.isNullable=(this.input.oneOf??this.input.anyOf)?.some(t=>X6(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>X6(t,this.context.document)?.type!=="null"?new HT({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0).filter(sp);else{let t=this.input.discriminator.mapping;if(t!=null){this.discriminated=!0,this.discriminant=this.input.discriminator.propertyName,this.discriminatedMapping={};let r=this.discriminatedMapping;Object.entries(t).map(([i,n])=>{let a=X6({$ref:n},this.context.document);if(a==null){this.context.errors.warning({message:`Expected schema reference. Received undefined reference: ${n}`,path:[...this.accessPath,"discriminator","mapping",i]});return}r[i]=new HT({input:a,context:this.context,accessPath:[...this.accessPath,"discriminator","mapping",i],pathId:i,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})})}}}convert(){if(!this.discriminated&&this.undiscriminatedMapping?.length===1){let n=this.undiscriminatedMapping?.flatMap(a=>a.convert()).filter(sp);return this.isNullable&&n!=null?n.map(WPi).filter(sp):n}let t=0,r=this.discriminated&&this.discriminant!=null&&this.discriminatedMapping!=null?{type:"discriminatedUnion",discriminant:Bh.PropertyKey(this.discriminant),variants:Object.entries(this.discriminatedMapping).flatMap(([n,a])=>dq(a.convert())?.map(c=>{if(!(c==null||c.type!=="object"))return{discriminantValue:n,displayName:a.name??eur(n),availability:a.availability?.convert(),description:a.description,...c}}).filter(sp)).filter(sp)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(n=>dq(n.convert())?.map(u=>{if(u==null)return;t+=1;let c=u.type==="object"?eur(`${this.schemaName??"Variant"} ${t}`):void 0;return{displayName:n.name??(u.type==="alias"&&u.value.type==="id"?eur(u.value.id):c),shape:u,description:n.description,availability:n.availability?.convert()}}).filter(sp)).filter(sp)}:void 0,i=this.isNullable?WPi(r):r;return i!=null?[i]:void 0}example(t){return this.input.example??this.input.examples?.[0]??this.undiscriminatedMapping?.[0]?.example(t)??Object.values(this.discriminatedMapping??{})[0]?.example(t)}};var Ryu=class extends Y6{default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.input.default!=null&&typeof this.input.default!="boolean"&&this.context.errors.warning({message:`Expected default value to be a boolean. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default}convert(){return{type:"alias",value:{type:"primitive",value:{type:"boolean",default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:!1)}};var p7i=class extends Y6{default;values=[];nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){if(this.input.enum!=null){let t=!0;this.values=this.input.enum.map((r,i)=>{if(t){if(AD(r)){let n=X6(r,this.context.document);r=typeof n=="string"?n:typeof n?.default=="string"?n?.default:typeof n?.example=="string"?n.example:void 0}if(typeof r!="string"){this.context.errors.error({message:`Expected enum values to be strings. Received ${r}`,path:[...this.accessPath,`enum[${i}]`]}),t=!1;return}return r}}).filter(sp),this.values=Array.from(new Set(this.values))}this.default=this.input.default}convert(){return{type:"enum",values:this.values.map(t=>({value:t,description:void 0,availability:void 0})),default:this.default}}example(){return this.input.example??this.input.examples?.[0]??this.default??this.values[0]??(this.nullable?null:void 0)}};var Uk_=ui(vx());function BOM(e){return CFc.includes(e)}var Nyu=class extends Y6{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be an integer. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(BOM(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${CFc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="integer";if(this.format!=null)switch(this.format){case"int64":t="long";break;case"int8":case"int16":case"int32":case"uint8":case"sf-integer":case void 0:t="integer";break;default:new Uk_.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var Fyu=class extends Y6{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return WPi({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var Vk_=ui(vx());function IOM(e){return TFc.includes(e)}var Lyu=class extends Y6{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be a number. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(IOM(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${TFc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="double";if(this.format!=null)switch(this.format){case"decimal":case"decimal128":case"double-int":case"double":case"float":case"sf-decimal":case void 0:t="double";break;default:new Vk_.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var Wk_=ui(vx());function zOM(e){return BFc.includes(e)}var Uyu=class extends Y6{format;regex;default;minLength;maxLength;enum;mimeType;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}mapToFdrType(t){switch(t){case"base64url":case"binary":case"byte":case"sf-binary":return"base64";case"date-time":return"datetime";case"int64":return"bigInteger";case"date":return"date";case"uuid":return"uuid";case"char":case"commonmark":case"decimal":case"decimal128":case"duration":case"email":case"hostname":case"html":case"http-date":case"idn-email":case"idn-hostname":case"ipv4":case"ipv6":case"iri-reference":case"iri":case"json-pointer":case"media-range":case"password":case"regex":case"relative-json-pointer":case"sf-boolean":case"sf-string":case"sf-token":case"time":case"uri-reference":case"uri-template":case"uri":case void 0:return"string";default:return new Wk_.UnreachableCaseError(t),"string"}}parse(){this.regex=this.input.pattern,this.minLength=this.input.minLength,this.maxLength=this.input.maxLength,this.mimeType=this.input.contentMediaType,this.input.default!=null&&typeof this.input.default!="string"&&this.context.errors.warning({message:`Expected default value to be a string. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(zOM(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${BFc.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new p7i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"enum",nullable:this.nullable}))}convert(){if(this.enum!=null)return this.enum.convert();let t="string";return this.format!=null&&(t=this.mapToFdrType(this.format)),{type:"alias",value:{type:"primitive",value:t==="base64"?{type:t,mimeType:this.mimeType,default:this.default}:{type:t,format:t==="string"?this.format:void 0,regex:this.regex,minLength:this.minLength,maxLength:this.maxLength,default:this.default}}}}example({override:t}){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:t??"string")}};var Hk_=ui(vx());var Vyu=class extends Y6{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,Hk_.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var Eon=class extends ese{description;availability;schemaId;maybeEnumConverterNode;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.description=t.description,this.availability=t.availability,this.safeParse()}parse(){this.schemaId=VXn(this.input);let t=X6(this.input,this.context.document);t?.enum!=null&&d7i(t)&&(this.maybeEnumConverterNode=new p7i({input:t,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",nullable:this.nullable})),this.schemaId==null&&this.context.errors.error({message:`Unprocessable reference: ${this.input.$ref}`,path:this.accessPath})}convert(){if(this.schemaId!=null)return{type:"alias",value:{type:"id",id:Bh.TypeId(this.schemaId),default:this.maybeEnumConverterNode?.default!=null?{type:"enum",value:this.maybeEnumConverterNode.default}:void 0}}}example(t){let r=X6(this.input,this.context.document);if(r!=null)return new HT({input:r,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName}).example(t)}};var HT=class e extends ese{typeShapeNode;description;name;examples;availability;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.description=this.input.description,this.availability=new Z6e({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),d7i(this.input)&&Rk_(this.input)&&(this.nullable=this.input.nullable!=null?this.input.nullable:this.nullable),AD(this.input)){let t=VXn(this.input);if(t==null){this.context.errors.error({message:"Reference object does not have a valid schema ID",path:this.accessPath});return}if(this.seenSchemas.has(t)){this.context.errors.warning({message:"Circular or deeply nested schema found, terminating",path:this.accessPath});return}this.seenSchemas.add(t),this.typeShapeNode=new Eon({input:this.input,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName,description:this.description,availability:this.availability})}else if(this.name=this.input.title,this.examples=this.input.example,this.input.const!=null)this.typeShapeNode=new Byu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(xk_(this.input))this.typeShapeNode=new Iyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(d7i(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new xyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(RFc(this.input)&&this.input.allOf!=null)this.typeShapeNode=new WXn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(d7i(this.input)&&this.input.enum!=null)this.typeShapeNode=new p7i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable});else if(typeof this.input.type=="string"||Array.isArray(this.input.type)&&this.input.type.length===1){if(this.input.type=Array.isArray(this.input.type)?this.input.type[0]:this.input.type,!Array.isArray(this.input.type))switch(this.input.type){case"object":RFc(this.input)&&(this.typeShapeNode=new WXn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"array":f7i(this.input)&&(this.typeShapeNode=new Cyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"boolean":Ik_(this.input)&&(this.typeShapeNode=new Ryu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"integer":zk_(this.input)&&(this.typeShapeNode=new Nyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"number":Fk_(this.input)&&(this.typeShapeNode=new Lyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"string":Lk_(this.input)&&(this.typeShapeNode=new Uyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"null":Nk_(this.input)&&(this.typeShapeNode=new Fyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case void 0:break;default:new $k_.UnreachableCaseError(this.input.type);break}}else if(Array.isArray(this.input.type)&&this.input.type.includes("null")&&this.input.type.length===2){let t=this.input.type.filter(r=>r!=="null")[0];t!=="array"&&(this.typeShapeNode=new e({input:{...this.input,type:t},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:!0,schemaName:this.schemaName}))}else this.input.properties!=null&&(this.typeShapeNode=new WXn({input:{...this.input,type:"object"},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));this.typeShapeNode==null&&(this.typeShapeNode=new Vyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),!AD(this.input)&&(!f7i(this.input)&&this.input==null||f7i(this.input)&&this.input.items==null)&&this.context.errors.error({message:"Expected type declaration. Received: null",path:this.accessPath}))}convert(){let t=this.typeShapeNode?.convert();if(t==null)return;let r=dq(t)?.map(i=>this.nullable?WPi(i):i).filter(sp);return Array.isArray(t)&&t.length>1?r:r?.[0]}example(t){return this.availability?.availability!=="deprecated"?this.typeShapeNode?.example(t):void 0}};function _7i(e){if(e!=null)return UXn(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(sp))}var iur=class extends Y6{availability;required;schema;description;inputExample;constructor(t){super(t),this.safeParse(t.parameterName)}parse(t){this.description=this.input.description;let r;AD(this.input)?r=this.input:this.input.schema!=null?(r=this.input.schema,this.required=this.input.required):(r={type:"string"},this.required=!1),this.availability=new Z6e({input:r,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new HT({input:r,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:t});let i=Ck_(this.input,this.context.document);this.inputExample=i?.example??Object.values(i?.examples??{})[0]}convert(){return this.schema?.convert()}example(t){return this.inputExample??this.schema?.example(t)}};function Gk_(e,t){return AD(e)?x$(e,t,void 0):e}var NFc=ui(vx());function Wyu(e){let{uniqueId:t,type:r,contextTypes:i,description:n,availability:a}=e;i[Bh.TypeId(t)]={name:t,shape:r,description:n,availability:a}}var Qk_=ui(pHs(),1),HXn=class e{type;subtype;essence;parameters;mimeType;input;constructor(t,r,i,n,a,u){this.type=t,this.subtype=r,this.essence=i,this.parameters=n,this.mimeType=a,this.input=u}static APPLICATION_JSON="application/json";static APPLICATION_OCTET_STREAM="application/octet-stream";static MULTIPART_FORM_DATA="multipart/form-data";static parse(t){if(t==null)return null;let r=Qk_.default.parse(t);return r==null?null:new e(r.type,r.subtype,r.essence,r.parameters,r,t)}toString(){return this.input}isText(){return this.type==="text"}isImage(){return this.type==="image"}isAudio(){return this.type==="audio"}isVideo(){return this.type==="video"}isFont(){return this.type==="font"}isMultipart(){return this.type==="multipart"}isApplication(){return this.type==="application"}isMessage(){return this.type==="message"}isModel(){return this.type==="model"}isCSS(){return this.isText()&&this.subtype==="css"}isCSV(){return this.isText()&&this.subtype==="csv"}isMarkdown(){return this.isText()&&this.subtype==="markdown"}isPlainText(){return this.isText()&&this.subtype==="plain"}isEventStream(){return this.isText()&&this.subtype==="event-stream"}isMultiPartFormData(){return this.isMultipart()&&this.subtype==="form-data"}isJSON(){return this.isApplication()&&this.subtype==="json"}containsJSON(){return this.isApplication()&&this.subtype.includes("json")}isURLEncoded(){return this.isApplication()&&this.subtype==="x-www-form-urlencoded"}isOctetStream(){return this.isApplication()&&this.subtype==="octet-stream"}isPDF(){return this.isApplication()&&this.subtype==="pdf"}isZip(){return this.isApplication()&&this.subtype==="zip"}isGzip(){return this.isApplication()&&this.subtype==="gzip"}isTar(){return this.isApplication()&&this.subtype==="tar"}isBrotli(){return this.isApplication()&&this.subtype==="br"}isDeflate(){return this.isApplication()&&this.subtype==="deflate"}isProtobuf(){return this.isApplication()&&this.subtype==="protobuf"}isAvif(){return this.isImage()&&this.subtype==="avif"}isWebP(){return this.isImage()&&this.subtype==="webp"}isSVG(){return this.isImage()&&this.subtype==="svg+xml"}isPNG(){return this.isImage()&&this.subtype==="png"}isJPEG(){return this.isImage()&&this.subtype==="jpeg"}isGIF(){return this.isImage()&&this.subtype==="gif"}isMPEG(){return this.isAudio()&&this.subtype==="mpeg"}isWAV(){return this.isAudio()&&this.subtype==="wav"}isHTML(){return this.mimeType.isHTML()}isXML(){return this.mimeType.isXML()}isJavaScript(){return this.mimeType.isJavaScript()}};function xOM(e){return typeof e.securitySchemes=="object"&&e.securitySchemes!=null}var $Xn=class extends A_{typeSchemas;securitySchemes;constructor(t){super(t),this.safeParse()}parse(){this.input.schemas!=null&&(this.typeSchemas=Object.fromEntries(Object.entries(this.input.schemas).map(([t,r])=>[t,new HT({input:r,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:new Set,nullable:void 0,schemaName:t})]))),xOM(this.input)&&this.input.securitySchemes!=null&&(this.securitySchemes=Object.fromEntries(Object.entries(this.input.securitySchemes??{}).map(([t,r],i)=>{let n;if(AD(r)?n=syu(r.$ref,this.context.document):n=r,n!=null)return[t,new FXn({input:n,context:this.context,accessPath:this.accessPath,pathId:["securitySchemes",`${i}`]})]}).filter(sp)))}convert(){return{auths:this.securitySchemes!=null?Object.fromEntries(Object.entries(this.securitySchemes??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[Bh.api.latest.AuthSchemeId(t),i]}).filter(sp)):void 0,types:this.typeSchemas!=null?Object.fromEntries(Object.entries(this.typeSchemas).map(([t,r])=>{let i=r.name??t,n=dq(r.convert());return n==null?[t,void 0]:[Bh.TypeId(t),{name:i,shape:n[0],description:r.description,availability:void 0}]}).filter(([t,r])=>sp(r))):void 0}}};var Hyu=class extends HT{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=X6(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${AD(this.input)?`Received undefined reference: ${this.input.$ref}`:""}`,path:this.accessPath});return}if(t.type==="string"&&t.format==="binary")this.multipartType="file",this.contentType=t.contentMediaType;else if(t.type==="array"){let r=X6(t.items,this.context.document);r?.type==="string"&&r?.format==="binary"?(this.multipartType="files",this.contentType=r?.contentMediaType):(this.context.errors.warning({message:"Expected multipart form data files definition with array type with internal string type and binary format.",path:this.accessPath}),this.multipartType=void 0,this.contentType=void 0)}else this.multipartType="property",this.contentType=t.contentMediaType}};var $yu=class extends A_{description;method;path;schema;isOptional;contentType;availability;requiredFields;fields;examples;constructor(t){super(t),this.method=t.method,this.path=t.path,this.safeParse(t)}parse({contentType:t}){if(this.input.schema!=null){let i=X6(this.input.schema,this.context.document);this.availability=new Z6e({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=AD(this.input.schema)?new Eon({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:!1,schemaName:"Request Body",description:this.input.schema.description,availability:this.availability}):void 0;let n=HXn.parse(t);n?.containsJSON()?(this.contentType="json",this.schema=this.schema??new HT({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:"Request Body"})):n?.isOctetStream()?(this.contentType="bytes",this.isOptional=i?.required==null):n?.isMultiPartFormData()?(this.contentType="form-data",this.requiredFields=i?.required,this.fields=Object.fromEntries(Object.entries(i?.properties??{}).map(([a,u])=>{if(u!=null)return[a,new Hyu({input:u,context:this.context,accessPath:this.accessPath,pathId:`schema.${a}`,seenSchemas:new Set,nullable:void 0,schemaName:a})]}).filter(sp))):this.context.errors.warning({message:`Expected request body of reference or object with json, streaming or form-data content types. Received: ${t}`,path:this.accessPath})}let r=this.schema?.example({includeOptionals:!0,override:void 0});this.examples={...this.input.example!=null?{[xU]:{value:this.input.example}}:{},...this.input.examples},r!=null&&Object.keys(this.examples).length===0&&(this.examples={[xU]:{value:r}})}convertJsonLike(){let t=this.schema?.convert();return t==null?void 0:dq(t)?.map(i=>{let n=i.type;switch(n){case"object":case"alias":return i;case"enum":case"undiscriminatedUnion":case"discriminatedUnion":{let a=aJt([this.method,this.path,this.contentType,"request"].join("_"));return Wyu({uniqueId:a,type:i,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:Bh.TypeId(a),default:i.type==="enum"&&i.default!=null?{type:"enum",value:i.default}:void 0}}}case void 0:return;default:new NFc.UnreachableCaseError(n);return}}).filter(sp)}convert(){if(this.schema instanceof Eon)return this.schema.convert();switch(this.contentType){case"json":return this.convertJsonLike();case"bytes":return{type:"bytes",isOptional:this.isOptional??!1,contentType:this.contentType};case"form-data":return Object.entries(this.fields??{}).map(([i,n])=>{switch(n.multipartType){case"file":return[{type:n.multipartType,key:Bh.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"files":return[{type:n.multipartType,key:Bh.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"property":{let a=dq(n.convert()),u=n.multipartType;return a?.map(c=>({type:u,key:Bh.PropertyKey(i),contentType:n.contentType,exploded:void 0,valueShape:c,description:n.description,availability:n.availability?.convert()}))}case void 0:return[];default:return new NFc.UnreachableCaseError(n.multipartType),[]}}).filter(sp).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(u=>[...a,u]):[[...a]]),[[]]).map(i=>({type:"formData",fields:i,availability:this.availability?.convert(),description:this.description}));case void 0:return this.convertJsonLike();default:return}}};var Gyu=class extends A_{description;requestBodiesByContentType;constructor(t){super(t),this.safeParse(t)}parse({method:t,path:r}){let i=Gk_(this.input,this.context.document);if(i==null){this.context.errors.error({message:"Expected request body. Received: null",path:this.accessPath});return}Object.entries(i.content).forEach(([n,a])=>{this.requestBodiesByContentType??={},this.requestBodiesByContentType[n]=new $yu({input:a,context:this.context,accessPath:this.accessPath,pathId:"content",contentType:n,method:t,path:r})})}convert(){return Object.entries(this.requestBodiesByContentType??{}).flatMap(([t,r])=>dq(r.convert())?.map(n=>({description:this.description,contentType:t,body:n}))).filter(sp)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>dq(t.convert())?.map(i=>{if(!(i.type!=="alias"&&i.type!=="object"))return{description:this.description,shape:i}})).filter(sp)}webhookExample(){return{payload:this.requestBodiesByContentType?.["application/json"]?.schema?.example({includeOptionals:!0,override:void 0})}}};var Jk_={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};function Kk_(e,t){if(AD(e)){let r=x$(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var Qyu=ui(vx());var Yk_="application/json";var Xk_="application/octet-stream";function Zk_(e,t){return e===t||t===xU||e===xU}var bVa=class extends A_{streamingFormat;path;method;statusCode;requests;shapes;schema;contentType;unsupportedContentType;contentSubtype;examples;empty;constructor(t,r,i,n,a,u,c,d){super(t),this.streamingFormat=i,this.path=n,this.method=a,this.statusCode=u,this.requests=c,this.shapes=d,this.safeParse(r)}matchRequestResponseExamplesByName(t,r,i){for(let n of t)for(let[a,u]of Object.entries(n?.examples??{}))for(let[c,d]of Object.entries(r))for(let s of d)Zk_(c,a)&&(i.add(c),this.examples?.push(new rur({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,c7i(a,c),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}matchExamplesByIndex(t,r){let i=0;for(let n of t){let a=0;for(let[u,c]of r){if(a===i){let[d,s,o]=n??[void 0,void 0,void 0];this.examples?.push(...c.map(l=>new rur({input:{requestExample:o,responseExample:l},context:this.context,accessPath:this.accessPath,pathId:s!=null&&s!==""?["examples",s]:"examples"},this.path,this.statusCode,c7i(s,u),{requestBody:d,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}a++}i++}if(t.length>r.length)for(let n of t.slice(r.length)){let[a,u]=r[r.length-1]??[void 0,void 0],[c,d,s]=n??[void 0,void 0,void 0];this.examples?.push(...(u??[void 0]).map(o=>new rur({input:{requestExample:s,responseExample:o},context:this.context,accessPath:this.accessPath,pathId:d!=null&&d!==""?["examples",d]:"examples"},this.path,this.statusCode,c7i(d,a),{requestBody:c,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}if(r.length>t.length){let[n,a,u]=t[t.length-1]??[void 0,void 0,void 0];for(let[c,d]of r.slice(t.length))this.examples?.push(...d.map(s=>new rur({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,c7i(a,c),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}}pushResponseExample(t,r,i,n){let a=t[xU];if(a!=null)for(let u of a)this.examples?.push(new rur({input:{requestExample:n,responseExample:u},context:this.context,accessPath:this.accessPath,pathId:i!=null&&i!==""?["examples",i]:"examples"},this.path,this.statusCode,c7i(i,void 0),{requestBody:r,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders}))}addGlobalFallbackExample(t,r){if(t==null||t.length===0)this.pushResponseExample(r,void 0,void 0,void 0);else for(let i of t)if(Object.keys(i.examples??{}).length===0)this.pushResponseExample(r,i,void 0,void 0);else for(let[n,a]of Object.entries(i.examples??{}))this.pushResponseExample(r,i,n,a)}parse(t){if(t==="empty")this.empty=!0;else{let c=HXn.parse(t);if(c?.isJSON()||c?.isEventStream())this.contentType=Yk_,this.input.schema==null?(this.streamingFormat==null||this.streamingFormat==="json")&&this.context.errors.error({message:"Expected schema for JSON response body. Received null",path:this.accessPath}):this.schema=new HT({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"type",seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"});else if(c?.isOctetStream())this.contentType=Xk_,this.contentSubtype=X6(this.input.schema,this.context.document)?.contentMediaType;else if(this.unsupportedContentType=t,this.input.schema==null){this.context.errors.error({message:"Expected schema for plain text response body. Received null",path:this.accessPath});return}else this.schema=new HT({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"})}let r={};this.input.examples!=null&&(r=Oyu(this.input.examples,c=>[c])),this.input.example!=null&&Object.keys(r).length===0&&(r[xU]??=[],r[xU]=[{value:this.input.example}]);let i=X6(this.input.schema,this.context.document);if(i!=null&&(i.examples!=null&&Object.keys(r).length===0&&(r=Oyu(i.examples,c=>[c])),i.example!=null&&Object.keys(r).length===0&&(r[xU]??=[],r[xU]?.push({value:i.example}))),Object.keys(r).length===0){let c=this.schema?.example({includeOptionals:!0,override:void 0});r[xU]??=[],r[xU]?.push(c!=null?{value:c}:void 0)}this.examples??=[];let n=new Set;this.matchRequestResponseExamplesByName(this.requests,r,n);let a=[];for(let c of this.requests)a.push(...Object.entries(c.examples??{}).filter(([d])=>!n.has(d)&&d!==xU).map(([d,s])=>[c,d,s]));let u=Object.entries(r).filter(([c,d])=>!n.has(c)&&sp(d)&&c!==xU);Object.keys(r).every(c=>c===xU)||this.matchExamplesByIndex(a,u),!n.has(xU)&&this.examples.length===0&&this.addGlobalFallbackExample(this.requests,r),this.examples.length===0&&(this.examples=void 0)}convertStreamingFormat(){switch(this.streamingFormat){case"json":return dq(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new Qyu.UnreachableCaseError(this.streamingFormat);return}}convertJsonLike(){return dq(this.schema?.convert())?.map(r=>{let i=r.type;switch(i){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":{let n=aJt([this.method,this.path,this.statusCode,"response"].join("_"));return Wyu({uniqueId:n,type:r,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:Bh.TypeId(n),default:r.type==="enum"&&r.default!=null?{type:"enum",value:r.default}:void 0}}}case"object":return r;default:new Qyu.UnreachableCaseError(i);return}}).filter(sp)}convert(){if(this.empty)return{type:"empty"};if(this.contentType!=null)switch(this.contentType){case"application/json":return this.streamingFormat==null?this.convertJsonLike():this.convertStreamingFormat();case"application/octet-stream":return{type:"fileDownload",contentType:this.contentSubtype};case"text/event-stream":return this.convertStreamingFormat();case void 0:return;default:new Qyu.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?this.convertJsonLike():void 0}};var gVa=class extends A_{path;method;statusCode;requests;shapes;headers;responses;description;constructor(t,r,i,n,a,u){super(t),this.path=r,this.method=i,this.statusCode=n,this.requests=a,this.shapes=u,this.safeParse()}parse(t){this.description=this.input.description;let r=Kk_(this.input,this.context.document);if(r==null){this.context.errors.error({message:AD(this.input)?`Undefined reference: ${this.input.$ref}`:"Expected response, received null",path:this.accessPath});return}Object.entries(r.headers??{}).forEach(([i,n])=>{this.headers??={},this.headers[i]=new iur({input:n,context:this.context,accessPath:this.accessPath,pathId:"headers",parameterName:i})}),r.content==null?(this.responses??=[],this.responses.push(new bVa({input:{},context:this.context,accessPath:this.accessPath,pathId:["content"]},"empty",t,this.path,this.method,this.statusCode,this.requests,this.shapes))):Object.entries(r.content??{}).forEach(([i,n])=>{this.responses??=[],this.responses.push(new bVa({input:n,context:this.context,accessPath:this.accessPath,pathId:["content",i]},i,t,this.path,this.method,this.statusCode,this.requests,this.shapes))})}convert(){return this.responses?.flatMap(t=>t.convert()).filter(sp)}};var Jyu=class extends A_{path;method;requests;shapes;responsesByStatusCode;errorsByStatusCode;constructor(t,r,i,n,a){super(t),this.path=r,this.method=i,this.requests=n,this.shapes=a,this.safeParse()}parse(){let t=this.input.default;Object.entries(this.input).forEach(([r,i])=>{r!=="default"&&(parseInt(r)>=400?(this.errorsByStatusCode??={},this.errorsByStatusCode[r]=new gVa({input:{...t,...i},context:this.context,accessPath:this.accessPath,pathId:"errors"},this.path,this.method,parseInt(r),[],this.shapes)):(this.responsesByStatusCode??={},this.responsesByStatusCode[r]=new gVa({input:i,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,parseInt(r),this.requests,this.shapes)))})}convertResponseObjectToHttpResponses(){return Object.entries(this.responsesByStatusCode??{}).flatMap(([t,r])=>{let i=r.convert();if(i!=null)return zyu(_7i(r.headers)).flatMap(n=>i?.map(a=>({headers:n,response:{statusCode:parseInt(t),body:a,description:r.description},examples:(r.responses??[]).flatMap(u=>(u.examples??[]).map(c=>c.convert()).filter(sp))})))}).filter(sp)}convertResponseObjectToErrors(){return Object.entries(this.errorsByStatusCode??{}).flatMap(([t,r])=>r.responses?.flatMap(i=>{let n=i.schema,a=dq(n?.convert());if(n!=null)return a?.map(u=>({statusCode:parseInt(t),shape:u,description:r.description??n.description,availability:n.availability?.convert(),name:n.name??Jk_[parseInt(t)]??"UNKNOWN ERROR",examples:i.examples?.map(c=>{let d=c.convert();if(d!=null&&d.responseBody?.type==="json")return{name:d.name,description:d.description,responseBody:d.responseBody}}).filter(sp)})).filter(sp)})).filter(sp)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var h7i=class extends A_{servers;globalAuth;path;method;basePath;isWebhook;endpointIds;description;displayName;operationId;pathParameters;queryParameters;requestHeaders;requests;responses;availability;auth;namespaces;xFernExamplesNode;redocExamplesNode;emptyResponseExamples;constructor(t){super(t),this.servers=t.servers,this.globalAuth=t.globalAuth,this.path=t.path,this.method=t.method,this.basePath=t.basePath,this.isWebhook=t.isWebhook,this.safeParse()}pushEmptyResponseExample(t,r,i){this.emptyResponseExamples??=[],this.emptyResponseExamples.push(new rur({input:{requestExample:t,responseExample:void 0},context:this.context,accessPath:this.accessPath,pathId:"examples"},this.path,200,c7i(i,void 0),{requestBody:r,pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}))}parse(){if(this.isWebhook&&this.method!=="POST"&&this.method!=="GET"){this.context.errors.error({message:`Webhook method must be POST or GET. Received: ${this.method}`,path:this.accessPath});return}this.description=this.input.description,this.displayName=this.input.summary,this.operationId=this.input.operationId,this.availability=new Z6e({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=tur(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new qyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((i,n)=>{if(AD(i)){let a=Syu(i,this.context.document);if(a!=null)i=a;else{this.context.errors.warning({message:`Expected parameter reference to resolve to an object. Received undefined reference: ${i.$ref}`,path:[...this.accessPath,`parameters[${n}]`]});return}}i.in==="path"?i.schema!=null&&(this.pathParameters??={},this.pathParameters[i.name]=new iur({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="query"?i.schema!=null&&(this.queryParameters??={},this.queryParameters[i.name]=new iur({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="header"&&i.schema!=null&&(this.requestHeaders??={},this.requestHeaders[i.name]=new iur({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name}))});for(let i of this.extractPathParameterIds()??[])this.pathParameters?.[i]==null&&this.context.errors.warning({message:`Path parameter not defined: ${i}`,path:[...this.accessPath,"parameters"]});if(this.redocExamplesNode=new Tyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new Gyu({input:this.input.requestBody,context:this.context,accessPath:this.accessPath,pathId:"requestBody",method:this.method,path:this.path}):void 0,this.responses=this.input.responses!=null?new Jyu({input:this.input.responses,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,Object.values(this.requests?.requestBodiesByContentType??{}),{pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}):void 0,this.responses==null){let i=this.requests?.requestBodiesByContentType;i==null||Object.keys(i).length===0?this.pushEmptyResponseExample(void 0,void 0,void 0):Object.values(i).forEach(n=>{if(Object.keys(n.examples??{}).length===0){let a=n.schema?.example({includeOptionals:!1,override:void 0});a!=null&&this.pushEmptyResponseExample({value:a},n,void 0)}else Object.entries(n.examples??{}).forEach(([a,u])=>{this.pushEmptyResponseExample(u,n,a)})})}let t=200;this.responses?.responsesByStatusCode!=null&&(t=Number(Object.keys(this.responses.responsesByStatusCode)?.filter(i=>Number(i)>=200&&Number(i)<300)[0])),this.globalAuth!=null&&(this.auth=this.globalAuth),this.input.security!=null&&(this.auth=new LXn({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespaces=[new vVa({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-group-name"})],this.namespaces?.every(i=>i.groupName==null)&&this.input.tags!=null&&(this.namespaces=this.input.tags.slice(0,1).map((i,n)=>new vVa({input:{[ayu]:i},context:this.context,accessPath:this.accessPath,pathId:["tags",`${n}`]})));let r=new Ayu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointIds=this.namespaces.map(i=>myu({namespace:dq(i?.groupName),path:this.path,method:this.method,sdkMethodName:r.sdkMethodName,operationId:this.input.operationId,displayName:this.displayName,isWebhook:this.isWebhook})).filter(sp),this.xFernExamplesNode=new Myu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-examples"},this.path,t,this.requests?.requestBodiesByContentType,this.responses?.responsesByStatusCode?.[t]?.responses)}extractPathParameterIds(){if(this.path!=null)return this.path.split("/").map(t=>{if(t.startsWith("{")&&t.endsWith("}"))return t.slice(1,-1).trim()}).filter(sp)}convertPathToPathParts(){if(this.path===void 0)return;let t=this.path.startsWith("/")?this.path.slice(1):this.path,r=this.basePath?.convert();return(r?[r,...t.split("/")]:t.split("/")).reduce((n,a)=>(n.push({type:"literal",value:"/"}),a.startsWith("{")&&a.endsWith("}")?n.push({type:"pathParameter",value:Bh.PropertyKey(a.slice(1,-1).trim())}):n.push({type:"literal",value:a}),n),[])}convert(){if(this.path==null||this.endpointIds==null)return;let{responses:t,errors:r}=this.responses?.convert()??{responses:void 0,errors:void 0},i=this.emptyResponseExamples?.map(o=>o.convert()).filter(sp),n=wk_(this.xFernExamplesNode?.convert(),[...i??[],...t?.flatMap(o=>o.examples)??[]])?.map(o=>({...o,snippets:jk_(o.snippets,this.redocExamplesNode?.convert())}));if(this.isWebhook)return this.endpointIds.map((o,l)=>{if(!(this.method!=="POST"&&this.method!=="GET"))return{id:Bh.WebhookId(o),description:this.description,availability:this.availability?.convert(),displayName:this.displayName,operationId:this.operationId,namespace:this.namespaces?.[l]?.convert(),method:this.method,path:this.convertPathToPathParts()?.map(v=>v.value.toString())??[],queryParameters:_7i(this.queryParameters)?.flat(),headers:_7i(this.requestHeaders)?.flat(),payloads:this.requests?.convertToWebhookPayload(),examples:[this.requests?.webhookExample()].filter(sp)}}).filter(sp);let a=this.servers?.map(o=>o.convert()).filter(sp),u=this.convertPathToPathParts();if(u==null)return;let c,d=this.auth?.convert();d!=null&&(c=Object.keys(d));let s=t?.flatMap(o=>o.headers).filter(sp);return this.endpointIds.map((o,l)=>({id:Bh.EndpointId(o),description:this.description,availability:this.availability?.convert(),namespace:this.namespaces?.[l]?.convert()?.map(v=>Bh.api.v1.SubpackageId(v)),displayName:this.displayName,operationId:this.operationId,method:this.method,path:u,auth:c?.map(v=>Bh.api.latest.AuthSchemeId(v)),defaultEnvironment:a?.[0]?.id,environments:a,pathParameters:_7i(this.pathParameters)?.flat(),queryParameters:_7i(this.queryParameters)?.flat(),requestHeaders:_7i(this.requestHeaders)?.flat(),responseHeaders:s!=null&&s.length>0?s:void 0,requests:this.requests?.convert(),responses:t?.map(v=>v.response),errors:r,examples:n,snippetTemplates:void 0,protocol:{type:"rest"}}))}};var GXn=class extends A_{description;get;post;put;patch;delete;path;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i,isWebhook:n}){this.description=this.input.description;let a=tur(t,this.input.servers,this.context,this.accessPath),u=Array.isArray(this.pathId)?this.pathId.join("/"):this.pathId;this.input.get!=null&&(this.get=new h7i({input:this.input.get,context:this.context,accessPath:this.accessPath,pathId:"get",servers:a,globalAuth:r,path:u,method:"GET",basePath:i,isWebhook:n})),this.input.post!=null&&(this.post=new h7i({input:this.input.post,context:this.context,accessPath:this.accessPath,pathId:"post",servers:a,globalAuth:r,path:u,method:"POST",basePath:i,isWebhook:n})),this.input.put!=null&&(this.put=new h7i({input:this.input.put,context:this.context,accessPath:this.accessPath,pathId:"put",servers:a,globalAuth:r,path:u,method:"PUT",basePath:i,isWebhook:!1})),this.input.patch!=null&&(this.patch=new h7i({input:this.input.patch,context:this.context,accessPath:this.accessPath,pathId:"patch",servers:a,globalAuth:r,path:u,method:"PATCH",basePath:i,isWebhook:!1})),this.input.delete!=null&&(this.delete=new h7i({input:this.input.delete,context:this.context,accessPath:this.accessPath,pathId:"delete",servers:a,globalAuth:r,path:u,method:"DELETE",basePath:i,isWebhook:!1}))}convert(){return[...this.get?.convert()??[],...this.post?.convert()??[],...this.put?.convert()??[],...this.patch?.convert()??[],...this.delete?.convert()??[]].filter(sp)}};function Kyu(e){return"payloads"in e}var Yyu=class extends A_{paths;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.paths=Object.entries(this.input).map(([n,a])=>{if(a!=null)return new GXn({input:a,context:this.context,accessPath:this.accessPath,pathId:n,servers:tur(t,a.servers,this.context,this.accessPath),globalAuth:r,basePath:i,isWebhook:void 0})}).filter(sp)}convert(){if(this.paths==null)return;let t={},r={};return this.paths.forEach(i=>{let n=i.convert();n?.forEach(a=>{Kyu(a)?r[Bh.WebhookId(a.id)]=a:t[Bh.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var Xyu=class extends A_{globalHeaders;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[VZ_]?.map(r=>{let{header:i,...n}=r;return(n.optional!=null&&!n.optional||Syu(n,this.context.document)?.required)&&(this.requiredProperties??=[],this.requiredProperties?.push(i)),[i,new iur({input:n,context:this.context,accessPath:this.accessPath,pathId:this.pathId,parameterName:i})]});t!=null&&(this.globalHeaders=Object.fromEntries(t))}convert(){return UXn(this.globalHeaders,this.requiredProperties)?.flat()}};function kk_(e,t){if(AD(e)){let r=x$(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var Zyu=class extends A_{webhooks;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.webhooks=Object.entries(this.input??{}).map(([n,a])=>{let u=kk_(a,this.context.document);if(u!=null)return new GXn({input:u,context:this.context,accessPath:this.accessPath,pathId:n,servers:t,globalAuth:r,basePath:i,isWebhook:!0})}).filter(sp)}convert(){return this.webhooks?.reduce((t,r)=>(r.convert()?.forEach(i=>{Kyu(i)&&(t[Bh.WebhookId(i.id)]=i)}),t),{})}};var kyu=class extends A_{paths;webhooks;components;auth;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){let t=tur(void 0,this.input.servers,this.context,this.accessPath);this.input.security!=null&&(this.auth=new LXn({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"}));let r=new wyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});this.input.paths==null&&this.input.webhooks==null&&this.context.errors.warning({message:"Expected 'paths' or 'webhooks' property to be specified",path:this.accessPath}),this.input.paths!=null&&(this.paths=new Yyu({input:this.input.paths,context:this.context,accessPath:this.accessPath,pathId:"paths",basePath:r,servers:t,globalAuth:this.auth})),this.input.webhooks!=null&&(this.webhooks=new Zyu({input:this.input.webhooks,context:this.context,accessPath:this.accessPath,pathId:"webhooks",basePath:r,servers:t,globalAuth:this.auth})),this.input.components!=null&&(this.components=new $Xn({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"})),this.globalHeaders=new Xyu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=_ue(),{webhookEndpoints:r,endpoints:i}=this.paths?.convert()??{},n={...this.webhooks?.convert()??{},...r??{}},a=ryu({endpoints:i,webhookEndpoints:n}),{types:u,auths:c}=this.components?.convert()??{};return{id:Bh.ApiDefinitionId(t),endpoints:i??{},websockets:{},webhooks:n,types:{...u,...this.context.generatedTypes},subpackages:a,auths:{...c,...this.auth?.convert()??{}},globalHeaders:this.globalHeaders?.convert(),snippetsConfiguration:void 0}}};var QXn=class extends xXn{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,this.pathId&&this.pathId!==this.accessPath[this.accessPath.length-1]&&(this.accessPath.push(this.pathId),r.logger.debug(`Processing #/${this.accessPath.join("/")}`))}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}};function k6e(e){return typeof e=="object"&&sp(e)&&"$ref"in e&&typeof e.$ref=="string"}function oJt(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(k6e(n)&&(n=oJt(n,t,r)),n)}function eeh(e,t){return k6e(e)?oJt(e,t,{name:"",params:[],result:{name:"",schema:{type:"object"}}}):e}var neh=ui(vx());function HPi(e){if(typeof e=="boolean")return e;if(e.enum!=null&&e.enum.length>0)return e.enum[0];if(e.const!=null)return e.const;if(e.examples!=null&&e.examples.length>0)return e.examples[0];if(e.type==="object"){let t={};if(e.properties!=null)for(let[r,i]of Object.entries(e.properties))t[r]=HPi(i);return t}if(e.type==="array")return e.items==null?[]:Array.isArray(e.items)?e.items.map(t=>HPi(t)):[HPi(e.items)];if(e.type==="string")return e.default??"string";if(e.type==="number"||e.type==="integer")return e.default??0;if(e.type==="boolean")return e.default??!1;if(e.type==="null")return null;if(e.oneOf?.[0]!=null)return HPi(e.oneOf[0]);if(e.anyOf?.[0]!=null)return HPi(e.anyOf[0]);if(e.allOf!=null&&e.allOf.length>0){let t={};for(let r of e.allOf)r!=null&&Object.assign(t,HPi(r));return t}}function OVa(e,t){return k6e(e)?oJt(e,t,{name:"",schema:{type:"object"}}):e}function teh(e,t){return k6e(e)?oJt(e,t,void 0):e}function reh(e,t){return k6e(e)?oJt(e,t,void 0):e}function ieh(e,t){return k6e(e)?oJt(e,t,void 0):e}var ROM={key:Bh.PropertyKey("apiKey"),description:void 0,availability:void 0,valueShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}}},evu=class extends QXn{method;servers=[];constructor(t,r){super(t),this.method=t.input,this.servers=r,this.safeParse()}parse(){}convert(){try{let t=this.method.result?OVa(this.method.result,this.context.openrpc):void 0,r=t?new HT({input:t.schema,context:this.context,accessPath:this.accessPath,pathId:"result",seenSchemas:new Set,nullable:void 0,schemaName:"Result"}).convert():void 0,n=this.method.params?.map(c=>OVa(c,this.context.openrpc)).filter(sp)?.map(c=>{let d=new HT({input:c.schema,context:this.context,accessPath:this.accessPath,pathId:["params",c.name],seenSchemas:new Set,nullable:void 0,schemaName:c.name}).convert();if(!d)return;let s=Array.isArray(d)?d[0]:d;if(s)return{key:Bh.PropertyKey(c.name),valueShape:c.required?s:{type:"alias",value:{type:"optional",shape:s,default:void 0}},description:c.description,availability:void 0}}).filter(sp),a=n.length>0?{contentType:"application/json",body:{type:"object",extends:[],properties:n,extraProperties:void 0},description:void 0}:void 0,u=this.method.examples?.map(c=>{let d=reh(c,this.context.openrpc);if(d)return{name:d.name??"Example",path:"",description:void 0,snippets:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:d.params.length>0?{type:"json",value:Object.fromEntries(d.params.map(s=>{let o=teh(s,this.context.openrpc);if(o)return[o.name??"",o.value]}).filter(sp))}:void 0,responseStatusCode:200,responseBody:d.result?{type:"json",value:d.result}:void 0}}).filter(sp)??[];if(u.length<=0){let c=HPi({type:"object",properties:Object.fromEntries(this.method.params?.map(s=>{let o=OVa(s,this.context.openrpc);return[o?.name??"",o?.schema??{}]})??[])}),d={name:"Example",path:"",pathParameters:{},queryParameters:{},headers:{},requestBody:{type:"json",value:c},responseStatusCode:200,responseBody:{type:"json",value:HPi(OVa(this.method.result,this.context.openrpc)?.schema??{})},snippets:void 0,description:void 0};u.push(d)}return{protocol:{type:"openrpc",methodName:this.input.name},id:Bh.EndpointId(this.input.name),displayName:this.input.name,method:"POST",path:[{type:"pathParameter",value:Bh.PropertyKey("apiKey")}],auth:void 0,pathParameters:[ROM],queryParameters:[],requests:a!=null?[a]:void 0,responses:r!=null?[this.convertToHttpResponse(r,this.input.description)].filter(sp):[],errors:[],examples:u,description:this.input.description??this.input.summary,operationId:this.input.name,defaultEnvironment:void 0,environments:this.servers.map(c=>c.convert()).filter(sp),availability:this.method.deprecated?"Deprecated":void 0,requestHeaders:[],responseHeaders:[],snippetTemplates:void 0,namespace:this.getNamespace()}}catch{this.context.errors.error({message:"Failed to convert method",path:this.accessPath});return}}getNamespace(){if(this.method.tags?.[0]==null)return;let t=ieh(this.method.tags[0],this.context.openrpc);if(t?.name!=null)return[Bh.api.v1.SubpackageId(t.name)]}convertToHttpResponse(t,r){if(t==null)return;let n=dq(t)?.map(a=>{let u=a.type;switch(u){case"alias":return a;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":return;case"object":return a;default:new neh.UnreachableCaseError(u);return}}).filter(sp)[0];if(n)return{statusCode:200,body:n,description:r}}};var mVa=class extends QXn{servers=[];methods=[];components;constructor(t){super(t),this.safeParse()}parse(){if(this.context.openrpc.servers!=null&&(this.servers=tur(this.servers,this.input.servers,this.context,this.accessPath)),this.input.methods!=null)for(let t of this.input.methods){let r=eeh(t,this.context.openrpc);r!=null&&this.methods.push(new evu({input:r,context:this.context,accessPath:this.accessPath,pathId:"methods"},this.servers))}this.context.openrpc.components!=null&&(this.components=new $Xn({input:this.context.openrpc.components,context:this.context,accessPath:this.accessPath,pathId:"components"}))}convert(){let t=_ue(),{types:r}=this.components?.convert()??{},i=this.methods?.map(u=>u.convert()).filter(sp),n=Object.fromEntries(i?.map(u=>[u.id,u])??[]),a=ryu({endpoints:n});return{id:Bh.ApiDefinitionId(t),types:r??{},endpoints:n,websockets:{},webhooks:{},subpackages:a,auths:{},globalHeaders:[],snippetsConfiguration:void 0}}};var PVa=class extends nyu{openrpc;logger;generatedTypes;constructor(t){super(),this.openrpc=t.openrpc,this.logger=t.logger,this.generatedTypes={}}get document(){return{openapi:"3.1.0",info:{title:"Mock API",version:"1.0.0"},paths:{},components:this.openrpc.components}}};async function jVa(e,t){if(e instanceof wor){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof D3))return;let r=new GQt(e.absoluteFilePath),i=await W6e({context:t,specs:e.specs}),n=await r.loadDocuments({context:t,specs:i}),a;for(let u of n){if(u.type!=="openapi")continue;let c={document:u.value,logger:t.logger,errors:new zXn,generatedTypes:{}},d=new kyu({input:u.value,context:c,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=AHs(a,d.convert())}return a}var aeh=require("fs/promises");async function oeh(e,t){let r=await(0,aeh.readFile)(e,"utf-8"),i=JSON.parse(r),n=new PVa({openrpc:i,logger:t.logger});return new mVa({input:i,context:n,accessPath:[],pathId:"openrpc"}).convert()}function NOM(e){return e.startsWith(".")||e.includes("/")||e.includes("\\")||e.includes(":")}function FOM(e){return/^(https?:)?\/\//.test(e)}async function LOM({pathToImage:e,absolutePathToFernFolder:t}){if(e==null||FOM(e))return;let r=$v(t,za.of(e));if(await Cf(r))return r}async function JXn({iconPath:e,filepaths:t,docsWorkspace:r}){if(NOM(e)){let i=await LOM({pathToImage:e,absolutePathToFernFolder:r.absoluteFilePath});i&&t.add(i)}}async function ueh({parsedDocsConfig:e,docsWorkspace:t}){let r=new Set;return e.logo?.dark!=null&&r.add(e.logo.dark),e.logo?.light!=null&&r.add(e.logo.light),e.favicon!=null&&r.add(e.favicon),e.backgroundImage?.dark!=null&&r.add(e.backgroundImage.dark),e.backgroundImage?.light!=null&&r.add(e.backgroundImage.light),e.metadata?.["og:image"]!=null&&e.metadata["og:image"].type==="filepath"&&r.add(e.metadata["og:image"].value),e.metadata?.["og:logo"]!=null&&e.metadata["og:logo"].type==="filepath"&&r.add(e.metadata["og:logo"].value),e.metadata?.["twitter:image"]!=null&&e.metadata["twitter:image"].type==="filepath"&&r.add(e.metadata["twitter:image"].value),e.typography?.bodyFont!=null&&e.typography.bodyFont.variants.forEach(n=>{r.add(n.absolutePath)}),e.typography?.headingsFont!=null&&e.typography.headingsFont.variants.forEach(n=>{r.add(n.absolutePath)}),e.typography?.codeFont!=null&&e.typography.codeFont.variants.forEach(n=>{r.add(n.absolutePath)}),e.navigation.type==="productgroup"&&e.navigation.products.forEach(n=>{n.image!=null&&r.add(n.image)}),(await FFc({navigation:e.navigation,docsWorkspace:t})).forEach(n=>{r.add(n)}),e.js!=null&&e.js.files.forEach(n=>{r.add(n.absolutePath)}),r}async function FFc({navigation:e,docsWorkspace:t}){let r=new Set;switch(e.type){case"untabbed":await Promise.all(e.items.map(i=>wVa({item:i,filepaths:r,docsWorkspace:t})));break;case"tabbed":await Promise.all(e.items.map(async i=>{i.icon!=null&&await JXn({iconPath:i.icon,filepaths:r,docsWorkspace:t}),i.child.type==="layout"&&i.child.layout!=null&&await Promise.all(i.child.layout.map(n=>wVa({item:n,filepaths:r,docsWorkspace:t})))}));break;case"versioned":await Promise.all(e.versions.map(async i=>{i.landingPage!=null&&await wVa({item:i.landingPage,filepaths:r,docsWorkspace:t}),(await FFc({navigation:i.navigation,docsWorkspace:t})).forEach(a=>r.add(a))}));break;case"productgroup":await Promise.all(e.products.map(async i=>{i.landingPage!=null&&await wVa({item:i.landingPage,filepaths:r,docsWorkspace:t}),(await FFc({navigation:i.navigation,docsWorkspace:t})).forEach(a=>r.add(a))}));break}return r}async function wVa({item:e,filepaths:t,docsWorkspace:r}){switch(e.type){case"page":e.icon!=null&&await JXn({iconPath:e.icon,filepaths:t,docsWorkspace:r});break;case"section":e.icon!=null&&await JXn({iconPath:e.icon,filepaths:t,docsWorkspace:r}),await Promise.all(e.contents.map(i=>wVa({item:i,filepaths:t,docsWorkspace:r})));break;case"apiSection":e.icon!=null&&await JXn({iconPath:e.icon,filepaths:t,docsWorkspace:r});break;case"link":e.icon!=null&&await JXn({iconPath:e.icon,filepaths:t,docsWorkspace:r});break;case"changelog":e.icon!=null&&await JXn({iconPath:e.icon,filepaths:t,docsWorkspace:r});break}}async function seh({navigation:e,apiWorkspaces:t,visitor:r,context:i}){VOM(e)?await Promise.all(e.map(async n=>{n.layout!=null&&await Promise.all(n.layout.map(async a=>{await LFc({navigationItem:a,visitor:r,apiWorkspaces:t,context:i})}))})):await Promise.all(e.map(async n=>{await LFc({navigationItem:n,visitor:r,apiWorkspaces:t,context:i})}))}async function LFc({navigationItem:e,visitor:t,apiWorkspaces:r,context:i}){if(await Ver(e,{alphabetized:$o,api:$o,apiName:$o,audiences:$o,displayErrors:$o,snippets:$o,summary:$o,title:$o,layout:$o,icon:$o,slug:$o,hidden:$o,skipSlug:$o,paginated:$o,playground:$o,flattened:$o,path:$o,page:$o,featureFlag:$o,openrpc:$o,contents:async n=>{n!=null&&await Promise.all(n.map(async a=>{await LFc({navigationItem:a,visitor:t,apiWorkspaces:r,context:i})}))},viewers:$o,orphaned:$o,availability:$o}),UOM(e)){let n=r.find(a=>a.workspaceName===e.apiName);n!=null&&await t.apiSection?.({config:e,workspace:n,context:i})}}function UOM(e){return e.api!=null}function VOM(e){return e[0]?.tab!=null}function Kee(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}ceh.default.extend(leh.default);var WOM=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),rvu=0,HOM=async({ir:e})=>(rvu++,`${e.apiName.snakeCase.unsafeName}-${rvu}`),$OM=async({api:e})=>(rvu++,`${e.id}-${rvu}`),uJt=class{domain;docsWorkspace;ossWorkspaces;apiWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;registerApiV2;constructor(t,r,i,n,a,u,c=WOM,d=HOM,s=$OM){this.domain=t,this.docsWorkspace=r,this.ossWorkspaces=i,this.apiWorkspaces=n,this.taskContext=a,this.editThisPage=u,this.uploadFiles=c,this.registerApi=d,this.registerApiV2=s}#e=khu.init();_parsedDocsConfig;get parsedDocsConfig(){if(this._parsedDocsConfig==null)throw new Error("parsedDocsConfig is not set");return this._parsedDocsConfig}collectedFileIds=new Map;markdownFilesToFullSlugs=new Map;markdownFilesToNoIndex=new Map;markdownFilesToTags=new Map;rawMarkdownFiles={};async resolve(){this._parsedDocsConfig=await WZs({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig});for(let[o,l]of Object.entries(this.parsedDocsConfig.pages))this.rawMarkdownFiles[za.of(o)]=l;let t=this.parsedDocsConfig.experimental?.openapiParserV3,r=t!=null&&!t;this.docsWorkspace.config.navigation!=null&&r&&await seh({navigation:this.docsWorkspace.config.navigation,visitor:{apiSection:async({workspace:o})=>{(await o.toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,preserveSchemaIds:!0,objectQueryParameters:!0,respectReadonlySchemas:!0})).changelog?.files.forEach(v=>{let g=BT(this.docsWorkspace.absoluteFilePath,v.absoluteFilepath);this.parsedDocsConfig.pages[g]=v.contents,this.rawMarkdownFiles[za.of(g)]=v.contents})}},apiWorkspaces:this.apiWorkspaces,context:this.taskContext}),this.markdownFilesToFullSlugs=await this.getMarkdownFilesToFullSlugs(this.parsedDocsConfig.pages),this.markdownFilesToNoIndex=await this.getMarkdownFilesToNoIndex(this.parsedDocsConfig.pages),this.markdownFilesToTags=await this.getMarkdownFilesToTags(this.parsedDocsConfig.pages);for(let[o,l]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[za.of(o)]=await pRc({markdown:l,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(o),context:this.taskContext});for(let[o,l]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[za.of(o)]=await dRc({markdown:l,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(o),context:this.taskContext});let i=await ueh({parsedDocsConfig:this.parsedDocsConfig,docsWorkspace:this.docsWorkspace});for(let[o,l]of Object.entries(this.parsedDocsConfig.pages))try{let{filepaths:v,markdown:g}=Ean(l,{absolutePathToMarkdownFile:this.resolveFilepath(o),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath});this.parsedDocsConfig.pages[za.of(o)]=g;for(let O of v)i.add(O)}catch(v){throw this.taskContext.logger.error(`Failed to parse ${o}: ${v instanceof Error?v.message:String(v)}`),v}let n=Array.from(i).map(o=>({absoluteFilePath:o,relativeFilePath:this.toRelativeFilepath(o)}));(await this.uploadFiles(n)).forEach(o=>{this.collectedFileIds.set(o.absoluteFilePath,o.fileId)});let u=await this.getMarkdownFilesToFullyQualifiedPathNames();for(let[o,l]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[za.of(o)]=fRc(l,this.collectedFileIds,u,{absolutePathToMarkdownFile:this.resolveFilepath(o),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);let c={};Object.entries(this.parsedDocsConfig.pages).forEach(([o,l])=>{let v=GOM(this.editThisPage,o),g=this.rawMarkdownFiles[za.of(o)];c[ZQt.PageId(o)]={markdown:l,editThisPageUrl:v?ZQt.Url(v):void 0,rawMarkdown:g}});let d=await this.convertDocsConfiguration(),s={};if(this._parsedDocsConfig.experimental?.mdxComponents!=null){let o=new Set;await Promise.all(this._parsedDocsConfig.experimental.mdxComponents.map(async l=>{let v=$v(this.docsWorkspace.absoluteFilePath,l);(await(0,ivu.stat)(v)).isDirectory()?(await Wae(v,"{js,ts,jsx,tsx,md,mdx}")).forEach(m=>{o.add(m)}):v.match(/\.(js|ts|jsx|tsx|md|mdx)$/)!=null&&o.add(v)})),s=Object.fromEntries(await Promise.all([...o].map(async l=>{let v=this.toRelativeFilepath(l),g=(await(0,ivu.readFile)(l)).toString();return[v,g]})))}return{config:d,pages:c,jsFiles:s}}resolveFilepath(t){if(t!=null)return $v(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return BT(this.docsWorkspace.absoluteFilePath,t)}async getMarkdownFilesToFullSlugs(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,tvu.default)(n).data.slug;typeof u=="string"&&u.trim().length>0&&r.set(this.resolveFilepath(i),u.trim())}return r}async getMarkdownFilesToNoIndex(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,tvu.default)(n).data.noindex;typeof u=="boolean"&&r.set(this.resolveFilepath(i),u)}return r}async getMarkdownFilesToTags(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,tvu.default)(n).data.tags;typeof u=="string"?r.set(this.resolveFilepath(i),u.split(",").map(c=>c.trim()).filter(c=>c.length>0)):Array.isArray(u)&&r.set(this.resolveFilepath(i),u)}return r}async getMarkdownFilesToFullyQualifiedPathNames(){let t={},r=Do.migrate.FernNavigationV1ToLatest.create().root(await this.toRootNode());return Do.NodeCollector.collect(r).slugMap.forEach((n,a)=>{if(n==null||!Do.isPage(n))return;let u=Do.getPageId(n);if(u==null)return;let c=Bu(this.docsWorkspace.absoluteFilePath,za.of(u));t[c]=a}),t}getDocsBasePath(){return new URL(Kee(this.domain)).pathname}async convertDocsConfiguration(){let t=await this.toRootNode();return{aiChatConfig:this.parsedDocsConfig.aiChatConfig!=null?{model:this.parsedDocsConfig.aiChatConfig.model,systemPrompt:this.parsedDocsConfig.aiChatConfig.systemPrompt}:void 0,hideNavLinks:void 0,title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?ZQt.Url(this.parsedDocsConfig.logo?.href):void 0,favicon:this.getFileId(this.parsedDocsConfig.favicon),navigation:void 0,root:t,colorsV3:this.convertColorConfigImageReferences(),navbarLinks:this.parsedDocsConfig.navbarLinks?.map(i=>({...i,url:ZQt.Url(i.url)})),typographyV2:this.convertDocsTypographyConfiguration(),layout:this.parsedDocsConfig.layout,css:this.parsedDocsConfig.css,js:this.convertJavascriptConfiguration(),metadata:this.convertMetadata(),redirects:this.parsedDocsConfig.redirects,integrations:this.parsedDocsConfig.integrations,footerLinks:this.parsedDocsConfig.footerLinks?.map(i=>({...i,value:ZQt.Url(i.value)})),defaultLanguage:this.parsedDocsConfig.defaultLanguage,analyticsConfig:{...this.parsedDocsConfig.analyticsConfig,segment:this.parsedDocsConfig.analyticsConfig?.segment,fullstory:this.parsedDocsConfig.analyticsConfig?.fullstory,intercom:this.parsedDocsConfig.analyticsConfig?.intercom?{appId:this.parsedDocsConfig.analyticsConfig.intercom.appId,apiBase:this.parsedDocsConfig.analyticsConfig.intercom.apiBase}:void 0,posthog:this.parsedDocsConfig.analyticsConfig?.posthog?{apiKey:this.parsedDocsConfig.analyticsConfig.posthog.apiKey,endpoint:this.parsedDocsConfig.analyticsConfig.posthog.endpoint}:void 0,gtm:this.parsedDocsConfig.analyticsConfig?.gtm?{containerId:this.parsedDocsConfig.analyticsConfig.gtm.containerId}:void 0,ga4:this.parsedDocsConfig.analyticsConfig?.ga4?{measurementId:this.parsedDocsConfig.analyticsConfig.ga4.measurementId}:void 0,amplitude:void 0,mixpanel:void 0,hotjar:void 0,koala:void 0,logrocket:void 0,pirsch:void 0,plausible:void 0,fathom:void 0,clearbit:void 0,heap:void 0},announcement:this.parsedDocsConfig.announcement!=null?{text:this.parsedDocsConfig.announcement.message}:void 0,logo:void 0,logoV2:void 0,colors:void 0,colorsV2:void 0,typography:void 0,backgroundImage:void 0}}getFernWorkspaceForApiSection(t){if(t.apiName!=null){let i=this.apiWorkspaces.find(n=>n.workspaceName===t.apiName);if(i!=null)return i}else if(this.apiWorkspaces.length===1&&this.apiWorkspaces[0]!=null)return this.apiWorkspaces[0];let r=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs`:"Failed to load API Definition referenced in docs";throw new Error(r)}getOpenApiWorkspaceForApiSection(t){if(t.apiName!=null){let i=this.ossWorkspaces.find(n=>n.workspaceName===t.apiName);if(i!=null)return i}else if(this.ossWorkspaces.length===1&&this.ossWorkspaces[0]!=null)return this.ossWorkspaces[0];let r=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs`:"Failed to load API Definition referenced in docs";throw new Error(r)}async toRootNode(){let t=Do.V1.SlugGenerator.init(Do.slugjoin(this.getDocsBasePath())),r=this.#e.get("root"),i=await this.toRootChild(t);return{type:"root",version:"v1",id:r,child:i,slug:t.get(),title:this.parsedDocsConfig.title??"Documentation",hidden:!1,icon:void 0,pointsTo:void 0,authed:void 0,viewers:void 0,orphaned:void 0,roles:this.parsedDocsConfig.roles?.map(n=>Do.RoleId(n)),featureFlags:void 0}}async toRootChild(t){return y8n(this.parsedDocsConfig.navigation)._visit({untabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),tabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),versioned:r=>this.toVersionedNode(r,t),productgroup:r=>this.toProductGroupNode({landingPageConfig:this.parsedDocsConfig.landingPage,productGroup:r,parentSlug:t})})}toLandingPageNode(t,r){let i=Do.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??TT(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{type:"landingPage",id:this.#e.get(i),title:t.title,slug:n.get(),icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toUnversionedNode({landingPage:t,navigationConfig:r,parentSlug:i}){let n=this.#e.get("unversioned"),a=t!=null?this.toLandingPageNode(t,i):void 0,u=r.type==="tabbed"?await this.convertTabbedNavigation(n,r.items,i):await this.toSidebarRootNode(n,r.items,i);return{type:"unversioned",id:n,landingPage:a,child:u}}async toVersionedNode(t,r){return{id:this.#e.get("versioned"),type:"versioned",children:await Promise.all(t.versions.map((n,a)=>this.toVersionNode(n,r,a===0)))}}async toProductGroupNode({productGroup:t,landingPageConfig:r,parentSlug:i}){let n=this.#e.get("productgroup"),a=r!=null?this.toLandingPageNode(r,i):void 0;return{id:n,type:"productgroup",landingPage:a,children:await Promise.all(t.products.map(u=>this.toProductNode(u,i)))}}async toProductNode(t,r){let i=r.setProductSlug(t.slug??TT(t.product)),n;switch(t.navigation.type){case"tabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.convertTabbedNavigation(this.#e.get(t.product),t.navigation.items,i)};break;case"untabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.toSidebarRootNode(this.#e.get(t.product),t.navigation.items,i)};break;case"versioned":n=await this.toVersionedNode(t.navigation,i);break;default:Ao(t.navigation)}return{type:"product",id:this.#e.get(t.product),productId:Do.V1.ProductId(t.product),title:t.product,subtitle:t.subtitle??"",slug:i.get(),child:n,default:!1,hidden:void 0,authed:void 0,icon:t.icon,image:t.image!=null?this.getFileId(t.image):void 0,pointsTo:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}async toVersionNode(t,r,i){let n=this.#e.get(t.version),a=r.setVersionSlug(t.slug??TT(t.version)),u=t.navigation.type==="tabbed"?await this.convertTabbedNavigation(n,t.navigation.items,a):await this.toSidebarRootNode(n,t.navigation.items,a);return{type:"version",id:n,versionId:Do.VersionId(t.version),title:t.version,slug:a.get(),child:u,default:i,availability:t.availability!=null?QOM(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,a):void 0,hidden:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,icon:void 0,pointsTo:void 0,featureFlags:t.featureFlags}}async toSidebarRootNode(t,r,i){let n=this.#e.get(`${t}/root`),a=await Promise.all(r.map(c=>this.toNavigationChild({prefix:n,item:c,parentSlug:i}))),u=[];return a.forEach(c=>{if(c.type==="apiReference"){u.push(c);return}if(c.type==="section"&&!c.collapsed){u.push(c);return}let d=u.length>0?u[u.length-1]:void 0,s;d?.type==="sidebarGroup"?s=d:(s={id:this.#e.get(`${n}/group`),type:"sidebarGroup",children:[]},u.push(s)),s.children.push(c)}),{type:"sidebarRoot",id:n,children:u}}async toNavigationChild({prefix:t,item:r,parentSlug:i,hideChildren:n,parentAvailability:a}){return y8n(r)._visit({page:async u=>this.toPageNode({item:u,parentSlug:i,hideChildren:n,parentAvailability:a}),apiSection:async u=>this.toApiSectionNode({item:u,parentSlug:i,hideChildren:n,parentAvailability:a}),section:async u=>this.toSectionNode({prefix:t,item:u,parentSlug:i,hideChildren:n,parentAvailability:a}),link:async u=>this.toLinkNode(u),changelog:async u=>this.toChangelogNode(u,i,n)})}async toApiSectionNode({item:t,parentSlug:r,hideChildren:i,parentAvailability:n}){if(t.openrpc!=null){let g=$v(this.docsWorkspace.absoluteFilePath,za.of(t.openrpc));if(!await Cf(g))throw new Error(`OpenRPC file does not exist at path: ${g}`);let O=await oeh(g,this.taskContext);if(O==null)throw new Error("Failed to generate API Definition from OpenRPC document");return await this.registerApiV2({api:O,apiName:t.apiName,snippetsConfig:eyu(t.snippetsConfiguration)}),new _Va(t,O,r,void 0,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,this.#e,i,n??t.availability).get()}if(this.parsedDocsConfig.experimental?.openapiParserV2){let g=this.getOpenApiWorkspaceForApiSection(t),O=eyu(t.snippetsConfiguration),m=await jVa(g,this.taskContext);if(m==null)throw new Error("Failed to generate API Definition from OpenAPI workspace");return await this.registerApiV2({api:m,snippetsConfig:O,apiName:t.apiName}),new _Va(t,m,r,g,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,this.#e,i,n??t.availability).get()}let a=eyu(t.snippetsConfiguration),u,c=await this.getFernWorkspaceForApiSection(t).toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,objectQueryParameters:!0,preserveSchemaIds:!0}),d=this.parsedDocsConfig.experimental?.openapiParserV3;if(d==null||d)try{u=await this.getOpenApiWorkspaceForApiSection(t).getIntermediateRepresentation({context:this.taskContext,audiences:t.audiences,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1})}catch{}u==null&&(u=bx({workspace:c,audiences:t.audiences,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!0},readme:void 0,version:void 0,packageName:void 0,context:this.taskContext,sourceResolver:new yx(this.taskContext,c)}));let o=await this.registerApi({ir:u,snippetsConfig:a,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName,workspace:c}),l=hVa({ir:u,apiDefinitionId:o,playgroundConfig:{oauth:t.playground?.oauth},context:this.taskContext});return new Xhu(t,l,r,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,this.#e,c,i,n??t.availability).get()}async toChangelogNode(t,r,i){return new UPi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:t.icon,viewers:t.viewers,hidden:i||t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:Do.V1.Url(t.url),icon:t.icon}}async toPageNode({item:t,parentSlug:r,hideChildren:i,parentAvailability:n}){let a=Do.PageId(this.toRelativeFilepath(t.absolutePath)),u=r.apply({urlSlug:t.slug??TT(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(a),type:"page",slug:u.get(),title:t.title,icon:t.icon,hidden:i||t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:a,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags,availability:t.availability??n}}async toSectionNode({prefix:t,item:r,parentSlug:i,hideChildren:n,parentAvailability:a}){let u=this.toRelativeFilepath(r.overviewAbsolutePath),c=u?Do.PageId(u):void 0,d=this.#e.get(c??`${t}/section`),s=i.apply({urlSlug:r.slug??TT(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug}),o=r.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(r.overviewAbsolutePath):void 0,l=n||r.hidden;return{id:d,type:"section",overviewPageId:c,slug:s.get(),title:r.title,icon:r.icon,collapsed:r.collapsed,hidden:l,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(v=>this.toNavigationChild({prefix:d,item:v,parentSlug:s,hideChildren:l,parentAvailability:r.availability??a}))),authed:void 0,pointsTo:void 0,noindex:o,featureFlags:r.featureFlags,availability:r.availability??a}}async convertTabbedNavigation(t,r,i){let n=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:n,children:await Promise.all(r.map(a=>this.toTabChild(n,a,i)))}}async toTabChild(t,r,i){return y8n(r.child)._visit({link:({href:n})=>this.toTabLinkNode(r,n),layout:({layout:n})=>this.toTabNode(t,r,n,i),changelog:({changelog:n})=>this.toTabChangelogNode(r,n,i)})}async toTabChangelogNode(t,r,i){return new UPi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:i,title:t.title,icon:t.icon,viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r){return{type:"link",id:this.#e.get(r),title:t.title,url:Do.V1.Url(r),icon:t.icon}}async toTabNode(t,r,i,n){let a=this.#e.get(`${t}/tab`),u=n.apply({urlSlug:r.slug??TT(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:u.get(),icon:r.icon,hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNode(a,i,u),featureFlags:r.featureFlags}}getFileId(t){if(t==null)return;let r=this.collectedFileIds.get(t);return r==null?this.taskContext.failAndThrow("Failed to locate file after uploading: "+t):ZQt.FileId(r)}convertColorConfigImageReferences(){let{colors:t}=this.parsedDocsConfig;if(t!=null)return t.type==="dark"?{...t,...this.convertLogoAndBackgroundImage({theme:"dark"})}:t.type==="light"?{...t,...this.convertLogoAndBackgroundImage({theme:"light"}),type:"light"}:{...t,dark:{...t.dark,...this.convertLogoAndBackgroundImage({theme:"dark"})},light:{...t.light,...this.convertLogoAndBackgroundImage({theme:"light"})}}}convertLogoAndBackgroundImage({theme:t}){let{logo:r,backgroundImage:i}=this.parsedDocsConfig,n=r?.[t],a=i?.[t];return{logo:this.getFileId(n),backgroundImage:this.getFileId(a)}}convertDocsTypographyConfiguration(){if(this.parsedDocsConfig.typography!=null)return{headingsFont:this.convertFont(this.parsedDocsConfig.typography.headingsFont,"headings"),bodyFont:this.convertFont(this.parsedDocsConfig.typography.bodyFont,"body"),codeFont:this.convertFont(this.parsedDocsConfig.typography.codeFont,"code")}}convertFont(t,r){if(t==null||t.variants[0]==null)return;let i=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${i}`,variants:t.variants.map(n=>({fontFile:this.getFileId(n.absolutePath),weight:n.weight,style:n.style!=null?[n.style]:void 0})),display:t.display,fallback:t.fallback,fontVariationSettings:t.fontVariationSettings}}convertJavascriptConfiguration(){if(this.parsedDocsConfig.js!=null)return{files:this.parsedDocsConfig.js.files.map(({absolutePath:t,strategy:r})=>({fileId:this.getFileId(t),strategy:r})).filter(yy),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:ZQt.Url(t.url)})),inline:void 0}}convertMetadata(){if(this.parsedDocsConfig.metadata==null)return;let{"og:image":t,"og:logo":r,"twitter:image":i,...n}=this.parsedDocsConfig.metadata;return{...n,"og:image":this.convertFileIdOrUrl(t),"og:logo":this.convertFileIdOrUrl(r),"twitter:image":this.convertFileIdOrUrl(i)}}convertFileIdOrUrl(t){if(t!=null)return y8n(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:ZQt.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function GOM(e,t){if(e?.github==null)return;let{owner:r,repo:i,branch:n="main",host:a="https://github.com"}=e.github;return`${Kee(a)}/${r}/${i}/blob/${n}/fern/${t}?plain=1`}function QOM(e){switch(e){case"beta":return Do.V1.NavigationV1Availability.Beta;case"deprecated":return Do.V1.NavigationV1Availability.Deprecated;case"ga":return Do.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return Do.V1.NavigationV1Availability.Stable;default:Ao(e)}}async function R$(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof D3?t:null))).filter(yy)}async function UFc(e,t,r){if(e instanceof wor){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof D3))return;let i=await e.getIntermediateRepresentation({context:t,audiences:r,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1});return Jee({ir:i,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0},playgroundConfig:{oauth:!0},context:t})}var wlh=ui(HFc(),1),Slh=ui(Ivu(),1),Dlh=ui(require("http"),1),Elh=ui(require("path"),1);var Lnh=require("events"),Fvu=ui(require("fs"),1),xon=ui(require("path"),1);var Pnh=ui(require("os"),1),jnh=300,m7i=20,GVa=1e7,wnh=Pnh.default.platform();var qEM=wnh==="darwin",L4c=wnh==="win32",P7i=qEM||L4c,Snh=3e3,Dnh=2e4,U4c=1250;var uur;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(uur||(uur={}));var zon;(function(e){e.CHANGE="change",e.RENAME="rename"})(zon||(zon={}));var QVa;(function(e){e.CHANGE="change",e.ERROR="error"})(QVa||(QVa={}));var F0;(function(e){e.ADD="add",e.ADD_DIR="addDir",e.CHANGE="change",e.RENAME="rename",e.RENAME_DIR="renameDir",e.UNLINK="unlink",e.UNLINK_DIR="unlinkDir"})(F0||(F0={}));var Zee;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(Zee||(Zee={}));var TEM=(e,t=1,r)=>{t=Math.max(1,t);let i=r?.leading??!1,n=r?.trailing??!0,a=Math.max(r?.maxWait??1/0,t),u,c,d=0,s=0,o=()=>{let E=Date.now(),T=E-d,z=E-s,G=T>=t||z>=a;return[E,G]},l=E=>{if(s=E,!u)return;let T=u;u=void 0,e.apply(void 0,T)},v=()=>{A(0)},g=()=>{c&&(v(),l(Date.now()))},O=E=>{if(s=E,i)return l(E)},m=E=>{if(n&&u)return l(E);u=void 0},P=()=>{c=void 0;let[E,T]=o();return T?m(E):D(E)},D=E=>{let T=E-d,z=E-s,G=t-T,I=a-z,R=Math.min(G,I);return A(R)},A=E=>{c&&clearTimeout(c),!(E<=0)&&(c=setTimeout(P,E))},M=(...E)=>{let[T,z]=o(),G=!!c;if(u=E,d=T,(z||!c)&&A(t),z)return G?l(T):O(T)};return M.cancel=v,M.flush=g,M},zvu=TEM;var $4c=ui(require("fs"),1),Rvu=ui(require("path"),1);var LM=ui(require("fs"),1),N$=require("util");var $Pi=(e,t)=>function(...i){return e.apply(void 0,i).catch(t)},sur=(e,t)=>function(...i){try{return e.apply(void 0,i)}catch(n){return t(n)}};var V4c=ui(require("process"),1),Enh=V4c.default.getuid?!V4c.default.getuid():!1,Mnh=1e4,ise=()=>{};var JVa={isChangeErrorOk:e=>{if(!JVa.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!Enh&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!JVa.isNodeError(e))return!1;let{code:t}=e;return t==="EMFILE"||t==="ENFILE"||t==="EAGAIN"||t==="EBUSY"||t==="EACCESS"||t==="EACCES"||t==="EACCS"||t==="EPERM"},onChangeError:e=>{if(!JVa.isNodeError(e))throw e;if(!JVa.isChangeErrorOk(e))throw e}},Z6=JVa;var W4c=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=Mnh,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(i),i=()=>t(r);this.add(i)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},Anh=new W4c;var GPi=(e,t)=>function(i){return function n(...a){return Anh.schedule().then(u=>{let c=s=>(u(),s),d=s=>{if(u(),Date.now()>=i)throw s;if(t(s)){let o=Math.round(100*Math.random());return new Promise(v=>setTimeout(v,o)).then(()=>n.apply(void 0,a))}throw s};return e.apply(void 0,a).then(c,d)})}},QPi=(e,t)=>function(i){return function n(...a){try{return e.apply(void 0,a)}catch(u){if(Date.now()>i)throw u;if(t(u))return n.apply(void 0,a);throw u}}};var CEM={attempt:{chmod:$Pi((0,N$.promisify)(LM.default.chmod),Z6.onChangeError),chown:$Pi((0,N$.promisify)(LM.default.chown),Z6.onChangeError),close:$Pi((0,N$.promisify)(LM.default.close),ise),fsync:$Pi((0,N$.promisify)(LM.default.fsync),ise),mkdir:$Pi((0,N$.promisify)(LM.default.mkdir),ise),realpath:$Pi((0,N$.promisify)(LM.default.realpath),ise),stat:$Pi((0,N$.promisify)(LM.default.stat),ise),unlink:$Pi((0,N$.promisify)(LM.default.unlink),ise),chmodSync:sur(LM.default.chmodSync,Z6.onChangeError),chownSync:sur(LM.default.chownSync,Z6.onChangeError),closeSync:sur(LM.default.closeSync,ise),existsSync:sur(LM.default.existsSync,ise),fsyncSync:sur(LM.default.fsync,ise),mkdirSync:sur(LM.default.mkdirSync,ise),realpathSync:sur(LM.default.realpathSync,ise),statSync:sur(LM.default.statSync,ise),unlinkSync:sur(LM.default.unlinkSync,ise)},retry:{close:GPi((0,N$.promisify)(LM.default.close),Z6.isRetriableError),fsync:GPi((0,N$.promisify)(LM.default.fsync),Z6.isRetriableError),open:GPi((0,N$.promisify)(LM.default.open),Z6.isRetriableError),readFile:GPi((0,N$.promisify)(LM.default.readFile),Z6.isRetriableError),rename:GPi((0,N$.promisify)(LM.default.rename),Z6.isRetriableError),stat:GPi((0,N$.promisify)(LM.default.stat),Z6.isRetriableError),write:GPi((0,N$.promisify)(LM.default.write),Z6.isRetriableError),writeFile:GPi((0,N$.promisify)(LM.default.writeFile),Z6.isRetriableError),closeSync:QPi(LM.default.closeSync,Z6.isRetriableError),fsyncSync:QPi(LM.default.fsyncSync,Z6.isRetriableError),openSync:QPi(LM.default.openSync,Z6.isRetriableError),readFileSync:QPi(LM.default.readFileSync,Z6.isRetriableError),renameSync:QPi(LM.default.renameSync,Z6.isRetriableError),statSync:QPi(LM.default.statSync,Z6.isRetriableError),writeSync:QPi(LM.default.writeSync,Z6.isRetriableError),writeFileSync:QPi(LM.default.writeFileSync,Z6.isRetriableError)}},qnh=CEM;var xvu=ui(require("fs"),1),KVa=ui(require("path"),1);var H4c=()=>{};var BEM=()=>{let e=H4c,t=H4c,r=!1,i=!1;return{promise:new Promise((d,s)=>{e=o=>(r=!0,d(o)),t=o=>(i=!0,s(o))}),resolve:e,reject:t,isPending:()=>!r&&!i,isResolved:()=>r,isRejected:()=>i}},Tnh=BEM;var IEM=()=>{let{promise:e,resolve:t,isPending:r}=Tnh(),i=0,n=()=>{i+=1},a=()=>{i-=1,!i&&t()};return(()=>{n(),queueMicrotask(a)})(),{promise:e,isPending:r,increment:n,decrement:a}},Cnh=IEM;var Bnh={then:e=>{e()}};var Inh=e=>Array.isArray(e)?e:[e],znh=e=>typeof e=="function";var zEM=(e,t)=>{let r=t?.followSymlinks??!1,i=t?.depth??1/0,n=t?.limit??1/0,a=t?.ignore??[],u=Inh(a).map(De=>znh(De)?De:Ae=>De.test(Ae)),c=De=>u.some(Ae=>Ae(De)),d=t?.signal??{aborted:!1},s=t?.onDirents||(()=>{}),o=[],l=new Set,v={},g=[],O=new Set,m={},P=[],D=new Set,A={},M={},E=new Set,T={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},z={directories:o,directoriesNames:l,directoriesNamesToPaths:v,files:g,filesNames:O,filesNamesToPaths:m,symlinks:P,symlinksNames:D,symlinksNamesToPaths:A,map:M},{promise:G,increment:I,decrement:R}=Cnh(),U=0,Y=(De,Ae,Ct,Pe)=>{E.has(Ae)||U>=n||(U+=1,De.directories.push(Ae),De.directoriesNames.add(Ct),o.push(Ae),l.add(Ct),v.propertyIsEnumerable(Ct)||(v[Ct]=[]),v[Ct].push(Ae),E.add(Ae),!(Pe>=i)&&(U>=n||me(Ae,Pe+1)))},J=(De,Ae,Ct)=>{E.has(Ae)||U>=n||(U+=1,De.files.push(Ae),De.filesNames.add(Ct),g.push(Ae),O.add(Ct),m.propertyIsEnumerable(Ct)||(m[Ct]=[]),m[Ct].push(Ae),E.add(Ae))},X=(De,Ae,Ct,Pe)=>{E.has(Ae)||U>=n||(U+=1,De.symlinks.push(Ae),De.symlinksNames.add(Ct),P.push(Ae),D.add(Ct),A.propertyIsEnumerable(Ct)||(A[Ct]=[]),A[Ct].push(Ae),E.add(Ae),r&&(Pe>=i||U>=n||Le(Ae,Pe+1)))},ae=(De,Ae,Ct,Pe,St)=>{d.aborted||c(Ae)||(Pe.isDirectory()?Y(De,Ae,Ct,St):Pe.isFile()?J(De,Ae,Ct):Pe.isSymbolicLink()&&X(De,Ae,Ct,St))},pe=(De,Ae,Ct,Pe)=>{if(d.aborted)return;let St=Ae===KVa.default.sep?"":KVa.default.sep,at=Ct.name,Oe=`${Ae}${St}${at}`;c(Oe)||(Ct.isDirectory()?Y(De,Oe,at,Pe):Ct.isFile()?J(De,Oe,at):Ct.isSymbolicLink()&&X(De,Oe,at,Pe))},de=(De,Ae,Ct,Pe)=>{for(let St=0,at=Ct.length;St<at;St++)pe(De,Ae,Ct[St],Pe)},me=(De,Ae)=>{d.aborted||Ae>i||U>=n||(I(),xvu.default.readdir(De,{withFileTypes:!0},(Ct,Pe)=>{if(Ct||d.aborted||!Pe.length)return R();(s(Pe)||Bnh).then(()=>{let at=M[De]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};de(at,De,Pe,Ae),R()})}))},Le=(De,Ae)=>{I(),xvu.default.realpath(De,(Ct,Pe)=>{if(Ct||d.aborted)return R();xvu.default.stat(Pe,(St,at)=>{if(St||d.aborted)return R();let Oe=KVa.default.basename(Pe),je=M[De]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};ae(je,Pe,Oe,at,Ae),R()})})};return(async(De,Ae=1)=>(De=KVa.default.normalize(De),E.add(De),me(De,Ae),await G,d.aborted?T:z))(e)},xnh=zEM;var cur={lang:{debounce:zvu,attempt:e=>{try{return e()}catch(t){return cur.lang.castError(t)}},castArray:e=>cur.lang.isArray(e)?e:[e],castError:e=>cur.lang.isError(e)?e:cur.lang.isString(e)?new Error(e):new Error("Unknown error"),defer:e=>setTimeout(e,0),isArray:e=>Array.isArray(e),isError:e=>e instanceof Error,isFunction:e=>typeof e=="function",isNaN:e=>Number.isNaN(e),isNumber:e=>typeof e=="number",isPrimitive:e=>{if(e===null)return!0;let t=typeof e;return t!=="object"&&t!=="function"},isShallowEqual:(e,t)=>{if(e===t)return!0;if(cur.lang.isNaN(e))return cur.lang.isNaN(t);if(cur.lang.isPrimitive(e)||cur.lang.isPrimitive(t))return e===t;for(let r in e)if(!(r in t))return!1;for(let r in t)if(e[r]!==t[r])return!1;return!0},isSet:e=>e instanceof Set,isString:e=>typeof e=="string",isUndefined:e=>e===void 0,noop:()=>{},uniq:e=>e.length<2?e:Array.from(new Set(e))},fs:{getDepth:e=>Math.max(0,e.split(Rvu.default.sep).length-1),getRealPath:(e,t)=>{try{return t?$4c.default.realpathSync.native(e):$4c.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===Rvu.default.sep&&t.length-e.length>Rvu.default.sep.length,poll:(e,t=Dnh)=>qnh.retry.stat(t)(e,{bigint:!0}).catch(cur.lang.noop),readdir:async(e,t,r=1/0,i=1/0,n,a)=>{if(a&&r===1&&e in a){let u=a[e];return[u.directories,u.files]}else{let u=await xnh(e,{depth:r,limit:i,ignore:t,signal:n});return[u.directories,u.files]}}}},sP=cur;var Nvu=ui(require("path"),1);var G4c=class{constructor(t,r,i){this.base=i,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||sP.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=jnh){return(()=>{let r=this.watcher._readyWait,i=[],n=new Set,a=async(c,d)=>{let s=this.options.ignoreInitial?[]:c,o=await this.eventsPopulate([...d]),l=this.eventsDeduplicate([...s,...o]);this.onTargetEvents(l)},u=sP.lang.debounce(()=>{this.watcher.isClosed()||(r=a(i,n),i=[],n=new Set)},t);return async(c,d="",s=!1)=>{s?await this.eventsPopulate([d],i,!0):n.add(d),r.then(u)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((i,n)=>{let[a,u]=n,c=r[u];return a===c||a===F0.CHANGE&&c===F0.ADD||(r[u]=a,i.push(n)),i},[])}async eventsPopulate(t,r=[],i=!1){return await Promise.all(t.map(async n=>{let a=await this.watcher._poller.update(n,this.options.pollingTimeout);await Promise.all(a.map(async u=>{r.push([u,n]),u===F0.ADD_DIR?await this.eventsPopulateAddDir(t,n,r,i):u===F0.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,n,r,i)}))})),r}async eventsPopulateAddDir(t,r,i=[],n=!1){if(n)return i;let a=this.options.recursive?this.options.depth??m7i:Math.min(1,this.options.depth??m7i),u=this.options.limit??GVa,[c,d]=await sP.fs.readdir(r,this.options.ignore,a,u,this.watcher._closeSignal),s=[...c,...d];return await Promise.all(s.map(o=>{if(!this.watcher.isIgnored(o,this.options.ignore)&&!t.includes(o))return this.eventsPopulate([o],i,!0)})),i}async eventsPopulateUnlinkDir(t,r,i=[],n=!1){if(n)return i;for(let a of this.watcher._poller.stats.keys())sP.fs.isSubPath(r,a)&&(t.includes(a)||await this.eventsPopulate([a],i,!0));return i}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(F0.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!P7i&&this.options.native!==!1&&this.watcher.watchDirectory(t,this.options,this.handler,void 0,this.base||this),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAddDir(t,this.options.renameTimeout):this.watcher.event(F0.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(F0.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(Nvu.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(F0.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(Nvu.default.dirname(t),t,!1),this.watcher.watchersClose(t),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlinkDir(t,this.options.renameTimeout):this.watcher.event(F0.UNLINK_DIR,t))}onTargetEvent(t){let[r,i]=t;r===F0.ADD?this.onTargetAdd(i):r===F0.ADD_DIR?this.onTargetAddDir(i):r===F0.CHANGE?this.onTargetChange(i):r===F0.UNLINK?this.onTargetUnlink(i):r===F0.UNLINK_DIR&&this.onTargetUnlinkDir(i)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,i=!1){return this.handlerBatched(t,r,i)}onWatcherChange(t=zon.CHANGE,r){if(this.watcher.isClosed())return;let i=Nvu.default.resolve(this.folderPath,r||"");this.filePath&&i!==this.folderPath&&i!==this.filePath||this.watcher.isIgnored(i,this.options.ignore)||this.onWatcherEvent(t,i)}onWatcherError(t){L4c&&t.code==="EPERM"?this.onWatcherChange(zon.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(QVa.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(QVa.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(zon.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&P7i&&this.options.native!==!1?this.options.depth??m7i:Math.min(1,this.options.depth??m7i),i=this.options.limit??GVa,[n,a]=await sP.fs.readdir(this.folderPath,this.options.ignore,r,i,this.watcher._closeSignal,this.options.readdirMap),u=[this.folderPath,...n,...a];await Promise.all(u.map(c=>{if(!this.watcher._poller.stats.has(c)&&!this.watcher.isIgnored(c,this.options.ignore))return this.onWatcherEvent(zon.CHANGE,c,t)}))}}},Rnh=G4c;var kee={interval:100,intervalId:void 0,fns:new Map,init:()=>{kee.intervalId||(kee.intervalId=setInterval(kee.resolve,kee.interval))},reset:()=>{kee.intervalId&&(clearInterval(kee.intervalId),delete kee.intervalId)},add:(e,t)=>{kee.fns.set(e,Date.now()+t),kee.init()},remove:e=>{kee.fns.delete(e)},resolve:()=>{if(!kee.fns.size)return kee.reset();let e=Date.now();for(let[t,r]of kee.fns)r>=e||(kee.remove(t),t())}},YVa=kee;var XVa=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=U4c){let{ino:i,targetPath:n,events:a,locks:u}=t,c=()=>{let l=this._watcher._poller.paths.find(i||-1,v=>v!==n);if(l&&l!==n){if(sP.fs.getRealPath(n,!0)===l)return;this._watcher.event(a.rename,l,n)}else this._watcher.event(a.add,n)};if(!i)return c();let d=()=>{u.add.delete(i),YVa.remove(s)},s=()=>{d(),c()};YVa.add(s,r);let o=()=>{let l=u.unlink.get(i);if(!l)return;d();let v=l();n===v?a.change&&this._watcher._poller.stats.has(n)&&this._watcher.event(a.change,n):this._watcher.event(a.rename,v,n)};u.add.set(i,o),o()}getLockUnlink(t,r=U4c){let{ino:i,targetPath:n,events:a,locks:u}=t,c=()=>{this._watcher.event(a.unlink,n)};if(!i)return c();let d=()=>{u.unlink.delete(i),YVa.remove(s)},s=()=>{d(),c()};YVa.add(s,r);let o=()=>(d(),n);u.unlink.set(i,o),u.add.get(i)?.()}getLockTargetAdd(t,r){let i=this._watcher._poller.getIno(t,F0.ADD,uur.FILE);return this.getLockAdd({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let i=this._watcher._poller.getIno(t,F0.ADD_DIR,uur.DIR);return this.getLockAdd({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let i=this._watcher._poller.getIno(t,F0.UNLINK,uur.FILE);return this.getLockUnlink({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let i=this._watcher._poller.getIno(t,F0.UNLINK_DIR,uur.DIR);return this.getLockUnlink({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};XVa.DIR_EVENTS={add:F0.ADD_DIR,rename:F0.RENAME_DIR,unlink:F0.UNLINK_DIR};XVa.FILE_EVENTS={add:F0.ADD,change:F0.CHANGE,rename:F0.RENAME,unlink:F0.UNLINK};var Nnh=XVa;var Q4c=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(sP.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let i=this.map.get(t);if(sP.lang.isSet(i)){let n=i.delete(r);return i.size||this.map.delete(t),n}else if(i===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let i=this.map.get(t);if(sP.lang.isSet(i))return Array.from(i).find(r);if(r(i))return i}}get(t){return this.map.get(t)}has(t,r){if(sP.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let i=this.map.get(t);return sP.lang.isSet(i)?i.has(r):i===r}return!1}set(t,r){if(this.map.has(t)){let i=this.map.get(t);sP.lang.isSet(i)?i.add(r):i!==r&&this.map.set(t,new Set([i,r]))}else this.map.set(t,r);return this}},J4c=Q4c;var K4c=class{constructor(t){this.ino=t.ino<=Number.MAX_SAFE_INTEGER?Number(t.ino):t.ino,this.size=Number(t.size),this.atimeMs=Number(t.atimeMs),this.mtimeMs=Number(t.mtimeMs),this.ctimeMs=Number(t.ctimeMs),this.birthtimeMs=Number(t.birthtimeMs),this._isFile=t.isFile(),this._isDirectory=t.isDirectory(),this._isSymbolicLink=t.isSymbolicLink()}isFile(){return this._isFile}isDirectory(){return this._isDirectory}isSymbolicLink(){return this._isSymbolicLink}},Fnh=K4c;var Y4c=class{constructor(){this.inos={},this.paths=new J4c,this.stats=new Map}getIno(t,r,i){let n=this.inos[r];if(!n)return;let a=n[t];if(a&&!(i&&a[1]!==i))return a[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let i=await sP.fs.poll(t,r);if(!(!i||!(i.isFile()||i.isDirectory())))return new Fnh(i)}reset(){this.inos={},this.paths=new J4c,this.stats=new Map}async update(t,r){let i=this.getStats(t),n=await this.poll(t,r);if(this.updateStats(t,n),!i&&n){if(n.isFile())return this.updateIno(t,F0.ADD,n),[F0.ADD];if(n.isDirectory())return this.updateIno(t,F0.ADD_DIR,n),[F0.ADD_DIR]}else if(i&&!n){if(i.isFile())return this.updateIno(t,F0.UNLINK,i),[F0.UNLINK];if(i.isDirectory())return this.updateIno(t,F0.UNLINK_DIR,i),[F0.UNLINK_DIR]}else if(i&&n){if(i.isFile()){if(n.isFile())return i.ino===n.ino&&!i.size&&!n.size?[]:(this.updateIno(t,F0.CHANGE,n),[F0.CHANGE]);if(n.isDirectory())return this.updateIno(t,F0.UNLINK,i),this.updateIno(t,F0.ADD_DIR,n),[F0.UNLINK,F0.ADD_DIR]}else if(i.isDirectory()){if(n.isFile())return this.updateIno(t,F0.UNLINK_DIR,i),this.updateIno(t,F0.ADD,n),[F0.UNLINK_DIR,F0.ADD];if(n.isDirectory())return i.ino===n.ino?[]:(this.updateIno(t,F0.UNLINK_DIR,i),this.updateIno(t,F0.ADD_DIR,n),[F0.UNLINK_DIR,F0.ADD_DIR])}}return[]}updateIno(t,r,i){let n=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=i.isFile()?uur.FILE:uur.DIR;n[t]=[i.ino,a]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let i=this.stats.get(t)?.ino||-1;this.paths.delete(i,t),this.stats.delete(t)}}},X4c=Y4c;var Z4c=class e extends Lnh.EventEmitter{constructor(t,r,i){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(Zee.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(n=>this.on(Zee.CLOSE,n)),this._readyWait=new Promise(n=>this.on(Zee.READY,n)),this._locker=new Nnh(this),this._roots=new Set,this._poller=new X4c,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,i)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(sP.lang.isFunction(r)?!!r(t):r.test(t))}isReady(){return this._ready}close(){return this._locker.reset(),this._poller.reset(),this._roots.clear(),this.watchersClose(),this.isClosed()?!1:(this._closed=!0,this.emit(Zee.CLOSE))}error(t){if(this.isClosed())return!1;let r=sP.lang.castError(t);return this.emit(Zee.ERROR,r)}event(t,r,i){return this.isClosed()?!1:(this.emit(Zee.ALL,t,r,i),this.emit(t,r,i))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(Zee.READY))}pollerExists(t,r){for(let i of this._pollers)if(i.targetPath===t&&sP.lang.isShallowEqual(i.options,r))return!0;return!1}subwatcherExists(t,r){for(let i of this._subwatchers)if(i.targetPath===t&&sP.lang.isShallowEqual(i.options,r))return!0;return!1}watchersClose(t,r,i=!0){if(t){let n=this._watchers[t];if(n)for(let a of[...n])r&&a.filePath!==r||this.watcherClose(a);if(i)for(let a in this._watchers)sP.fs.isSubPath(t,a)&&this.watchersClose(a,r,!1)}else for(let n in this._watchers)this.watchersClose(n,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,i]of t)this.watchPath(r,i.options,i.handler)}async watcherAdd(t,r){let{folderPath:i}=t;(this._watchers[i]=this._watchers[i]||[]).push(t);let a=new Rnh(this,t,r);return await a.init(),a}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let a=r.indexOf(t);r.splice(a,1),r.length||delete this._watchers[t.folderPath]}let i=t.filePath||t.folderPath;this._roots.has(i)&&(this._watchersRestorable[i]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=sP.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,i,n){if(this._watchers[t]?.find(c=>c.handler===i&&(!c.filePath||c.filePath===n)&&c.options.ignore===r.ignore&&!!c.options.native==!!r.native&&(!r.recursive||c.options.recursive)))return!0;let u=xon.default.dirname(t);for(let c=1;c<1/0;c++){if(this._watchers[u]?.find(o=>(c===1||o.options.recursive&&c<=(o.options.depth??m7i))&&o.handler===i&&(!o.filePath||o.filePath===n)&&o.options.ignore===r.ignore&&!!o.options.native==!!r.native&&(!r.recursive||o.options.recursive&&P7i&&o.options.native!==!1)))return!0;if(!P7i)break;let s=xon.default.dirname(t);if(u===s)break;u=s}return!1}async watchDirectories(t,r,i,n,a){if(this.isClosed())return;t=sP.lang.uniq(t).sort();let u;for(let c of t)if(!this.isIgnored(c,r.ignore)&&!this.watcherExists(c,r,i,n))try{let d=!r.recursive||P7i&&r.native!==!1?r:{...r,recursive:!1},o={watcher:Fvu.default.watch(c,d),handler:i,options:r,folderPath:c,filePath:n},l=u=await this.watcherAdd(o,a);if(this._roots.has(n||c)){let g={...r,ignoreInitial:!0,recursive:!1},O=xon.default.dirname(c),m=c;await this.watchDirectories([O],g,i,m,l)}}catch(d){this.error(d)}return u}async watchDirectory(t,r,i,n,a){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||P7i&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,i,n,a));{r={...r,recursive:!0};let u=r.depth??m7i,c=r.limit??GVa,[d]=await sP.fs.readdir(t,r.ignore,u,c,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let s=await this.watchDirectories([t],r,i,n,a);if(d.length){let o=sP.fs.getDepth(t);for(let l of d){let v=sP.fs.getDepth(l),g=Math.max(0,u-(v-o)),O={...r,depth:g};await this.watchDirectories([l],O,i,n,a||s)}}})}}}async watchFileOnce(t,r,i){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let n={targetPath:t,options:r},a=(s,o)=>{o===t&&(d(),i())},u=new e(a),c=()=>{this._subwatchers.add(n),this.on(Zee.CLOSE,d),u.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(n),this.removeListener(Zee.CLOSE,d),u.close()};return c()}async watchFile(t,r,i){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let n=xon.default.dirname(t);return this.watchDirectory(n,r,i,t)}async watchPollingOnce(t,r,i){if(this.isClosed())return;let n=!1,a=new X4c,u=await this.watchPolling(t,r,async()=>{n||!(await a.update(t,r.pollingTimeout)).length||n||(n=!0,u(),i())})}async watchPolling(t,r,i){if(this.isClosed())return sP.lang.noop;if(this.pollerExists(t,r))return sP.lang.noop;let n={...r,interval:r.pollingInterval??Snh},a={targetPath:t,options:r},u=()=>{this._pollers.add(a),this.on(Zee.CLOSE,c),Fvu.default.watchFile(t,n,i)},c=()=>{this._pollers.delete(a),this.removeListener(Zee.CLOSE,c),Fvu.default.unwatchFile(t,i)};return sP.lang.attempt(u),()=>sP.lang.attempt(c)}async watchUnknownChild(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchFileOnce(t,r,n)}async watchUnknownTarget(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchPollingOnce(t,r,n)}async watchPaths(t,r,i){if(this.isClosed())return;if(t=sP.lang.uniq(t).sort(),t.every((a,u)=>t.every((c,d)=>d===u||!sP.fs.isSubPath(a,c))))await Promise.all(t.map(a=>this.watchPath(a,r,i)));else for(let a of t)await this.watchPath(a,r,i)}async watchPath(t,r,i){if(this.isClosed()||(t=xon.default.resolve(t),this.isIgnored(t,r.ignore)))return;let n=await sP.fs.poll(t,r.pollingTimeout);if(n){if(n.isFile())return this.watchFile(t,r,i);if(n.isDirectory())return this.watchDirectory(t,r,i);this.error(`"${t}" is not supported`)}else{let a=xon.default.dirname(t);return(await sP.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,i):this.watchUnknownTarget(t,r,i)}}async watch(t,r,i=sP.lang.noop){if(sP.lang.isFunction(t))return this.watch([],{},t);if(sP.lang.isUndefined(t))return this.watch([],r,i);if(sP.lang.isFunction(r))return this.watch(t,{},r);if(sP.lang.isUndefined(r))return this.watch(t,{},i);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let n=sP.lang.castArray(t);n.forEach(a=>this._roots.add(a)),await this.watchPaths(n,r,i),!this.isClosed()&&(i!==sP.lang.noop&&this.on(Zee.ALL,i),r.readdirMap=void 0,this.ready())}},Lvu=Z4c;var eAM=ui(zah(),1),tAM=ui(c2c(),1),rAM=ui(d2c(),1),oWa=ui(Zvu(),1),uWa=ui(Hah(),1);var alh=ui(Abu(),1),tte=require("fs/promises"),olh=require("os"),ulh=ui($k(),1),slh=ui(nlh(),1),Gbu=process.platform==="win32",_CM="etag",hCM="preview",yCM="app-preview",vCM="bundle",bCM=".next",gCM="standalone",OCM=".fern",mCM="packages/fern-docs/bundle/.next/server/instrumentation.js",PCM=".npmrc",jCM=".pnpmfile.cjs",wCM="pnpm-workspace.yaml",SCM='Cannot find matching keyid: {"signatures":';function DCM(){return Bu($c.of((0,olh.homedir)()),za.of(OCM))}function Qbu({app:e=!1}){return Bu(DCM(),za.of(e?yCM:hCM))}function q7i({app:e=!1}){return Bu(Qbu({app:e}),za.of(e?bCM:vCM))}function EWa({app:e=!1}){return Bu(q7i({app:e}),za.of(gCM))}function ECM({app:e=!1}){return Bu(EWa({app:e}),za.of(mCM))}function MCM({app:e=!1}){return Bu(EWa({app:e}),za.of(wCM))}function ACM({app:e=!1}){return Bu(EWa({app:e}),za.of(jCM))}function qCM({app:e=!1}){return Bu(EWa({app:e}),za.of(PCM))}function Qon(e){return new Error(`${e}. Please reach out to support@buildwithfern.com.`)}function TCM({app:e=!1}){return Bu(Qbu({app:e}),za.of(_CM))}var CCM=`packages:
|
|
2332
2332
|
- "packages/**"
|
|
2333
2333
|
- "!**/dist"
|
|
2334
2334
|
`,BCM=`module.exports = {
|