fern-api 5.226.1 → 5.226.2
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 +6 -6
- package/package.json +1 -1
package/cli.cjs
CHANGED
|
@@ -547,7 +547,7 @@ For more information, see https://buildwithfern.com/learn/api-definition/introdu
|
|
|
547
547
|
`,s+1),c=a===-1?"":o.slice(a+1);String(n.stack).endsWith(c)||(n.stack+=`
|
|
548
548
|
`+o)}}catch{}}throw n}}_request(t,r){typeof t=="string"?(r=r||{},r.url=t):r=t||{},r=KK(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:o}=r;n!==void 0&&K8t.assertOptions(n,{silentJSONParsing:u8.transitional(u8.boolean),forcedJSONParsing:u8.transitional(u8.boolean),clarifyTimeoutError:u8.transitional(u8.boolean),legacyInterceptorReqResOrdering:u8.transitional(u8.boolean)},!1),i!=null&&(lr.isFunction(i)?r.paramsSerializer={serialize:i}:K8t.assertOptions(i,{encode:u8.function,serialize:u8.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),K8t.assertOptions(r,{baseUrl:u8.spelling("baseURL"),withXsrfToken:u8.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let s=o&&lr.merge(o.common,o[r.method]);o&&lr.forEach(["delete","get","head","post","put","patch","query","common"],m=>{delete o[m]}),r.headers=Kb.concat(s,o);let a=[],c=!0;this.interceptors.request.forEach(function(g){if(typeof g.runWhen=="function"&&g.runWhen(r)===!1)return;c=c&&g.synchronous;let A=r.transitional||gSe;A&&A.legacyInterceptorReqResOrdering?a.unshift(g.fulfilled,g.rejected):a.push(g.fulfilled,g.rejected)});let l=[];this.interceptors.response.forEach(function(g){l.push(g.fulfilled,g.rejected)});let u,p=0,d;if(!c){let m=[uHr.bind(this),void 0];for(m.unshift(...a),m.push(...l),d=m.length,u=Promise.resolve(r);p<d;)u=u.then(m[p++],m[p++]);return u}d=a.length;let f=r;for(;p<d;){let m=a[p++],g=a[p++];try{f=m(f)}catch(A){g.call(this,A);break}}try{u=uHr.call(this,f)}catch(m){return Promise.reject(m)}for(p=0,d=l.length;p<d;)u=u.then(l[p++],l[p++]);return u}getUri(t){t=KK(this.defaults,t);let r=nUe(t.baseURL,t.url,t.allowAbsoluteUrls);return tUe(r,t.params,t.paramsSerializer)}};lr.forEach(["delete","get","head","options"],function(t){gct.prototype[t]=function(r,n){return this.request(KK(n||{},{method:t,url:r,data:(n||{}).data}))}});lr.forEach(["post","put","patch","query"],function(t){function r(n){return function(o,s,a){return this.request(KK(a||{},{method:t,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:s}))}}gct.prototype[t]=r(),t!=="query"&&(gct.prototype[t+"Form"]=r(!0))});J8t=gct});var u8o,K9l,J9l=h(()=>{"use strict";rUe();u8o=class e{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(o){r=o});let n=this;this.promise.then(i=>{if(!n._listeners)return;let o=n._listeners.length;for(;o-- >0;)n._listeners[o](i);n._listeners=null}),this.promise.then=i=>{let o,s=new Promise(a=>{n.subscribe(a),o=a}).then(i);return s.cancel=function(){n.unsubscribe(o)},s},t(function(o,s,a){n.reason||(n.reason=new s3(o,s,a),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;let r=this._listeners.indexOf(t);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){let t=new AbortController,r=n=>{t.abort(n)};return this.subscribe(r),t.signal.unsubscribe=()=>this.unsubscribe(r),t.signal}static source(){let t;return{token:new e(function(i){t=i}),cancel:t}}},K9l=u8o});function p8o(e){return function(r){return e.apply(null,r)}}var Y9l=h(()=>{"use strict"});function f8o(e){return lr.isObject(e)&&e.isAxiosError===!0}var X9l=h(()=>{"use strict";Qy()});var d8o,Z9l,$9l=h(()=>{"use strict";d8o={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(d8o).forEach(([e,t])=>{d8o[t]=e});Z9l=d8o});function eql(e){let t=new J8t(e),r=D8t(J8t.prototype.request,t);return lr.extend(r,J8t.prototype,t,{allOwnKeys:!0}),lr.extend(r,t,null,{allOwnKeys:!0}),r.create=function(i){return eql(KK(e,i))},r}var qx,Vd,tql=h(()=>{"use strict";Qy();p5o();H9l();sHr();eHr();S5o();rUe();J9l();T5o();G8t();j8t();o3();Y9l();X9l();WK();c8o();$9l();qx=eql(dct);qx.Axios=J8t;qx.CanceledError=s3;qx.CancelToken=K9l;qx.isCancel=M8t;qx.VERSION=Rme;qx.toFormData=hSe;qx.AxiosError=ai;qx.Cancel=qx.CanceledError;qx.all=function(t){return Promise.all(t)};qx.spread=p8o;qx.isAxiosError=f8o;qx.mergeConfig=KK;qx.AxiosHeaders=Kb;qx.formToJSON=e=>$7r(lr.isHTMLForm(e)?new FormData(e):e);qx.getAdapter=lHr.getAdapter;qx.HttpStatusCode=Z9l;qx.default=qx;Vd=qx});var qjv,Act,Wjv,Hjv,Kjv,Jjv,Yjv,Xjv,Zjv,$jv,ezv,tzv,rzv,nzv,izv,ozv,szv,_Q=h(()=>{"use strict";tql();({Axios:qjv,AxiosError:Act,CanceledError:Wjv,isCancel:Hjv,CancelToken:Kjv,VERSION:Jjv,all:Yjv,Cancel:Xjv,isAxiosError:Zjv,spread:$jv,toFormData:ezv,AxiosHeaders:tzv,HttpStatusCode:rzv,formToJSON:nzv,getAdapter:izv,mergeConfig:ozv,create:szv}=Vd)});function x8m(e,t,r){let n=t,i=t?t.next:e.head,o=new gGo(r,n,i,e);return o.next===void 0&&(e.tail=o),o.prev===void 0&&(e.head=o),e.length++,o}function S8m(e,t){e.tail=new gGo(t,e.tail,void 0,e),e.head||(e.head=e.tail),e.length++}function w8m(e,t){e.head=new gGo(t,void 0,e.head,e),e.tail||(e.tail=e.head),e.length++}var Fql,M2,UHr,cGo,Nql,uGo,gUe,GHr,Qql,QHr,wSe,sql,Mql,hUe,Wql,bGt,ZK,G8o,Yql,Z8o,yGo,rWl,bGo,Ed,Hx,EGo,vGt,Tct,VQ,pWl,EGt,IGo,UQ,CGo,p5m,f5m,rql,d5m,m5m,h5m,Nme,jme,ASe,fHr,Y8t,dHr,nql,mHr,iql,JK,yct,DT,X8t,vct,RT,Q2,kT,m8o,hHr,gR,IC,h8o,g8o,oql,A8o,gre,y8o,gHr,Z8t,aUe,a3,$8t,g5m,A5m,y5m,b5m,jql,E5m,I5m,v5m,EUe,C5m,OSe,eJ,eGt,ig,b8o,Lme,E8o,L8o,_8o,pGt,AHr,wct,Oct,I8o,Cct,PSe,$K,vSe,Are,xct,v8o,Mme,tGt,C8o,THr,cUe,OHr,AUe,lGo,x5m,VHr,zql,S5m,w5m,T5m,O5m,P5m,B5m,D5m,pGo,IGt,R5m,Ere,k5m,aql,F5m,x8o,yUe,yHr,S8o,fGo,Lql,N5m,j5m,_ql,z5m,Q5m,Uql,M5m,L5m,_5m,U5m,V5m,G5m,q5m,W5m,Vql,Gql,H5m,PHr,K5m,qql,qHr,dGo,bUe,J5m,lUe,w8o,Y5m,CSe,X5m,Z5m,$5m,xSe,e8m,t8m,r8m,T8o,n8m,uUe,MHr,i8m,o8m,s8m,a8m,lf,c8m,WHr,l8m,U8o,V8o,u8m,p8,pUe,zme,O8o,cql,yre,rGt,ySe,lql,Jb,Qme,bSe,P8o,fUe,Wx,bHr,EHr,B8o,uql,pql,nGt,D8o,IHr,bct,ESe,vHr,dUe,CHr,xHr,fql,p8m,yGt,fGt,f8m,Kql,d8m,m8m,HHr,Jql,h8m,dql,mGo,KHr,hGo,g8m,A8m,mql,y8m,Xql,b8m,hql,gql,Aql,q8o,yql,iGt,BHr,W8o,DHr,H8o,K8o,J8o,Y8o,SSe,LHr,X8o,R8o,bre,Zql,E8m,I8m,v8m,C8m,gGo,bql,Eql,RHr,oGt,YK,sGt,ISe,mUe,aGt,SHr,XK,k8o,kHr,Iql,$8o,eGo,FHr,NHr,vql,F8o,jHr,$ql,N8o,JHr,AGo,T8m,O8m,eWl,tWl,P8m,B8m,YHr,D8m,nWl,iWl,Cql,oWl,sWl,aWl,R8m,k8m,F8m,xql,cWl,tGo,_Hr,N8m,lWl,j8m,uWl,fWl,XHr,z8m,Q8m,rGo,dWl,M8m,L8m,j8o,Sql,Ect,_8m,U8m,V8m,G8m,q8m,W8m,wql,nGo,Tql,iGo,f8,oGo,sGo,zHr,Oql,Pql,uGt,Bql,Dql,z8o,TSe,FT,wHr,Rql,Ict,Q8o,M8o,aGo,dGt,mGt,hGt,gGt,H8m,AGt,K8m,J8m,Y8m,kql,vGo,cGt,mWl,X8m,Z8m,hWl,$8m,eGm,tGm,rGm,nGm,lGt,czv,iGm,ZHr=h(()=>{"use strict";Fql=Ae(require("events"),1),M2=Ae(require("fs"),1),UHr=require("events"),cGo=Ae(require("stream"),1),Nql=require("string_decoder"),uGo=Ae(require("path"),1),gUe=Ae(require("fs"),1),GHr=require("path"),Qql=require("events"),QHr=Ae(require("assert"),1),wSe=require("buffer"),sql=Ae(require("zlib"),1),Mql=Ae(require("zlib"),1),hUe=require("path"),Wql=require("path"),bGt=Ae(require("fs"),1),ZK=Ae(require("fs"),1),G8o=Ae(require("path"),1),Yql=require("path"),Z8o=Ae(require("path"),1),yGo=Ae(require("fs"),1),rWl=Ae(require("assert"),1),bGo=require("crypto"),Ed=Ae(require("fs"),1),Hx=Ae(require("path"),1),EGo=Ae(require("fs"),1),vGt=Ae(require("fs"),1),Tct=Ae(require("path"),1),VQ=Ae(require("fs"),1),pWl=Ae(require("fs/promises"),1),EGt=Ae(require("path"),1),IGo=require("path"),UQ=Ae(require("fs"),1),CGo=Ae(require("path"),1),p5m=Object.defineProperty,f5m=(e,t)=>{for(var r in t)p5m(e,r,{get:t[r],enumerable:!0})},rql=typeof process=="object"&&process?process:{stdout:null,stderr:null},d5m=e=>!!e&&typeof e=="object"&&(e instanceof EUe||e instanceof cGo.default||m5m(e)||h5m(e)),m5m=e=>!!e&&typeof e=="object"&&e instanceof UHr.EventEmitter&&typeof e.pipe=="function"&&e.pipe!==cGo.default.Writable.prototype.pipe,h5m=e=>!!e&&typeof e=="object"&&e instanceof UHr.EventEmitter&&typeof e.write=="function"&&typeof e.end=="function",Nme=Symbol("EOF"),jme=Symbol("maybeEmitEnd"),ASe=Symbol("emittedEnd"),fHr=Symbol("emittingEnd"),Y8t=Symbol("emittedError"),dHr=Symbol("closed"),nql=Symbol("read"),mHr=Symbol("flush"),iql=Symbol("flushChunk"),JK=Symbol("encoding"),yct=Symbol("decoder"),DT=Symbol("flowing"),X8t=Symbol("paused"),vct=Symbol("resume"),RT=Symbol("buffer"),Q2=Symbol("pipes"),kT=Symbol("bufferLength"),m8o=Symbol("bufferPush"),hHr=Symbol("bufferShift"),gR=Symbol("objectMode"),IC=Symbol("destroyed"),h8o=Symbol("error"),g8o=Symbol("emitData"),oql=Symbol("emitEnd"),A8o=Symbol("emitEnd2"),gre=Symbol("async"),y8o=Symbol("abort"),gHr=Symbol("aborted"),Z8t=Symbol("signal"),aUe=Symbol("dataListeners"),a3=Symbol("discarded"),$8t=e=>Promise.resolve().then(e),g5m=e=>e(),A5m=e=>e==="end"||e==="finish"||e==="prefinish",y5m=e=>e instanceof ArrayBuffer||!!e&&typeof e=="object"&&e.constructor&&e.constructor.name==="ArrayBuffer"&&e.byteLength>=0,b5m=e=>!Buffer.isBuffer(e)&&ArrayBuffer.isView(e),jql=class{src;dest;opts;ondrain;constructor(e,t,r){this.src=e,this.dest=t,this.opts=r,this.ondrain=()=>e[vct](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},E5m=class extends jql{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(e,t,r){super(e,t,r),this.proxyErrors=n=>this.dest.emit("error",n),e.on("error",this.proxyErrors)}},I5m=e=>!!e.objectMode,v5m=e=>!e.objectMode&&!!e.encoding&&e.encoding!=="buffer",EUe=class extends UHr.EventEmitter{[DT]=!1;[X8t]=!1;[Q2]=[];[RT]=[];[gR];[JK];[gre];[yct];[Nme]=!1;[ASe]=!1;[fHr]=!1;[dHr]=!1;[Y8t]=null;[kT]=0;[IC]=!1;[Z8t];[gHr]=!1;[aUe]=0;[a3]=!1;writable=!0;readable=!0;constructor(...e){let t=e[0]||{};if(super(),t.objectMode&&typeof t.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");I5m(t)?(this[gR]=!0,this[JK]=null):v5m(t)?(this[JK]=t.encoding,this[gR]=!1):(this[gR]=!1,this[JK]=null),this[gre]=!!t.async,this[yct]=this[JK]?new Nql.StringDecoder(this[JK]):null,t&&t.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[RT]}),t&&t.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Q2]});let{signal:r}=t;r&&(this[Z8t]=r,r.aborted?this[y8o]():r.addEventListener("abort",()=>this[y8o]()))}get bufferLength(){return this[kT]}get encoding(){return this[JK]}set encoding(e){throw new Error("Encoding must be set at instantiation time")}setEncoding(e){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[gR]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[gre]}set async(e){this[gre]=this[gre]||!!e}[y8o](){this[gHr]=!0,this.emit("abort",this[Z8t]?.reason),this.destroy(this[Z8t]?.reason)}get aborted(){return this[gHr]}set aborted(e){}write(e,t,r){if(this[gHr])return!1;if(this[Nme])throw new Error("write after end");if(this[IC])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof t=="function"&&(r=t,t="utf8"),t||(t="utf8");let n=this[gre]?$8t:g5m;if(!this[gR]&&!Buffer.isBuffer(e)){if(b5m(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(y5m(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[gR]?(this[DT]&&this[kT]!==0&&this[mHr](!0),this[DT]?this.emit("data",e):this[m8o](e),this[kT]!==0&&this.emit("readable"),r&&n(r),this[DT]):e.length?(typeof e=="string"&&!(t===this[JK]&&!this[yct]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[JK]&&(e=this[yct].write(e)),this[DT]&&this[kT]!==0&&this[mHr](!0),this[DT]?this.emit("data",e):this[m8o](e),this[kT]!==0&&this.emit("readable"),r&&n(r),this[DT]):(this[kT]!==0&&this.emit("readable"),r&&n(r),this[DT])}read(e){if(this[IC])return null;if(this[a3]=!1,this[kT]===0||e===0||e&&e>this[kT])return this[jme](),null;this[gR]&&(e=null),this[RT].length>1&&!this[gR]&&(this[RT]=[this[JK]?this[RT].join(""):Buffer.concat(this[RT],this[kT])]);let t=this[nql](e||null,this[RT][0]);return this[jme](),t}[nql](e,t){if(this[gR])this[hHr]();else{let r=t;e===r.length||e===null?this[hHr]():typeof r=="string"?(this[RT][0]=r.slice(e),t=r.slice(0,e),this[kT]-=e):(this[RT][0]=r.subarray(e),t=r.subarray(0,e),this[kT]-=e)}return this.emit("data",t),!this[RT].length&&!this[Nme]&&this.emit("drain"),t}end(e,t,r){return typeof e=="function"&&(r=e,e=void 0),typeof t=="function"&&(r=t,t="utf8"),e!==void 0&&this.write(e,t),r&&this.once("end",r),this[Nme]=!0,this.writable=!1,(this[DT]||!this[X8t])&&this[jme](),this}[vct](){this[IC]||(!this[aUe]&&!this[Q2].length&&(this[a3]=!0),this[X8t]=!1,this[DT]=!0,this.emit("resume"),this[RT].length?this[mHr]():this[Nme]?this[jme]():this.emit("drain"))}resume(){return this[vct]()}pause(){this[DT]=!1,this[X8t]=!0,this[a3]=!1}get destroyed(){return this[IC]}get flowing(){return this[DT]}get paused(){return this[X8t]}[m8o](e){this[gR]?this[kT]+=1:this[kT]+=e.length,this[RT].push(e)}[hHr](){return this[gR]?this[kT]-=1:this[kT]-=this[RT][0].length,this[RT].shift()}[mHr](e=!1){do;while(this[iql](this[hHr]())&&this[RT].length);!e&&!this[RT].length&&!this[Nme]&&this.emit("drain")}[iql](e){return this.emit("data",e),this[DT]}pipe(e,t){if(this[IC])return e;this[a3]=!1;let r=this[ASe];return t=t||{},e===rql.stdout||e===rql.stderr?t.end=!1:t.end=t.end!==!1,t.proxyErrors=!!t.proxyErrors,r?t.end&&e.end():(this[Q2].push(t.proxyErrors?new E5m(this,e,t):new jql(this,e,t)),this[gre]?$8t(()=>this[vct]()):this[vct]()),e}unpipe(e){let t=this[Q2].find(r=>r.dest===e);t&&(this[Q2].length===1?(this[DT]&&this[aUe]===0&&(this[DT]=!1),this[Q2]=[]):this[Q2].splice(this[Q2].indexOf(t),1),t.unpipe())}addListener(e,t){return this.on(e,t)}on(e,t){let r=super.on(e,t);if(e==="data")this[a3]=!1,this[aUe]++,!this[Q2].length&&!this[DT]&&this[vct]();else if(e==="readable"&&this[kT]!==0)super.emit("readable");else if(A5m(e)&&this[ASe])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[Y8t]){let n=t;this[gre]?$8t(()=>n.call(this,this[Y8t])):n.call(this,this[Y8t])}return r}removeListener(e,t){return this.off(e,t)}off(e,t){let r=super.off(e,t);return e==="data"&&(this[aUe]=this.listeners("data").length,this[aUe]===0&&!this[a3]&&!this[Q2].length&&(this[DT]=!1)),r}removeAllListeners(e){let t=super.removeAllListeners(e);return(e==="data"||e===void 0)&&(this[aUe]=0,!this[a3]&&!this[Q2].length&&(this[DT]=!1)),t}get emittedEnd(){return this[ASe]}[jme](){!this[fHr]&&!this[ASe]&&!this[IC]&&this[RT].length===0&&this[Nme]&&(this[fHr]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[dHr]&&this.emit("close"),this[fHr]=!1)}emit(e,...t){let r=t[0];if(e!=="error"&&e!=="close"&&e!==IC&&this[IC])return!1;if(e==="data")return!this[gR]&&!r?!1:this[gre]?($8t(()=>this[g8o](r)),!0):this[g8o](r);if(e==="end")return this[oql]();if(e==="close"){if(this[dHr]=!0,!this[ASe]&&!this[IC])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(e==="error"){this[Y8t]=r,super.emit(h8o,r);let i=!this[Z8t]||this.listeners("error").length?super.emit("error",r):!1;return this[jme](),i}else if(e==="resume"){let i=super.emit("resume");return this[jme](),i}else if(e==="finish"||e==="prefinish"){let i=super.emit(e);return this.removeAllListeners(e),i}let n=super.emit(e,...t);return this[jme](),n}[g8o](e){for(let r of this[Q2])r.dest.write(e)===!1&&this.pause();let t=this[a3]?!1:super.emit("data",e);return this[jme](),t}[oql](){return this[ASe]?!1:(this[ASe]=!0,this.readable=!1,this[gre]?($8t(()=>this[A8o]()),!0):this[A8o]())}[A8o](){if(this[yct]){let t=this[yct].end();if(t){for(let r of this[Q2])r.dest.write(t);this[a3]||super.emit("data",t)}}for(let t of this[Q2])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[gR]||(e.dataLength=0);let t=this.promise();return this.on("data",r=>{e.push(r),this[gR]||(e.dataLength+=r.length)}),await t,e}async concat(){if(this[gR])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[JK]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(IC,()=>t(new Error("stream destroyed"))),this.on("error",r=>t(r)),this.on("end",()=>e())})}[Symbol.asyncIterator](){this[a3]=!1;let e=!1,t=async()=>(this.pause(),e=!0,{value:void 0,done:!0});return{next:()=>{if(e)return t();let r=this.read();if(r!==null)return Promise.resolve({done:!1,value:r});if(this[Nme])return t();let n,i,o=l=>{this.off("data",s),this.off("end",a),this.off(IC,c),t(),i(l)},s=l=>{this.off("error",o),this.off("end",a),this.off(IC,c),this.pause(),n({value:l,done:!!this[Nme]})},a=()=>{this.off("error",o),this.off("data",s),this.off(IC,c),t(),n({done:!0,value:void 0})},c=()=>o(new Error("stream destroyed"));return new Promise((l,u)=>{i=u,n=l,this.once(IC,c),this.once("error",o),this.once("end",a),this.once("data",s)})},throw:t,return:t,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[a3]=!1;let e=!1,t=()=>(this.pause(),this.off(h8o,t),this.off(IC,t),this.off("end",t),e=!0,{done:!0,value:void 0}),r=()=>{if(e)return t();let n=this.read();return n===null?t():{done:!1,value:n}};return this.once("end",t),this.once(h8o,t),this.once(IC,t),{next:r,throw:t,return:t,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(e){if(this[IC])return e?this.emit("error",e):this.emit(IC),this;this[IC]=!0,this[a3]=!0,this[RT].length=0,this[kT]=0;let t=this;return typeof t.close=="function"&&!this[dHr]&&t.close(),e?this.emit("error",e):this.emit(IC),this}static get isStream(){return d5m}},C5m=M2.default.writev,OSe=Symbol("_autoClose"),eJ=Symbol("_close"),eGt=Symbol("_ended"),ig=Symbol("_fd"),b8o=Symbol("_finished"),Lme=Symbol("_flags"),E8o=Symbol("_flush"),L8o=Symbol("_handleChunk"),_8o=Symbol("_makeBuf"),pGt=Symbol("_mode"),AHr=Symbol("_needDrain"),wct=Symbol("_onerror"),Oct=Symbol("_onopen"),I8o=Symbol("_onread"),Cct=Symbol("_onwrite"),PSe=Symbol("_open"),$K=Symbol("_path"),vSe=Symbol("_pos"),Are=Symbol("_queue"),xct=Symbol("_read"),v8o=Symbol("_readSize"),Mme=Symbol("_reading"),tGt=Symbol("_remain"),C8o=Symbol("_size"),THr=Symbol("_write"),cUe=Symbol("_writing"),OHr=Symbol("_defaultFlag"),AUe=Symbol("_errored"),lGo=class extends EUe{[AUe]=!1;[ig];[$K];[v8o];[Mme]=!1;[C8o];[tGt];[OSe];constructor(e,t){if(t=t||{},super(t),this.readable=!0,this.writable=!1,typeof e!="string")throw new TypeError("path must be a string");this[AUe]=!1,this[ig]=typeof t.fd=="number"?t.fd:void 0,this[$K]=e,this[v8o]=t.readSize||16*1024*1024,this[Mme]=!1,this[C8o]=typeof t.size=="number"?t.size:1/0,this[tGt]=this[C8o],this[OSe]=typeof t.autoClose=="boolean"?t.autoClose:!0,typeof this[ig]=="number"?this[xct]():this[PSe]()}get fd(){return this[ig]}get path(){return this[$K]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[PSe](){M2.default.open(this[$K],"r",(e,t)=>this[Oct](e,t))}[Oct](e,t){e?this[wct](e):(this[ig]=t,this.emit("open",t),this[xct]())}[_8o](){return Buffer.allocUnsafe(Math.min(this[v8o],this[tGt]))}[xct](){if(!this[Mme]){this[Mme]=!0;let e=this[_8o]();if(e.length===0)return process.nextTick(()=>this[I8o](null,0,e));M2.default.read(this[ig],e,0,e.length,null,(t,r,n)=>this[I8o](t,r,n))}}[I8o](e,t,r){this[Mme]=!1,e?this[wct](e):this[L8o](t,r)&&this[xct]()}[eJ](){if(this[OSe]&&typeof this[ig]=="number"){let e=this[ig];this[ig]=void 0,M2.default.close(e,t=>t?this.emit("error",t):this.emit("close"))}}[wct](e){this[Mme]=!0,this[eJ](),this.emit("error",e)}[L8o](e,t){let r=!1;return this[tGt]-=e,e>0&&(r=super.write(e<t.length?t.subarray(0,e):t)),(e===0||this[tGt]<=0)&&(r=!1,this[eJ](),super.end()),r}emit(e,...t){switch(e){case"prefinish":case"finish":return!1;case"drain":return typeof this[ig]=="number"&&this[xct](),!1;case"error":return this[AUe]?!1:(this[AUe]=!0,super.emit(e,...t));default:return super.emit(e,...t)}}},x5m=class extends lGo{[PSe](){let e=!0;try{this[Oct](null,M2.default.openSync(this[$K],"r")),e=!1}finally{e&&this[eJ]()}}[xct](){let e=!0;try{if(!this[Mme]){this[Mme]=!0;do{let t=this[_8o](),r=t.length===0?0:M2.default.readSync(this[ig],t,0,t.length,null);if(!this[L8o](r,t))break}while(!0);this[Mme]=!1}e=!1}finally{e&&this[eJ]()}}[eJ](){if(this[OSe]&&typeof this[ig]=="number"){let e=this[ig];this[ig]=void 0,M2.default.closeSync(e),this.emit("close")}}},VHr=class extends Fql.default{readable=!1;writable=!0;[AUe]=!1;[cUe]=!1;[eGt]=!1;[Are]=[];[AHr]=!1;[$K];[pGt];[OSe];[ig];[OHr];[Lme];[b8o]=!1;[vSe];constructor(e,t){t=t||{},super(t),this[$K]=e,this[ig]=typeof t.fd=="number"?t.fd:void 0,this[pGt]=t.mode===void 0?438:t.mode,this[vSe]=typeof t.start=="number"?t.start:void 0,this[OSe]=typeof t.autoClose=="boolean"?t.autoClose:!0;let r=this[vSe]!==void 0?"r+":"w";this[OHr]=t.flags===void 0,this[Lme]=t.flags===void 0?r:t.flags,this[ig]===void 0&&this[PSe]()}emit(e,...t){if(e==="error"){if(this[AUe])return!1;this[AUe]=!0}return super.emit(e,...t)}get fd(){return this[ig]}get path(){return this[$K]}[wct](e){this[eJ](),this[cUe]=!0,this.emit("error",e)}[PSe](){M2.default.open(this[$K],this[Lme],this[pGt],(e,t)=>this[Oct](e,t))}[Oct](e,t){this[OHr]&&this[Lme]==="r+"&&e&&e.code==="ENOENT"?(this[Lme]="w",this[PSe]()):e?this[wct](e):(this[ig]=t,this.emit("open",t),this[cUe]||this[E8o]())}end(e,t){return e&&this.write(e,t),this[eGt]=!0,!this[cUe]&&!this[Are].length&&typeof this[ig]=="number"&&this[Cct](null,0),this}write(e,t){return typeof e=="string"&&(e=Buffer.from(e,t)),this[eGt]?(this.emit("error",new Error("write() after end()")),!1):this[ig]===void 0||this[cUe]||this[Are].length?(this[Are].push(e),this[AHr]=!0,!1):(this[cUe]=!0,this[THr](e),!0)}[THr](e){M2.default.write(this[ig],e,0,e.length,this[vSe],(t,r)=>this[Cct](t,r))}[Cct](e,t){e?this[wct](e):(this[vSe]!==void 0&&typeof t=="number"&&(this[vSe]+=t),this[Are].length?this[E8o]():(this[cUe]=!1,this[eGt]&&!this[b8o]?(this[b8o]=!0,this[eJ](),this.emit("finish")):this[AHr]&&(this[AHr]=!1,this.emit("drain"))))}[E8o](){if(this[Are].length===0)this[eGt]&&this[Cct](null,0);else if(this[Are].length===1)this[THr](this[Are].pop());else{let e=this[Are];this[Are]=[],C5m(this[ig],e,this[vSe],(t,r)=>this[Cct](t,r))}}[eJ](){if(this[OSe]&&typeof this[ig]=="number"){let e=this[ig];this[ig]=void 0,M2.default.close(e,t=>t?this.emit("error",t):this.emit("close"))}}},zql=class extends VHr{[PSe](){let e;if(this[OHr]&&this[Lme]==="r+")try{e=M2.default.openSync(this[$K],this[Lme],this[pGt])}catch(t){if(t?.code==="ENOENT")return this[Lme]="w",this[PSe]();throw t}else e=M2.default.openSync(this[$K],this[Lme],this[pGt]);this[Oct](null,e)}[eJ](){if(this[OSe]&&typeof this[ig]=="number"){let e=this[ig];this[ig]=void 0,M2.default.closeSync(e),this.emit("close")}}[THr](e){let t=!0;try{this[Cct](null,M2.default.writeSync(this[ig],e,0,e.length,this[vSe])),t=!1}finally{if(t)try{this[eJ]()}catch{}}}},S5m=new Map([["C","cwd"],["f","file"],["z","gzip"],["P","preservePaths"],["U","unlink"],["strip-components","strip"],["stripComponents","strip"],["keep-newer","newer"],["keepNewer","newer"],["keep-newer-files","newer"],["keepNewerFiles","newer"],["k","keep"],["keep-existing","keep"],["keepExisting","keep"],["m","noMtime"],["no-mtime","noMtime"],["p","preserveOwner"],["L","follow"],["h","follow"],["onentry","onReadEntry"]]),w5m=e=>!!e.sync&&!!e.file,T5m=e=>!e.sync&&!!e.file,O5m=e=>!!e.sync&&!e.file,P5m=e=>!e.sync&&!e.file,B5m=e=>!!e.file,D5m=e=>S5m.get(e)||e,pGo=(e={})=>{if(!e)return{};let t={};for(let[r,n]of Object.entries(e)){let i=D5m(r);t[i]=n}return t.chmod===void 0&&t.noChmod===!1&&(t.chmod=!0),delete t.noChmod,t},IGt=(e,t,r,n,i)=>Object.assign((o=[],s,a)=>{Array.isArray(o)&&(s=o,o={}),typeof s=="function"&&(a=s,s=void 0),s=s?Array.from(s):[];let c=pGo(o);if(i?.(c,s),w5m(c)){if(typeof a=="function")throw new TypeError("callback not supported for sync tar functions");return e(c,s)}else if(T5m(c)){let l=t(c,s);return a?l.then(()=>a(),a):l}else if(O5m(c)){if(typeof a=="function")throw new TypeError("callback not supported for sync tar functions");return r(c,s)}else if(P5m(c)){if(typeof a=="function")throw new TypeError("callback only supported with file option");return n(c,s)}throw new Error("impossible options??")},{syncFile:e,asyncFile:t,syncNoFile:r,asyncNoFile:n,validate:i}),R5m=Mql.default.constants||{ZLIB_VERNUM:4736},Ere=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},R5m)),k5m=wSe.Buffer.concat,aql=Object.getOwnPropertyDescriptor(wSe.Buffer,"concat"),F5m=e=>e,x8o=aql?.writable===!0||aql?.set!==void 0?e=>{wSe.Buffer.concat=e?F5m:k5m}:e=>{},yUe=Symbol("_superWrite"),yHr=class extends Error{code;errno;constructor(e,t){super("zlib: "+e.message,{cause:e}),this.code=e.code,this.errno=e.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+e.message,Error.captureStackTrace(this,t??this.constructor)}get name(){return"ZlibError"}},S8o=Symbol("flushFlag"),fGo=class extends EUe{#e=!1;#t=!1;#r;#n;#i;#o;#s;get sawError(){return this.#e}get handle(){return this.#o}get flushFlag(){return this.#r}constructor(e,t){if(!e||typeof e!="object")throw new TypeError("invalid options for ZlibBase constructor");if(super(e),this.#r=e.flush??0,this.#n=e.finishFlush??0,this.#i=e.fullFlushFlag??0,typeof sql[t]!="function")throw new TypeError("Compression method not supported: "+t);try{this.#o=new sql[t](e)}catch(r){throw new yHr(r,this.constructor)}this.#s=r=>{this.#e||(this.#e=!0,this.close(),this.emit("error",r))},this.#o?.on("error",r=>this.#s(new yHr(r))),this.once("end",()=>this.close)}close(){this.#o&&(this.#o.close(),this.#o=void 0,this.emit("close"))}reset(){if(!this.#e)return(0,QHr.default)(this.#o,"zlib binding closed"),this.#o.reset?.()}flush(e){this.ended||(typeof e!="number"&&(e=this.#i),this.write(Object.assign(wSe.Buffer.alloc(0),{[S8o]:e})))}end(e,t,r){return typeof e=="function"&&(r=e,t=void 0,e=void 0),typeof t=="function"&&(r=t,t=void 0),e&&(t?this.write(e,t):this.write(e)),this.flush(this.#n),this.#t=!0,super.end(r)}get ended(){return this.#t}[yUe](e){return super.write(e)}write(e,t,r){if(typeof t=="function"&&(r=t,t="utf8"),typeof e=="string"&&(e=wSe.Buffer.from(e,t)),this.#e)return;(0,QHr.default)(this.#o,"zlib binding closed");let n=this.#o._handle,i=n.close;n.close=()=>{};let o=this.#o.close;this.#o.close=()=>{},x8o(!0);let s;try{let c=typeof e[S8o]=="number"?e[S8o]:this.#r;s=this.#o._processChunk(e,c),x8o(!1)}catch(c){x8o(!1),this.#s(new yHr(c,this.write))}finally{this.#o&&(this.#o._handle=n,n.close=i,this.#o.close=o,this.#o.removeAllListeners("error"))}this.#o&&this.#o.on("error",c=>this.#s(new yHr(c,this.write)));let a;if(s)if(Array.isArray(s)&&s.length>0){let c=s[0];a=this[yUe](wSe.Buffer.from(c));for(let l=1;l<s.length;l++)a=this[yUe](s[l])}else a=this[yUe](wSe.Buffer.from(s));return r&&r(),a}},Lql=class extends fGo{#e;#t;constructor(e,t){e=e||{},e.flush=e.flush||Ere.Z_NO_FLUSH,e.finishFlush=e.finishFlush||Ere.Z_FINISH,e.fullFlushFlag=Ere.Z_FULL_FLUSH,super(e,t),this.#e=e.level,this.#t=e.strategy}params(e,t){if(!this.sawError){if(!this.handle)throw new Error("cannot switch params when binding is closed");if(!this.handle.params)throw new Error("not supported in this implementation");if(this.#e!==e||this.#t!==t){this.flush(Ere.Z_SYNC_FLUSH),(0,QHr.default)(this.handle,"zlib binding closed");let r=this.handle.flush;this.handle.flush=(n,i)=>{typeof n=="function"&&(i=n,n=this.flushFlag),this.flush(n),i?.()};try{this.handle.params(e,t)}finally{this.handle.flush=r}this.handle&&(this.#e=e,this.#t=t)}}}},N5m=class extends Lql{#e;constructor(e){super(e,"Gzip"),this.#e=e&&!!e.portable}[yUe](e){return this.#e?(this.#e=!1,e[9]=255,super[yUe](e)):super[yUe](e)}},j5m=class extends Lql{constructor(e){super(e,"Unzip")}},_ql=class extends fGo{constructor(e,t){e=e||{},e.flush=e.flush||Ere.BROTLI_OPERATION_PROCESS,e.finishFlush=e.finishFlush||Ere.BROTLI_OPERATION_FINISH,e.fullFlushFlag=Ere.BROTLI_OPERATION_FLUSH,super(e,t)}},z5m=class extends _ql{constructor(e){super(e,"BrotliCompress")}},Q5m=class extends _ql{constructor(e){super(e,"BrotliDecompress")}},Uql=class extends fGo{constructor(e,t){e=e||{},e.flush=e.flush||Ere.ZSTD_e_continue,e.finishFlush=e.finishFlush||Ere.ZSTD_e_end,e.fullFlushFlag=Ere.ZSTD_e_flush,super(e,t)}},M5m=class extends Uql{constructor(e){super(e,"ZstdCompress")}},L5m=class extends Uql{constructor(e){super(e,"ZstdDecompress")}},_5m=(e,t)=>{if(Number.isSafeInteger(e))e<0?V5m(e,t):U5m(e,t);else throw Error("cannot encode number outside of javascript safe integer range");return t},U5m=(e,t)=>{t[0]=128;for(var r=t.length;r>1;r--)t[r-1]=e&255,e=Math.floor(e/256)},V5m=(e,t)=>{t[0]=255;var r=!1;e=e*-1;for(var n=t.length;n>1;n--){var i=e&255;e=Math.floor(e/256),r?t[n-1]=Vql(i):i===0?t[n-1]=0:(r=!0,t[n-1]=Gql(i))}},G5m=e=>{let t=e[0],r=t===128?W5m(e.subarray(1,e.length)):t===255?q5m(e):null;if(r===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(r))throw Error("parsed number outside of javascript safe integer range");return r},q5m=e=>{for(var t=e.length,r=0,n=!1,i=t-1;i>-1;i--){var o=Number(e[i]),s;n?s=Vql(o):o===0?s=o:(n=!0,s=Gql(o)),s!==0&&(r-=s*Math.pow(256,t-i-1))}return r},W5m=e=>{for(var t=e.length,r=0,n=t-1;n>-1;n--){var i=Number(e[n]);i!==0&&(r+=i*Math.pow(256,t-n-1))}return r},Vql=e=>(255^e)&255,Gql=e=>(255^e)+1&255,H5m={};f5m(H5m,{code:()=>dGo,isCode:()=>PHr,isName:()=>K5m,name:()=>qHr,normalFsTypes:()=>qql});PHr=e=>qHr.has(e),K5m=e=>dGo.has(e),qql=new Set(["0","","1","2","3","4","5","6","7","D"]),qHr=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]),dGo=new Map(Array.from(qHr).map(e=>[e[1],e[0]])),bUe=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#e="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(e,t=0,r,n){Buffer.isBuffer(e)?this.decode(e,t||0,r,n):e&&this.#t(e)}decode(e,t,r,n){if(t||(t=0),!e||!(e.length>=t+512))throw new Error("need 512 bytes for header");let i=lUe(e,t+156,1),o=qql.has(i),s=o?r:void 0,a=o?n:void 0;if(this.path=s?.path??lUe(e,t,100),this.mode=s?.mode??a?.mode??CSe(e,t+100,8),this.uid=s?.uid??a?.uid??CSe(e,t+108,8),this.gid=s?.gid??a?.gid??CSe(e,t+116,8),this.size=s?.size??a?.size??CSe(e,t+124,12),this.mtime=s?.mtime??a?.mtime??w8o(e,t+136,12),this.cksum=CSe(e,t+148,12),a&&this.#t(a,!0),s&&this.#t(s),PHr(i)&&(this.#e=i||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=lUe(e,t+157,100),e.subarray(t+257,t+265).toString()==="ustar\x0000")if(this.uname=s?.uname??a?.uname??lUe(e,t+265,32),this.gname=s?.gname??a?.gname??lUe(e,t+297,32),this.devmaj=s?.devmaj??a?.devmaj??CSe(e,t+329,8)??0,this.devmin=s?.devmin??a?.devmin??CSe(e,t+337,8)??0,e[t+475]!==0){let l=lUe(e,t+345,155);this.path=l+"/"+this.path}else{let l=lUe(e,t+345,130);l&&(this.path=l+"/"+this.path),this.atime=r?.atime??n?.atime??w8o(e,t+476,12),this.ctime=r?.ctime??n?.ctime??w8o(e,t+488,12)}let c=256;for(let l=t;l<t+148;l++)c+=e[l];for(let l=t+156;l<t+512;l++)c+=e[l];this.cksumValid=c===this.cksum,this.cksum===void 0&&c===256&&(this.nullBlock=!0)}#t(e,t=!1){Object.assign(this,Object.fromEntries(Object.entries(e).filter(([r,n])=>!(n==null||r==="path"&&t||r==="linkpath"&&t||r==="global"))))}encode(e,t=0){if(e||(e=this.block=Buffer.alloc(512)),this.#e==="Unsupported"&&(this.#e="0"),!(e.length>=t+512))throw new Error("need 512 bytes for header");let r=this.ctime||this.atime?130:155,n=J5m(this.path||"",r),i=n[0],o=n[1];this.needPax=!!n[2],this.needPax=uUe(e,t,100,i)||this.needPax,this.needPax=xSe(e,t+100,8,this.mode)||this.needPax,this.needPax=xSe(e,t+108,8,this.uid)||this.needPax,this.needPax=xSe(e,t+116,8,this.gid)||this.needPax,this.needPax=xSe(e,t+124,12,this.size)||this.needPax,this.needPax=T8o(e,t+136,12,this.mtime)||this.needPax,e[t+156]=Number(this.#e.codePointAt(0)),this.needPax=uUe(e,t+157,100,this.linkpath)||this.needPax,e.write("ustar\x0000",t+257,8),this.needPax=uUe(e,t+265,32,this.uname)||this.needPax,this.needPax=uUe(e,t+297,32,this.gname)||this.needPax,this.needPax=xSe(e,t+329,8,this.devmaj)||this.needPax,this.needPax=xSe(e,t+337,8,this.devmin)||this.needPax,this.needPax=uUe(e,t+345,r,o)||this.needPax,e[t+475]!==0?this.needPax=uUe(e,t+345,155,o)||this.needPax:(this.needPax=uUe(e,t+345,130,o)||this.needPax,this.needPax=T8o(e,t+476,12,this.atime)||this.needPax,this.needPax=T8o(e,t+488,12,this.ctime)||this.needPax);let s=256;for(let a=t;a<t+148;a++)s+=e[a];for(let a=t+156;a<t+512;a++)s+=e[a];return this.cksum=s,xSe(e,t+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:qHr.get(this.#e)}get typeKey(){return this.#e}set type(e){let t=String(dGo.get(e));if(PHr(t)||t==="Unsupported")this.#e=t;else if(PHr(e))this.#e=e;else throw new TypeError("invalid entry type: "+e)}},J5m=(e,t)=>{let r=e,n="",i,o=hUe.posix.parse(e).root||".";if(Buffer.byteLength(r)<100)i=[r,n,!1];else{n=hUe.posix.dirname(r),r=hUe.posix.basename(r);do Buffer.byteLength(r)<=100&&Buffer.byteLength(n)<=t?i=[r,n,!1]:Buffer.byteLength(r)>100&&Buffer.byteLength(n)<=t?i=[r.slice(0,99),n,!0]:(r=hUe.posix.join(hUe.posix.basename(n),r),n=hUe.posix.dirname(n));while(n!==o&&i===void 0);i||(i=[e.slice(0,99),"",!0])}return i},lUe=(e,t,r)=>e.subarray(t,t+r).toString("utf8").replace(/\0.*/,""),w8o=(e,t,r)=>Y5m(CSe(e,t,r)),Y5m=e=>e===void 0?void 0:new Date(e*1e3),CSe=(e,t,r)=>Number(e[t])&128?G5m(e.subarray(t,t+r)):Z5m(e,t,r),X5m=e=>isNaN(e)?void 0:e,Z5m=(e,t,r)=>X5m(parseInt(e.subarray(t,t+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),$5m={12:8589934591,8:2097151},xSe=(e,t,r,n)=>n===void 0?!1:n>$5m[r]||n<0?(_5m(n,e.subarray(t,t+r)),!0):(e8m(e,t,r,n),!1),e8m=(e,t,r,n)=>e.write(t8m(n,r),t,r,"ascii"),t8m=(e,t)=>r8m(Math.floor(e).toString(8),t),r8m=(e,t)=>(e.length===t-1?e:new Array(t-e.length-1).join("0")+e+" ")+"\0",T8o=(e,t,r,n)=>n===void 0?!1:xSe(e,t,r,n.getTime()/1e3),n8m=new Array(156).join("\0"),uUe=(e,t,r,n)=>n===void 0?!1:(e.write(n+n8m,t,r,"utf8"),n.length!==Buffer.byteLength(n)||n.length>r),MHr=class Hql{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(t,r=!1){this.atime=t.atime,this.charset=t.charset,this.comment=t.comment,this.ctime=t.ctime,this.dev=t.dev,this.gid=t.gid,this.global=r,this.gname=t.gname,this.ino=t.ino,this.linkpath=t.linkpath,this.mtime=t.mtime,this.nlink=t.nlink,this.path=t.path,this.size=t.size,this.uid=t.uid,this.uname=t.uname}encode(){let t=this.encodeBody();if(t==="")return Buffer.allocUnsafe(0);let r=Buffer.byteLength(t),n=512*Math.ceil(1+r/512),i=Buffer.allocUnsafe(n);for(let o=0;o<512;o++)i[o]=0;new bUe({path:("PaxHeader/"+(0,Wql.basename)(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:r,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(i),i.write(t,512,r,"utf8");for(let o=r+512;o<i.length;o++)i[o]=0;return i}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(t){if(this[t]===void 0)return"";let r=this[t],n=r instanceof Date?r.getTime()/1e3:r,i=" "+(t==="dev"||t==="ino"||t==="nlink"?"SCHILY.":"")+t+"="+n+`
|
|
549
549
|
`,o=Buffer.byteLength(i),s=Math.floor(Math.log(o)/Math.log(10))+1;return o+s>=Math.pow(10,s)&&(s+=1),s+o+i}static parse(t,r,n=!1){return new Hql(i8m(o8m(t),r),n)}},i8m=(e,t)=>t?Object.assign({},t,e):e,o8m=e=>e.replace(/\n$/,"").split(`
|
|
550
|
-
`).reduce(s8m,Object.create(null)),s8m=(e,t)=>{let r=parseInt(t,10);if(r!==Buffer.byteLength(t)+1)return e;t=t.slice((r+" ").length);let n=t.split("="),i=n.shift();if(!i)return e;let o=i.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),s=n.join("=");return e[o]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(o)?new Date(Number(s)*1e3):/^[0-9]+$/.test(s)?+s:s,e},a8m=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,lf=a8m!=="win32"?e=>e:e=>e&&e.replaceAll(/\\/g,"/"),c8m=class extends EUe{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(e,t,r){switch(super({}),this.pause(),this.extended=t,this.globalExtended=r,this.header=e,this.remain=e.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=e.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!e.path)throw new Error("no path provided for tar.ReadEntry");this.path=lf(e.path),this.mode=e.mode,this.mode&&(this.mode=this.mode&4095),this.uid=e.uid,this.gid=e.gid,this.uname=e.uname,this.gname=e.gname,this.size=this.remain,this.mtime=e.mtime,this.atime=e.atime,this.ctime=e.ctime,this.linkpath=e.linkpath?lf(e.linkpath):void 0,this.uname=e.uname,this.gname=e.gname,t&&this.#e(t),r&&this.#e(r,!0)}write(e){let t=e.length;if(t>this.blockRemain)throw new Error("writing more to entry than is appropriate");let r=this.remain,n=this.blockRemain;return this.remain=Math.max(0,r-t),this.blockRemain=Math.max(0,n-t),this.ignore?!0:r>=t?super.write(e):super.write(e.subarray(0,r))}#e(e,t=!1){e.path&&(e.path=lf(e.path)),e.linkpath&&(e.linkpath=lf(e.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(e).filter(([r,n])=>!(n==null||r==="path"&&t))))}},WHr=(e,t,r,n={})=>{e.file&&(n.file=e.file),e.cwd&&(n.cwd=e.cwd),n.code=r instanceof Error&&r.code||t,n.tarCode=t,!e.strict&&n.recoverable!==!1?(r instanceof Error&&(n=Object.assign(r,n),r=r.message),e.emit("warn",t,r,n)):r instanceof Error?e.emit("error",Object.assign(r,n)):e.emit("error",Object.assign(new Error(`${t}: ${r}`),n))},l8m=1024*1024,U8o=Buffer.from([31,139]),V8o=Buffer.from([40,181,47,253]),u8m=Math.max(U8o.length,V8o.length),p8=Symbol("state"),pUe=Symbol("writeEntry"),zme=Symbol("readEntry"),O8o=Symbol("nextEntry"),cql=Symbol("processEntry"),yre=Symbol("extendedHeader"),rGt=Symbol("globalExtendedHeader"),ySe=Symbol("meta"),lql=Symbol("emitMeta"),Jb=Symbol("buffer"),Qme=Symbol("queue"),bSe=Symbol("ended"),P8o=Symbol("emittedEnd"),fUe=Symbol("emit"),Wx=Symbol("unzip"),bHr=Symbol("consumeChunk"),EHr=Symbol("consumeChunkSub"),B8o=Symbol("consumeBody"),uql=Symbol("consumeMeta"),pql=Symbol("consumeHeader"),nGt=Symbol("consuming"),D8o=Symbol("bufferConcat"),IHr=Symbol("maybeEnd"),bct=Symbol("writing"),ESe=Symbol("aborted"),vHr=Symbol("onDone"),dUe=Symbol("sawValidEntry"),CHr=Symbol("sawNullBlock"),xHr=Symbol("sawEOF"),fql=Symbol("closeStream"),p8m=()=>!0,yGt=class extends Qql.EventEmitter{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[Qme]=[];[Jb];[zme];[pUe];[p8]="begin";[ySe]="";[yre];[rGt];[bSe]=!1;[Wx];[ESe]=!1;[dUe];[CHr]=!1;[xHr]=!1;[bct]=!1;[nGt]=!1;[P8o]=!1;constructor(e={}){super(),this.file=e.file||"",this.on(vHr,()=>{(this[p8]==="begin"||this[dUe]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),e.ondone?this.on(vHr,e.ondone):this.on(vHr,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!e.strict,this.maxMetaEntrySize=e.maxMetaEntrySize||l8m,this.filter=typeof e.filter=="function"?e.filter:p8m;let t=e.file&&(e.file.endsWith(".tar.br")||e.file.endsWith(".tbr"));this.brotli=!(e.gzip||e.zstd)&&e.brotli!==void 0?e.brotli:t?void 0:!1;let r=e.file&&(e.file.endsWith(".tar.zst")||e.file.endsWith(".tzst"));this.zstd=!(e.gzip||e.brotli)&&e.zstd!==void 0?e.zstd:r?!0:void 0,this.on("end",()=>this[fql]()),typeof e.onwarn=="function"&&this.on("warn",e.onwarn),typeof e.onReadEntry=="function"&&this.on("entry",e.onReadEntry)}warn(e,t,r={}){WHr(this,e,t,r)}[pql](e,t){this[dUe]===void 0&&(this[dUe]=!1);let r;try{r=new bUe(e,t,this[yre],this[rGt])}catch(n){return this.warn("TAR_ENTRY_INVALID",n)}if(r.nullBlock)this[CHr]?(this[xHr]=!0,this[p8]==="begin"&&(this[p8]="header"),this[fUe]("eof")):(this[CHr]=!0,this[fUe]("nullBlock"));else if(this[CHr]=!1,!r.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:r});else if(!r.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:r});else{let n=r.type;if(/^(Symbolic)?Link$/.test(n)&&!r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:r});else if(!/^(Symbolic)?Link$/.test(n)&&!/^(Global)?ExtendedHeader$/.test(n)&&r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:r});else{let i=this[pUe]=new c8m(r,this[yre],this[rGt]);if(!this[dUe])if(i.remain){let o=()=>{i.invalid||(this[dUe]=!0)};i.on("end",o)}else this[dUe]=!0;i.meta?i.size>this.maxMetaEntrySize?(i.ignore=!0,this[fUe]("ignoredEntry",i),this[p8]="ignore",i.resume()):i.size>0&&(this[ySe]="",i.on("data",o=>this[ySe]+=o),this[p8]="meta"):(this[yre]=void 0,i.ignore=i.ignore||!this.filter(i.path,i),i.ignore?(this[fUe]("ignoredEntry",i),this[p8]=i.remain?"ignore":"header",i.resume()):(i.remain?this[p8]="body":(this[p8]="header",i.end()),this[zme]?this[Qme].push(i):(this[Qme].push(i),this[O8o]())))}}}[fql](){queueMicrotask(()=>this.emit("close"))}[cql](e){let t=!0;if(!e)this[zme]=void 0,t=!1;else if(Array.isArray(e)){let[r,...n]=e;this.emit(r,...n)}else this[zme]=e,this.emit("entry",e),e.emittedEnd||(e.on("end",()=>this[O8o]()),t=!1);return t}[O8o](){do;while(this[cql](this[Qme].shift()));if(this[Qme].length===0){let e=this[zme];!e||e.flowing||e.size===e.remain?this[bct]||this.emit("drain"):e.once("drain",()=>this.emit("drain"))}}[B8o](e,t){let r=this[pUe];if(!r)throw new Error("attempt to consume body without entry??");let n=r.blockRemain??0,i=n>=e.length&&t===0?e:e.subarray(t,t+n);return r.write(i),r.blockRemain||(this[p8]="header",this[pUe]=void 0,r.end()),i.length}[uql](e,t){let r=this[pUe],n=this[B8o](e,t);return!this[pUe]&&r&&this[lql](r),n}[fUe](e,t,r){this[Qme].length===0&&!this[zme]?this.emit(e,t,r):this[Qme].push([e,t,r])}[lql](e){switch(this[fUe]("meta",this[ySe]),e.type){case"ExtendedHeader":case"OldExtendedHeader":this[yre]=MHr.parse(this[ySe],this[yre],!1);break;case"GlobalExtendedHeader":this[rGt]=MHr.parse(this[ySe],this[rGt],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let t=this[yre]??Object.create(null);this[yre]=t,t.path=this[ySe].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let t=this[yre]||Object.create(null);this[yre]=t,t.linkpath=this[ySe].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+e.type)}}abort(e){this[ESe]=!0,this.emit("abort",e),this.warn("TAR_ABORT",e,{recoverable:!1})}write(e,t,r){if(typeof t=="function"&&(r=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,typeof t=="string"?t:"utf8")),this[ESe])return r?.(),!1;if((this[Wx]===void 0||this.brotli===void 0&&this[Wx]===!1)&&e){if(this[Jb]&&(e=Buffer.concat([this[Jb],e]),this[Jb]=void 0),e.length<u8m)return this[Jb]=e,r?.(),!0;for(let s=0;this[Wx]===void 0&&s<U8o.length;s++)e[s]!==U8o[s]&&(this[Wx]=!1);let i=!1;if(this[Wx]===!1&&this.zstd!==!1){i=!0;for(let s=0;s<V8o.length;s++)if(e[s]!==V8o[s]){i=!1;break}}let o=this.brotli===void 0&&!i;if(this[Wx]===!1&&o)if(e.length<512)if(this[bSe])this.brotli=!0;else return this[Jb]=e,r?.(),!0;else try{new bUe(e.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Wx]===void 0||this[Wx]===!1&&(this.brotli||i)){let s=this[bSe];this[bSe]=!1,this[Wx]=this[Wx]===void 0?new j5m({}):i?new L5m({}):new Q5m({}),this[Wx].on("data",c=>this[bHr](c)),this[Wx].on("error",c=>this.abort(c)),this[Wx].on("end",()=>{this[bSe]=!0,this[bHr]()}),this[bct]=!0;let a=!!this[Wx][s?"end":"write"](e);return this[bct]=!1,r?.(),a}}this[bct]=!0,this[Wx]?this[Wx].write(e):this[bHr](e),this[bct]=!1;let n=this[Qme].length>0?!1:this[zme]?this[zme].flowing:!0;return!n&&this[Qme].length===0&&this[zme]?.once("drain",()=>this.emit("drain")),r?.(),n}[D8o](e){e&&!this[ESe]&&(this[Jb]=this[Jb]?Buffer.concat([this[Jb],e]):e)}[IHr](){if(this[bSe]&&!this[P8o]&&!this[ESe]&&!this[nGt]){this[P8o]=!0;let e=this[pUe];if(e&&e.blockRemain){let t=this[Jb]?this[Jb].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${e.blockRemain} more bytes, only ${t} available)`,{entry:e}),this[Jb]&&e.write(this[Jb]),e.end()}this[fUe](vHr)}}[bHr](e){if(this[nGt]&&e)this[D8o](e);else if(!e&&!this[Jb])this[IHr]();else if(e){if(this[nGt]=!0,this[Jb]){this[D8o](e);let t=this[Jb];this[Jb]=void 0,this[EHr](t)}else this[EHr](e);for(;this[Jb]&&this[Jb]?.length>=512&&!this[ESe]&&!this[xHr];){let t=this[Jb];this[Jb]=void 0,this[EHr](t)}this[nGt]=!1}(!this[Jb]||this[bSe])&&this[IHr]()}[EHr](e){let t=0,r=e.length;for(;t+512<=r&&!this[ESe]&&!this[xHr];)switch(this[p8]){case"begin":case"header":this[pql](e,t),t+=512;break;case"ignore":case"body":t+=this[B8o](e,t);break;case"meta":t+=this[uql](e,t);break;default:throw new Error("invalid state: "+this[p8])}t<r&&(this[Jb]=this[Jb]?Buffer.concat([e.subarray(t),this[Jb]]):e.subarray(t))}end(e,t,r){return typeof e=="function"&&(r=e,t=void 0,e=void 0),typeof t=="function"&&(r=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,t)),r&&this.once("finish",r),this[ESe]||(this[Wx]?(e&&this[Wx].write(e),this[Wx].end()):(this[bSe]=!0,(this.brotli===void 0||this.zstd===void 0)&&(e=e||Buffer.alloc(0)),e&&this.write(e),this[IHr]())),this}},fGt=e=>{let t=e.length-1,r=-1;for(;t>-1&&e.charAt(t)==="/";)r=t,t--;return r===-1?e:e.slice(0,r)},f8m=e=>{let t=e.onReadEntry;e.onReadEntry=t?r=>{t(r),r.resume()}:r=>r.resume()},Kql=(e,t)=>{let r=new Map(t.map(o=>[fGt(o),!0])),n=e.filter,i=(o,s="")=>{let a=s||(0,GHr.parse)(o).root||".",c;if(o===a)c=!1;else{let l=r.get(o);c=l!==void 0?l:i((0,GHr.dirname)(o),a)}return r.set(o,c),c};e.filter=n?(o,s)=>n(o,s)&&i(fGt(o)):o=>i(fGt(o))},d8m=e=>{let t=new yGt(e),r=e.file,n;try{n=gUe.default.openSync(r,"r");let i=gUe.default.fstatSync(n),o=e.maxReadSize||16*1024*1024;if(i.size<o){let s=Buffer.allocUnsafe(i.size),a=gUe.default.readSync(n,s,0,i.size,0);t.end(a===s.byteLength?s:s.subarray(0,a))}else{let s=0,a=Buffer.allocUnsafe(o);for(;s<i.size;){let c=gUe.default.readSync(n,a,0,o,s);if(c===0)break;s+=c,t.write(a.subarray(0,c))}t.end()}}finally{if(typeof n=="number")try{gUe.default.closeSync(n)}catch{}}},m8m=(e,t)=>{let r=new yGt(e),n=e.maxReadSize||16*1024*1024,i=e.file;return new Promise((o,s)=>{r.on("error",s),r.on("end",o),gUe.default.stat(i,(a,c)=>{if(a)s(a);else{let l=new lGo(i,{readSize:n,size:c.size});l.on("error",s),l.pipe(r)}})})},HHr=IGt(d8m,m8m,e=>new yGt(e),e=>new yGt(e),(e,t)=>{t?.length&&Kql(e,t),e.noResume||f8m(e)}),Jql=(e,t,r)=>(e&=4095,r&&(e=(e|384)&-19),t&&(e&256&&(e|=64),e&32&&(e|=8),e&4&&(e|=1)),e),{isAbsolute:h8m,parse:dql}=Yql.win32,mGo=e=>{let t="",r=dql(e);for(;h8m(e)||r.root;){let n=e.charAt(0)==="/"&&e.slice(0,4)!=="//?/"?"/":r.root;e=e.slice(n.length),t+=n,r=dql(e)}return[t,e]},KHr=["|","<",">","?",":"],hGo=KHr.map(e=>String.fromCodePoint(61440+Number(e.codePointAt(0)))),g8m=new Map(KHr.map((e,t)=>[e,hGo[t]])),A8m=new Map(hGo.map((e,t)=>[e,KHr[t]])),mql=e=>KHr.reduce((t,r)=>t.split(r).join(g8m.get(r)),e),y8m=e=>hGo.reduce((t,r)=>t.split(r).join(A8m.get(r)),e),Xql=(e,t)=>t?(e=lf(e).replace(/^\.(\/|$)/,""),fGt(t)+"/"+e):lf(e),b8m=16*1024*1024,hql=Symbol("process"),gql=Symbol("file"),Aql=Symbol("directory"),q8o=Symbol("symlink"),yql=Symbol("hardlink"),iGt=Symbol("header"),BHr=Symbol("read"),W8o=Symbol("lstat"),DHr=Symbol("onlstat"),H8o=Symbol("onread"),K8o=Symbol("onreadlink"),J8o=Symbol("openfile"),Y8o=Symbol("onopenfile"),SSe=Symbol("close"),LHr=Symbol("mode"),X8o=Symbol("awaitDrain"),R8o=Symbol("ondrain"),bre=Symbol("prefix"),Zql=class extends EUe{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#e=!1;constructor(e,t={}){let r=pGo(t);super(),this.path=lf(e),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||b8m,this.linkCache=r.linkCache||new Map,this.statCache=r.statCache||new Map,this.preservePaths=!!r.preservePaths,this.cwd=lf(r.cwd||process.cwd()),this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.mtime=r.mtime,this.prefix=r.prefix?lf(r.prefix):void 0,this.onWriteEntry=r.onWriteEntry,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let n=!1;if(!this.preservePaths){let[o,s]=mGo(this.path);o&&typeof s=="string"&&(this.path=s,n=o)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=y8m(this.path.replaceAll(/\\/g,"/")),e=e.replaceAll(/\\/g,"/")),this.absolute=lf(r.absolute||G8o.default.resolve(this.cwd,e)),this.path===""&&(this.path="./"),n&&this.warn("TAR_ENTRY_INFO",`stripping ${n} from absolute path`,{entry:this,path:n+this.path});let i=this.statCache.get(this.absolute);i?this[DHr](i):this[W8o]()}warn(e,t,r={}){return WHr(this,e,t,r)}emit(e,...t){return e==="error"&&(this.#e=!0),super.emit(e,...t)}[W8o](){ZK.default.lstat(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[DHr](t)})}[DHr](e){this.statCache.set(this.absolute,e),this.stat=e,e.isFile()||(e.size=0),this.type=v8m(e),this.emit("stat",e),this[hql]()}[hql](){switch(this.type){case"File":return this[gql]();case"Directory":return this[Aql]();case"SymbolicLink":return this[q8o]();default:return this.end()}}[LHr](e){return Jql(e,this.type==="Directory",this.portable)}[bre](e){return Xql(e,this.prefix)}[iGt](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new bUe({path:this[bre](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[bre](this.linkpath):this.linkpath,mode:this[LHr](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new MHr({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[bre](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[bre](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let e=this.header?.block;if(!e)throw new Error("failed to encode header");super.write(e)}[Aql](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[iGt](),this.end()}[q8o](){ZK.default.readlink(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[K8o](t)})}[K8o](e){this.linkpath=lf(e),this[iGt](),this.end()}[yql](e){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=lf(G8o.default.relative(this.cwd,e)),this.stat.size=0,this[iGt](),this.end()}[gql](){if(!this.stat)throw new Error("cannot create file entry without stat");if(this.stat.nlink>1){let e=`${this.stat.dev}:${this.stat.ino}`,t=this.linkCache.get(e);if(t?.indexOf(this.cwd)===0)return this[yql](t);this.linkCache.set(e,this.absolute)}if(this[iGt](),this.stat.size===0)return this.end();this[J8o]()}[J8o](){ZK.default.open(this.absolute,"r",(e,t)=>{if(e)return this.emit("error",e);this[Y8o](t)})}[Y8o](e){if(this.fd=e,this.#e)return this[SSe]();if(!this.stat)throw new Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let t=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(t),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[BHr]()}[BHr](){let{fd:e,buf:t,offset:r,length:n,pos:i}=this;if(e===void 0||t===void 0)throw new Error("cannot read file without first opening");ZK.default.read(e,t,r,n,i,(o,s)=>{if(o)return this[SSe](()=>this.emit("error",o));this[H8o](s)})}[SSe](e=()=>{}){this.fd!==void 0&&ZK.default.close(this.fd,e)}[H8o](e){if(e<=0&&this.remain>0){let r=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[SSe](()=>this.emit("error",r))}if(e>this.remain){let r=Object.assign(new Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[SSe](()=>this.emit("error",r))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(e===this.remain)for(let r=e;r<this.length&&e<this.blockRemain;r++)this.buf[r+this.offset]=0,e++,this.remain++;let t=this.offset===0&&e===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+e);this.write(t)?this[R8o]():this[X8o](()=>this[R8o]())}[X8o](e){this.once("drain",e)}write(e,t,r){if(typeof t=="function"&&(r=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,typeof t=="string"?t:"utf8")),this.blockRemain<e.length){let n=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",n)}return this.remain-=e.length,this.blockRemain-=e.length,this.pos+=e.length,this.offset+=e.length,super.write(e,null,r)}[R8o](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[SSe](e=>e?this.emit("error",e):this.end());if(!this.buf)throw new Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[BHr]()}},E8m=class extends Zql{sync=!0;[W8o](){this[DHr](ZK.default.lstatSync(this.absolute))}[q8o](){this[K8o](ZK.default.readlinkSync(this.absolute))}[J8o](){this[Y8o](ZK.default.openSync(this.absolute,"r"))}[BHr](){let e=!0;try{let{fd:t,buf:r,offset:n,length:i,pos:o}=this;if(t===void 0||r===void 0)throw new Error("fd and buf must be set in READ method");let s=ZK.default.readSync(t,r,n,i,o);this[H8o](s),e=!1}finally{if(e)try{this[SSe](()=>{})}catch{}}}[X8o](e){e()}[SSe](e=()=>{}){this.fd!==void 0&&ZK.default.closeSync(this.fd),e()}},I8m=class extends EUe{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(e,t,r={}){return WHr(this,e,t,r)}constructor(e,t={}){let r=pGo(t);super(),this.preservePaths=!!r.preservePaths,this.portable=!!r.portable,this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.onWriteEntry=r.onWriteEntry,this.readEntry=e;let{type:n}=e;if(n==="Unsupported")throw new Error("writing entry that should be ignored");this.type=n,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=r.prefix,this.path=lf(e.path),this.mode=e.mode!==void 0?this[LHr](e.mode):void 0,this.uid=this.portable?void 0:e.uid,this.gid=this.portable?void 0:e.gid,this.uname=this.portable?void 0:e.uname,this.gname=this.portable?void 0:e.gname,this.size=e.size,this.mtime=this.noMtime?void 0:r.mtime||e.mtime,this.atime=this.portable?void 0:e.atime,this.ctime=this.portable?void 0:e.ctime,this.linkpath=e.linkpath!==void 0?lf(e.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let i=!1;if(!this.preservePaths){let[s,a]=mGo(this.path);s&&typeof a=="string"&&(this.path=a,i=s)}this.remain=e.size,this.blockRemain=e.startBlockSize,this.onWriteEntry?.(this),this.header=new bUe({path:this[bre](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[bre](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),i&&this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute path`,{entry:this,path:i+this.path}),this.header.encode()&&!this.noPax&&super.write(new MHr({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[bre](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[bre](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let o=this.header?.block;if(!o)throw new Error("failed to encode header");super.write(o),e.pipe(this)}[bre](e){return Xql(e,this.prefix)}[LHr](e){return Jql(e,this.type==="Directory",this.portable)}write(e,t,r){typeof t=="function"&&(r=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,typeof t=="string"?t:"utf8"));let n=e.length;if(n>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=n,super.write(e,r)}end(e,t,r){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof e=="function"&&(r=e,t=void 0,e=void 0),typeof t=="function"&&(r=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,t??"utf8")),r&&this.once("finish",r),e?super.end(e,r):super.end(r),this}},v8m=e=>e.isFile()?"File":e.isDirectory()?"Directory":e.isSymbolicLink()?"SymbolicLink":"Unsupported",C8m=class Sct{tail;head;length=0;static create(t=[]){return new Sct(t)}constructor(t=[]){for(let r of t)this.push(r)}*[Symbol.iterator](){for(let t=this.head;t;t=t.next)yield t.value}removeNode(t){if(t.list!==this)throw new Error("removing node which does not belong to this list");let r=t.next,n=t.prev;return r&&(r.prev=n),n&&(n.next=r),t===this.head&&(this.head=r),t===this.tail&&(this.tail=n),this.length--,t.next=void 0,t.prev=void 0,t.list=void 0,r}unshiftNode(t){if(t===this.head)return;t.list&&t.list.removeNode(t);let r=this.head;t.list=this,t.next=r,r&&(r.prev=t),this.head=t,this.tail||(this.tail=t),this.length++}pushNode(t){if(t===this.tail)return;t.list&&t.list.removeNode(t);let r=this.tail;t.list=this,t.prev=r,r&&(r.next=t),this.tail=t,this.head||(this.head=t),this.length++}push(...t){for(let r=0,n=t.length;r<n;r++)S8m(this,t[r]);return this.length}unshift(...t){for(var r=0,n=t.length;r<n;r++)w8m(this,t[r]);return this.length}pop(){if(!this.tail)return;let t=this.tail.value,r=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,r.list=void 0,this.length--,t}shift(){if(!this.head)return;let t=this.head.value,r=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,r.list=void 0,this.length--,t}forEach(t,r){r=r||this;for(let n=this.head,i=0;n;i++)t.call(r,n.value,i,this),n=n.next}forEachReverse(t,r){r=r||this;for(let n=this.tail,i=this.length-1;n;i--)t.call(r,n.value,i,this),n=n.prev}get(t){let r=0,n=this.head;for(;n&&r<t;r++)n=n.next;if(r===t&&n)return n.value}getReverse(t){let r=0,n=this.tail;for(;n&&r<t;r++)n=n.prev;if(r===t&&n)return n.value}map(t,r){r=r||this;let n=new Sct;for(let i=this.head;i;)n.push(t.call(r,i.value,this)),i=i.next;return n}mapReverse(t,r){r=r||this;var n=new Sct;for(let i=this.tail;i;)n.push(t.call(r,i.value,this)),i=i.prev;return n}reduce(t,r){let n,i=this.head;if(arguments.length>1)n=r;else if(this.head)i=this.head.next,n=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var o=0;i;o++)n=t(n,i.value,o),i=i.next;return n}reduceReverse(t,r){let n,i=this.tail;if(arguments.length>1)n=r;else if(this.tail)i=this.tail.prev,n=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let o=this.length-1;i;o--)n=t(n,i.value,o),i=i.prev;return n}toArray(){let t=new Array(this.length);for(let r=0,n=this.head;n;r++)t[r]=n.value,n=n.next;return t}toArrayReverse(){let t=new Array(this.length);for(let r=0,n=this.tail;n;r++)t[r]=n.value,n=n.prev;return t}slice(t=0,r=this.length){r<0&&(r+=this.length),t<0&&(t+=this.length);let n=new Sct;if(r<t||r<0)return n;t<0&&(t=0),r>this.length&&(r=this.length);let i=this.head,o=0;for(o=0;i&&o<t;o++)i=i.next;for(;i&&o<r;o++,i=i.next)n.push(i.value);return n}sliceReverse(t=0,r=this.length){r<0&&(r+=this.length),t<0&&(t+=this.length);let n=new Sct;if(r<t||r<0)return n;t<0&&(t=0),r>this.length&&(r=this.length);let i=this.length,o=this.tail;for(;o&&i>r;i--)o=o.prev;for(;o&&i>t;i--,o=o.prev)n.push(o.value);return n}splice(t,r=0,...n){t>this.length&&(t=this.length-1),t<0&&(t=this.length+t);let i=this.head;for(let s=0;i&&s<t;s++)i=i.next;let o=[];for(let s=0;i&&s<r;s++)o.push(i.value),i=this.removeNode(i);i?i!==this.tail&&(i=i.prev):i=this.tail;for(let s of n)i=x8m(this,i,s);return o}reverse(){let t=this.head,r=this.tail;for(let n=t;n;n=n.prev){let i=n.prev;n.prev=n.next,n.next=i}return this.head=r,this.tail=t,this}};gGo=class{list;next;prev;value;constructor(e,t,r,n){this.list=n,this.value=e,t?(t.next=this,this.prev=t):this.prev=void 0,r?(r.prev=this,this.next=r):this.next=void 0}},bql=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(e,t){this.path=e||"./",this.absolute=t}},Eql=Buffer.alloc(1024),RHr=Symbol("onStat"),oGt=Symbol("ended"),YK=Symbol("queue"),sGt=Symbol("pendingLinks"),ISe=Symbol("current"),mUe=Symbol("process"),aGt=Symbol("processing"),SHr=Symbol("processJob"),XK=Symbol("jobs"),k8o=Symbol("jobDone"),kHr=Symbol("addFSEntry"),Iql=Symbol("addTarEntry"),$8o=Symbol("stat"),eGo=Symbol("readdir"),FHr=Symbol("onreaddir"),NHr=Symbol("pipe"),vql=Symbol("entry"),F8o=Symbol("entryOpt"),jHr=Symbol("writeEntryClass"),$ql=Symbol("write"),N8o=Symbol("ondrain"),JHr=class extends EUe{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[jHr];onWriteEntry;[YK];[sGt]=new Map;[XK]=0;[aGt]=!1;[oGt]=!1;constructor(e={}){if(super(),this.opt=e,this.file=e.file||"",this.cwd=e.cwd||process.cwd(),this.maxReadSize=e.maxReadSize,this.preservePaths=!!e.preservePaths,this.strict=!!e.strict,this.noPax=!!e.noPax,this.prefix=lf(e.prefix||""),this.linkCache=e.linkCache||new Map,this.statCache=e.statCache||new Map,this.readdirCache=e.readdirCache||new Map,this.onWriteEntry=e.onWriteEntry,this[jHr]=Zql,typeof e.onwarn=="function"&&this.on("warn",e.onwarn),this.portable=!!e.portable,e.gzip||e.brotli||e.zstd){if((e.gzip?1:0)+(e.brotli?1:0)+(e.zstd?1:0)>1)throw new TypeError("gzip, brotli, zstd are mutually exclusive");if(e.gzip&&(typeof e.gzip!="object"&&(e.gzip={}),this.portable&&(e.gzip.portable=!0),this.zip=new N5m(e.gzip)),e.brotli&&(typeof e.brotli!="object"&&(e.brotli={}),this.zip=new z5m(e.brotli)),e.zstd&&(typeof e.zstd!="object"&&(e.zstd={}),this.zip=new M5m(e.zstd)),!this.zip)throw new Error("impossible");let t=this.zip;t.on("data",r=>super.write(r)),t.on("end",()=>super.end()),t.on("drain",()=>this[N8o]()),this.on("resume",()=>t.resume())}else this.on("drain",this[N8o]);this.noDirRecurse=!!e.noDirRecurse,this.follow=!!e.follow,this.noMtime=!!e.noMtime,e.mtime&&(this.mtime=e.mtime),this.filter=typeof e.filter=="function"?e.filter:()=>!0,this[YK]=new C8m,this[XK]=0,this.jobs=Number(e.jobs)||4,this[aGt]=!1,this[oGt]=!1}[$ql](e){return super.write(e)}add(e){return this.write(e),this}end(e,t,r){return typeof e=="function"&&(r=e,e=void 0),typeof t=="function"&&(r=t,t=void 0),e&&this.add(e),this[oGt]=!0,this[mUe](),r&&r(),this}write(e){if(this[oGt])throw new Error("write after end");return typeof e=="string"?this[kHr](e):this[Iql](e),this.flowing}[Iql](e){let t=lf(Z8o.default.resolve(this.cwd,e.path));if(!this.filter(e.path,e))e.resume();else{let r=new bql(e.path,t);r.entry=new I8m(e,this[F8o](r)),r.entry.on("end",()=>this[k8o](r)),this[XK]+=1,this[YK].push(r)}this[mUe]()}[kHr](e){let t=lf(Z8o.default.resolve(this.cwd,e));this[YK].push(new bql(e,t)),this[mUe]()}[$8o](e){e.pending=!0,this[XK]+=1;let t=this.follow?"stat":"lstat";bGt.default[t](e.absolute,(r,n)=>{e.pending=!1,this[XK]-=1,r?this.emit("error",r):this[RHr](e,n)})}[RHr](e,t){if(this.statCache.set(e.absolute,t),e.stat=t,!this.filter(e.path,t))e.ignore=!0;else if(t.isFile()&&t.nlink>1&&!this.linkCache.get(`${t.dev}:${t.ino}`)&&!this.sync)if(e===this[ISe])this[SHr](e);else{let r=`${t.dev}:${t.ino}`,n=this[sGt].get(r);n?n.push(e):this[sGt].set(r,[e]),e.pendingLink=!0,e.pending=!0}this[mUe]()}[eGo](e){e.pending=!0,this[XK]+=1,bGt.default.readdir(e.absolute,(t,r)=>{if(e.pending=!1,this[XK]-=1,t)return this.emit("error",t);this[FHr](e,r)})}[FHr](e,t){this.readdirCache.set(e.absolute,t),e.readdir=t,this[mUe]()}[mUe](){if(!this[aGt]){this[aGt]=!0;for(let e=this[YK].head;e&&this[XK]<this.jobs;e=e.next)if(this[SHr](e.value),e.value.ignore){let t=e.next;this[YK].removeNode(e),e.next=t}this[aGt]=!1,this[oGt]&&this[YK].length===0&&this[XK]===0&&(this.zip?this.zip.end(Eql):(super.write(Eql),super.end()))}}get[ISe](){return this[YK]&&this[YK].head&&this[YK].head.value}[k8o](e){this[YK].shift(),this[XK]-=1;let{stat:t}=e;if(t&&t.isFile()&&t.nlink>1){let r=`${t.dev}:${t.ino}`,n=this[sGt].get(r);if(n){this[sGt].delete(r);for(let i of n)i.pending=!1,this[SHr](i)}}this[mUe]()}[SHr](e){if(e.pending&&e.pendingLink&&e===this[ISe]&&(e.pending=!1,e.pendingLink=!1),!e.pending){if(e.entry){e===this[ISe]&&!e.piped&&this[NHr](e);return}if(!e.stat){let t=this.statCache.get(e.absolute);t?this[RHr](e,t):this[$8o](e)}if(e.stat&&!e.ignore){if(!this.noDirRecurse&&e.stat.isDirectory()&&!e.readdir){let t=this.readdirCache.get(e.absolute);if(t?this[FHr](e,t):this[eGo](e),!e.readdir)return}if(e.entry=this[vql](e),!e.entry){e.ignore=!0;return}e===this[ISe]&&!e.piped&&this[NHr](e)}}}[F8o](e){return{onwarn:(t,r,n)=>this.warn(t,r,n),noPax:this.noPax,cwd:this.cwd,absolute:e.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[vql](e){this[XK]+=1;try{return new this[jHr](e.path,this[F8o](e)).on("end",()=>this[k8o](e)).on("error",t=>this.emit("error",t))}catch(t){this.emit("error",t)}}[N8o](){this[ISe]&&this[ISe].entry&&this[ISe].entry.resume()}[NHr](e){e.piped=!0,e.readdir&&e.readdir.forEach(n=>{let i=e.path,o=i==="./"?"":i.replace(/\/*$/,"/");this[kHr](o+n)});let t=e.entry,r=this.zip;if(!t)throw new Error("cannot pipe without source");r?t.on("data",n=>{r.write(n)||t.pause()}):t.on("data",n=>{super.write(n)||t.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(e,t,r={}){WHr(this,e,t,r)}},AGo=class extends JHr{sync=!0;constructor(e){super(e),this[jHr]=E8m}pause(){}resume(){}[$8o](e){let t=this.follow?"statSync":"lstatSync";this[RHr](e,bGt.default[t](e.absolute))}[eGo](e){this[FHr](e,bGt.default.readdirSync(e.absolute))}[NHr](e){let t=e.entry,r=this.zip;if(e.readdir&&e.readdir.forEach(n=>{let i=e.path,o=i==="./"?"":i.replace(/\/*$/,"/");this[kHr](o+n)}),!t)throw new Error("Cannot pipe without source");r?t.on("data",n=>{r.write(n)}):t.on("data",n=>{super[$ql](n)})}},T8m=(e,t)=>{let r=new AGo(e),n=new zql(e.file,{mode:e.mode||438});r.pipe(n),eWl(r,t)},O8m=(e,t)=>{let r=new JHr(e),n=new VHr(e.file,{mode:e.mode||438});r.pipe(n);let i=new Promise((o,s)=>{n.on("error",s),n.on("close",o),r.on("error",s)});return tWl(r,t).catch(o=>r.emit("error",o)),i},eWl=(e,t)=>{t.forEach(r=>{r.charAt(0)==="@"?HHr({file:uGo.default.resolve(e.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r)}),e.end()},tWl=async(e,t)=>{for(let r of t)r.charAt(0)==="@"?await HHr({file:uGo.default.resolve(String(e.cwd),r.slice(1)),noResume:!0,onReadEntry:n=>{e.add(n)}}):e.add(r);e.end()},P8m=(e,t)=>{let r=new AGo(e);return eWl(r,t),r},B8m=(e,t)=>{let r=new JHr(e);return tWl(r,t).catch(n=>r.emit("error",n)),r},YHr=IGt(T8m,O8m,P8m,B8m,(e,t)=>{if(!t?.length)throw new TypeError("no paths specified to add to archive")}),D8m=process.env.__FAKE_PLATFORM__||process.platform,nWl=D8m==="win32",{O_CREAT:iWl,O_NOFOLLOW:Cql,O_TRUNC:oWl,O_WRONLY:sWl}=EGo.default.constants,aWl=Number(process.env.__FAKE_FS_O_FILENAME__)||EGo.default.constants.UV_FS_O_FILEMAP||0,R8m=nWl&&!!aWl,k8m=512*1024,F8m=aWl|oWl|iWl|sWl,xql=!nWl&&typeof Cql=="number"?Cql|oWl|iWl|sWl:null,cWl=xql!==null?()=>xql:R8m?e=>e<k8m?F8m:"w":()=>"w",tGo=(e,t,r)=>{try{return vGt.default.lchownSync(e,t,r)}catch(n){if(n?.code!=="ENOENT")throw n}},_Hr=(e,t,r,n)=>{vGt.default.lchown(e,t,r,i=>{n(i&&i?.code!=="ENOENT"?i:null)})},N8m=(e,t,r,n,i)=>{if(t.isDirectory())lWl(Tct.default.resolve(e,t.name),r,n,o=>{if(o)return i(o);let s=Tct.default.resolve(e,t.name);_Hr(s,r,n,i)});else{let o=Tct.default.resolve(e,t.name);_Hr(o,r,n,i)}},lWl=(e,t,r,n)=>{vGt.default.readdir(e,{withFileTypes:!0},(i,o)=>{if(i){if(i.code==="ENOENT")return n();if(i.code!=="ENOTDIR"&&i.code!=="ENOTSUP")return n(i)}if(i||!o.length)return _Hr(e,t,r,n);let s=o.length,a=null,c=l=>{if(!a){if(l)return n(a=l);if(--s===0)return _Hr(e,t,r,n)}};for(let l of o)N8m(e,l,t,r,c)})},j8m=(e,t,r,n)=>{t.isDirectory()&&uWl(Tct.default.resolve(e,t.name),r,n),tGo(Tct.default.resolve(e,t.name),r,n)},uWl=(e,t,r)=>{let n;try{n=vGt.default.readdirSync(e,{withFileTypes:!0})}catch(i){let o=i;if(o?.code==="ENOENT")return;if(o?.code==="ENOTDIR"||o?.code==="ENOTSUP")return tGo(e,t,r);throw o}for(let i of n)j8m(e,i,t,r);return tGo(e,t,r)},fWl=class extends Error{path;code;syscall="chdir";constructor(e,t){super(`${t}: Cannot cd into '${e}'`),this.path=e,this.code=t}get name(){return"CwdError"}},XHr=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(e,t){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=e,this.path=t}get name(){return"SymlinkError"}},z8m=(e,t)=>{VQ.default.stat(e,(r,n)=>{(r||!n.isDirectory())&&(r=new fWl(e,r?.code||"ENOTDIR")),t(r)})},Q8m=(e,t,r)=>{e=lf(e);let n=t.umask??18,i=t.mode|448,o=(i&n)!==0,s=t.uid,a=t.gid,c=typeof s=="number"&&typeof a=="number"&&(s!==t.processUid||a!==t.processGid),l=t.preserve,u=t.unlink,p=lf(t.cwd),d=(m,g)=>{m?r(m):g&&c?lWl(g,s,a,A=>d(A)):o?VQ.default.chmod(e,i,r):r()};if(e===p)return z8m(e,d);if(l)return pWl.default.mkdir(e,{mode:i,recursive:!0}).then(m=>d(null,m??void 0),d);let f=lf(EGt.default.relative(p,e)).split("/");rGo(p,f,i,u,p,void 0,d)},rGo=(e,t,r,n,i,o,s)=>{if(t.length===0)return s(null,o);let a=t.shift(),c=lf(EGt.default.resolve(e+"/"+a));VQ.default.mkdir(c,r,dWl(c,t,r,n,i,o,s))},dWl=(e,t,r,n,i,o,s)=>a=>{a?VQ.default.lstat(e,(c,l)=>{if(c)c.path=c.path&&lf(c.path),s(c);else if(l.isDirectory())rGo(e,t,r,n,i,o,s);else if(n)VQ.default.unlink(e,u=>{if(u)return s(u);VQ.default.mkdir(e,r,dWl(e,t,r,n,i,o,s))});else{if(l.isSymbolicLink())return s(new XHr(e,e+"/"+t.join("/")));s(a)}}):(o=o||e,rGo(e,t,r,n,i,o,s))},M8m=e=>{let t=!1,r;try{t=VQ.default.statSync(e).isDirectory()}catch(n){r=n?.code}finally{if(!t)throw new fWl(e,r??"ENOTDIR")}},L8m=(e,t)=>{e=lf(e);let r=t.umask??18,n=t.mode|448,i=(n&r)!==0,o=t.uid,s=t.gid,a=typeof o=="number"&&typeof s=="number"&&(o!==t.processUid||s!==t.processGid),c=t.preserve,l=t.unlink,u=lf(t.cwd),p=m=>{m&&a&&uWl(m,o,s),i&&VQ.default.chmodSync(e,n)};if(e===u)return M8m(u),p();if(c)return p(VQ.default.mkdirSync(e,{mode:n,recursive:!0})??void 0);let d=lf(EGt.default.relative(u,e)).split("/"),f;for(let m=d.shift(),g=u;m&&(g+="/"+m);m=d.shift()){g=lf(EGt.default.resolve(g));try{VQ.default.mkdirSync(g,n),f=f||g}catch{let A=VQ.default.lstatSync(g);if(A.isDirectory())continue;if(l){VQ.default.unlinkSync(g),VQ.default.mkdirSync(g,n),f=f||g;continue}else if(A.isSymbolicLink())return new XHr(g,g+"/"+d.join("/"))}}return p(f)},j8o=Object.create(null),Sql=1e4,Ect=new Set,_8m=e=>{Ect.has(e)?Ect.delete(e):j8o[e]=e.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Ect.add(e);let t=j8o[e],r=Ect.size-Sql;if(r>Sql/10){for(let n of Ect)if(Ect.delete(n),delete j8o[n],--r<=0)break}return t},U8m=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,V8m=U8m==="win32",G8m=e=>e.split("/").slice(0,-1).reduce((t,r)=>{let n=t.at(-1);return n!==void 0&&(r=(0,IGo.join)(n,r)),t.push(r||"/"),t},[]),q8m=class{#e=new Map;#t=new Map;#r=new Set;reserve(e,t){e=V8m?["win32 parallelization disabled"]:e.map(n=>fGt((0,IGo.join)(_8m(n))));let r=new Set(e.map(n=>G8m(n)).reduce((n,i)=>n.concat(i)));this.#t.set(t,{dirs:r,paths:e});for(let n of e){let i=this.#e.get(n);i?i.push(t):this.#e.set(n,[t])}for(let n of r){let i=this.#e.get(n);if(!i)this.#e.set(n,[new Set([t])]);else{let o=i.at(-1);o instanceof Set?o.add(t):i.push(new Set([t]))}}return this.#i(t)}#n(e){let t=this.#t.get(e);if(!t)throw new Error("function does not have any path reservations");return{paths:t.paths.map(r=>this.#e.get(r)),dirs:[...t.dirs].map(r=>this.#e.get(r))}}check(e){let{paths:t,dirs:r}=this.#n(e);return t.every(n=>n&&n[0]===e)&&r.every(n=>n&&n[0]instanceof Set&&n[0].has(e))}#i(e){return this.#r.has(e)||!this.check(e)?!1:(this.#r.add(e),e(()=>this.#o(e)),!0)}#o(e){if(!this.#r.has(e))return!1;let t=this.#t.get(e);if(!t)throw new Error("invalid reservation");let{paths:r,dirs:n}=t,i=new Set;for(let o of r){let s=this.#e.get(o);if(!s||s?.[0]!==e)continue;let a=s[1];if(!a){this.#e.delete(o);continue}if(s.shift(),typeof a=="function")i.add(a);else for(let c of a)i.add(c)}for(let o of n){let s=this.#e.get(o),a=s?.[0];if(!(!s||!(a instanceof Set)))if(a.size===1&&s.length===1){this.#e.delete(o);continue}else if(a.size===1){s.shift();let c=s[0];typeof c=="function"&&i.add(c)}else a.delete(e)}return this.#r.delete(e),i.forEach(o=>this.#i(o)),!0}},W8m=()=>process.umask(),wql=Symbol("onEntry"),nGo=Symbol("checkFs"),Tql=Symbol("checkFs2"),iGo=Symbol("isReusable"),f8=Symbol("makeFs"),oGo=Symbol("file"),sGo=Symbol("directory"),zHr=Symbol("link"),Oql=Symbol("symlink"),Pql=Symbol("hardlink"),uGt=Symbol("ensureNoSymlink"),Bql=Symbol("unsupported"),Dql=Symbol("checkPath"),z8o=Symbol("stripAbsolutePath"),TSe=Symbol("mkdir"),FT=Symbol("onError"),wHr=Symbol("pending"),Rql=Symbol("pend"),Ict=Symbol("unpend"),Q8o=Symbol("ended"),M8o=Symbol("maybeClose"),aGo=Symbol("skip"),dGt=Symbol("doChown"),mGt=Symbol("uid"),hGt=Symbol("gid"),gGt=Symbol("checkedCwd"),H8m=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,AGt=H8m==="win32",K8m=1024,J8m=(e,t)=>{if(!AGt)return Ed.default.unlink(e,t);let r=e+".DELETE."+(0,bGo.randomBytes)(16).toString("hex");Ed.default.rename(e,r,n=>{if(n)return t(n);Ed.default.unlink(r,t)})},Y8m=e=>{if(!AGt)return Ed.default.unlinkSync(e);let t=e+".DELETE."+(0,bGo.randomBytes)(16).toString("hex");Ed.default.renameSync(e,t),Ed.default.unlinkSync(t)},kql=(e,t,r)=>e!==void 0&&e===e>>>0?e:t!==void 0&&t===t>>>0?t:r,vGo=class extends yGt{[Q8o]=!1;[gGt]=!1;[wHr]=0;reservations=new q8m;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(e={}){if(e.ondone=()=>{this[Q8o]=!0,this[M8o]()},super(e),this.transform=e.transform,this.chmod=!!e.chmod,typeof e.uid=="number"||typeof e.gid=="number"){if(typeof e.uid!="number"||typeof e.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(e.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=e.uid,this.gid=e.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;this.preserveOwner=e.preserveOwner===void 0&&typeof e.uid!="number"?!!(process.getuid&&process.getuid()===0):!!e.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof e.maxDepth=="number"?e.maxDepth:K8m,this.forceChown=e.forceChown===!0,this.win32=!!e.win32||AGt,this.newer=!!e.newer,this.keep=!!e.keep,this.noMtime=!!e.noMtime,this.preservePaths=!!e.preservePaths,this.unlink=!!e.unlink,this.cwd=lf(Hx.default.resolve(e.cwd||process.cwd())),this.strip=Number(e.strip)||0,this.processUmask=this.chmod?typeof e.processUmask=="number"?e.processUmask:W8m():0,this.umask=typeof e.umask=="number"?e.umask:this.processUmask,this.dmode=e.dmode||511&~this.umask,this.fmode=e.fmode||438&~this.umask,this.on("entry",t=>this[wql](t))}warn(e,t,r={}){return(e==="TAR_BAD_ARCHIVE"||e==="TAR_ABORT")&&(r.recoverable=!1),super.warn(e,t,r)}[M8o](){this[Q8o]&&this[wHr]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[z8o](e,t){let r=e[t],{type:n}=e;if(!r||this.preservePaths)return!0;let[i,o]=mGo(r),s=o.replaceAll(/\\/g,"/").split("/");if(s.includes("..")||AGt&&/^[a-z]:\.\.$/i.test(s[0]??"")){if(t==="path"||n==="Link")return this.warn("TAR_ENTRY_ERROR",`${t} contains '..'`,{entry:e,[t]:r}),!1;let a=Hx.default.posix.dirname(e.path),c=Hx.default.posix.normalize(Hx.default.posix.join(a,s.join("/")));if(c.startsWith("../")||c==="..")return this.warn("TAR_ENTRY_ERROR",`${t} escapes extraction directory`,{entry:e,[t]:r}),!1}return i&&(e[t]=String(o),this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute ${t}`,{entry:e,[t]:r})),!0}[Dql](e){let t=lf(e.path),r=t.split("/");if(this.strip){if(r.length<this.strip)return!1;if(e.type==="Link"){let n=lf(String(e.linkpath)).split("/");if(n.length>=this.strip)e.linkpath=n.slice(this.strip).join("/");else return!1}r.splice(0,this.strip),e.path=r.join("/")}if(isFinite(this.maxDepth)&&r.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:e,path:t,depth:r.length,maxDepth:this.maxDepth}),!1;if(!this[z8o](e,"path")||!this[z8o](e,"linkpath"))return!1;if(e.absolute=Hx.default.isAbsolute(e.path)?lf(Hx.default.resolve(e.path)):lf(Hx.default.resolve(this.cwd,e.path)),!this.preservePaths&&typeof e.absolute=="string"&&e.absolute.indexOf(this.cwd+"/")!==0&&e.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:e,path:lf(e.path),resolvedPath:e.absolute,cwd:this.cwd}),!1;if(e.absolute===this.cwd&&e.type!=="Directory"&&e.type!=="GNUDumpDir")return!1;if(this.win32){let{root:n}=Hx.default.win32.parse(String(e.absolute));e.absolute=n+mql(String(e.absolute).slice(n.length));let{root:i}=Hx.default.win32.parse(e.path);e.path=i+mql(e.path.slice(i.length))}return!0}[wql](e){if(!this[Dql](e))return e.resume();switch(rWl.default.equal(typeof e.absolute,"string"),e.type){case"Directory":case"GNUDumpDir":e.mode&&(e.mode=e.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[nGo](e);default:return this[Bql](e)}}[FT](e,t){e.name==="CwdError"?this.emit("error",e):(this.warn("TAR_ENTRY_ERROR",e,{entry:t}),this[Ict](),t.resume())}[TSe](e,t,r){Q8m(lf(e),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:t},r)}[dGt](e){return this.forceChown||this.preserveOwner&&(typeof e.uid=="number"&&e.uid!==this.processUid||typeof e.gid=="number"&&e.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[mGt](e){return kql(this.uid,e.uid,this.processUid)}[hGt](e){return kql(this.gid,e.gid,this.processGid)}[oGo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.fmode,n=new VHr(String(e.absolute),{flags:cWl(e.size),mode:r,autoClose:!1});n.on("error",a=>{n.fd&&Ed.default.close(n.fd,()=>{}),n.write=()=>!0,this[FT](a,e),t()});let i=1,o=a=>{if(a){n.fd&&Ed.default.close(n.fd,()=>{}),this[FT](a,e),t();return}--i===0&&n.fd!==void 0&&Ed.default.close(n.fd,c=>{c?this[FT](c,e):this[Ict](),t()})};n.on("finish",()=>{let a=String(e.absolute),c=n.fd;if(typeof c=="number"&&e.mtime&&!this.noMtime){i++;let l=e.atime||new Date,u=e.mtime;Ed.default.futimes(c,l,u,p=>p?Ed.default.utimes(a,l,u,d=>o(d&&p)):o())}if(typeof c=="number"&&this[dGt](e)){i++;let l=this[mGt](e),u=this[hGt](e);typeof l=="number"&&typeof u=="number"&&Ed.default.fchown(c,l,u,p=>p?Ed.default.chown(a,l,u,d=>o(d&&p)):o())}o()});let s=this.transform&&this.transform(e)||e;s!==e&&(s.on("error",a=>{this[FT](a,e),t()}),e.pipe(s)),s.pipe(n)}[sGo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.dmode;this[TSe](String(e.absolute),r,n=>{if(n){this[FT](n,e),t();return}let i=1,o=()=>{--i===0&&(t(),this[Ict](),e.resume())};e.mtime&&!this.noMtime&&(i++,Ed.default.utimes(String(e.absolute),e.atime||new Date,e.mtime,o)),this[dGt](e)&&(i++,Ed.default.chown(String(e.absolute),Number(this[mGt](e)),Number(this[hGt](e)),o)),o()})}[Bql](e){e.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${e.type}`,{entry:e}),e.resume()}[Oql](e,t){let r=lf(Hx.default.relative(this.cwd,Hx.default.resolve(Hx.default.dirname(String(e.absolute)),String(e.linkpath)))).split("/");this[uGt](e,this.cwd,r,()=>this[zHr](e,String(e.linkpath),"symlink",t),n=>{this[FT](n,e),t()})}[Pql](e,t){let r=lf(Hx.default.resolve(this.cwd,String(e.linkpath))),n=lf(String(e.linkpath)).split("/");this[uGt](e,this.cwd,n,()=>this[zHr](e,r,"link",t),i=>{this[FT](i,e),t()})}[uGt](e,t,r,n,i){let o=r.shift();if(this.preservePaths||o===void 0)return n();let s=Hx.default.resolve(t,o);Ed.default.lstat(s,(a,c)=>{if(a)return n();if(c?.isSymbolicLink())return i(new XHr(s,Hx.default.resolve(s,r.join("/"))));this[uGt](e,s,r,n,i)})}[Rql](){this[wHr]++}[Ict](){this[wHr]--,this[M8o]()}[aGo](e){this[Ict](),e.resume()}[iGo](e,t){return e.type==="File"&&!this.unlink&&t.isFile()&&t.nlink<=1&&!AGt}[nGo](e){this[Rql]();let t=[e.path];e.linkpath&&t.push(e.linkpath),this.reservations.reserve(t,r=>this[Tql](e,r))}[Tql](e,t){let r=s=>{t(s)},n=()=>{this[TSe](this.cwd,this.dmode,s=>{if(s){this[FT](s,e),r();return}this[gGt]=!0,i()})},i=()=>{if(e.absolute!==this.cwd){let s=lf(Hx.default.dirname(String(e.absolute)));if(s!==this.cwd)return this[TSe](s,this.dmode,a=>{if(a){this[FT](a,e),r();return}o()})}o()},o=()=>{Ed.default.lstat(String(e.absolute),(s,a)=>{if(a&&(this.keep||this.newer&&a.mtime>(e.mtime??a.mtime))){this[aGo](e),r();return}if(s||this[iGo](e,a))return this[f8](null,e,r);if(a.isDirectory()){if(e.type==="Directory"){let c=this.chmod&&e.mode&&(a.mode&4095)!==e.mode,l=u=>this[f8](u??null,e,r);return c?Ed.default.chmod(String(e.absolute),Number(e.mode),l):l()}if(e.absolute!==this.cwd)return Ed.default.rmdir(String(e.absolute),c=>this[f8](c??null,e,r))}if(e.absolute===this.cwd)return this[f8](null,e,r);J8m(String(e.absolute),c=>this[f8](c??null,e,r))})};this[gGt]?i():n()}[f8](e,t,r){if(e){this[FT](e,t),r();return}switch(t.type){case"File":case"OldFile":case"ContiguousFile":return this[oGo](t,r);case"Link":return this[Pql](t,r);case"SymbolicLink":return this[Oql](t,r);case"Directory":case"GNUDumpDir":return this[sGo](t,r)}}[zHr](e,t,r,n){Ed.default[r](t,String(e.absolute),i=>{i?this[FT](i,e):(this[Ict](),e.resume()),n()})}},cGt=e=>{try{return[null,e()]}catch(t){return[t,null]}},mWl=class extends vGo{sync=!0;[f8](e,t){return super[f8](e,t,()=>{})}[nGo](e){if(!this[gGt]){let i=this[TSe](this.cwd,this.dmode);if(i)return this[FT](i,e);this[gGt]=!0}if(e.absolute!==this.cwd){let i=lf(Hx.default.dirname(String(e.absolute)));if(i!==this.cwd){let o=this[TSe](i,this.dmode);if(o)return this[FT](o,e)}}let[t,r]=cGt(()=>Ed.default.lstatSync(String(e.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(e.mtime??r.mtime)))return this[aGo](e);if(t||this[iGo](e,r))return this[f8](null,e);if(r.isDirectory()){if(e.type==="Directory"){let o=this.chmod&&e.mode&&(r.mode&4095)!==e.mode,[s]=o?cGt(()=>{Ed.default.chmodSync(String(e.absolute),Number(e.mode))}):[];return this[f8](s,e)}let[i]=cGt(()=>Ed.default.rmdirSync(String(e.absolute)));this[f8](i,e)}let[n]=e.absolute===this.cwd?[]:cGt(()=>Y8m(String(e.absolute)));this[f8](n,e)}[oGo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.fmode,n=s=>{let a;try{Ed.default.closeSync(i)}catch(c){a=c}(s||a)&&this[FT](s||a,e),t()},i;try{i=Ed.default.openSync(String(e.absolute),cWl(e.size),r)}catch(s){return n(s)}let o=this.transform&&this.transform(e)||e;o!==e&&(o.on("error",s=>this[FT](s,e)),e.pipe(o)),o.on("data",s=>{try{Ed.default.writeSync(i,s,0,s.length)}catch(a){n(a)}}),o.on("end",()=>{let s=null;if(e.mtime&&!this.noMtime){let a=e.atime||new Date,c=e.mtime;try{Ed.default.futimesSync(i,a,c)}catch(l){try{Ed.default.utimesSync(String(e.absolute),a,c)}catch{s=l}}}if(this[dGt](e)){let a=this[mGt](e),c=this[hGt](e);try{Ed.default.fchownSync(i,Number(a),Number(c))}catch(l){try{Ed.default.chownSync(String(e.absolute),Number(a),Number(c))}catch{s=s||l}}}n(s)})}[sGo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.dmode,n=this[TSe](String(e.absolute),r);if(n){this[FT](n,e),t();return}if(e.mtime&&!this.noMtime)try{Ed.default.utimesSync(String(e.absolute),e.atime||new Date,e.mtime)}catch{}if(this[dGt](e))try{Ed.default.chownSync(String(e.absolute),Number(this[mGt](e)),Number(this[hGt](e)))}catch{}t(),e.resume()}[TSe](e,t){try{return L8m(lf(e),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:t})}catch(r){return r}}[uGt](e,t,r,n,i){if(this.preservePaths||r.length===0)return n();let o=t;for(let s of r){o=Hx.default.resolve(o,s);let[a,c]=cGt(()=>Ed.default.lstatSync(o));if(a)return n();if(c.isSymbolicLink())return i(new XHr(o,Hx.default.resolve(t,r.join("/"))))}n()}[zHr](e,t,r,n){let i=`${r}Sync`;try{Ed.default[i](t,String(e.absolute)),n(),e.resume()}catch(o){return this[FT](o,e)}}},X8m=e=>{let t=new mWl(e),r=e.file,n=yGo.default.statSync(r),i=e.maxReadSize||16*1024*1024;new x5m(r,{readSize:i,size:n.size}).pipe(t)},Z8m=(e,t)=>{let r=new vGo(e),n=e.maxReadSize||16*1024*1024,i=e.file;return new Promise((o,s)=>{r.on("error",s),r.on("close",o),yGo.default.stat(i,(a,c)=>{if(a)s(a);else{let l=new lGo(i,{readSize:n,size:c.size});l.on("error",s),l.pipe(r)}})})},hWl=IGt(X8m,Z8m,e=>new mWl(e),e=>new vGo(e),(e,t)=>{t?.length&&Kql(e,t)}),$8m=(e,t)=>{let r=new AGo(e),n=!0,i,o;try{try{i=UQ.default.openSync(e.file,"r+")}catch(c){if(c?.code==="ENOENT")i=UQ.default.openSync(e.file,"w+");else throw c}let s=UQ.default.fstatSync(i),a=Buffer.alloc(512);e:for(o=0;o<s.size;o+=512){for(let u=0,p=0;u<512;u+=p){if(p=UQ.default.readSync(i,a,u,a.length-u,o+u),o===0&&a[0]===31&&a[1]===139)throw new Error("cannot append to compressed archives");if(!p)break e}let c=new bUe(a);if(!c.cksumValid)break;let l=512*Math.ceil((c.size||0)/512);if(o+l+512>s.size)break;o+=l,e.mtimeCache&&c.mtime&&e.mtimeCache.set(String(c.path),c.mtime)}n=!1,eGm(e,r,o,i,t)}finally{if(n)try{UQ.default.closeSync(i)}catch{}}},eGm=(e,t,r,n,i)=>{let o=new zql(e.file,{fd:n,start:r});t.pipe(o),rGm(t,i)},tGm=(e,t)=>{t=Array.from(t);let r=new JHr(e),n=(i,o,s)=>{let a=(d,f)=>{d?UQ.default.close(i,m=>s(d)):s(null,f)},c=0;if(o===0)return a(null,0);let l=0,u=Buffer.alloc(512),p=(d,f)=>{if(d||f===void 0)return a(d);if(l+=f,l<512&&f)return UQ.default.read(i,u,l,u.length-l,c+l,p);if(c===0&&u[0]===31&&u[1]===139)return a(new Error("cannot append to compressed archives"));if(l<512)return a(null,c);let m=new bUe(u);if(!m.cksumValid)return a(null,c);let g=512*Math.ceil((m.size??0)/512);if(c+g+512>o||(c+=g+512,c>=o))return a(null,c);e.mtimeCache&&m.mtime&&e.mtimeCache.set(String(m.path),m.mtime),l=0,UQ.default.read(i,u,0,512,c,p)};UQ.default.read(i,u,0,512,c,p)};return new Promise((i,o)=>{r.on("error",o);let s="r+",a=(c,l)=>{if(c&&c.code==="ENOENT"&&s==="r+")return s="w+",UQ.default.open(e.file,s,a);if(c||!l)return o(c);UQ.default.fstat(l,(u,p)=>{if(u)return UQ.default.close(l,()=>o(u));n(l,p.size,(d,f)=>{if(d)return o(d);let m=new VHr(e.file,{fd:l,start:f});r.pipe(m),m.on("error",o),m.on("close",i),nGm(r,t)})})};UQ.default.open(e.file,s,a)})},rGm=(e,t)=>{t.forEach(r=>{r.charAt(0)==="@"?HHr({file:CGo.default.resolve(e.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r)}),e.end()},nGm=async(e,t)=>{for(let r of t)r.charAt(0)==="@"?await HHr({file:CGo.default.resolve(String(e.cwd),r.slice(1)),noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r);e.end()},lGt=IGt($8m,tGm,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(e,t)=>{if(!B5m(e))throw new TypeError("file is required");if(e.gzip||e.brotli||e.zstd||e.file.endsWith(".br")||e.file.endsWith(".tbr"))throw new TypeError("cannot append to compressed archives");if(!t?.length)throw new TypeError("no paths specified to add/replace")}),czv=IGt(lGt.syncFile,lGt.asyncFile,lGt.syncNoFile,lGt.asyncNoFile,(e,t=[])=>{lGt.validate?.(e,t),iGm(e)}),iGm=e=>{let t=e.filter;e.mtimeCache||(e.mtimeCache=new Map),e.filter=t?(r,n)=>t(r,n)&&!((e.mtimeCache?.get(r)??n.mtime??0)>(n.mtime??0)):(r,n)=>!((e.mtimeCache?.get(r)??n.mtime??0)>(n.mtime??0))}});var Ki,$Hr=h(()=>{"use strict";zn();Ki=class e{breadcrumbs=[];context;static STRING=$t.TypeReference.primitive({v1:"STRING",v2:$t.PrimitiveTypeV2.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=$t.TypeReference.container($t.ContainerType.optional(e.STRING));constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r}}});var xGo,gWl,AWl=h(()=>{"use strict";xGo=class{_map;_path;_lastScalar;_fragments;_count;constructor(){this._map={},this._path=[],this._lastScalar="",this._fragments=[],this._count=0}get map(){return this._map}resolveNode(t,r){if(t.path==="."&&(r="."),!this._map[r]){let{line:n,position:i,lineStart:o}=t;this._map[r]={line:n,position:i,lineStart:o}}t.children&&t.children.length>0&&t.children.forEach(n=>{this.resolveNode(n,(r==="."?"":r)+"."+n.path)})}iterFragments(t,r){for(let n=this._fragments.length-1;n>=0;n--){if(!this._fragments[n].path.startsWith(t)||this._fragments[n].path===t)continue;let i=this._fragments.pop();r(i)}}handleState(t,r){if(t==="close"){let n=r.result,i=r.kind,o=this._path.join(".");if(i==="scalar"){this._path.pop(),this._lastScalar=`${n}`;let{line:s,position:a,lineStart:c}=r;this._path.length===0?this._map["."+n]={line:s,position:a,lineStart:c}:this._fragments.push({path:this._path.join(".")+"."+n,line:s,position:a,lineStart:c})}else if(i==="mapping"){let s={path:o,children:[],line:0,position:0,lineStart:0},a=0;this.iterFragments(o,c=>{a++,!((!c.children||c.children.length===0)&&a%2===1)&&(this._path.length===1?this.resolveNode(c,c.path):(s.children.push({...c,path:c.path.slice(o.length+1)}),s.line=c.line,s.position=c.position,s.lineStart=c.lineStart))}),s.children&&s.children.length>0&&this._fragments.push(s),this._path.pop()}else if(i==="sequence"){let s={path:o,children:[],line:0,position:0,lineStart:0},a=new Set,c=n.length;this.iterFragments(o,l=>{a.has(l.position)||(c--,a.add(l.position),this._path.length===1?this.resolveNode(l,`${o}.${c}`):(s.children.push({...l,path:c.toString()}),s.line=l.line,s.position=l.position,s.lineStart=l.lineStart))}),s.children&&s.children.length>0&&this._fragments.push(s),this._path.pop()}else this._path.pop()}if(t==="open"){if(this._count===0){let{line:n,position:i,lineStart:o}=r;this._map["."]={line:n,position:i,lineStart:o}}this._path.push(this._lastScalar),this._count++}}listen(){return this.handleState.bind(this)}lookup(t){let r=t instanceof Array?t.map(i=>`${i}`).join("."):`${t}`;r.startsWith(".")||(r="."+r),r.startsWith("..")&&(r=r.slice(1)),r=r.replace(/\[/g,".").replace(/\]/g,"");let n=this._map[r];if(n)return{line:n.line+1,column:n.position-n.lineStart+1,position:n.position}}},gWl=xGo});var yWl,HE,Ire,SGo,CGt=h(()=>{"use strict";tr();Ey();yWl=require("fs/promises");Ko();AWl();(function(e){e.WARNING="warning",e.ERROR="error"})(HE||(HE={}));Ire=class{errors=[];logger;breadcrumbToLineNumberMapper;relativeFilepathToSpec;constructor({logger:t,relativeFilepathToSpec:r}){this.logger=t,this.relativeFilepathToSpec=r,r&&(this.breadcrumbToLineNumberMapper=new SGo({logger:t,relativePathToFile:be.of(r)}))}collect(t){this.errors.push(t)}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}dedupe(){let t=[],r=new Set,n=0;for(let i of this.errors){let o=i.path?i.path.join("->"):"",s=`${i.message}|${i.level||HE.WARNING}|${o}`;r.has(s)?n++:(r.add(s),t.push(i))}return this.errors=t,n}getErrorStats(){this.dedupe();let t=0,r=0;for(let n of this.errors)n.level===HE.ERROR?t++:(n.level===HE.WARNING||n.level===void 0)&&r++;return{numErrors:t,numWarnings:r}}async logErrors({logWarnings:t}){this.dedupe();for(let r of this.errors){let n=r.level??HE.WARNING;if(!(n===HE.WARNING&&!t))switch(n){case HE.ERROR:if(this.logger.log(Un.Debug,r.message),r.path&&r.path.length>0){let i=await this.breadcrumbToLineNumberMapper?.getSourceLocation(r.path),o=i?`${this.relativeFilepathToSpec}:${i.line}:${i.column}`:r.path.join(" -> ");this.logger.log(Un.Debug,` - at location (${o})`)}break;case HE.WARNING:if(this.logger.log(Un.Warn,r.message),r.path&&r.path.length>0){let i=await this.breadcrumbToLineNumberMapper?.getSourceLocation(r.path),o=i?`${this.relativeFilepathToSpec}:${i.line}:${i.column}`:r.path.join(" -> ");this.logger.log(Un.Warn,` - at location (${o})`)}r.resolution&&this.logger.log(Un.Warn,` - resolution: ${r.resolution}`);break}}}},SGo=class{logger;relativePathToFile;map=new gWl;initialized=!1;constructor({relativePathToFile:t,logger:r}){this.relativePathToFile=t,this.logger=r}async initialize(){if(!this.initialized)try{let t=await(0,yWl.readFile)(this.relativePathToFile,"utf-8");Er.load(t,{listener:this.map.listen()}),this.initialized=!0}catch(t){this.logger.log(Un.Warn,`Failed to initialize line number mapping for ${this.relativePathToFile}: ${JSON.stringify(t)}`)}}async getSourceLocation(t){return this.initialized||await this.initialize(),this.map.lookup(t)}}});function sGm(e){return"deprecated"in e&&e.deprecated===!0}async function aGm(e){let t=await fetch(e);if(t.ok)try{let r=await t.text();try{return JSON.parse(r)}catch{return Er.load(r)}}catch{return}}var Yb,bWl=h(()=>{"use strict";QK();mt();zn();Ko();xo();CGt();Uo();Yb=class e{args;spec;settings;errorCollector;logger;generationLanguage;smartCasing;casingsGenerator;namespace;exampleGenerationArgs;authOverrides;environmentOverrides;globalHeaderOverrides;enableUniqueErrorsPerEndpoint;generateV1Examples;documentBaseDir;externalDocuments=new Map;discriminatedVariantsInProgress=new Set;constructor(t){this.args=t,this.spec=t.spec,this.settings=t.settings,this.errorCollector=t.errorCollector,this.logger=t.logger,this.generationLanguage=t.generationLanguage,this.smartCasing=t.smartCasing,this.namespace=t.namespace,this.casingsGenerator=Tw({generationLanguage:t.generationLanguage,keywords:void 0,smartCasing:t.smartCasing}),this.exampleGenerationArgs=t.exampleGenerationArgs,this.authOverrides=t.authOverrides,this.environmentOverrides=t.environmentOverrides,this.globalHeaderOverrides=t.globalHeaderOverrides,this.enableUniqueErrorsPerEndpoint=t.enableUniqueErrorsPerEndpoint,this.generateV1Examples=t.generateV1Examples,this.documentBaseDir=t.documentBaseDir}static BREADCRUMBS_TO_IGNORE=["properties","allOf","anyOf"];convertBreadcrumbsToName(t){let r=e.getPropertyNameIndices(t),n=t.filter((o,s)=>r.has(s)?!0:!(/^\d+$/.test(o)||e.BREADCRUMBS_TO_IGNORE.includes(o)||s===0&&o==="components"||s===1&&o==="schemas"||t[0]==="paths"&&(s===0||s===1&&["get","post","put","delete","patch"].includes(o)||s===2&&t[1]!=null&&["get","post","put","delete","patch"].includes(t[1])&&o==="parameters"))),i=ao(n.join("_"));return G6(i)}static getPropertyNameIndices(t){let r=new Set;for(let[n,i]of t.entries())i==="properties"&&!r.has(n)&&n+1<t.length&&r.add(n+1);return r}createFernFilepath(t={}){let r=this.namespace!=null?[this.casingsGenerator.generateName(this.namespace)]:[],n=t.name!=null?this.casingsGenerator.generateName(t.name):void 0;return{allParts:n?[...r,n]:r,packagePath:r,file:n}}resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:n}){let i=this.spec,o=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(s=>s.replace(/~1/g,"/"));for(let s of o){if(typeof i!="object"||i==null)return n||this.errorCollector.collect({level:HE.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1};i=i[s]}return i==null?(n||this.errorCollector.collect({level:HE.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1}):{resolved:!0,value:i}}getErrorMessageForMissingRef({reference:t}){let r=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/");return r.length>=3&&r[0]==="components"&&r[1]==="schemas"?`Schema ${r[2]} does not exist`:`${t.$ref} does not exist`}async resolveMaybeExternalReference(t){let r=this.spec,n,i=!1,o=null,s;if(this.isExternalReference(t.$ref)){i=!0;let l=t.$ref.split("#"),u=l[0];if(n=l[1],!u)return{resolved:!1};if(s=u,o=await this.loadExternalDocument(u),r=o,r==null)return{resolved:!1};if(!n)return{resolved:!0,value:r}}let a=n??t.$ref;if(a==null||typeof a!="string")return{resolved:!1};let c=a.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(l=>l.replace(/~1/g,"/"));for(let l of c){if(typeof r!="object"||r==null)return{resolved:!1};r=r[l]}if(r==null)return{resolved:!1};if(i&&typeof r=="object"&&r!==null){let l=new Set;l.add(t.$ref),r=await this.resolveNestedExternalReferences(r,o,l,s)}return{resolved:!0,value:r}}async loadExternalDocument(t){let r=this.externalDocuments.get(t);r==null&&(r=aGm(t),this.externalDocuments.set(t,r));try{let n=await r;return n==null&&this.forgetExternalDocument(t,r),structuredClone(n)}catch(n){throw this.forgetExternalDocument(t,r),n}}forgetExternalDocument(t,r){this.externalDocuments.get(t)===r&&this.externalDocuments.delete(t)}async resolveNestedExternalReferences(t,r,n,i){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){let s=[];for(let a of t)s.push(await this.resolveNestedExternalReferences(a,r,n,i));return s}if(this.isReferenceObject(t)){let s=t.$ref;if(this.isExternalReference(s)){if(n.has(s))return t;n.add(s);let a=await this.resolveMaybeExternalReference({$ref:s});if(n.delete(s),a.resolved)return a.value}else{let a=`${i}${s}`;if(n.has(a))return t;n.add(a);let c=r,l=s.substring(2).split("/").map(D0);for(let u of l){if(typeof c!="object"||c===null)return t;c=c[u]}if(c!=null){let u=await this.resolveNestedExternalReferences(c,r,n,i);return n.delete(s),u}n.delete(s)}return t}let o={};for(let[s,a]of Object.entries(t))typeof a=="object"&&a!==null?o[s]=await this.resolveNestedExternalReferences(a,r,n,i):o[s]=a;return o}getExamplesFromSchema({schema:t,breadcrumbs:r}){if(t==null)return[];let n=t.example!=null?[t.example]:[];return t.examples!=null&&(Array.isArray(t.examples)?n.push(...t.examples):this.errorCollector.collect({message:"Received non-array schema examples",path:r})),n}getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:r,defaultExampleName:n}){if(t==null)return[];let i=[];if(t.example!=null){let o=this.generateUniqueName({prefix:n??`${r.join("_")}_example`,existingNames:[]});i.push([o,{value:t.example}])}return t.examples!=null&&i.push(...Object.entries(t.examples)),i}resolveMaybeReference({schemaOrReference:t,breadcrumbs:r,skipErrorCollector:n}){if(this.isReferenceObject(t)){let i=this.resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:n});return i.resolved?i.value:void 0}return t}resolveExampleRecursively({example:t,breadcrumbs:r,maxDepth:n=10}){let i=t,o=0;for(;this.isReferenceObject(i);){if(o>=n){this.errorCollector.collect({message:`Maximum reference depth (${n}) exceeded while resolving example reference`,path:r});return}let s=this.resolveReference({reference:i,breadcrumbs:r,skipErrorCollector:!0});if(!s.resolved)return;i=s.value,o++}return i}resolveExample(t){if(!this.isReferenceObject(t))return t;let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}resolveExampleWithValue(t){if(!this.isReferenceObject(t))return this.returnExampleValue(t);let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}returnExampleValue(t){return this.isExampleWithValue(t)?t.value:t}getPropertyAccess(t){let r=t;for(;this.isReferenceObject(r);){let o=this.resolveReference({reference:r});if(!o.resolved)return;r=o.value}let{readOnly:n,writeOnly:i}=this.getReadOnlyWriteOnlyFromSchema(r);if(!(n&&i)){if(n)return $t.ObjectPropertyAccess.ReadOnly;if(i)return $t.ObjectPropertyAccess.WriteOnly}}getReadOnlyWriteOnlyFromSchema(t){if(t.allOf&&t.allOf.length>0){let r=!0,n=!0;for(let i of t.allOf){let o=i;if(this.isReferenceObject(i)){let a=this.resolveReference({reference:i});if(!a.resolved)continue;o=a.value}let s=this.getReadOnlyWriteOnlyFromSchema(o);r=r&&s.readOnly,n=n&&s.writeOnly}return{readOnly:r,writeOnly:n}}else return{readOnly:!!t.readOnly,writeOnly:!!t.writeOnly}}getAudiences({operation:t,breadcrumbs:r}){let i=new vC.AudienceExtension({operation:t,breadcrumbs:r,context:this}).convert();if(i!=null)return i.audiences}getAvailability({node:t,breadcrumbs:r}){let n=new Set;for(;this.isReferenceObject(t);){let i=this.getDeclaredAvailability({node:t,breadcrumbs:r});if(i!=null)return i;if(n.has(t.$ref))return;n.add(t.$ref);let o=this.resolveReference({reference:t});if(!o.resolved)return;t=o.value}return this.getDeclaredAvailability({node:t,breadcrumbs:r})}getDeclaredAvailability({node:t,breadcrumbs:r}){let i=new vC.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(i!=null)return{status:i,message:void 0};if(sGm(t))return{status:eh.Deprecated,message:void 0}}getNamespacedSchemaId(t){if(this.namespace==null)return t;let r=`${this.namespace}:`;return t.startsWith(r)?t:`${r}${t}`}getRawSchemaId(t){if(this.namespace==null)return t;let r=`${this.namespace}:`;return t.startsWith(r)?t.slice(r.length):t}getTypeIdFromSchemaReference(t){let r=t.$ref.match(/\/schemas\/(.+)$/);if(!(!r||!r[1]))return this.getNamespacedSchemaId(r[1])}getRawSchemaNameFromReference(t){let r=t.$ref.match(/\/schemas\/([^/]+)/);if(!(!r||!r[1]))return r[1]}createNamedTypeReference(t,r){return Hr.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(t),typeId:this.getNamespacedSchemaId(t),displayName:r,default:void 0,inline:!1})}typeReferenceToDeclaredTypeName(t){if(t.type==="named")return{typeId:t.typeId,fernFilepath:{allParts:[],packagePath:[],file:void 0},name:t.name,displayName:t.displayName}}removeSchemaFromInlinedTypes({id:t,inlinedTypes:r}){let n=this.getNamespacedSchemaId(t);return Object.fromEntries(Object.entries(r).filter(([i])=>i!==n))}static maybeTrimPrefix(t,r){return t.startsWith(r)?t.slice(r.length):t}generateUniqueName({prefix:t,existingNames:r}){if(!r.includes(t))return t;let n=0;for(;r.includes(`${t}_${n}`);)n++;return`${t}_${n}`}isReferenceObject(t){return typeof t=="object"&&t!==null&&"$ref"in t}isExternalReference(t){return typeof t=="string"&&Yh(t)}isReferenceObjectWithIdentifier(t){return this.isReferenceObject(t)&&("title"in t||"name"in t||"messageId"in t||"summary"in t)}isExampleWithSummary(t){return typeof t=="object"&&t!=null&&"summary"in t&&typeof t.summary=="string"&&t.summary.length>0}isExampleWithValue(t){return typeof t=="object"&&t!=null&&"value"in t}isOptional(t){return t.type==="container"&&t.container.type==="optional"}isNullable(t){return t.type==="container"&&t.container.type==="nullable"}isList(t){return t.type==="container"&&t.container.type==="list"}isFile(t){return t.type==="primitive"&&t.primitive.v2?.type==="string"&&t.primitive.v2.validation?.format==="binary"}getAsString(t){if(typeof t=="string")return t}getAsInteger(t){if(typeof t=="number"&&Number.isInteger(t))return t}getAsNumber(t){if(typeof t=="number")return t}getAsBoolean(t){if(typeof t=="boolean")return t}getAsArray(t){if(Array.isArray(t))return t}getAsObject(t){if(gr(t))return t}getGroup({groupParts:t,namespace:r}){let n=[];return r!=null&&n.push(r),n.push(...t??[]),n}isObjectSchemaType(t){return t.type==="object"||t.properties!=null}}});var Vo,AR=h(()=>{"use strict";Vo=class{breadcrumbs;context;constructor(t){this.breadcrumbs=t.breadcrumbs,this.context=t.context}getExtensionValue(t,r){if(typeof t!="object"||t==null)return;let n=t[this.key];if(n!=null)return n;if(r!=null)return t[r]}}});var Pct,wGo=h(()=>{"use strict";AR();Pct=class extends Vo{operation;key="x-fern-audiences";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(n=>typeof n=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{audiences:r}}}});var eKr,EWl=h(()=>{"use strict";zn();AR();eKr=class extends Vo{node;key="x-fern-availability";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t==null||typeof t!="string")return;switch(t.toUpperCase().replace(/[-_\s]/g,"_")){case"IN_DEVELOPMENT":return eh.InDevelopment;case"PRE_RELEASE":return eh.PreRelease;case"GENERAL_AVAILABILITY":case"GENERALLY_AVAILABLE":case"GA":case"STABLE":return eh.GeneralAvailability;case"DEPRECATED":return eh.Deprecated;case"ALPHA":return eh.Alpha;case"BETA":return eh.Beta;case"PREVIEW":return eh.Preview;case"LEGACY":return eh.Legacy;default:return}}}});var Bct,TGo=h(()=>{"use strict";AR();Bct=class extends Vo{node;key="x-fern-discriminated";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t!=null&&typeof t=="boolean")return t}}});var Dct,OGo=h(()=>{"use strict";AR();Dct=class extends Vo{node;key="x-fern-discriminator-context";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t==="data"||t==="protocol")return t}}});var cGm,lGm,IWl,vWl=h(()=>{"use strict";nn();cGm=Xt.object({snake:Xt.string().optional(),camel:Xt.string().optional(),screamingSnake:Xt.string().optional(),pascal:Xt.string().optional()}),lGm=Xt.object({description:Xt.string().optional(),name:Xt.string().optional(),casing:cGm.optional()}),IWl=Xt.record(lGm)});var Rct,PGo=h(()=>{"use strict";AR();vWl();Rct=class extends Vo{schema;key="x-fern-enum";constructor({breadcrumbs:t,schema:r,context:n}){super({breadcrumbs:t,context:n}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t==null)return;let r=IWl.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-enum extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data}}});var IUe,CWl=h(()=>{"use strict";AR();IUe=class extends Vo{operation;key="x-fern-ignore";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-ignore",path:this.breadcrumbs});return}return t}}}});var tKr,xWl=h(()=>{"use strict";AR();tKr=class extends Vo{parameter;key="x-fern-optional";constructor({breadcrumbs:t,parameter:r,context:n}){super({breadcrumbs:t,context:n}),this.parameter=r}convert(){let t=this.getExtensionValue(this.parameter);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-optional",path:this.breadcrumbs});return}return t}}}});var rKr,SWl=h(()=>{"use strict";AR();rKr=class extends Vo{operation;key="x-fern-sdk-group-name";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(n=>typeof n=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{groups:r}}}});var nKr,wWl=h(()=>{"use strict";AR();nKr=class extends Vo{operation;key="x-fern-sdk-method-name";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null&&typeof t=="string")return{methodName:t}}}});var iKr,TWl=h(()=>{"use strict";AR();iKr=class extends Vo{operation;key="x-fern-server-name";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation,"x-name");if(!(t==null||typeof t!="string"))return t}}});var oKr,OWl=h(()=>{"use strict";AR();oKr=class extends Vo{schema;key="x-fern-type";constructor({breadcrumbs:t,schema:r,context:n}){super({breadcrumbs:t,context:n}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t!=null&&typeof t=="string")return t}}});var sKr,PWl=h(()=>{"use strict";AR();sKr=class extends Vo{schema;key="x-fern-type-name";constructor({breadcrumbs:t,schema:r,context:n}){super({breadcrumbs:t,context:n}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(typeof t=="string")return t}}});function uGm({isText:e,isAttribute:t}){return e?rQ.Text:t?rQ.Attribute:rQ.Element}function RWl(e){return typeof e=="object"&&e!=null}function aKr(e,t){if(!(typeof e!="object"||e==null))return e[t]}function BGo(...e){return e.find(t=>t!=null)}var BWl,DWl,kct,Fct,cKr=h(()=>{"use strict";zn();AR();BWl="x-fern-xml-text",DWl="x-fern-xml-list-separator",kct=class extends Vo{schema;fallbackName;key="xml";constructor({breadcrumbs:t,schema:r,fallbackName:n,context:i}){super({breadcrumbs:t,context:i}),this.schema=r,this.fallbackName=n}convert(){let t=this.getExtensionValue(this.schema);if(RWl(t))return{name:typeof t.name=="string"?t.name:this.fallbackName,namespace:typeof t.namespace=="string"?t.namespace:void 0,prefix:typeof t.prefix=="string"?t.prefix:void 0}}},Fct=class extends Vo{propertySchema;resolvedPropertySchema;key="xml";constructor({breadcrumbs:t,propertySchema:r,resolvedPropertySchema:n,context:i}){super({breadcrumbs:t,context:i}),this.propertySchema=r,this.resolvedPropertySchema=n}convert(){let t=this.propertySchema,r=this.resolvedPropertySchema,n=BGo(this.getExtensionValue(t),this.getExtensionValue(r)),i=BGo(aKr(t,BWl),aKr(r,BWl)),o=BGo(aKr(t,DWl),aKr(r,DWl)),s=RWl(n)?n:{};return{kind:uGm({isText:i===!0,isAttribute:s.attribute===!0}),name:typeof s.name=="string"?s.name:void 0,wrapped:typeof s.wrapped=="boolean"?s.wrapped:void 0,listSeparator:typeof o=="string"?o:void 0}}}});var vC={};ne(vC,{AudienceExtension:()=>Pct,FernAvailabilityExtension:()=>eKr,FernDiscriminatedExtension:()=>Bct,FernDiscriminatorContextExtension:()=>Dct,FernEnumExtension:()=>Rct,FernIgnoreExtension:()=>IUe,FernOptionalExtension:()=>tKr,FernTypeExtension:()=>oKr,FernTypeNameExtension:()=>sKr,SdkGroupNameExtension:()=>rKr,SdkMethodNameExtension:()=>nKr,ServerFromOperationNameExtension:()=>iKr,XmlPropertyExtension:()=>Fct,XmlSchemaExtension:()=>kct});var DGo=h(()=>{"use strict";wGo();EWl();TGo();OGo();PGo();CWl();xWl();SWl();wWl();TWl();OWl();PWl();cKr()});function FWl(e){let t=new Map,r=(i,o)=>{if(t.has(i))return t.get(i);let s=e[i];if(s==null||o.has(i))return;o.add(i);let a=n(s,o);return o.delete(i),t.set(i,a),a},n=(i,o)=>{let s=a=>dw.named({name:i.name,shape:a});switch(i.shape.type){case"object":return s(KD.Object);case"enum":return s(KD.Enum);case"union":return s(KD.Union);case"undiscriminatedUnion":return s(KD.UndiscriminatedUnion);case"alias":{let{resolvedType:a}=i.shape,c=kWl(a);return c!=null?r(c,o):a}default:return}};for(let[i,o]of Object.entries(e)){if(o.shape.type!=="alias"||kWl(o.shape.resolvedType)==null)continue;let s=r(i,new Set);s!=null&&(e[i]={...o,shape:ic.alias({aliasOf:o.shape.aliasOf,resolvedType:s})})}}function kWl(e){if(e.type!=="named")return;let t=e;return e.shape==null&&typeof t.typeId=="string"?t.typeId:void 0}var NWl=h(()=>{"use strict";zn()});var tJ,jWl=h(()=>{"use strict";zn();sc();xo();$Hr();DGo();NWl();tJ=class extends Ki{ir;audiences;irGraph;constructor({breadcrumbs:t=[],context:r,audiences:n}){super({breadcrumbs:t,context:r}),this.audiences=n,this.irGraph=new M4e(n),this.ir={auth:{docs:void 0,requirement:$t.AuthSchemesRequirement.All,schemes:[]},selfHosted:!1,types:{},services:{},errors:{},webhookGroups:{},websocketChannels:void 0,headers:[],idempotencyHeaders:[],apiVersion:void 0,apiDisplayName:void 0,apiDocs:void 0,basePath:void 0,pathParameters:[],errorDiscriminationStrategy:$t.ErrorDiscriminationStrategy.statusCode(),variables:[],globalParameters:void 0,serviceTypeReferenceInfo:{sharedTypes:[],typesReferencedOnlyByService:{}},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0,environments:void 0,fdrApiDefinitionId:void 0,rootPackage:this.createPackage(),subpackages:{},sdkConfig:{hasFileDownloadEndpoints:!1,hasPaginatedEndpoints:!1,hasStreamingEndpoints:!1,isAuthMandatory:!0,idempotencyKeyGeneration:void 0,webhookSignatureVerification:void 0,platformHeaders:{language:"",sdkName:"",sdkVersion:"",userAgent:void 0}},audiences:void 0,generationMetadata:void 0,apiPlayground:void 0,casingsConfig:void 0,specVersion:void 0}}removeXFernIgnores({document:t,breadcrumbs:r=[]}){return Array.isArray(t)?t.filter((n,i)=>!new IUe({breadcrumbs:[...r,String(i)],operation:n,context:this.context}).convert()).map((n,i)=>this.removeXFernIgnores({document:n,breadcrumbs:[...r,String(i)]})):t!=null&&typeof t=="object"?Object.fromEntries(Object.entries(t).filter(([n,i])=>!new IUe({breadcrumbs:[...r,n],operation:i,context:this.context}).convert()).map(([n,i])=>[n,this.removeXFernIgnores({document:i,breadcrumbs:[...r,n]})])):t}finalizeIr(){let t=Object.values(this.ir.services).some(a=>a.endpoints.some(c=>c.response?.body?.type==="streaming")),r=Object.values(this.ir.services).some(a=>a.endpoints.some(c=>c.pagination!=null)),n=Object.values(this.ir.services).some(a=>a.endpoints.some(c=>c.response?.body?.type==="fileDownload"));this.ir.sdkConfig={...this.ir.sdkConfig,hasStreamingEndpoints:t,hasPaginatedEndpoints:r,hasFileDownloadEndpoints:n},$5t(this.ir,{onWarning:a=>this.context.logger.warn(a)}),FWl(this.ir.types);let i={...this.ir,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})},audiences:this.audiences.type==="select"?this.audiences.audiences:void 0};this.irGraph.hasNoAudiences()||(i=this.filterIrForAudiences(i)),K5t({ir:i});let o=this.context.exampleGenerationArgs,s=d4o({ir:i,exampleGeneration:o,logger:this.context.logger});if(this.context.generateV1Examples){let a=Y5t({ir:i,exampleGeneration:o});return{...i,...a,...s}}return{...i,...s}}filterIrForAudiences(t){return{...Z5t(t,this.irGraph.build()),sdkConfig:t.sdkConfig,subpackages:t.subpackages,rootPackage:t.rootPackage}}async resolveAllExternalRefs({spec:t}){let r=[t];for(let n=0;n<r.length;n++){let i=r[n];i!=null&&(Array.isArray(i)?await this.resolveExternalRefsInArray(i,r):typeof i=="object"&&await this.resolveExternalRefsInObject(i,r))}return t}async resolveExternalRefsInArray(t,r){for(let n=0;n<t.length;n++)t[n]=await this.resolveReferenceChain(t[n],r)}async resolveExternalRefsInObject(t,r){for(let[n,i]of Object.entries(t))t[n]=await this.resolveReferenceChain(i,r)}async resolveReferenceChain(t,r){let n=t;if(!this.context.isReferenceObject(n))return r.push(n),t;for(;this.context.isReferenceObject(n);){let i=this.context.isExternalReference(n.$ref),o=await this.context.resolveMaybeExternalReference(n);if(o.resolved){if(n=o.value,i)return n}else return t}return t}shouldAddServerToCollectedServers({server:t,currentServers:r,specType:n="openapi"}){return n==="openapi"?!r.some(i=>i.url===t.url&&"x-fern-server-name"in i&&"x-fern-server-name"in t&&i["x-fern-server-name"]===t["x-fern-server-name"]):!r.some(i=>i.url===t.url&&"name"in i&&"name"in t&&i.name===t.name)}addEndpointToIr({endpoint:t,audiences:r,endpointGroup:n,endpointGroupDisplayName:i,endpointGroupDescription:o,serviceName:s,inlinedRequestPropertiesByAudience:a,queryParametersByAudience:c}){let l=this.context.getGroup({groupParts:n,namespace:this.context.namespace}),u=this.getOrCreatePackage({group:n});u!==this.ir.rootPackage&&u.docs==null&&o!=null&&(u.docs=o);let p=[...l].map(m=>this.context.casingsGenerator.generateName(m)),d=p[p.length-1];u.service==null&&(u.service=s??`service_${l.map(m=>ao(m)).join("/")}`),this.ir.services[u.service]==null&&(this.ir.services[u.service]=this.createNewService({allParts:p,finalpart:d,endpointGroupDisplayName:i})),this.ir.services[u.service]?.endpoints.push(t);let f=this.ir.services[u.service];f!=null&&(this.irGraph.addEndpoint(f,t),this.irGraph.markEndpointForAudience(f.name,[t],r),a!=null&&Object.keys(a).length>0&&this.irGraph.markInlinedRequestPropertiesForAudiences(t.id,a),c!=null&&Object.keys(c).length>0&&this.irGraph.markQueryParametersForAudiences(t.id,c))}addWebhookToIr({webhook:t,operationId:r,audiences:n,group:i,inlinedPayloadPropertiesByAudience:o}){let s=i?.join(".")??r,a=this.getOrCreatePackage({group:i});this.ir.webhookGroups[s]==null&&(this.ir.webhookGroups[s]=[]),this.ir.webhookGroups[s].push(t),a.webhooks=s;let c=this.context.createFernFilepath();this.irGraph.addWebhook(c,t),n!=null&&this.irGraph.markWebhookForAudiences(c,t,n),t.id!=null&&o!=null&&Object.keys(o).length>0&&this.irGraph.markInlinedWebhookPayloadPropertiesForAudiences(t.id,o)}addWebsocketChannelToIr({websocketChannel:t,channelPath:r,audiences:n,websocketGroup:i}){let o=ao(i?.join(".")),s=ao(r),a=this.context.namespace?`${ao(this.context.namespace)}/`:"",c=o?`channel_${a}${o}`:`channel_${a}${s}`,l=i?this.getOrCreatePackage({group:i}):this.getOrCreatePackage({group:[s]});this.ir.websocketChannels={...this.ir.websocketChannels,[c]:t},c!==""?l.websocket==null&&(l.websocket=c):this.ir.rootPackage.websocket="";let u=this.context.createFernFilepath();this.irGraph.addChannel(u,c,t),n!=null&&this.irGraph.markChannelForAudiences(u,c,n)}addAuthToIR(t){this.ir.auth=t}addErrorsToIr(t){this.ir.errors=t;for(let r of Object.values(t))this.irGraph.addError(r)}addGlobalHeadersToIr(t){this.ir.headers=t}addEnvironmentsToIr({environmentConfig:t,audiences:r}){if(this.ir.environments=t,t==null)return;let n=t.environments.environments,i=r==null||n.every(o=>o.audiences==null);for(let o of n)this.irGraph.markEnvironmentForAudiences(o,r?.[o.id]??[],i)}addTypeToRootPackage(t){this.ir.rootPackage.types.push(t)}addSchemaOutputToIr(t,r){let{convertedSchema:n,inlinedTypes:i}=r,o=this.context.getNamespacedSchemaId(t),a=Object.keys(i).some(c=>c===o)?`${o}Wrapper`:o;this.addTypeToPackage(a),this.addTypesToIr({...i,[a]:n})}addTypeToPackage(t){let r=this.context.getGroup({groupParts:[],namespace:this.context.namespace});this.getOrCreatePackage({group:r}).types.push(t)}addTypesToIr(t){Object.assign(this.ir.types,Object.fromEntries(Object.entries(t).map(([r,n])=>[r,n.typeDeclaration])));for(let r of Object.values(t))this.irGraph.addType({declaredTypeName:r.typeDeclaration.name,descendantTypeIds:r.typeDeclaration.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:r.propertiesByAudience,descendantFilepaths:new Set}),this.irGraph.markTypeForAudiences(r.typeDeclaration.name,r.audiences)}updateEndpointsWithDefaultUrl(t){if(t!=null)for(let r of Object.values(this.ir.services))for(let n of r.endpoints)n.baseUrl==null&&(n.baseUrl=t)}createNewService({allParts:t,finalpart:r,endpointGroupDisplayName:n}){return{name:{fernFilepath:{allParts:t,packagePath:t.slice(0,-1),file:r}},displayName:n,basePath:jy(""),headers:[],pathParameters:[],availability:void 0,endpoints:[],transport:void 0,encoding:void 0,audiences:void 0}}createPackage(t={}){return{fernFilepath:this.context.createFernFilepath(t),service:void 0,types:[],errors:[],subpackages:[],docs:void 0,webhooks:void 0,websocket:void 0,hasEndpointsInTree:!1,hasWebSocketInTree:void 0,navigationConfig:void 0}}getOrCreatePackage({group:t}){let r=[];if(this.context.namespace!=null&&r.push(this.context.namespace),r.push(...(t??[]).map(i=>ao(i))),r.length==0)return this.ir.rootPackage;let n=this.ir.rootPackage;for(let i=0;i<r.length;i++){let o=r[i]??"",a=`subpackage_${r.slice(0,i+1).join("/")}`;this.ir.subpackages[a]==null&&(this.ir.subpackages[a]={name:this.context.casingsGenerator.generateName(o),displayName:void 0,...this.createPackage({name:o})});let c=this.ir.subpackages[a];n.subpackages.includes(a)||n.subpackages.push(a),n=c}return n}}});function vUe(e){return typeof e=="object"&&e!==null&&!("$ref"in e)}function dGm(e){if(!vUe(e))return!1;if("nullable"in e&&e.nullable===!0)return!0;let t=r=>Array.isArray(r)&&r.some(n=>vUe(n)&&n.type==="null");return t(e.anyOf)||t(e.oneOf)}function mGm(e){return e.type==="array"||e.properties||e.oneOf||e.anyOf||e.allOf||e.additionalProperties?!1:!!(e.type==="string"||e.type==="number"||e.type==="integer"||e.type==="boolean"||e.const!==void 0||Array.isArray(e.enum)&&e.enum.length>0)}function QWl(e){if(e.const!==void 0)return e.const;if(Array.isArray(e.enum)&&e.enum.length>0)return e.enum[0]}var pGm,zWl,fGm,Bw,BSe=h(()=>{"use strict";mt();Uo();pGm=/^literal<\s*(?:"(.*)"|(true|false))\s*>$/,zWl=new WeakMap,fGm=new Set(["type","properties","required","allOf","description","title","deprecated","readOnly","writeOnly","xml","externalDocs","discriminator"]);Bw=class e extends Ki{MAX_DEPTH=12;EXAMPLE_STRING=Mo.STRING;EXAMPLE_NUMBER=Mo.DOUBLE;EXAMPLE_BOOLEAN=Mo.BOOLEAN;EXAMPLE_INTEGER=Mo.INT;EXAMPLE_DATE=Mo.DATE;EXAMPLE_DATE_TIME=Mo.DATE_TIME;schema;example;depth;exampleGenerationStrategy;generateOptionalProperties;seenRefs;sharedState;constructor({breadcrumbs:t,context:r,schema:n,example:i,depth:o=0,exampleGenerationStrategy:s,generateOptionalProperties:a=!1,seenRefs:c=new Set}){super({breadcrumbs:t,context:r}),this.example=i,this.schema=n,this.depth=o,this.exampleGenerationStrategy=s,this.generateOptionalProperties=a,this.seenRefs=c;let l=zWl.get(r);l!=null?this.sharedState=l:(this.sharedState={mergedAllOfProperties:new WeakMap,mergeOnlyAllOfSchemas:new WeakMap},zWl.set(r,this.sharedState))}convert(){if(this.depth>this.MAX_DEPTH)return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:typeof this.example<"u"?this.example:{},errors:[]};if(this.context.isReferenceObject(this.schema)){let n=this.schema.$ref;if(this.seenRefs.has(n))return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}}let t=this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(t!=null&&this.context.isReferenceObject(t))return new e({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(t==null)return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:"Schema is not resolvable",path:this.breadcrumbs}]};if(typeof t!="object")return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Schema should be an object: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]};if("nullable"in t&&t.nullable===!0&&this.example===null)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let r=this.maybeConvertLiteralFernType(t);return r??(Array.isArray(t.type)?this.convertSchemaTypeArray({resolvedSchema:t}):t.type=="null"?this.convertNull():t.type=="boolean"?this.convertBoolean():t.enum!=null?this.convertEnum(t):t.type=="number"?this.convertNumber():t.type=="string"?this.convertString():t.type=="integer"?this.convertInteger():t.type=="array"?this.convertArray({resolvedSchema:t}):"oneOf"in t&&t.oneOf!=null?this.convertOneOf({resolvedSchema:t}):"anyOf"in t&&t.anyOf!=null?this.convertAnyOf({resolvedSchema:t}):t.type=="object"||t.properties!=null||t.allOf!=null?this.convertObject({resolvedSchema:t}):typeof t=="object"&&Object.keys(t).length===0?{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Unsupported schema type: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]})}convertNull(){let t=this.example===null;return t?{isValid:t,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Example is not null: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertBoolean(){let t=typeof this.example=="boolean";if(t)return{isValid:t,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.default:this.schema.default,n=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.const:this.schema.const;return typeof r=="boolean"||typeof n=="boolean"?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n??r,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_BOOLEAN,errors:[{message:`Example is not a boolean: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertEnum(t){let r=t.enum?.includes(this.example)??!1;if(r)return{isValid:r,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let n=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return n!==void 0&&t.enum?.includes(n)?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n,errors:[]}:{isValid:r,coerced:!1,usedProvidedExample:!1,validExample:t.enum?.[0],errors:[{message:`Example is not one of the allowed enum values: ${JSON.stringify(t.enum,null,2)}`,path:this.breadcrumbs}]}}convertNumber(){if(typeof this.example=="number")return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let t=Number(this.example);if(!isNaN(t))return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):this.schema,n=r?.default;return typeof n=="number"?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.adjustNumberToConstraints(this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_NUMBER,r),errors:[{message:`Example is not a number: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}adjustNumberToConstraints(t,r){if(r==null)return this.context.logger.debug("[ExampleConverter.adjustNumberToConstraints] Schema object is null, returning original number","number:",t.toString()),t;let{minimum:n,maximum:i,exclusiveMinimum:o,exclusiveMaximum:s}=r,a;o!=null?typeof o=="boolean"?a=n!=null?n+Math.max(Number.EPSILON,Math.abs(n)*1e-10):void 0:a=o+Math.max(Number.EPSILON,Math.abs(o)*1e-10):n!=null&&(a=n);let c;return s!=null?typeof s=="boolean"?c=i!=null?i-Math.max(Number.EPSILON,Math.abs(i)*Number.EPSILON):void 0:c=s-Math.max(Number.EPSILON,Math.abs(s)*Number.EPSILON):i!=null&&(c=i),a!==void 0&&c!==void 0?(t<a||t>c)&&(t=a+(c-a)/2):a!==void 0&&t<a?t=a+Math.abs(a*.1):c!==void 0&&t>c&&(t=c-Math.abs(c*.1)),Number(Number(t).toPrecision(3))}convertString(){if(typeof this.example=="string")return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};if(typeof this.example!="object"&&!Array.isArray(this.example)&&this.example!=null)return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:String(this.example),errors:[]};let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;if(typeof t=="string")return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):this.schema,n=r?.format==="date"?this.EXAMPLE_DATE:r?.format==="date-time"?this.EXAMPLE_DATE_TIME:this.EXAMPLE_STRING;return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??n,errors:[{message:`Example cannot be converted to string: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertInteger(){if(typeof this.example=="number"&&Number.isInteger(this.example))return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};if(typeof this.example=="string"){let r=Number(this.example);if(!isNaN(r)&&Number.isInteger(r))return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:r,errors:[]}}let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return typeof t=="number"&&Number.isInteger(t)?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:t,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_INTEGER,errors:[{message:`Example is not an integer: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertArray({resolvedSchema:t}){if(t.type!="array")return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};t.items==null&&(t.items={type:"string"});let r=this.example==null,n=this.example??t.example,o=(Array.isArray(n)?n:[n]).map(c=>new e({breadcrumbs:[...this.breadcrumbs,"items"],context:this.context,schema:t.items,example:c,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),s=o.every(c=>c?.isValid??!1)&&!r,a=!r&&o.some(c=>c.usedProvidedExample);return{isValid:s,coerced:!1,usedProvidedExample:a,validExample:o.map(c=>c.validExample),errors:s?[]:o.flatMap(c=>c.errors)}}convertObject({resolvedSchema:t}){if(t.type=="object"&&t.properties==null&&t.allOf==null)return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example??{},errors:[]};let r=typeof this.example!="object"||this.example==null?{}:this.example,n=this.example===void 0&&this.canGenerateFromMergedAllOf(t),{mergedProperties:i,mergedRequired:o}=this.mergeAllOfProperties(t,new Set,0,n),s=Object.entries(i).map(([b,I])=>{if(typeof I!="object")return{key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if(this.isDeprecatedProperty(I)&&!this.isRequiredProperty({key:b,resolvedSchema:t}))return{key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("readOnly"in I&&I.readOnly===!0&&"writeOnly"in I&&I.writeOnly===!0)return{key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("readOnly"in I&&I.readOnly===!0&&this.exampleGenerationStrategy==="request")return{key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("writeOnly"in I&&I.writeOnly===!0&&this.exampleGenerationStrategy==="response")return{key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};let C=dGm(I),x=!(b in r)||!C&&r[b]==null||C&&r[b]===void 0,S=!o.includes(b);if(x&&S){if(this.example===void 0&&this.generateOptionalProperties){let P=this.maybeResolveSchemaExample(I),D=new e({breadcrumbs:[...this.breadcrumbs,b],context:this.context,schema:I,example:P,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()});return{key:b,result:D.convert()}}return{key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}}}else{let P=r[b],D=P!==void 0?P:this.maybeResolveSchemaExample(I),O=new e({breadcrumbs:[...this.breadcrumbs,b],context:this.context,schema:I,example:D,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();return{key:b,result:O}}}),a=n?[]:(t.allOf??[]).map((b,I)=>{let C=this.context.resolveMaybeReference({schemaOrReference:b,breadcrumbs:[...this.breadcrumbs,`allOf[${I}]`],skipErrorCollector:!0});return C&&this.isConstraintOnlySchema(C)?{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}:new e({breadcrumbs:[...this.breadcrumbs,`allOf[${I}]`],context:this.context,schema:{...t,...b,allOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()}),c=this.example!==void 0&&(s.some(({result:b})=>b.usedProvidedExample)||a.some(b=>b.usedProvidedExample)),l=Object.fromEntries(s.map(({key:b,result:I})=>[b,I.validExample]).filter(([b,I])=>I!==void 0));for(let b of a)if(typeof b.validExample=="object"&&b.validExample!==null){let I=b.validExample,C=Object.fromEntries(Object.entries(I).filter(([x,S])=>S!==void 0));for(let[x,S]of Object.entries(C))(!(x in l)||l[x]==null)&&(l[x]=S)}let u=[],p=this.collectAllPropertyKeys(t),d=Object.keys(r).filter(b=>!p.has(b)),f=this.schemaHasPatternProperties(t),m=f?d:[],g=f?[]:d;if(m.forEach(b=>{u.push({key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:r[b],errors:[]}})}),g.length>0)if(t.additionalProperties===!1)g.forEach(b=>{let I=[...this.breadcrumbs,b].join("."),C={message:`Found unexpected property '${b}' in example. This property does not exist in the schema${I?` at path: ${I}`:""}`,path:[...this.breadcrumbs,b]};u.push({key:b,result:{isValid:!1,coerced:!1,usedProvidedExample:!0,validExample:void 0,errors:[C]}})});else if(t.additionalProperties===!0||t.additionalProperties===void 0)g.forEach(b=>{u.push({key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:r[b],errors:[]}})});else{let b=t.additionalProperties;g.forEach(I=>{let x=new e({breadcrumbs:[...this.breadcrumbs,I],context:this.context,schema:b,example:r[I],depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();u.push({key:I,result:x})})}for(let{key:b,result:I}of u)I.validExample!==void 0&&l[b]===void 0&&(l[b]=I.validExample);let A=s.every(b=>b.result.isValid)&&a.every(b=>b.isValid)&&u.every(({result:b})=>b.isValid);if(Object.keys(l).length===0){let b=a.find(I=>I.validExample!==void 0&&(typeof I.validExample!="object"||I.validExample===null));b&&(l=b.validExample)}return{isValid:A,coerced:!1,usedProvidedExample:c,validExample:l,errors:[...s.flatMap(({result:b})=>b.errors),...a.flatMap(b=>b.errors),...u.flatMap(({result:b})=>b.errors)]}}convertSchemaTypeArray({resolvedSchema:t}){if(!Array.isArray(t.type))return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};if(t.type.length===1)return new e({breadcrumbs:this.breadcrumbs,context:this.context,schema:{...t,type:t.type[0]},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();let r=t.type.map((a,c)=>new e({breadcrumbs:[...this.breadcrumbs,`type[${c}]`],context:this.context,schema:{...t,type:a},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),n=r.some(a=>a?.isValid??!1),o=r.find(a=>a.isValid)?.validExample??r[0]?.validExample??null,s=r.some(a=>a.usedProvidedExample);return{isValid:n,coerced:!1,usedProvidedExample:s,validExample:o,errors:n?[]:r.flatMap(a=>a?.errors??[])}}convertUnion({resolvedSchema:t,unionType:r}){let n=r==="oneOf"?t.oneOf:t.anyOf;if(!(r in t)||n==null)return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};let i=this.example!==void 0?this.example:this.maybeResolveSchemaExample(t);if(this.example===void 0){let d=[];for(let m of n){if(!m)continue;let g=this.context.resolveMaybeReference({schemaOrReference:m,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});g&&d.push(g)}if(d.length>0&&d.every(m=>mGm(m))){let m=d.findIndex(g=>QWl(g)!==void 0);if(m!==-1){let g=n[m],A=d[m];if(g&&A){let b=QWl(A),C=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${m}]`],context:this.context,schema:r==="oneOf"?{...t,...g,oneOf:void 0}:g,example:b,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(C.isValid)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:C.validExample,errors:[]}}}}}let o=[],s=null,a=null;for(let d=0;d<n.length;d++){let f=n[d];if(!f)continue;let m=r==="oneOf"?{...t,...f,oneOf:void 0}:f,g=i!==void 0?i:this.maybeResolveSchemaExample(m),b=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${d}]`],context:this.context,schema:m,example:g,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(b.isValid&&!b.coerced&&b.usedProvidedExample)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:b.validExample,errors:[]};if(b.isValid&&!b.coerced&&this.example===void 0)return{isValid:!0,coerced:!1,usedProvidedExample:b.usedProvidedExample,validExample:b.validExample,errors:[]};o.push(b),b.isValid&&b.usedProvidedExample&&a===null&&(a=b),b.isValid&&s===null&&(s=b)}let c=a??s,l=c!==null,u=c?.validExample??o[0]?.validExample,p=c?.usedProvidedExample??!1;return{isValid:l,coerced:!1,usedProvidedExample:p,validExample:u,errors:l?[]:o.flatMap(d=>d.errors)}}convertOneOf({resolvedSchema:t}){return this.convertUnion({resolvedSchema:t,unionType:"oneOf"})}convertAnyOf({resolvedSchema:t}){return this.convertUnion({resolvedSchema:t,unionType:"anyOf"})}getMaybeUpdatedSeenRefs(){let t=new Set(this.seenRefs);return this.context.isReferenceObject(this.schema)&&t.add(this.schema.$ref),t}maybeResolveSchemaExample(t){if("example"in t)return t.example;if("examples"in t){let n=t.examples;if(Array.isArray(n)&&n.length>0)return n[0];if(n!=null&&typeof n=="object")return Object.values(n)[0]}let r=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(r!=null){if("example"in r)return r.example;if("examples"in r){let n=r.examples;return Array.isArray(n)&&n.length>0?n[0]:Object.values(n??{})[0]}}}maybeConvertLiteralFernType(t){let r=t["x-fern-type"];if(typeof r!="string")return;let n=r.match(pGm);if(n!=null){if(n[1]!=null)return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n[1],errors:[]};if(n[2]!=null)return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n[2]==="true",errors:[]}}}mergeAllOfProperties(t,r=new Set,n=0,i=!1){if(i){let p=this.sharedState.mergedAllOfProperties.get(t)?.get(n);if(p!=null)return p}let o=t.properties??{},s=t.required??[];if(n>this.MAX_DEPTH||t.allOf==null||t.allOf.length===0){let p={mergedProperties:o,mergedRequired:s};return i&&this.cacheMergedAllOfProperties(t,n,p),p}let a={},c=new Set(s);for(let p of t.allOf){let d=this.context.resolveMaybeReference({schemaOrReference:p,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(d==null)continue;let f=this.context.isReferenceObject(p)?p.$ref:void 0;if(!(f!=null&&r.has(f))){if(d.allOf!=null&&d.allOf.length>0){let m=new Set(r);f!=null&&m.add(f);let g=this.mergeAllOfProperties(d,m,n+1,i);for(let A of g.mergedRequired)c.add(A);for(let[A,b]of Object.entries(g.mergedProperties))if(typeof b=="object"&&b!==null){let I=a[A];I!=null&&vUe(I)&&vUe(b)?a[A]={...I,...b}:a[A]=b}continue}if(d.required!=null)for(let m of d.required)c.add(m);if(d.properties!=null){for(let[m,g]of Object.entries(d.properties))if(typeof g=="object"&&g!==null){let A=a[m];A!=null&&vUe(A)&&vUe(g)?a[m]={...A,...g}:a[m]=g}}}}let l={...o};for(let[p,d]of Object.entries(l)){let f=a[p];if(f==null||!vUe(d))continue;let m="$ref"in f?this.context.resolveMaybeReference({schemaOrReference:f,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):f;m!=null&&(l[p]={...m,...d})}for(let[p,d]of Object.entries(a))p in l||(l[p]=d);let u={mergedProperties:l,mergedRequired:[...c]};return i&&this.cacheMergedAllOfProperties(t,n,u),u}cacheMergedAllOfProperties(t,r,n){let i=this.sharedState.mergedAllOfProperties.get(t);i!=null?i.set(r,n):this.sharedState.mergedAllOfProperties.set(t,new Map([[r,n]]))}canGenerateFromMergedAllOf(t,r=new WeakSet){if(t.allOf==null||t.allOf.length===0||!this.isMergeOnlyObjectSchema(t))return!1;let n=this.sharedState.mergeOnlyAllOfSchemas.get(t);if(n!=null)return n;if(r.has(t))return!1;r.add(t);let i=t.allOf.every(o=>{let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});return s==null||!this.isMergeOnlyObjectSchema(s)?!1:s.allOf==null||s.allOf.length===0?!0:this.canGenerateFromMergedAllOf(s,r)});return r.delete(t),this.sharedState.mergeOnlyAllOfSchemas.set(t,i),i}isMergeOnlyObjectSchema(t){return t.type!=null&&t.type!=="object"||t.type==null&&t.properties==null&&t.allOf==null?!1:Object.keys(t).every(r=>fGm.has(r))}isConstraintOnlySchema(t){if(typeof t!="object"||t===null||t.type!==void 0||t.properties!==void 0||t.allOf!==void 0||t.oneOf!==void 0||t.anyOf!==void 0||"items"in t||t.additionalProperties!==void 0||t.enum!==void 0||t.const!==void 0)return!1;let r=new Set(["required","description","title","deprecated","readOnly","writeOnly","nullable","example","examples","default","minLength","maxLength","minimum","maximum","exclusiveMinimum","exclusiveMaximum","minItems","maxItems","uniqueItems","pattern","format"]),n=Object.keys(t);return n.length>0&&n.every(i=>r.has(i))}isDeprecatedProperty(t){return t!=null&&"availability"in t&&t.availability==="deprecated"}isRequiredProperty({key:t,resolvedSchema:r}){return r.required?.includes(t)??!1}collectAllPropertyKeys(t,r=new Set){let n=new Set;if(t.properties)for(let i of Object.keys(t.properties))n.add(i);for(let i of t.allOf??[]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)){r.add(s);let a=this.collectAllPropertyKeys(o,r);for(let c of a)n.add(c)}}}for(let i of[...t.oneOf??[],...t.anyOf??[]]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)){r.add(s);let a=this.collectAllPropertyKeys(o,r);for(let c of a)n.add(c)}}}return n}schemaHasPatternProperties(t,r=new Set){let n=t.patternProperties;if(n&&typeof n=="object"&&Object.keys(n).length>0)return!0;for(let i of[...t.allOf??[],...t.oneOf??[],...t.anyOf??[]]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)&&(r.add(s),this.schemaHasPatternProperties(o,r)))return!0}}return!1}}});function MWl(e){return fC({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return Hr.primitive({v1:"BASE_64",v2:di.base64({})});case"BOOLEAN":return Hr.primitive({v1:"BOOLEAN",v2:di.boolean({default:void 0})});case"DATE":return Hr.primitive({v1:"DATE",v2:di.date({})});case"DATE_TIME":return Hr.primitive({v1:"DATE_TIME",v2:di.dateTime({})});case"DATE_TIME_RFC_2822":return Hr.primitive({v1:"DATE_TIME_RFC_2822",v2:di.dateTimeRfc2822({})});case"FLOAT":return Hr.primitive({v1:"FLOAT",v2:di.float({default:void 0,validation:void 0})});case"DOUBLE":return Hr.primitive({v1:"DOUBLE",v2:di.double({default:void 0,validation:void 0})});case"UINT":return Hr.primitive({v1:"UINT",v2:di.uint({default:void 0,validation:void 0})});case"UINT_64":return Hr.primitive({v1:"UINT_64",v2:di.uint64({default:void 0,validation:void 0})});case"INTEGER":return Hr.primitive({v1:"INTEGER",v2:di.integer({default:void 0,validation:void 0})});case"LONG":return Hr.primitive({v1:"LONG",v2:di.long({default:void 0,validation:void 0})});case"STRING":return Hr.primitive({v1:"STRING",v2:di.string({default:void 0,validation:void 0})});case"UUID":return Hr.primitive({v1:"UUID",v2:di.uuid({})});case"BIG_INTEGER":return Hr.primitive({v1:"BIG_INTEGER",v2:di.bigInteger({default:void 0})});default:return}},unknown:()=>Hr.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return Hr.container(As.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return Hr.container(As.list(t))},optional:t=>{if(t!=null)return Hr.container(As.optional(t))},nullable:t=>{if(t!=null)return Hr.container(As.nullable(t))},set:t=>{if(t!=null)return Hr.container(As.set(t))},literal:t=>Hr.container(As.literal(t._visit({string:r=>kE.string(r),boolean:r=>kE.boolean(r),_other:()=>{throw new T({message:"Unexpected literal type",code:T.Code.InternalError})}}))),named:()=>{}}})}var LWl=h(()=>{"use strict";lo();zn();Bt()});var DSe,lKr=h(()=>{"use strict";zn();sc();Uo();DSe=class extends Ki{schema;maybeFernEnum;forwardCompatible;constructor({context:t,breadcrumbs:r,schema:n,maybeFernEnum:i,forwardCompatible:o}){super({context:t,breadcrumbs:r}),this.schema=n,this.maybeFernEnum=i,this.forwardCompatible=o??!1}convert(){if(!this.schema.enum)return;let r=this.schema.enum.filter(i=>typeof i=="string"||typeof i=="number").map(i=>{let o=i.toString(),s=this.maybeFernEnum?.[o],a=s?.name??o;return{name:this.context.casingsGenerator.generateNameAndWireValue({name:a,wireValue:o}),docs:s?.description,availability:void 0,casing:s?.casing}});if(r.length===0){this.context.errorCollector.collect({message:`Received enum schema with no valid values: ${JSON.stringify(this.schema)}`,path:this.breadcrumbs});return}let n=this.context.getAsString(this.schema.default);return{type:ic.enum({default:n!=null?r.find(i=>cr(i.name)===n):void 0,values:r,forwardCompatible:this.forwardCompatible||void 0})}}}});var uKr,_Wl=h(()=>{"use strict";zn();Uo();Nct();CUe();uKr=class extends Ki{schemaOrReferenceOrBoolean;constructor({context:t,breadcrumbs:r,schemaOrReferenceOrBoolean:n}){super({context:t,breadcrumbs:r}),this.schemaOrReferenceOrBoolean=n}convert(){let t=this.tryConvertUnknownMap();if(t!=null)return t;let r=this.tryConvertTypedMap();if(r!=null)return r}tryConvertUnknownMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean"){let t=Hr.container(As.map({keyType:Ki.STRING,valueType:Hr.unknown()}));return{type:ic.alias({aliasOf:t,resolvedType:t}),referencedTypes:new Set,inlinedTypes:{}}}}tryConvertTypedMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean")return;let r=new NT({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schemaOrReferenceOrBoolean}).convert();if(r!=null){let n=Hr.container(As.map({keyType:Ki.STRING,valueType:r.type})),i=new Set;for(let o of r.schema?.typeDeclaration.referencedTypes??[])i.add(o);for(let o of Object.keys(r.inlinedTypes))i.add(o);return c3(r.type,i),{type:ic.alias({aliasOf:n,resolvedType:n}),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}}});function GWl(e,t,r){let n=qWl(t,r),i={};for(let o of n)i=RGo(i,o);return EGm(i,e),i}function qWl(e,t,r){let n=r??new Set,i=[];for(let o of e)if(Array.isArray(o.allOf)&&o.allOf.length>0){let{allOf:s,...a}=o,c=[];for(let l of s)if("$ref"in l){if(t==null)continue;let u=l.$ref;if(n.has(u))continue;n.add(u);let p=t(l);p!=null&&c.push(p)}else c.push(l);i.push(...qWl(c,t,n)),Object.keys(a).length>0&&i.push(a)}else i.push(o);return i}function RGo(e,t){let r={...e};for(let[n,i]of Object.entries(t)){if(i===void 0||yGm.includes(n))continue;let o=r[n];if(n==="required"){let s=Array.isArray(o)?o:[],a=Array.isArray(i)?i:[];r[n]=[...new Set([...s,...a])];continue}if(n==="properties"){r[n]=bGm(o??{},i);continue}if(n==="items"){gr(o)&&gr(i)?r[n]=RGo(o,i):r[n]=i;continue}if(UWl.includes(n)){gr(o)&&gr(i)?r[n]=WWl(o,i):r[n]=i;continue}if(VWl.includes(n)){r[n]=!!o||!!i;continue}if(gGm.includes(n)){typeof o=="number"&&typeof i=="number"?r[n]=Math.max(o,i):r[n]=i;continue}if(AGm.includes(n)){typeof o=="number"&&typeof i=="number"?r[n]=Math.min(o,i):r[n]=i;continue}r[n]=i}return r}function bGm(e,t){let r={...e};for(let[n,i]of Object.entries(t)){let o=r[n];gr(o)&&gr(i)?r[n]=RGo(o,i):r[n]=i}return r}function WWl(e,t){let r={...e};for(let[n,i]of Object.entries(t)){let o=r[n];gr(o)&&gr(i)?r[n]=WWl(o,i):r[n]=i}return r}function EGm(e,t){for(let r of hGm){let n=t[r];n!=null&&(e[r]=n)}for(let r of UWl){let n=t[r];n!=null&&(e[r]=n)}for(let r of VWl)t[r]===!0&&(e[r]=!0)}var hGm,UWl,VWl,gGm,AGm,yGm,HWl=h(()=>{"use strict";mt();hGm=["description","title","format","type","discriminator","xml","externalDocs","extensions"],UWl=["example","default"],VWl=["deprecated","readOnly","writeOnly","uniqueItems","nullable"],gGm=["minimum","exclusiveMinimum","minLength","minItems","minProperties"],AGm=["maximum","exclusiveMaximum","maxLength","maxItems","maxProperties"],yGm=["allOf","oneOf","anyOf"]});var jct,kGo=h(()=>{"use strict";mt();zn();sc();cKr();Uo();Nct();jct=class extends Ki{schema;xmlEncoding;constructor({context:t,breadcrumbs:r,schema:n,id:i}){super({context:t,breadcrumbs:r}),this.schema=n,this.xmlEncoding=new kct({breadcrumbs:this.breadcrumbs,schema:n,fallbackName:i,context:t}).convert()}convert(){let t=typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties;if(!this.schema.properties&&!this.schema.allOf)return{type:ic.object({properties:[],extends:[],extendedProperties:[],extraProperties:t,deferredUnionBaseProperties:void 0}),propertiesByAudience:{},inlinedTypes:{},referencedTypes:new Set,xmlEncoding:this.xmlEncoding};let{convertedProperties:r,inlinedTypesFromProperties:n,referencedTypes:i,propertiesByAudience:o}=xUe({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector,withinXmlElement:this.xmlEncoding!=null}),s=[],a=i,c=this.schema.required!=null&&this.schema.required.length>0,l=n,u=o,p={};for(let d of this.schema.allOf??[])if(this.context.isReferenceObject(d)){let f=this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:this.breadcrumbs});if(f?.properties!=null)for(let[m,g]of Object.entries(f.properties))!this.context.isReferenceObject(g)&&p[m]==null&&(p[m]=g)}for(let[d,f]of(this.schema.allOf??[]).entries()){let m=[...this.breadcrumbs,"allOf",d.toString()],g,A=!1;if(this.context.isReferenceObject(f)){let D=this.context.resolveMaybeReference({schemaOrReference:f,breadcrumbs:m});if(D==null){this.context.logger.debug?.(`[ObjectSchemaConverter] allOf[${d}] reference could not be resolved. Skipping: ${JSON.stringify(f)}`);continue}if(g=D,typeof g.additionalProperties=="boolean"&&g.additionalProperties&&(t=!0),!c||Object.keys(g.properties??{}).every(R=>!this.schema.required?.includes(R))){this.addTypeReferenceToExtends({reference:f,breadcrumbs:m,extends_:s,referencedTypes:a});continue}}else g=f,A=!0;typeof g.additionalProperties=="boolean"&&g.additionalProperties&&(t=!0);let b=g.oneOf??g.anyOf;if(b!=null&&g.type==null&&g.properties==null){let D=new Set(r.map(R=>cr(R.name)));for(let[R,O]of b.entries()){let j=[...m,g.oneOf!=null?"oneOf":"anyOf",R.toString()],Y=this.context.isReferenceObject(O)?this.context.resolveMaybeReference({schemaOrReference:O,breadcrumbs:j}):O;if(Y==null)continue;let ee={};for(let[Te,pe]of Object.entries(Y.properties??{}))!this.context.isReferenceObject(pe)&&"not"in pe||(ee[Te]=pe);let te=Object.keys(ee).filter(Te=>!D.has(Te));if(te.length===0)continue;let ce={};for(let Te of te){let pe=ee[Te];pe!=null&&(ce[Te]=pe,D.add(Te))}let{convertedProperties:le,inlinedTypesFromProperties:ae,referencedTypes:he,propertiesByAudience:xe}=xUe({properties:ce,required:[],breadcrumbs:j,context:this.context,errorCollector:this.context.errorCollector,withinXmlElement:this.xmlEncoding!=null});r.push(...le),l={...l,...ae},u={...u,...xe},he.forEach(Te=>{a.add(Te)})}continue}let I=g.properties??{};if(A){I={};for(let[D,R]of Object.entries(g.properties??{})){let O=p[D];O!=null&&!this.context.isReferenceObject(R)?I[D]={...O,...R}:I[D]=R}}let{convertedProperties:C,inlinedTypesFromProperties:x,referencedTypes:S,propertiesByAudience:P}=xUe({properties:I,required:[...this.schema.required??[],...g.required??[],...Hue(g)],breadcrumbs:m,context:this.context,errorCollector:this.context.errorCollector,withinXmlElement:this.xmlEncoding!=null});r.push(...C),l={...l,...x},u={...u,...P},S.forEach(D=>{a.add(D)})}for(let d of Object.keys(l))a.add(d);return{type:ic.object({properties:r,extends:s.map(d=>this.context.typeReferenceToDeclaredTypeName(d)).filter(gs),extendedProperties:[],extraProperties:t,deferredUnionBaseProperties:void 0}),propertiesByAudience:u,referencedTypes:a,inlinedTypes:l,xmlEncoding:this.xmlEncoding}}addTypeReferenceToExtends({reference:t,breadcrumbs:r,extends_:n,referencedTypes:i}){let o=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:r});o.ok&&n.push(o.reference);let s=this.context.getTypeIdFromSchemaReference(t);s!=null&&i.add(s)}}});function IGm(e){return e.type==="union"&&e.types.length===0}function vGm({schema:e,discriminantProperty:t}){let r=e.properties?.[t];if(r==null||"$ref"in r)return;let n=r.const;if(typeof n=="string")return n;if(r.enum?.length===1&&typeof r.enum[0]=="string")return r.enum[0]}var SUe,FGo=h(()=>{"use strict";zn();TGo();OGo();PGo();Uo();Nct();lKr();pKr();CUe();SUe=class extends Ki{schema;id;constructor({context:t,breadcrumbs:r,schema:n,id:i,inlinedTypes:o}){super({context:t,breadcrumbs:r}),this.schema=n,this.id=i}convert(){if(this.shouldConvertAsNullableSchemaOrReference())return this.convertAsNullableSchemaOrReference();if(new Bct({context:this.context,breadcrumbs:this.breadcrumbs,node:this.schema}).convert()===!1)return this.convertAsUndiscriminatedUnion();if(this.schema.discriminator!=null){let n=this.convertAsDiscriminatedUnion();return n!=null&&!IGm(n.type)?n:this.convertAsUndiscriminatedUnion()??n}if(this.context.settings.inferForwardCompatible){let n=this.convertAsOpenEndedEnum();if(n!=null)return n}return this.convertAsUndiscriminatedUnion()}convertAsOpenEndedEnum(){let t=this.schema.oneOf??this.schema.anyOf;if(t==null||t.length!==2)return;let r,n=!1;for(let c of t){let l;if(this.context.isReferenceObject(c)){let u=this.context.resolveReference({reference:c,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});u.resolved&&(l=u.value)}else l=c;l!=null&&(l.enum!=null&&l.enum.length>1&&(l.type==="string"||l.type==null)?r=l:l.type==="string"&&l.enum==null&&(n=!0))}if(r==null||!n)return;let o=new Rct({breadcrumbs:this.breadcrumbs,schema:r,context:this.context}).convert(),a=new DSe({context:this.context,breadcrumbs:this.breadcrumbs,schema:r,maybeFernEnum:o,forwardCompatible:!0}).convert();if(a!=null)return{...a,referencedTypes:new Set,inlinedTypes:{}}}getEnclosingComponentRef(){let[t,r,n]=this.breadcrumbs;return t==="components"&&r==="schemas"&&n!=null?`#/components/schemas/${n}`:void 0}filterDiscriminantFromSchema(t,r){if(t.properties==null||!(r in t.properties))return t;let{[r]:n,...i}=t.properties,o=t.required?.filter(s=>s!==r);return{...t,properties:i,required:o}}getVariants(t){let r=this.schema.discriminator?.mapping;if(r!=null){let o=[];for(let[s,a]of Object.entries(r)){let c=this.context.getTypeIdFromSchemaReference({$ref:a});c!=null&&o.push({discriminant:s,typeId:c,ref:a,schema:this.resolveVariantSchema({$ref:a}),breadcrumbs:[...this.breadcrumbs,"discriminator","mapping",s]})}return o}let n=this.schema.oneOf??this.schema.anyOf??[],i=[];for(let[o,s]of n.entries()){let a=this.resolveVariantSchema(s),c=a!=null?vGm({schema:a,discriminantProperty:t}):void 0;if(!this.context.isReferenceObject(s)){if(c==null)return[];i.push({discriminant:c,typeId:this.context.convertBreadcrumbsToName([`${this.id}_${o}`]),schema:a,breadcrumbs:[...this.breadcrumbs,`oneOf[${o}]`]});continue}let l=s.$ref,u=l.split("/").pop(),p=this.context.getTypeIdFromSchemaReference(s),d=c??u;if(p==null||d==null)return[];i.push({discriminant:d,typeId:p,ref:l,schema:a,breadcrumbs:[...this.breadcrumbs,"discriminator","mapping",d]})}return i}resolveVariantSchema(t){if(!this.context.isReferenceObject(t))return t;let r=this.context.resolveReference({reference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});return r.resolved?r.value:void 0}convertAsDiscriminatedUnion(){if(this.schema.discriminator==null)return;let t=this.schema.discriminator.propertyName,r=[],n=new Set,i={};for(let{discriminant:u,typeId:p,ref:d,schema:f,breadcrumbs:m}of this.getVariants(t)){let g=d!=null?{$ref:d}:f,A=p!=null&&this.context.discriminatedVariantsInProgress.has(p),b=d!=null&&d===this.getEnclosingComponentRef(),I=f?.properties!=null&&t in f.properties&&!((A||b)&&d!=null);if(I&&f!=null&&(g=this.filterDiscriminantFromSchema(f,t)),g==null)continue;let C=new NT({context:this.context,schemaOrReference:g,schemaIdOverride:p??void 0,breadcrumbs:m});p!=null&&n.add(p);let x=I&&p!=null&&!A;x&&this.context.discriminatedVariantsInProgress.add(p);let S;try{S=C.convert()}finally{x&&this.context.discriminatedVariantsInProgress.delete(p)}if(S?.type!=null&&p!=null){for(let Y of Object.keys(S?.inlinedTypes??{}))n.add(Y);for(let Y of S.schema?.typeDeclaration.referencedTypes??[])n.add(Y);let P=this.context.casingsGenerator.generateNameAndWireValue({name:u,wireValue:u}),D=d?.split("/").pop()??p,R=f?.title,O=f?.description,j=R??u??D;S.schema?.typeDeclaration!=null&&R!=null&&(S.schema.typeDeclaration.name.displayName=R),r.push({docs:O,discriminantValue:P,availability:S.availability,displayName:j,shape:eT.samePropertiesAsObject({typeId:p,name:this.context.casingsGenerator.generateName(D),fernFilepath:{allParts:[],packagePath:[],file:void 0},displayName:j})}),i={...i,...S.inlinedTypes}}}let{convertedProperties:o,referencedTypes:s,inlinedTypesFromProperties:a}=xUe({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector});n=new Set([...n,...s]);let c=[];for(let[u,p]of(this.schema.allOf??[]).entries()){let d=[...this.breadcrumbs,"allOf",u.toString()];if(this.context.isReferenceObject(p)){let f=this.context.convertReferenceToTypeReference({reference:p,breadcrumbs:d});if(f.ok){let g=this.context.typeReferenceToDeclaredTypeName(f.reference);g!=null&&c.push(g)}let m=this.context.getTypeIdFromSchemaReference(p);m!=null&&n.add(m);continue}}for(let u of Object.keys({...i,...a}))n.add(u);let l=new Dct({context:this.context,breadcrumbs:[...this.breadcrumbs,"discriminator"],node:this.schema.discriminator});return{type:ic.union({baseProperties:o,inheritedBaseProperties:[],discriminant:this.context.casingsGenerator.generateNameAndWireValue({name:this.schema.discriminator.propertyName,wireValue:this.schema.discriminator.propertyName}),extends:c,types:r,default:void 0,discriminatorContext:l.convert()}),referencedTypes:n,inlinedTypes:{...i,...a}}}convertAsUndiscriminatedUnion(){if(!this.schema.oneOf&&!this.schema.anyOf||this.schema.anyOf?.length===0&&this.schema.oneOf?.length===0)return;let t=[],r=new Set,n={};for(let[a,c]of[...(this.schema.oneOf??[]).entries(),...(this.schema.anyOf??[]).entries()]){if(this.context.isReferenceObject(c)){let g;if(this.context.isReferenceObjectWithIdentifier(c))g=this.context.convertReferenceToTypeReference({reference:c,displayNameOverride:c.summary??c.title??c.name??c.messageId,displayNameOverrideSource:"reference_identifier"});else{let b=this.getDiscriminatorKeyForRef(c);b!=null?g=this.context.convertReferenceToTypeReference({reference:c,displayNameOverride:b,displayNameOverrideSource:"discriminator_key"}):g=this.context.convertReferenceToTypeReference({reference:c,breadcrumbs:this.breadcrumbs})}if(g.ok){let b=this.context.resolveReference({reference:c,breadcrumbs:this.breadcrumbs}),I=b.resolved?b.value.description:void 0;t.push({type:g.reference,docs:I})}let A=this.context.getTypeIdFromSchemaReference(c);A!=null&&r.add(A);continue}let u=Object.keys(this.schema.properties??{}).length>0?void 0:this.extendSubSchema(c),p=this.context.convertBreadcrumbsToName([`${this.id}_${a}`]),d=c.title,m=new RSe({context:this.context,id:p,nameOverride:d,breadcrumbs:[...this.breadcrumbs,`oneOf[${a}]`],schema:u??c}).convert();if(m!=null){let g=m.convertedSchema.typeDeclaration.shape;if(g.type==="alias"&&this.typeReferenceIsWrappedPrimitive(g.aliasOf))t.push({type:g.aliasOf,docs:c.description});else if(g.type==="object"&&g.properties.length===0&&g.extends.length===0)t.push({type:Hr.container(As.map({keyType:Ki.STRING,valueType:Hr.unknown()})),docs:c.description});else{t.push({type:this.context.createNamedTypeReference(p,d),docs:c.description});let A=this.context.getNamespacedSchemaId(p);n={...n,...m.inlinedTypes,[A]:m.convertedSchema},r.add(A);for(let b of Object.keys(m.inlinedTypes))r.add(b)}m.convertedSchema.typeDeclaration.referencedTypes.forEach(A=>{r.add(A)})}}let{convertedProperties:i,referencedTypes:o,inlinedTypesFromProperties:s}=xUe({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector});for(let a of Object.keys(s))r.add(a);for(let a of o)r.add(a);return{type:ic.undiscriminatedUnion({members:t,baseProperties:i.length>0?i:void 0}),referencedTypes:r,inlinedTypes:{...n,...s}}}shouldConvertAsNullableSchemaOrReference(){return this.schema.oneOf!=null?this.schema.oneOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):this.schema.anyOf!=null?this.schema.anyOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):!1}removeNullFromOneOfOrAnyOf(){let t=this.schema.oneOf??this.schema.anyOf,r=this.schema.oneOf!=null?"oneOf":"anyOf";if(t==null)return;let n=t.filter(i=>!(typeof i=="object"&&i!==null&&"type"in i&&i.type==="null"));if(n.length===0){this.context.errorCollector.collect({message:`Received ${r} schema with no valid non-null types`,path:this.breadcrumbs});return}return n.length===1?{...this.schema,[r]:void 0,...n[0]}:{...this.schema,[r]:n}}convertAsNullableSchemaOrReference(){let t=this.removeNullFromOneOfOrAnyOf();if(t==null)return;let n=new NT({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(n==null)return;let i=this.wrapInNullable(n.type);return{type:ic.alias({aliasOf:i,resolvedType:i}),referencedTypes:n.schema?.typeDeclaration.referencedTypes??new Set,inlinedTypes:n.inlinedTypes}}typeReferenceIsWrappedPrimitive(t){switch(t.type){case"container":return this.containerTypeIsWrappedPrimitive(t.container);case"named":return!1;case"primitive":return!0;case"unknown":return!0;default:return!1}}containerTypeIsWrappedPrimitive(t){switch(t.type){case"list":return this.typeReferenceIsWrappedPrimitive(t.list);case"map":return this.typeReferenceIsWrappedPrimitive(t.keyType)&&this.typeReferenceIsWrappedPrimitive(t.valueType);case"nullable":return this.typeReferenceIsWrappedPrimitive(t.nullable);case"optional":return this.typeReferenceIsWrappedPrimitive(t.optional);case"set":return this.typeReferenceIsWrappedPrimitive(t.set);case"literal":return!0;default:return!1}}wrapInNullable(t){return Hr.container(As.nullable(t))}mergeIntoObjectSchema(t,r){return{...t,properties:{...r,...t.properties??{}}}}extendSubSchema(t){if(Object.entries(this.schema.properties??{}).length===0)return t;if(t.type==="object")return this.mergeIntoObjectSchema(t,this.schema.properties??{});this.context.isObjectSchemaType(t)||this.context.errorCollector.collect({message:"Received additional object properties for oneOf/anyOf that are not objects",path:this.breadcrumbs})}getDiscriminatorKeyForRef(t){return Object.entries(this.schema.discriminator?.mapping??{}).find(([r,n])=>n===t.$ref)?.[0]}}});var zct,NGo=h(()=>{"use strict";zn();Uo();zct=class extends Ki{schema;constructor({context:t,breadcrumbs:r,schema:n}){super({context:t,breadcrumbs:r}),this.schema=n}convert(){switch(this.schema.type){case"string":{let t=this.context.getAsString(this.schema.const);if(t!=null)return Hr.container(As.literal(kE.string(t)));if(this.schema.format==="date-time-rfc-2822")return Hr.primitive({v1:ss.DateTimeRfc2822,v2:di.dateTimeRfc2822({})});if(this.context.settings.typeDatesAsStrings===!1){if(this.schema.format==="date")return Hr.primitive({v1:ss.Date,v2:di.date({})});if(this.schema.format==="date-time")return Hr.primitive({v1:ss.DateTime,v2:di.dateTime({})})}return Hr.primitive({v1:"STRING",v2:di.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":switch(this.schema.format){case"double":return Hr.primitive({v1:"DOUBLE",v2:di.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return Hr.primitive({v1:"FLOAT",v2:di.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return Hr.primitive({v1:"INTEGER",v2:di.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return Hr.primitive({v1:"LONG",v2:di.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return Hr.primitive({v1:"UINT",v2:di.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return Hr.primitive({v1:"UINT_64",v2:di.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return Hr.primitive({v1:"DOUBLE",v2:di.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"integer":switch(this.schema.format){case"double":return Hr.primitive({v1:"DOUBLE",v2:di.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return Hr.primitive({v1:"FLOAT",v2:di.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return Hr.primitive({v1:"INTEGER",v2:di.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return Hr.primitive({v1:"LONG",v2:di.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return Hr.primitive({v1:"UINT",v2:di.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return Hr.primitive({v1:"UINT_64",v2:di.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return Hr.primitive({v1:"INTEGER",v2:di.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"boolean":{let t=this.context.getAsBoolean(this.schema.const);return t!=null?Hr.container(As.literal(kE.boolean(t))):Hr.primitive({v1:"BOOLEAN",v2:di.boolean({default:this.context.getAsBoolean(this.schema.default)})})}default:return}}getNumberValidation(t){let r=t.minimum,n=t.maximum,i,o;return typeof t.exclusiveMinimum=="boolean"?i=t.exclusiveMinimum:typeof t.exclusiveMinimum=="number"&&(r=t.exclusiveMinimum,i=!0),typeof t.exclusiveMaximum=="boolean"?o=t.exclusiveMaximum:typeof t.exclusiveMaximum=="number"&&(n=t.exclusiveMaximum,o=!0),{max:n,min:r,exclusiveMax:o,exclusiveMin:i,multipleOf:t.multipleOf}}getStringValidation(t){let r=t.format??(t.contentMediaType==="application/octet-stream"?"binary":void 0);return{minLength:t.minLength,maxLength:t.maxLength,pattern:t.pattern,format:r}}}});function xGm(e){let t=Hue(e);return t.length===0?e:{...e,required:[...new Set([...e.required??[],...t])]}}var CGm,RSe,pKr=h(()=>{"use strict";mt();zn();Uo();Nct();LWl();BSe();jGo();lKr();_Wl();HWl();kGo();FGo();NGo();CGm=["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],RSe=class e extends Ki{static MAX_DISTRIBUTED_VARIANTS=64;schema;id;inlined;audiences;nameOverride;visitedRefs;constructor({context:t,breadcrumbs:r,schema:n,id:i,inlined:o=!1,nameOverride:s,visitedRefs:a}){super({context:t,breadcrumbs:r}),this.schema=n,this.id=i,this.inlined=o,this.nameOverride=s,this.visitedRefs=a??new Set,this.audiences=this.context.getAudiences({operation:this.schema,breadcrumbs:this.breadcrumbs})??[]}convert(){let t=this.tryConvertFernTypeDeclaration();if(t!=null)return t;let r=this.tryConvertReferenceSchema();if(r!=null)return r;let n=this.tryConvertEnumSchema();if(n!=null)return n;let i=this.tryDistributeAllOfOverOneOf();if(i!=null)return i;let o=this.tryConvertSingularAllOfSchema();if(o!=null)return o;let s=this.tryConvertPrimitiveSchema();if(s!=null)return s;let a=this.tryConvertArraySchema();if(a!=null)return a;let c=this.tryConvertTypeArraySchema();if(c!=null)return c;let l=this.tryConvertSiblingAnyOfConstraint();if(l!=null)return l;let u=this.tryConvertSiblingOneOfConstraint();if(u!=null)return u;let p=this.tryConvertOneOfAnyOfSchema();if(p!=null)return p;let d=this.tryConvertMapSchema();if(d!=null)return d;let f=this.tryConvertDiscriminatorMappingSchema();if(f!=null)return f;let m=this.tryConvertObjectAllOfSchema();if(m!=null)return m;let g=this.tryConvertUntypedSchema();if(g!=null)return g;this.context.errorCollector.collect({message:`Failed to convert schema object: ${JSON.stringify(this.schema,null,2)}`,path:this.breadcrumbs})}tryConvertReferenceSchema(){if(!this.context.isReferenceObject(this.schema))return;let t=this.schema;if(this.visitedRefs.has(t.$ref)||t.$ref===`#/components/schemas/${this.id}`)return;let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(!r.ok)return;let n=new Set;return c3(r.reference,n),{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:ic.alias({aliasOf:r.reference,resolvedType:r.reference}),referencedTypes:n}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes??{}}}tryConvertEnumSchema(){if(!this.schema.enum?.length)return;let r=new vC.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),i=new DSe({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,maybeFernEnum:r}).convert();if(i!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:i.type,referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertSingularAllOfSchema(){if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&this.schema.allOf?.length===1&&this.schema.allOf[0]!=null){let r=this.schema.allOf[0];if(this.context.isReferenceObject(r)){let i=r.$ref;if(this.visitedRefs.has(i))return}let n=this.context.resolveMaybeReference({schemaOrReference:r,breadcrumbs:this.breadcrumbs});if(n!=null){let i=this.context.isReferenceObject(r)?new Set([...this.visitedRefs,r.$ref]):this.visitedRefs,s=new e({context:this.context,breadcrumbs:[...this.breadcrumbs,"allOf","0"],schema:n,id:this.id,inlined:this.inlined,visitedRefs:i}).convert();if(s?.convertedSchema.typeDeclaration?.shape.type!=="object"){if(s!=null){let a=s.convertedSchema.typeDeclaration;this.schema.description!=null&&a.docs==null&&(a.docs=this.schema.description);let c=this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs});c!=null&&a.availability==null&&(a.availability=c)}return s}}}if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&Array.isArray(this.schema.allOf)&&this.schema.allOf.length>=1){let r=new Set,n=[],i=!1;for(let c of this.schema.allOf??[]){let l;if(this.context.isReferenceObject(c)){let p=c.$ref;if(this.visitedRefs.has(p)){i=!0;break}if(r.has(p))continue;r.add(p);let d=this.context.resolveMaybeReference({schemaOrReference:c,breadcrumbs:this.breadcrumbs});if(d==null)return;l=d}else l=c;let u=l.oneOf??l.anyOf;if(!this.context.isReferenceObject(c)&&u!=null&&l.type==null&&l.properties==null){let p={};for(let d of u){let f=this.context.isReferenceObject(d)?this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:this.breadcrumbs}):d;if(f!=null)for(let[m,g]of Object.entries(f.properties??{}))!this.context.isReferenceObject(g)&&"not"in g||m in p||(p[m]=g)}Object.keys(p).length>0&&n.push({properties:p});continue}n.push(xGm(l))}if(i)return;let o=GWl(this.schema,n,c=>{let l=this.context.resolveMaybeReference({schemaOrReference:c,breadcrumbs:this.breadcrumbs});if(!(l!=null&&this.context.isReferenceObject(l)))return l}),s=new Set([...this.visitedRefs,...r]);return new e({context:this.context,breadcrumbs:this.breadcrumbs,schema:o,id:this.id,inlined:this.inlined,visitedRefs:s}).convert()}}tryDistributeAllOfOverOneOf(){if(!this.context.settings.preserveOneOfInAllOf)return;let t=this.schema.allOf;if(!Array.isArray(t)||t.length===0||this.schema.oneOf!=null||this.schema.anyOf!=null)return;let r=this.getDistributableUnions(t),n=r[0];if(n==null)return;let i=r.reduce((c,l)=>c*l.variants.length,1);if(i>e.MAX_DISTRIBUTED_VARIANTS){this.context.logger.warn(`Not distributing allOf over its ${r.length} unions at ${this.breadcrumbs.join(".")}: it would produce ${i} variants (max ${e.MAX_DISTRIBUTED_VARIANTS}).`);return}let o=t.filter((c,l)=>l!==n.index);(this.schema.properties!=null||this.schema.required!=null)&&o.push({type:"object",properties:this.schema.properties,required:this.schema.required});let s={...this.schema};return delete s.allOf,delete s.properties,delete s.required,new e({context:this.context,breadcrumbs:this.breadcrumbs,schema:{...s,oneOf:n.variants.map(c=>{let l=this.getVariantTitle(c);return{...l!=null?{title:l}:{},allOf:[c,...o]}})},id:this.id,inlined:this.inlined,nameOverride:this.nameOverride,visitedRefs:this.visitedRefs}).convert()}getVariantTitle(t){return this.context.isReferenceObject(t)?this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs})?.title??t.$ref.split("/").pop():t.title}getDistributableUnions(t){let r=[];for(let[n,i]of t.entries()){let o=this.context.isReferenceObject(i)?this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:this.breadcrumbs}):i;if(o==null||o.properties!=null||o.type!=null&&o.type!=="object"||o.discriminator!=null)continue;let s=o.oneOf??o.anyOf;s==null||s.length===0||r.push({index:n,variants:s})}return r}tryConvertPrimitiveSchema(){let r=new zct({context:this.context,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:ic.alias({aliasOf:r,resolvedType:r}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertArraySchema(){if(this.schema.type==="array"){let r=new Qct({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:ic.alias({aliasOf:r.typeReference,resolvedType:r.typeReference}),referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertTypeArraySchema(){if(Array.isArray(this.schema.type)&&this.schema.type.length>0)return this.schema.type.length===1?this.schema.type=this.schema.type[0]:(this.schema.oneOf=this.schema.type.map(t=>({type:t})),this.schema.type=void 0),this.convert()}tryConvertSiblingAnyOfConstraint(){if(!this.context.settings.anyOfSiblingPropertiesAsObject||!Sze(this.schema))return;this.context.logger.debug(`Treating the anyOf at ${this.breadcrumbs.join(".")} as an "at least one of" constraint over its sibling properties rather than a union, and converting the schema as an object.`);let{anyOf:t,...r}=this.schema;return new e({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:r,inlined:this.inlined,nameOverride:this.nameOverride,visitedRefs:this.visitedRefs}).convert()}tryConvertSiblingOneOfConstraint(){if(!wze(this.schema)||new vC.FernDiscriminatedExtension({context:this.context,breadcrumbs:this.breadcrumbs,node:this.schema}).convert()===!0)return;this.context.logger.debug(`Treating the oneOf at ${this.breadcrumbs.join(".")} as an "exactly one of" constraint over its sibling properties rather than a union, and converting the schema as an object.`);let r=Hue(this.schema),{oneOf:n,...i}=this.schema;return r.length>0&&(i.required=[...new Set([...i.required??[],...r])]),new e({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:i,inlined:this.inlined,nameOverride:this.nameOverride,visitedRefs:this.visitedRefs}).convert()}tryConvertOneOfAnyOfSchema(){if(this.schema.oneOf!=null||this.schema.anyOf!=null){let r=new SUe({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,inlinedTypes:{}}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertMapSchema(){if((typeof this.schema.additionalProperties=="object"||typeof this.schema.additionalProperties=="boolean")&&this.schema.additionalProperties!=null&&!this.schema.properties&&!this.schema.allOf){if(typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties===!1)return;let r=new uKr({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReferenceOrBoolean:this.schema.additionalProperties}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertDiscriminatorMappingSchema(){if(this.schema.discriminator?.mapping!=null&&Object.keys(this.schema.discriminator.mapping).length>0&&this.schema.oneOf==null&&this.schema.anyOf==null){let t={...this.schema,oneOf:Object.values(this.schema.discriminator.mapping).map(i=>({$ref:i}))},n=new SUe({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:t,inlinedTypes:{}}).convert();if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:n.type,referencedTypes:n.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:n.inlinedTypes}}}tryConvertObjectAllOfSchema(){if(this.schema.type==="object"||this.schema.properties!=null||this.schema.allOf!=null){let r=new jct({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,id:this.id}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes,encoding:r.xmlEncoding!=null?{json:void 0,proto:void 0,xml:r.xmlEncoding}:void 0}),audiences:this.audiences,propertiesByAudience:r.propertiesByAudience},inlinedTypes:r.inlinedTypes}}}tryConvertUntypedSchema(){if(this.isUntypedSchema())return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:ic.alias({aliasOf:Hr.unknown(),resolvedType:Hr.unknown()}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertFernTypeDeclaration(){let r=new vC.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r==null)return;let n=MWl(r);if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:ic.alias({aliasOf:n,resolvedType:n}),referencedTypes:new Set,omitV2Examples:!0}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}createTypeDeclaration({shape:t,referencedTypes:r,omitV2Examples:n,encoding:i}){return{name:this.convertDeclaredTypeName(),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:i,availability:this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs}),docs:this.schema.description,referencedTypes:r,source:void 0,inline:this.inlined,v2Examples:n?void 0:this.convertSchemaExamples()}}convertDeclaredTypeName(){let t=this.context.getRawSchemaId(this.id);return{typeId:this.context.getNamespacedSchemaId(this.id),fernFilepath:this.context.createFernFilepath(),name:this.context.casingsGenerator.generateName(t),displayName:this.nameOverride}}schemaOnlyHasAllowedKeys(t){let r=[...CGm,...t];return Object.keys(this.schema).every(i=>r.includes(i))}isUntypedSchema(){return!!(this.schema&&typeof this.schema=="object"&&!("oneOf"in this.schema)&&!("anyOf"in this.schema)&&!("allOf"in this.schema)&&!("items"in this.schema)&&!("properties"in this.schema))}convertSchemaExamples(){let t={userSpecifiedExamples:{},autogeneratedExamples:{}},r=this.context.getExamplesFromSchema({schema:this.schema,breadcrumbs:this.breadcrumbs});if(r.length===0){let n=this.generateOrValidateExample({example:void 0,ignoreErrors:!0});return t.autogeneratedExamples={[`${this.id}_example_autogenerated`]:n},t}return t.userSpecifiedExamples=this.convertUserSpecifiedExamples(r),t}convertUserSpecifiedExamples(t){let r={};for(let[n,i]of t.entries()){let o=this.context.resolveExample(i),s=`${this.id}_example_${n}`,a=this.generateOrValidateExample({example:o,exampleName:s});r[s]=a}return r}generateOrValidateExample({example:t}){let r=new Bw({breadcrumbs:this.breadcrumbs,context:this.context,schema:this.schema,example:t}),{validExample:n}=r.convert();return n}}});function wGm(e){return Object.keys(e).every(t=>SGm.has(t))}var NT,SGm,CUe=h(()=>{"use strict";zn();Uo();pKr();NT=class extends Ki{schemaOrReference;schemaIdOverride;wrapAsOptional;wrapAsNullable;constructor({context:t,breadcrumbs:r,schemaOrReference:n,schemaIdOverride:i,wrapAsOptional:o=!1,wrapAsNullable:s=!1}){super({context:t,breadcrumbs:r}),this.schemaOrReference=n,this.schemaIdOverride=i,this.wrapAsOptional=o,this.wrapAsNullable=s}convert(){let t=this.maybeConvertReferenceObject({schemaOrReference:this.schemaOrReference});if(t!=null)return t;let r=this.maybeConvertSingularAllOfReferenceObject();return r??this.convertSchemaObject({schema:this.schemaOrReference})}maybeConvertReferenceObject({schemaOrReference:t}){if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:r.inlinedTypes??{},availability:this.context.getAvailability({node:t,breadcrumbs:this.breadcrumbs})}}}maybeConvertSingularAllOfReferenceObject(){if(this.context.isReferenceObject(this.schemaOrReference)||this.schemaOrReference.allOf==null)return;if(this.schemaOrReference.allOf.length===1){let i=this.schemaOrReference.allOf[0];if(this.context.isReferenceObject(i)){let o=this.context.convertReferenceToTypeReference({reference:i,breadcrumbs:this.breadcrumbs});if(o.ok)return{type:this.wrapTypeReference(o.reference),inlinedTypes:o.inlinedTypes??{},availability:this.getAvailabilityOfSelfOrReference(i)}}return}let t=this.schemaOrReference.allOf.filter(i=>this.context.isReferenceObject(i)),r=this.schemaOrReference.allOf.filter(i=>typeof i=="object"&&i!==null&&!this.context.isReferenceObject(i)),n=t.length===1?t[0]:void 0;if(n!=null&&r.every(i=>wGm(i))){let i=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:this.breadcrumbs});if(i!=null&&i.type!=="object"&&!i.properties&&!i.allOf&&!i.oneOf&&!i.anyOf&&!i.format){let o=this.context.convertReferenceToTypeReference({reference:n,breadcrumbs:this.breadcrumbs});if(o.ok)return{type:this.wrapTypeReference(o.reference),inlinedTypes:o.inlinedTypes??{},availability:this.getAvailabilityOfSelfOrReference(n)}}}}getAvailabilityOfSelfOrReference(t){for(let r of[...this.getSelfAndInlineAllOfElements(),t]){let n=this.context.getAvailability({node:r,breadcrumbs:this.breadcrumbs});if(n!=null)return n}}getSelfAndInlineAllOfElements(){return this.context.isReferenceObject(this.schemaOrReference)||this.schemaOrReference.allOf==null?[this.schemaOrReference]:[this.schemaOrReference,...this.schemaOrReference.allOf.filter(t=>!this.context.isReferenceObject(t))]}convertSchemaObject({schema:t}){let r=this.schemaIdOverride??this.context.convertBreadcrumbsToName(this.breadcrumbs),n=this.context.getNamespacedSchemaId(r),i=new RSe({context:this.context,breadcrumbs:this.breadcrumbs,schema:t,id:r}),o=this.context.getAvailability({node:t,breadcrumbs:this.breadcrumbs}),s=i.convert();if(s!=null){let a=s.convertedSchema.typeDeclaration.shape;return a.type==="alias"?{type:this.wrapTypeReference(a.aliasOf),schema:s.convertedSchema,inlinedTypes:s.inlinedTypes,availability:o}:{type:this.wrapTypeReference(this.context.createNamedTypeReference(r)),schema:s.convertedSchema,inlinedTypes:{...s.inlinedTypes,[n]:s.convertedSchema},availability:o}}}wrapTypeReference(t){return this.wrapAsOptional&&this.wrapAsNullable?this.wrapInOptional(this.wrapInNullable(t)):this.wrapAsOptional?this.wrapInOptional(t):this.wrapAsNullable?this.wrapInNullable(t):t}wrapInOptional(t){return Hr.container(As.optional(t))}wrapInNullable(t){return Hr.container(As.nullable(t))}},SGm=new Set(["description","title","deprecated","readOnly","writeOnly","xml","externalDocs","x-fern-type-name"])});function xUe({properties:e,required:t,breadcrumbs:r,context:n,errorCollector:i,withinXmlElement:o=!1}){let s=[],a={},c={},l=new Set;for(let[u,p]of Object.entries(e??{})){let d=[...r,"properties",u];if(typeof p!="object"){i.collect({message:`Schema property ${u} should be an object`,path:d});continue}let f=OGm(r,p,n)??n.convertBreadcrumbsToName(d),m="nullable"in p?p.nullable:!1,A=new NT({context:n,breadcrumbs:d,schemaOrReference:p,schemaIdOverride:f,wrapAsOptional:!t.includes(u),wrapAsNullable:m}).convert();if(A!=null){let b=n.resolveMaybeReference({schemaOrReference:p,breadcrumbs:d,skipErrorCollector:!0});s.push({name:n.casingsGenerator.generateNameAndWireValue({name:u,wireValue:u}),valueType:A.type,docs:p.description??A.schema?.typeDeclaration.docs,availability:A.availability,propertyAccess:n.getPropertyAccess(p),defaultValue:b?.default,xml:o?new Fct({breadcrumbs:d,propertySchema:p,resolvedPropertySchema:b??void 0,context:n}).convert():void 0,v2Examples:A.schema?.typeDeclaration?.v2Examples??TGm({propertySchema:p,breadcrumbs:d,context:n,propertyId:f})}),a={...a,...A.inlinedTypes},A.schema?.typeDeclaration.referencedTypes!=null&&A.schema.typeDeclaration.referencedTypes.forEach(I=>{l.add(I)}),c3(A.type,l);for(let I of A.schema?.audiences??[])c[I]==null&&(c[I]=new Set),c[I].add(u)}}for(let u of Object.keys(a))l.add(u);return{convertedProperties:s,propertiesByAudience:c,inlinedTypesFromProperties:a,referencedTypes:l}}function TGm({propertySchema:e,breadcrumbs:t,context:r,propertyId:n}){let i=r.resolveMaybeReference({schemaOrReference:e,breadcrumbs:t,skipErrorCollector:!0}),o=r.getExamplesFromSchema({schema:i??void 0,breadcrumbs:t});if(o.length>0){let l={};for(let[u,p]of o.entries()){let d=r.resolveExample(p),f=`${n}_example_${u}`,m=new Bw({breadcrumbs:t,context:r,schema:e,example:d}),{validExample:g}=m.convert();l[f]=g}return{userSpecifiedExamples:l,autogeneratedExamples:{}}}let s=`${n}_example_autogenerated`,a=new Bw({breadcrumbs:t,context:r,schema:e,example:void 0,generateOptionalProperties:!0}),{validExample:c}=a.convert();return{userSpecifiedExamples:{},autogeneratedExamples:{[s]:c}}}function OGm(e,t,r){return r.isReferenceObject(t)?void 0:new vC.FernTypeNameExtension({breadcrumbs:e,schema:t,context:r}).convert()}function c3(e,t){switch(e.type){case"named":t.add(e.typeId);return;case"primitive":case"unknown":return;case"container":PGm(e.container,t);return}}function PGm(e,t){switch(e.type){case"list":c3(e.list,t);return;case"set":c3(e.set,t);return;case"optional":c3(e.optional,t);return;case"nullable":c3(e.nullable,t);return;case"map":c3(e.keyType,t),c3(e.valueType,t);return;case"literal":return}}var Nct=h(()=>{"use strict";BSe();CUe();cKr();Uo()});var Qct,jGo=h(()=>{"use strict";zn();Uo();Nct();CUe();Qct=class e extends Ki{static LIST_UNKNOWN=Hr.container(As.list(Hr.unknown()));schema;constructor({context:t,breadcrumbs:r,schema:n}){super({context:t,breadcrumbs:r}),this.schema=n}convert(){if(this.schema.items!=null){Array.isArray(this.schema.items)&&(this.schema.items={oneOf:this.schema.items});let r=new NT({context:this.context,breadcrumbs:[...this.breadcrumbs,"items"],schemaOrReference:this.schema.items}).convert();if(r!=null){let n=new Set;for(let i of r.schema?.typeDeclaration.referencedTypes??[])n.add(i);return r.inlinedTypes!=null&&Object.values(r.inlinedTypes).forEach(i=>{i.typeDeclaration.referencedTypes.forEach(o=>{n.add(o)})}),c3(r.type,n),{typeReference:Hr.container(As.list(r.type)),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}}});var zGo={};ne(zGo,{ArraySchemaConverter:()=>Qct,EnumSchemaConverter:()=>DSe,ObjectSchemaConverter:()=>jct,OneOfSchemaConverter:()=>SUe,PrimitiveSchemaConverter:()=>zct,SchemaConverter:()=>RSe,SchemaOrReferenceConverter:()=>NT});var QGo=h(()=>{"use strict";jGo();lKr();kGo();FGo();NGo();pKr();CUe()});var fKr,KWl=h(()=>{"use strict";xo();Uo();BSe();QGo();fKr=class extends Ki{group;method;constructor({context:t,breadcrumbs:r,group:n,method:i}){super({context:t,breadcrumbs:r}),this.group=n,this.method=i}parseMediaTypeObject({mediaTypeObject:t,resolveSchema:r,contentType:n,schemaId:i}){if(t.schema==null)return;if(r){let c=this.context.resolveMaybeReference({schemaOrReference:t.schema,breadcrumbs:[...this.breadcrumbs,"content",n]});if(c==null)return;t.schema=c}let s=new NT({context:this.context,breadcrumbs:[...this.breadcrumbs,"content",n,"schema"],schemaOrReference:t.schema,schemaIdOverride:i}).convert();if(s==null)return;let a=t.examples!=null?Object.fromEntries(Object.entries(t.examples).map(([c,l])=>{if(this.context.isReferenceObject(l)){let u=this.context.resolveReference({reference:l,breadcrumbs:[...this.breadcrumbs,"content",n,"examples"],skipErrorCollector:!0});return u.resolved?[c,u.value.value??u.value]:null}return[c,l.value??l]}).filter(c=>c!=null)):void 0;return{...s,examples:a}}parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:r}){let i=new NT({context:this.context,breadcrumbs:[...this.breadcrumbs],schemaOrReference:t,schemaIdOverride:r}).convert();if(i!=null)return{...i,examples:void 0}}getIdForExample({key:t,example:r,usedExampleNames:n}){if(this.context.isExampleWithSummary(r)){let i=r.summary;if(!n.has(i))return i;let o=`${i} (${t})`;return n.has(o)?t:o}return t}convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:r,exampleGenerationStrategy:n}){let i={userSpecifiedExamples:{},autogeneratedExamples:{}},o=t?.schema,s=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_example`}),a=new Set;for(let[c,l]of s){let u=this.context.resolveExampleWithValue(l),p=this.context.resolveExampleRecursively({example:l,breadcrumbs:this.breadcrumbs}),d=this.getIdForExample({key:c,example:p,usedExampleNames:a});a.add(d),u!=null&&(o!=null?i.userSpecifiedExamples[d]=this.generateOrValidateExample({schema:o,example:u,exampleGenerationStrategy:n,exampleName:d}):i.userSpecifiedExamples[d]=u)}if(o!=null&&Object.keys(i.userSpecifiedExamples).length===0){let c=this.getExamplesFromSchemaOrReference(o);c.length>1&&c.forEach((l,u)=>{let p=`Example ${u+1}`;i.userSpecifiedExamples[p]=this.generateOrValidateExample({schema:o,example:l,exampleGenerationStrategy:n,exampleName:p})})}if(Object.keys(i.userSpecifiedExamples).length===0&&o!=null){let c=ao(`${[...this.group,this.method].join("_")}_example`);i.autogeneratedExamples[c]=this.generateOrValidateExample({schema:o,example:void 0,ignoreErrors:!0,generateOptionalProperties:r,exampleGenerationStrategy:n,exampleName:c})}return i}getExamplesFromSchemaOrReference(t){let r=new Set,n=t;for(;this.context.isReferenceObject(n);){if(r.has(n.$ref))return[];r.add(n.$ref);let i=this.context.resolveReference({reference:n,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(!i.resolved)return[];n=i.value}return this.context.getExamplesFromSchema({schema:n,breadcrumbs:this.breadcrumbs})}generateOrValidateExample({schema:t,example:r,generateOptionalProperties:n,exampleGenerationStrategy:i}){let o=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(o==null)return;let s=this.context.getExamplesFromSchema({schema:o,breadcrumbs:this.breadcrumbs}),a=new Bw({breadcrumbs:this.breadcrumbs,context:this.context,schema:o,example:r??s[0],generateOptionalProperties:n??!1,exampleGenerationStrategy:i}),{validExample:c}=a.convert();return c}}});var dKr,JWl=h(()=>{"use strict";Uo();BSe();dKr=class extends Ki{parameter;constructor({context:t,breadcrumbs:r,parameter:n}){super({context:t,breadcrumbs:r}),this.parameter=n}convertToOutput({schema:t,typeReference:r,inlinedTypes:n}){let i=this.context.getAvailability({node:this.parameter,breadcrumbs:this.breadcrumbs}),o=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs}),s=this.getParameterSchemaWithExampleOverride({schema:o}),a=o?.default,c=this.getParameterDescription({schema:t});switch(this.parameter.in){case"query":return{type:"query",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:c,valueType:r??Ki.OPTIONAL_STRING,allowMultiple:this.parameter.explode??!1,clientDefault:void 0,defaultValue:a,v2Examples:this.convertParameterExamples({schema:s??t,originalSchema:t}),availability:i,explode:this.getExplodeForQueryParameter()},inlinedTypes:n};case"header":return{type:"header",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:c,valueType:r??Ki.OPTIONAL_STRING,env:void 0,clientDefault:void 0,defaultValue:a,v2Examples:this.convertParameterExamples({schema:s??t,originalSchema:t}),availability:i},inlinedTypes:n};case"path":return{type:"path",parameter:{name:this.context.casingsGenerator.generateName(this.parameter.name),docs:c,valueType:r??Ki.STRING,location:"ENDPOINT",variable:void 0,clientDefault:void 0,v2Examples:this.convertParameterExamples({schema:s??t,originalSchema:t}),explode:this.getExplodeForPathParameter()},inlinedTypes:n};default:return}}getParameterDescription({schema:t}){if(this.parameter.description!=null)return this.parameter.description;if("description"in t&&typeof t.description=="string")return t.description}getParameterSchemaWithExampleOverride({schema:t}){if(t!=null)return t.type==="string"&&t.example==null?{...t,example:this.parameter.name}:t}convertParameterExamples({schema:t,originalSchema:r}){let n={userSpecifiedExamples:{},autogeneratedExamples:{}},i=this.parameter.example,o=this.parameter.examples;for(let[s,a]of Object.entries(o??{})){let c=this.context.resolveExampleWithValue(a);c!=null&&(n.userSpecifiedExamples[s]=this.generateOrValidateExample({schema:t,example:c,exampleName:s}))}if(i!=null){let s=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(n.userSpecifiedExamples)});n.userSpecifiedExamples[s]=this.generateOrValidateExample({schema:t,example:i,exampleName:s})}if(Object.keys(n.userSpecifiedExamples).length===0){let s=this.context.getExamplesFromSchema({schema:this.resolveSchemaChain(r),breadcrumbs:this.breadcrumbs});for(let a of s){let c=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(n.userSpecifiedExamples)});n.userSpecifiedExamples[c]=this.generateOrValidateExample({schema:t,example:this.context.resolveExample(a),exampleName:c})}}if(Object.keys(n.userSpecifiedExamples).length===0){let s=`${this.parameter.name}_example`;n.autogeneratedExamples[s]=this.generateOrValidateExample({schema:t,example:void 0,ignoreErrors:!0,exampleName:s})}return n}resolveSchemaChain(t){let r=new Set,n=t;for(;this.context.isReferenceObject(n);){if(r.has(n.$ref))return;r.add(n.$ref);let i=this.context.resolveReference({reference:n,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(!i.resolved)return;n=i.value}return n}generateOrValidateExample({schema:t,example:r}){let n=new Bw({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:r}),{validExample:i}=n.convert();return i}getExplodeForQueryParameter(){let t=this.parameter.style??"form",r=this.parameter.explode;if(r!==void 0)return t==="form"||t==="deepObject"?r===!0?void 0:r:r===!1?void 0:r}getExplodeForPathParameter(){let t=this.parameter.explode;if(t!==void 0)return t===!1?void 0:t}}});var MGo={};ne(MGo,{AbstractMediaTypeObjectConverter:()=>fKr,AbstractParameterConverter:()=>dKr});var YWl=h(()=>{"use strict";KWl();JWl()});function Mct({context:e,breadcrumbs:t,headers:r}){let n=[],i={},o=t??[];if(r==null)return{headers:n,inlinedTypes:i};for(let[s,a]of Object.entries(r)){let c=e.resolveMaybeReference({schemaOrReference:a,breadcrumbs:[...o,"headers",s]});if(c==null)continue;let l=BGm({context:e,header:c}),u=l?.schema,p=c.required===!0,d=b=>p?b:Hr.container(As.optional(b)),f=d(Ki.STRING),m,g=e.getAvailability({node:c,breadcrumbs:[...o,"headers",s]});if(u!=null)if(m=e.resolveMaybeReference({schemaOrReference:u,breadcrumbs:[...o,"headers",s,"schema"]}),m?.type==="number"||m?.type==="integer")f=d(Hr.primitive({v1:m.type==="integer"?"INTEGER":"DOUBLE",v2:m.type==="integer"?di.integer({default:void 0,validation:void 0}):di.double({default:void 0,validation:void 0})}));else if(m?.type==="boolean")f=d(Hr.primitive({v1:"BOOLEAN",v2:di.boolean({default:void 0})}));else{let b=new NT({context:e,breadcrumbs:[...o,"headers",s,"schema"],schemaOrReference:u,wrapAsOptional:!p,schemaIdOverride:e.convertBreadcrumbsToName([...o,"headers",s])}).convert();if(b!=null){f=b.type;for(let[I,C]of Object.entries(b.inlinedTypes))i[I]=C}}let A=DGm({context:e,breadcrumbs:o,header:c,headerName:s,schema:u,mediaTypeObject:l?.mediaTypeObject});n.push({name:e.casingsGenerator.generateNameAndWireValue({name:s,wireValue:s}),docs:c.description,valueType:f,env:void 0,v2Examples:A,availability:g,clientDefault:void 0,defaultValue:m?.default})}return{headers:n,inlinedTypes:i}}function BGm({context:e,header:t}){if(t.schema!=null)return{schema:t.schema};if(!(!e.settings.respectParameterContent||t.content==null)){for(let[r,n]of Object.entries(t.content))if(n.schema!=null&&gp.parse(r)?.isJSON())return{schema:n.schema,mediaTypeObject:n}}}function DGm({context:e,breadcrumbs:t,header:r,headerName:n,schema:i,mediaTypeObject:o}){let s={userSpecifiedExamples:{},autogeneratedExamples:{}},a=r.example,c=r.examples;for(let[l,u]of Object.entries(c??{})){let p=e.resolveExampleWithValue(u);p!=null&&(s.userSpecifiedExamples[l]=xGt({context:e,breadcrumbs:t,schema:i,example:p}))}if(a!=null){let l=e.generateUniqueName({prefix:`${n}_example`,existingNames:Object.keys(s.userSpecifiedExamples)});s.userSpecifiedExamples[l]=xGt({context:e,breadcrumbs:t,schema:i,example:a})}if(Object.keys(s.userSpecifiedExamples).length===0&&o!=null)for(let[l,u]of e.getNamedExamplesFromMediaTypeObject({mediaTypeObject:o,breadcrumbs:[...t,"headers",n,"content"],defaultExampleName:`${n}_example`})){let p=e.resolveExampleWithValue(u);if(p!=null){let d=e.generateUniqueName({prefix:l,existingNames:Object.keys(s.userSpecifiedExamples)});s.userSpecifiedExamples[d]=xGt({context:e,breadcrumbs:t,schema:i,example:p})}}if(Object.keys(s.userSpecifiedExamples).length===0&&i!=null){let l=e.getExamplesFromSchema({schema:RGm({context:e,schema:i,breadcrumbs:[...t,"headers",n,"schema"]}),breadcrumbs:[...t,"headers",n,"schema"]});for(let u of l){let p=e.generateUniqueName({prefix:`${n}_example`,existingNames:Object.keys(s.userSpecifiedExamples)});s.userSpecifiedExamples[p]=xGt({context:e,breadcrumbs:t,schema:i,example:e.resolveExample(u)})}}if(Object.keys(s.userSpecifiedExamples).length===0&&i!=null){let l=`${n}_example`;s.autogeneratedExamples[l]=xGt({context:e,breadcrumbs:t,schema:i,example:void 0,ignoreErrors:!0})}return s}function RGm({context:e,schema:t,breadcrumbs:r}){let n=new Set,i=t;for(;e.isReferenceObject(i);){if(n.has(i.$ref))return;n.add(i.$ref);let o=e.resolveReference({reference:i,breadcrumbs:r,skipErrorCollector:!0});if(!o.resolved)return;i=o.value}return i}function xGt({context:e,breadcrumbs:t,schema:r,example:n,ignoreErrors:i}){if(r==null)return n;let o=new Bw({breadcrumbs:t,context:e,schema:r,example:n}),{validExample:s,errors:a}=o.convert();return i||a.forEach(c=>{e.errorCollector.collect({message:c.message,path:c.path})}),s}var XWl=h(()=>{"use strict";mt();zn();$Hr();BSe();CUe()});var mKr,ZWl=h(()=>{"use strict";AR();mKr=class extends Vo{server;key="x-fern-server-name";constructor({breadcrumbs:t,server:r,context:n}){super({breadcrumbs:t,context:n}),this.server=r}convert(){let t=this.getExtensionValue(this.server,"x-name");if(!(t==null||typeof t!="string"))return t}}});var $Wl,kGm,l3,e7l=h(()=>{"use strict";mt();zn();wGo();ZWl();Uo();$Wl="Base",kGm="x-fern-default-url",l3=class e extends Ki{servers;endpointLevelServers;baseUrlEnvVar;constructor({breadcrumbs:t,context:r,servers:n,endpointLevelServers:i,baseUrlEnvVar:o}){super({breadcrumbs:t,context:r}),this.servers=n,this.endpointLevelServers=i,this.baseUrlEnvVar=o}convert(){if(this.servers==null||this.servers.length===0||this.servers[0]==null)return;if(this.endpointLevelServers!=null&&this.endpointLevelServers.length>0){let n=this.getDefaultBaseUrlName(),i={id:n,name:this.context.casingsGenerator.generateName(n)},o=this.endpointLevelServers.map(c=>{let l=e.getServerName({server:c,context:this.context});return{id:l,name:this.context.casingsGenerator.generateName(l)}}).filter((c,l,u)=>u.findIndex(p=>p.id===c.id)===l),s=[i,...o],a=this.servers.map(c=>{let l=e.getServerName({server:c,context:this.context}),u=this.endpointLevelServers?.map(g=>[e.getServerName({server:g,context:this.context}),this.getServerUrl(g)]),p=e.getServerAudiences({server:c,context:this.context}),{defaultUrls:d,urlTemplates:f,urlVariables:m}=this.buildMultiUrlTemplateFields({defaultBaseUrlId:n,topLevelServer:c,endpointServers:this.endpointLevelServers??[]});return{id:l,name:this.context.casingsGenerator.generateName(l),urls:{[n]:this.getServerUrl(c),...Object.fromEntries(u??[])},docs:c.description,audiences:p,defaultUrls:d,urlTemplates:f,urlVariables:m}});return{value:{defaultEnvironment:a[0]?.id,baseUrlEnvVar:this.baseUrlEnvVar,environments:DE.multipleBaseUrls({baseUrls:s,environments:a})},defaultUrl:i.id}}let t=this.extractFernDefaultUrl(),r=this.servers.map(n=>{let i=e.getServerName({server:n,context:this.context}),o=e.getServerAudiences({server:n,context:this.context});return n.variables!=null&&Object.keys(n.variables).length>0&&n.variables!=null?{id:i,name:this.context.casingsGenerator.generateName(i),url:this.maybeRemoveTrailingSlashIfNotEmpty(this.getServerUrl(n)),audiences:o,defaultUrl:t,urlTemplate:this.maybeRemoveTrailingSlashIfNotEmpty(n.url),urlVariables:this.convertServerVariables(n.variables),docs:n.description}:{id:i,name:this.context.casingsGenerator.generateName(i),url:this.maybeRemoveTrailingSlashIfNotEmpty(this.getServerUrl(n)),audiences:o,defaultUrl:void 0,urlTemplate:void 0,urlVariables:void 0,docs:n.description}}).filter(gs);return{value:{defaultEnvironment:r[0]?.id,baseUrlEnvVar:this.baseUrlEnvVar,environments:DE.singleBaseUrl({environments:r})},defaultUrl:r[0]?.id}}convertServerVariables(t){return Object.entries(t).map(([r,n])=>({id:r,name:this.context.casingsGenerator.generateName(r),default:n.default,values:n.enum}))}static getServerExtensionName({server:t,context:r}){return new mKr({breadcrumbs:[],server:t,context:r}).convert()}static getServerAudiences({server:t,context:r}){return new Pct({breadcrumbs:[],operation:t,context:r}).convert()?.audiences}static getServerName({server:t,context:r}){return t.name!=null?t.name:e.getServerExtensionName({server:t,context:r})??t.description??t.url}getServerUrl(t){if(t.variables==null)return t.url;let r=t.url;for(let[n,i]of Object.entries(t.variables))i.default!=null&&(r=r.replace(`{${n}}`,encodeURIComponent(i.default)));return r}getDefaultBaseUrlName(){return this.servers==null||this.servers.length===0||this.servers[0]==null?$Wl:e.getServerExtensionName({server:this.servers[0],context:this.context})??$Wl}maybeRemoveTrailingSlashIfNotEmpty(t){return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}buildMultiUrlTemplateFields({defaultBaseUrlId:t,topLevelServer:r,endpointServers:n}){let i={},o={},s={},a=!1;if(r.variables!=null&&Object.keys(r.variables).length>0){a=!0;let c=this.extractFernDefaultUrlFromServer(r);c!=null&&(i[t]=c),o[t]=this.maybeRemoveTrailingSlashIfNotEmpty(r.url),s[t]=this.convertServerVariables(r.variables)}for(let c of n){let l=e.getServerName({server:c,context:this.context});if(c.variables!=null&&Object.keys(c.variables).length>0){a=!0;let u=this.extractFernDefaultUrlFromServer(c);u!=null&&(i[l]=u),o[l]=this.maybeRemoveTrailingSlashIfNotEmpty(c.url),s[l]=this.convertServerVariables(c.variables)}}return a?{defaultUrls:Object.keys(i).length>0?i:void 0,urlTemplates:o,urlVariables:s}:{defaultUrls:void 0,urlTemplates:void 0,urlVariables:void 0}}extractFernDefaultUrlFromServer(t){let r=t[kGm];if(typeof r=="string")return this.maybeRemoveTrailingSlashIfNotEmpty(r)}extractFernDefaultUrl(){if(this.servers!=null)for(let t of this.servers){let r=this.extractFernDefaultUrlFromServer(t);if(r!=null)return r}}}});var Tm={};ne(Tm,{AbstractConverters:()=>MGo,ExampleConverter:()=>Bw,SchemaConverters:()=>zGo,ServersConverter:()=>l3,convertResponseHeaders:()=>Mct});var LGo=h(()=>{"use strict";YWl();BSe();XWl();QGo();e7l()});var SGt,t7l=h(()=>{"use strict";BSe();CGt();SGt=class{context;constructor({context:t}){this.context=t}validateExample({example:t,schema:r,breadcrumbs:n,exampleGenerationStrategy:i}){return new Bw({breadcrumbs:n,context:this.context,schema:r,example:t,depth:0,exampleGenerationStrategy:i,generateOptionalProperties:!1}).convert()}validateEndpointExample({exampleToValidate:t}){let r=[],n=[],i=!0,o=!1,s,a=[t.endpointPath,t.method];if(t.requestExample!==void 0&&t.requestSchema!==void 0){let l=this.validateExample({example:t.requestExample,schema:t.requestSchema,breadcrumbs:[...a,"request"],exampleGenerationStrategy:"request"});if(!l.isValid){i=!1;let u=t.exampleSource==="human"?HE.WARNING:HE.ERROR;r.push(...l.errors.map(p=>({...p,level:u,message:`Invalid request example: ${p.message}`})))}l.coerced&&(o=!0,n.push({level:HE.WARNING,message:"Request example was coerced to match schema",path:[...a,"request"]})),s={request:l.validExample}}let c=this.getResponseSchemaForValidation(t);if(t.responseExample!==void 0&&c!==void 0){let l=this.validateExample({example:t.responseExample,schema:c,breadcrumbs:[...a,"response"],exampleGenerationStrategy:"response"});if(!l.isValid){i=!1;let u=t.exampleSource==="human"?HE.WARNING:HE.ERROR;r.push(...l.errors.map(p=>({...p,level:u,message:`Invalid response example: ${p.message}`})))}l.coerced&&(o=!0,n.push({level:HE.WARNING,message:"Response example was coerced to match schema",path:[...a,"response"]})),s={...typeof s=="object"&&s!==null?s:{},response:l.validExample}}return{isValid:i,errors:r,warnings:n,endpointPath:t.endpointPath,method:t.method,exampleSource:t.exampleSource,exampleName:t.exampleName,validExample:s,coerced:o}}getResponseSchemaForValidation(t){let{responseStatusCode:r,responseSchemas:n,responseSchema:i}=t;return n&&Object.keys(n).length>0?r&&n[r]?n[r]:n[200]??n[201]:i}validateAiExamples({aiExamples:t,spec:r}){let n=[],i=[];for(let o of t){let{requestSchema:s,responseSchema:a,responseSchemas:c}=this.getSchemasForEndpoint({spec:r,endpointPath:o.endpointPath,method:o.method}),l={endpointPath:o.endpointPath,method:o.method,exampleSource:"ai",requestExample:o.request?.body,responseExample:o.response?.body,requestSchema:s,responseSchema:a,responseSchemas:c},u=this.validateEndpointExample({exampleToValidate:l}),p=this.hasUnexpectedProperties({requestExample:o.request?.body,responseExample:o.response?.body,requestSchema:s,responseSchema:a}),d=u.errors.length>0||u.warnings.length>0;!u.isValid||d||p?i.push({example:o,validationResult:u}):n.push(o)}return{validExamples:n,invalidExamples:i}}hasUnexpectedProperties({requestExample:t,responseExample:r,requestSchema:n,responseSchema:i}){return!!(t&&n&&this.exampleHasUnexpectedProperties(t,n)||r&&i&&this.exampleHasUnexpectedProperties(r,i))}exampleHasUnexpectedProperties(t,r){if(!t||typeof t!="object"||t===null)return!1;let n=this.context.resolveMaybeReference({schemaOrReference:r,breadcrumbs:[],skipErrorCollector:!0});if(!n||!n.properties&&!n.allOf&&!n.oneOf&&!n.anyOf||this.schemaHasPatternProperties(n))return!1;let i=t,o=this.collectAllPropertyKeys(n);return Object.keys(i).some(a=>!o.has(a))}collectAllPropertyKeys(t,r=new Set){let n=new Set;if(t.properties)for(let i of Object.keys(t.properties))n.add(i);for(let i of t.allOf??[]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:[],skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)){r.add(s);let a=this.collectAllPropertyKeys(o,r);for(let c of a)n.add(c)}}}for(let i of[...t.oneOf??[],...t.anyOf??[]]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:[],skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)){r.add(s);let a=this.collectAllPropertyKeys(o,r);for(let c of a)n.add(c)}}}return n}schemaHasPatternProperties(t,r=new Set){let n=t.patternProperties;if(n&&typeof n=="object"&&Object.keys(n).length>0)return!0;for(let i of[...t.allOf??[],...t.oneOf??[],...t.anyOf??[]]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:[],skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)&&(r.add(s),this.schemaHasPatternProperties(o,r)))return!0}}return!1}validateHumanExamples({spec:t}){let r=[],n=0,i=0,o=0,s=[],a=[];if(!t.paths)return{endpoints:r,totalExamples:n,validExamples:i,invalidExamples:o,hasInvalidHumanExamples:!1,hasInvalidAiExamples:!1,invalidHumanExamples:s,invalidAiExamples:a};for(let[c,l]of Object.entries(t.paths)){if(!l)continue;let u=["get","post","put","delete","patch","options","head","trace"];for(let p of u){let d=l[p];if(!d)continue;let f=[],{requestSchema:m,responseSchema:g,responseSchemas:A}=this.getSchemasForOperation({operation:d}),b=this.extractExamplesFromOperation({operation:d,path:c,method:p});for(let I of b){n++;let C={endpointPath:c,method:p,exampleName:I.name,exampleSource:I.source,requestExample:I.request,responseExample:I.response,requestSchema:m,responseSchema:g,responseStatusCode:I.statusCode,responseSchemas:A},x=this.validateEndpointExample({exampleToValidate:C});f.push(x),x.isValid?i++:(o++,I.source==="human"?s.push(x):I.source==="ai"&&a.push(x))}f.length>0&&r.push({endpointPath:c,method:p,results:f,hasInvalidExamples:f.some(I=>!I.isValid),invalidExampleCount:f.filter(I=>!I.isValid).length})}}return{endpoints:r,totalExamples:n,validExamples:i,invalidExamples:o,hasInvalidHumanExamples:s.length>0,hasInvalidAiExamples:a.length>0,invalidHumanExamples:s,invalidAiExamples:a}}getSchemasForEndpoint({spec:t,endpointPath:r,method:n}){let i=t.paths?.[r];if(!i)return{responseSchemas:{}};let o=i[n.toLowerCase()];return!o||typeof o!="object"||!("responses"in o)?{responseSchemas:{}}:this.getSchemasForOperation({operation:o})}getSchemasForOperation({operation:t}){let r,n,i={};if(t.requestBody&&!this.context.isReferenceObject(t.requestBody)){let s=t.requestBody.content?.["application/json"];s?.schema&&(r=s.schema)}if(t.responses){for(let[o,s]of Object.entries(t.responses)){if(!s||this.context.isReferenceObject(s))continue;let c=s.content?.["application/json"];c?.schema&&(i[o]=c.schema)}n=i[200]??i[201]}return{requestSchema:r,responseSchema:n,responseSchemas:i}}extractExamplesFromOperation({operation:t,path:r,method:n}){let i=[];if(t.requestBody&&!this.context.isReferenceObject(t.requestBody)){let a=t.requestBody.content?.["application/json"];if(a?.example!==void 0&&i.push({name:`${n}_${r}_request_example`,source:"openapi",request:a.example}),a?.examples)for(let[c,l]of Object.entries(a.examples)){let u=this.context.isReferenceObject(l)?this.context.resolveExample(l):l;u&&typeof u=="object"&&"value"in u&&i.push({name:c,source:"human",request:u.value})}}if(t.responses)for(let[s,a]of Object.entries(t.responses)){if(!a||this.context.isReferenceObject(a))continue;let l=a.content?.["application/json"];if(l?.example!==void 0){let u=i.find(p=>p.request!==void 0&&p.response===void 0);u?(u.response=l.example,u.statusCode=s):i.push({name:`${n}_${r}_response_${s}_example`,source:"openapi",response:l.example,statusCode:s})}if(l?.examples)for(let[u,p]of Object.entries(l.examples)){let d=this.context.isReferenceObject(p)?this.context.resolveExample(p):p;if(d&&typeof d=="object"&&"value"in d){let f=i.find(m=>m.name===u);f?(f.response=d.value,f.statusCode=s):i.push({name:u,source:"human",response:d.value,statusCode:s})}}}let o=t["x-fern-examples"];if(Array.isArray(o)){for(let s of o)if(typeof s=="object"&&s!==null){let a=s;i.push({name:a.name,source:"human",request:a.request?.body,response:a.response?.body})}}return i}}});function r7l({tags:e,errorCollector:t}){for(let r of e)if(Lct.test(r.name)){let n=[...r.name].filter(i=>Lct.test(i));t.collect({level:HE.ERROR,message:`Tag name "${r.name}" contains non-ASCII characters: ${n.join(", ")}. Non-ASCII characters in tag names will be included in URL paths and HTTP headers, which only support ASCII characters. This will cause runtime errors (ERR_INVALID_CHAR).`,path:["tags",r.name],resolution:`Remove non-ASCII characters from the tag name. For example, rename "${r.name}" to "${r.name.replace(Lct,"").trim()}".`})}}function n7l({description:e,path:t,errorCollector:r}){FGm.test(e)&&r.collect({level:HE.ERROR,message:'Description contains "---" frontmatter delimiters which will cause YAML parsing failures in the generated docs site. The docs renderer interprets content between "---" delimiters as YAML frontmatter, which will fail if the content is not valid YAML.',path:t,resolution:'Remove the "---" delimiters from the description.'})}function _Go({spec:e,errorCollector:t}){if(Array.isArray(e.tags)){let n=e.tags.filter(i=>typeof i=="object"&&i!=null&&"name"in i&&typeof i.name=="string");r7l({tags:n,errorCollector:t})}let r=["get","post","put","delete","patch","options","head","trace"];if(e.paths!=null&&typeof e.paths=="object"){let n=new Set;for(let[i,o]of Object.entries(e.paths)){if(o==null||typeof o!="object")continue;let s=o;for(let a of r){let c=s[a];if(c==null||typeof c!="object")continue;let l=c;if(typeof l.description=="string"&&n7l({description:l.description,path:["paths",i,a,"description"],errorCollector:t}),Array.isArray(l.tags)&&!Array.isArray(e.tags)){for(let u of l.tags)if(typeof u=="string"&&!n.has(u)&&Lct.test(u)){n.add(u);let p=[...u].filter(d=>Lct.test(d));t.collect({level:HE.ERROR,message:`Tag name "${u}" contains non-ASCII characters: ${p.join(", ")}. Non-ASCII characters in tag names will be included in URL paths and HTTP headers, which only support ASCII characters. This will cause runtime errors (ERR_INVALID_CHAR).`,path:["paths",i,a,"tags"],resolution:`Remove non-ASCII characters from the tag name. For example, rename "${u}" to "${u.replace(Lct,"").trim()}".`})}}}}}}var Lct,FGm,i7l=h(()=>{"use strict";CGt();Lct=new RegExp("[^\\x00-\\x7F]"),FGm=/(?:^|\n)\s*---\s*(?:\n|$)/});var hKr,NGm,o7l=h(()=>{"use strict";hKr={400:"BadRequestError",401:"UnauthorizedError",402:"PaymentRequiredError",403:"ForbiddenError",404:"NotFoundError",405:"MethodNotAllowedError",406:"NotAcceptableError",407:"ProxyAuthenticationRequiredError",408:"RequestTimeoutError",409:"ConflictError",410:"GoneError",411:"LengthRequiredError",412:"PreconditionFailedError",413:"ContentTooLargeError",414:"URITooLongError",415:"UnsupportedMediaTypeError",416:"RangeNotSatisfiableError",417:"ExpectationFailedError",418:"ImATeapotError",419:"AuthenticationTimeoutError",420:"MethodFailureError",421:"MisdirectedRequestError",422:"UnprocessableEntityError",423:"LockedError",424:"FailedDependencyError",425:"TooEarlyError",426:"UpgradeRequiredError",428:"PreconditionError",429:"TooManyRequestsError",430:"RequestHeaderFieldsTooLargeError",431:"RequestHeaderFieldsTooLargeError",444:"NoResponseError",449:"RetryWithError",450:"BlockedByWindowsParentalControlsError",451:"UnavailableForLegalReasonsError",498:"InvalidTokenError",499:"ClientClosedRequestError",500:"InternalServerError",501:"NotImplementedError",502:"BadGatewayError",503:"ServiceUnavailableError",504:"GatewayTimeoutError",505:"HTTPVersionNotSupportedError",506:"VariantAlsoNegotiatesError",507:"InsufficientStorageError",508:"LoopDetectedError",509:"BandwidthLimitExceededError",510:"NotExtendedError",511:"NetworkAuthenticationRequiredError"},NGm=new Set(Object.values(hKr))});function UGo(e){if(e!=null)return e.map(t=>Object.fromEntries(Object.entries(t).map(([r,n])=>[r,n??[]])))}var s7l=h(()=>{"use strict"});var Uo=h(()=>{"use strict";$Hr();bWl();AR();jWl();LGo();LGo();CGt();t7l();DGo();i7l();o7l();s7l()});var jGm,zGm,a7l,c7l=h(()=>{"use strict";nn();jGm=Xt.object({type:Xt.string(),channelId:Xt.string().optional(),messageId:Xt.string(),value:Xt.any()}),zGm=Xt.object({summary:Xt.string().optional(),description:Xt.string().optional(),"query-parameters":Xt.record(Xt.string()).optional(),headers:Xt.record(Xt.string()).optional(),messages:Xt.array(jGm)}),a7l=Xt.array(zGm)});var gKr,l7l=h(()=>{"use strict";Uo();c7l();gKr=class extends Vo{channel;baseDir;key="x-fern-examples";constructor({breadcrumbs:t,channel:r,context:n,baseDir:i}){super({breadcrumbs:t??[],context:n}),this.channel=r,this.baseDir=i}convert(){let t=this.getExtensionValue(this.channel);if(t==null)return;let r=a7l.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-examples extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data.map(n=>({summary:n.summary,description:n.description,queryParameters:n["query-parameters"],headers:n.headers,messages:n.messages.map(i=>({type:i.type,channelId:i.channelId,messageId:i.messageId,value:i.value}))}))}}});var _ct,VGo=h(()=>{"use strict";Uo();l7l();_ct=class extends Ki{channel;channelPath;inlinedTypes={};websocketGroup;constructor({context:t,breadcrumbs:r,websocketGroup:n,channel:i,channelPath:o}){super({context:t,breadcrumbs:r}),this.websocketGroup=n,this.channel=i,this.channelPath=o}convertExamples({fullPath:t,baseUrl:r,asyncApiVersion:n}){let o=new gKr({context:this.context,breadcrumbs:this.breadcrumbs,channel:this.channel,baseDir:this.context.documentBaseDir}).convert();return o==null?{}:Object.fromEntries(o.map((s,a)=>[a.toString(),{channel:{method:"GET",path:t},baseUrl:t,environment:r,auth:void 0,pathParameters:{},queryParameters:s.queryParameters,headers:s.headers,messages:s.messages.map(c=>({type:n==="v2"?c.type:c.messageId,body:c.value}))}]))}transformToValidPath(t){return t.startsWith("/")?t:"/"+t}}});var QGm,rJ,wGt=h(()=>{"use strict";zn();Uo();QGm="x-fern-server-name",rJ=class e extends Ki{servers;constructor({context:t,breadcrumbs:r,servers:n}){super({context:t,breadcrumbs:r}),this.servers=n}convert(){if(this.servers==null||Object.keys(this.servers).length===0)return;let t=[],r;for(let[n,i]of Object.entries(this.servers)){let o=e.getServerName(n,i),s=this.buildSingleBaseUrlEnvironment(this.context,o,i);t.push(s),r==null&&(r=s.id)}return{defaultEnvironment:r,baseUrlEnvVar:void 0,environments:DE.singleBaseUrl({environments:t})}}static getServerName(t,r){if(r!=null&&typeof r=="object"){let n=r[QGm];if(typeof n=="string"&&n.length>0)return n}return t}constructServerUrl(t,r){return r.includes("://")?r:`${t}://${r}`}}});var kSe,GGo=h(()=>{"use strict";Uo();kSe=class extends Tm.AbstractConverters.AbstractParameterConverter{parameterNamePrefix;constructor({context:t,breadcrumbs:r,parameter:n,parameterNamePrefix:i}){super({context:t,breadcrumbs:r,parameter:n}),this.parameterNamePrefix=i}convert(){let t,r={},i=new vC.FernOptionalExtension({breadcrumbs:this.breadcrumbs,parameter:this.parameter,context:this.context}).convert()??this.parameter.required===!1,o=this.parameter.schema??{...this.parameter,type:"string",enum:this.parameter.enum,default:this.parameter.default,example:this.parameter.example??this.parameter.name,examples:Object.values(this.parameter.examples??{}),deprecated:this.parameter.deprecated,required:void 0},a=new Tm.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaIdOverride:this.parameterNamePrefix?`${this.parameterNamePrefix}_${this.parameter.name}`:this.parameter.name,schemaOrReference:o,wrapAsOptional:i}).convert();return a!=null&&(t=a.type,r=a.inlinedTypes??{}),this.convertToOutput({schema:o,typeReference:t,inlinedTypes:r})}}});var AKr,u7l=h(()=>{"use strict";Uo();AKr=class extends Vo{channel;key="x-fern-address";constructor({breadcrumbs:t,channel:r,context:n}){super({breadcrumbs:t,context:n}),this.channel=r}convert(){let t=this.getExtensionValue(this.channel);if(!(t==null||typeof t!="string"))return t}}});var FSe,qGo=h(()=>{"use strict";Uo();FSe=class extends Vo{node;key="x-fern-display-name";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(!(t==null||typeof t!="string"))return t}}});var NSe,WGo=h(()=>{"use strict";Uo();NSe=class extends Vo{node;key="x-fern-explorer";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-explorer",path:this.breadcrumbs});return}return t}}}});var yKr,p7l=h(()=>{"use strict";Uo();yKr=class extends Vo{operation;key="x-fern-sdk-method-name";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(!(t==null||typeof t!="string"))return t}}});var bKr,f7l=h(()=>{"use strict";zn();sc();Uo();xo();VGo();wGt();GGo();u7l();qGo();WGo();p7l();bKr=class extends _ct{inlinedTypes={};constructor({context:t,breadcrumbs:r,websocketGroup:n,channel:i,channelPath:o}){super({context:t,breadcrumbs:r,websocketGroup:n,channel:i,channelPath:o})}convert(){let t=[],r=[],n=[],o=new FSe({breadcrumbs:this.breadcrumbs,node:this.channel,context:this.context}).convert()??this.websocketGroup?.join(".");this.channel.parameters&&this.convertPathParameters({context:this.context,pathParameters:t}),this.channel.bindings?.ws!=null&&(this.convertHeaders({context:this.context,headers:n}),this.convertBindingQueryParameters({context:this.context,queryParameters:r}));let s;this.channel.subscribe!=null&&(s=this.convertMessage({context:this.context,operation:this.channel.subscribe,origin:"server"}));let a;this.channel.publish!=null&&(a=this.convertMessage({context:this.context,operation:this.channel.publish,origin:"client"}));let c=[];s!=null&&c.push(s),a!=null&&c.push(a);let u=new AKr({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert(),p=this.transformToValidPath(u??this.channelPath),d=this.resolveServerName(this.channel.servers?.[0])??this.resolveServerName(Object.keys(this.context.spec.servers??{})[0]),f=jy(p),m=ao(this.channelPath),g=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[],A=this.hasServerSecurity()||this.context.authOverrides?.auth!=null,b=new NSe({context:this.context,breadcrumbs:this.breadcrumbs,node:this.context.spec}).convert(),C=new NSe({context:this.context,breadcrumbs:this.breadcrumbs,node:this.channel}).convert()??b;return{channel:{name:this.context.casingsGenerator.generateName(m),displayName:o,connectMethodName:void 0,baseUrl:d,path:f,auth:A,headers:n,queryParameters:r,pathParameters:t,messages:c,availability:this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({fullPath:p,baseUrl:d,asyncApiVersion:"v2"})},apiPlayground:C},audiences:g,inlinedTypes:this.inlinedTypes}}hasServerSecurity(){let t=this.context.spec.servers??{};if(this.channel.servers&&this.channel.servers.length>0){for(let r of this.channel.servers){let n=t[r];if(n?.security&&n.security.length>0)return!0}return!1}for(let r of Object.values(t)){let n=r;if(n.security&&n.security.length>0)return!0}return!1}convertMessage({context:t,operation:r,origin:n}){let i,o=n==="server"?"subscribe":"publish",s=[...this.breadcrumbs,o],a=t.resolveMaybeReference({schemaOrReference:r.message,breadcrumbs:s});a!=null&&(r.message=a);let c=Qze(ao(`${this.channelPath}_${o}`)).replace(/ /g,"");if("oneOf"in r.message){let u=new Tm.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:s,schemaOrReference:r.message,schemaIdOverride:c}).convert();u!=null&&u.schema!=null&&(i=u.schema,this.inlinedTypes={...this.inlinedTypes,...u.inlinedTypes})}else if(t.isMessageWithPayload(r.message)){let l=t.resolveMaybeReference({schemaOrReference:r.message.payload,breadcrumbs:s});if(l!=null){let p=new Tm.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:s,schemaOrReference:l,schemaIdOverride:c}).convert();p!=null&&p.schema!=null&&(i=p.schema,this.inlinedTypes={...this.inlinedTypes,...p.inlinedTypes})}}if(i!=null){let l=i,u=Hr.named({fernFilepath:t.createFernFilepath(),name:l.typeDeclaration.name.name,typeId:l.typeDeclaration.name.typeId,displayName:void 0,default:void 0,inline:!1}),p=ZP.reference({bodyType:u,docs:r.description}),d=n==="server"?"subscribe":"publish",m=new FSe({breadcrumbs:[...this.breadcrumbs,d],node:r,context:this.context}).convert()??d;return{type:d,displayName:m,origin:n,body:p,availability:t.getAvailability({node:r,breadcrumbs:this.breadcrumbs}),docs:r.description,methodName:this.getOperationMethodName(r)}}}convertPathParameters({context:t,pathParameters:r}){for(let[n,i]of Object.entries(this.channel.parameters??{})){let o=t.resolveMaybeReference({schemaOrReference:i,breadcrumbs:this.breadcrumbs});if(o==null)continue;let a=new kSe({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...o,name:n,in:"path",description:o.description,required:o.required??!0},parameterNamePrefix:this.channelPath}).convert();a!=null&&(this.inlinedTypes={...this.inlinedTypes,...a.inlinedTypes},a.type==="path"&&r.push(a.parameter))}}convertHeaders({context:t,headers:r}){if(this.channel.bindings?.ws?.headers!=null){let n=this.channel.bindings.ws.headers.required??[];for(let[i,o]of Object.entries(this.channel.bindings.ws.headers.properties??{})){let s=t.resolveMaybeReference({schemaOrReference:o,breadcrumbs:[...this.breadcrumbs,i]});if(s==null)continue;let c=new kSe({context:this.context,breadcrumbs:[...this.breadcrumbs,i],parameter:{name:i,in:"header",required:n.includes(i),schema:s,description:"description"in s?s.description:void 0},parameterNamePrefix:this.channelPath}).convert();c!=null&&c.type==="header"&&(this.inlinedTypes={...this.inlinedTypes,...c.inlinedTypes},r.push(c.parameter))}}}resolveServerName(t){if(t==null)return;let r=this.context.spec.servers;if(r!=null&&t in r){let n=r[t];return rJ.getServerName(t,n)}return t}getOperationMethodName(t){return new yKr({breadcrumbs:this.breadcrumbs,operation:t,context:this.context}).convert()}convertBindingQueryParameters({context:t,queryParameters:r}){if(this.channel.bindings?.ws?.query!=null){let n=this.channel.bindings.ws.query.required??[];for(let[i,o]of Object.entries(this.channel.bindings.ws.query.properties??{})){let s=t.resolveMaybeReference({schemaOrReference:o,breadcrumbs:[...this.breadcrumbs,i]});if(s==null)continue;let c=new kSe({context:this.context,breadcrumbs:[...this.breadcrumbs,i],parameter:{name:i,in:"query",required:n.includes(i),schema:s,description:"description"in s?s.description:void 0,deprecated:s.deprecated??!1},parameterNamePrefix:this.channelPath}).convert();c!=null&&c.type==="query"&&(this.inlinedTypes={...this.inlinedTypes,...c.inlinedTypes},r.push(c.parameter))}}}}});var EKr,d7l=h(()=>{"use strict";wGt();EKr=class extends rJ{constructor({context:t,breadcrumbs:r,servers:n}){super({context:t,breadcrumbs:r,servers:n})}buildSingleBaseUrlEnvironment(t,r,n){return{id:r,name:t.casingsGenerator.generateName(r),url:this.constructServerUrl(n.protocol,n.url),docs:void 0,audiences:void 0,defaultUrl:void 0,urlTemplate:void 0,urlVariables:void 0}}}});var HGo,m7l,KGo,IKr,h7l=h(()=>{"use strict";zn();sc();Bt();VGo();wGt();GGo();qGo();WGo();HGo="$message.",m7l="#/channels/",KGo="#/servers/",IKr=class extends _ct{operations;inlinedTypes={};constructor({context:t,breadcrumbs:r,websocketGroup:n,channel:i,channelPath:o,operations:s}){super({context:t,breadcrumbs:r,websocketGroup:n,channel:i,channelPath:o}),this.operations=s}convert(){let t=[],r=[],n=[],o=new FSe({breadcrumbs:this.breadcrumbs,node:this.channel,context:this.context}).convert()??this.websocketGroup?.join(".")??this.channelPath;this.channel.parameters&&this.convertChannelParameters({pathParameters:t,queryParameters:r,headers:n,channelPath:this.channelPath});let s=Object.entries(this.operations).reduce((A,[b,I])=>{try{this.getChannelPathFromOperation(I)===this.channelPath&&(A[b]=I)}catch{}return A},{}),a=[];for(let[A,b]of Object.entries(s)){let C=new FSe({breadcrumbs:[...this.breadcrumbs,A],node:b,context:this.context}).convert()??A;for(let x of b.messages){let S=this.context.convertReferenceToTypeReference({reference:x});if(S.ok){let P=this.resolveMessageDocs(x)??b.description,D=ZP.reference({bodyType:S.reference,docs:P});a.push({type:A,displayName:C,origin:b.action==="send"?"client":"server",body:D,availability:this.context.getAvailability({node:b,breadcrumbs:this.breadcrumbs}),docs:P,methodName:void 0})}}}let c=this.resolveChannelServersFromReference(this.channel.servers??[])??this.resolveFirstServerName(),l=this.transformToValidPath(this.channel.address??this.channelPath),u=jy(l),p=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[],d=this.hasServerSecurity()||this.context.authOverrides?.auth!=null,f=new NSe({context:this.context,breadcrumbs:this.breadcrumbs,node:this.context.spec}).convert(),g=new NSe({context:this.context,breadcrumbs:this.breadcrumbs,node:this.channel}).convert()??f;return{channel:{name:this.context.casingsGenerator.generateName(o),displayName:o,connectMethodName:void 0,baseUrl:c,path:u,auth:d,headers:n,queryParameters:r,pathParameters:t,messages:a,availability:this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({fullPath:l,baseUrl:c,asyncApiVersion:"v3"})},apiPlayground:g},audiences:p,inlinedTypes:this.inlinedTypes}}hasServerSecurity(){let r=this.context.spec.servers??{};if(this.channel.servers&&this.channel.servers.length>0){for(let n of this.channel.servers){let i=n.$ref.replace(KGo,""),o=r[i];if(o?.security&&o.security.length>0)return!0}return!1}for(let n of Object.values(r))if(n.security&&n.security.length>0)return!0;return!1}convertChannelParameters({pathParameters:t,queryParameters:r,headers:n,channelPath:i}){for(let o of Object.values(this.channel.parameters??{})){let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:[...this.breadcrumbs,"parameters"]});if(s==null)continue;let a=this.convertChannelParameterLocation(s.location);if(a==null)continue;let{type:c,parameterKey:l}=a,p=new kSe({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...s,name:l,in:c},parameterNamePrefix:this.channelPath}).convert();if(p!=null)switch(this.inlinedTypes={...this.inlinedTypes,...p.inlinedTypes},p.type){case"path":t.push(p.parameter);break;case"query":r.push(p.parameter);break;case"header":n.push(p.parameter);break}}}convertChannelParameterLocation(t){try{let[r,n]=t.split("#/");if(r==null||n==null){this.context.errorCollector.collect({message:`Invalid location format: ${t}; unable to parse message type and parameter key`,path:this.breadcrumbs});return}if(!r.startsWith(HGo)){this.context.errorCollector.collect({message:`Invalid location format: ${t}; expected ${HGo} prefix`,path:this.breadcrumbs});return}let i=r.substring(HGo.length);if(i!=="header"&&i!=="path"&&i!=="payload"){this.context.errorCollector.collect({message:`Invalid message type: ${i}. Must be one of: header, path, payload`,path:this.breadcrumbs});return}return i==="payload"?{type:"query",parameterKey:n}:{type:i,parameterKey:n}}catch{this.context.errorCollector.collect({message:`Invalid location format: ${t}; see here for more details: https://www.asyncapi.com/docs/reference/specification/v3.0.0#runtimeExpression`,path:this.breadcrumbs});return}}resolveMessageDocs(t){let r=t,n=new Set;for(;this.context.isReferenceObject(r);){if(n.has(r.$ref))return;n.add(r.$ref);let i=this.context.resolveReference({reference:r,breadcrumbs:this.breadcrumbs});if(!i.resolved)return;r=i.value}return r.description??r.summary}resolveChannelServersFromReference(t){if(t==null||t.length===0||t[0]==null)return;let r=t[0];if(!r.$ref.startsWith(KGo)){this.context.errorCollector.collect({message:`Failed to resolve server name from server ref ${r.$ref}`,path:this.breadcrumbs});return}let n=r.$ref.substring(KGo.length);if(n==null){this.context.errorCollector.collect({message:`Failed to find server with name ${n}`,path:this.breadcrumbs});return}let i=this.context.spec.servers;if(i!=null&&n in i){let o=i[n];return rJ.getServerName(n,o)}return n}resolveFirstServerName(){let t=this.context.spec.servers;if(t==null)return;let r=Object.keys(t)[0];if(r==null)return;let n=t[r];return rJ.getServerName(r,n)}getChannelPathFromOperation(t){if(!t.channel.$ref.startsWith(m7l))throw new T({message:`Failed to resolve channel path from operation ${t.channel.$ref}`,code:T.Code.ReferenceError});return t.channel.$ref.substring(m7l.length)}}});var vKr,g7l=h(()=>{"use strict";wGt();vKr=class extends rJ{constructor({context:t,breadcrumbs:r,servers:n}){super({context:t,breadcrumbs:r,servers:n})}buildSingleBaseUrlEnvironment(t,r,n){return{id:r,name:t.casingsGenerator.generateName(r),url:this.constructServerUrl(n.protocol,n.host),docs:void 0,audiences:void 0,defaultUrl:void 0,urlTemplate:void 0,urlVariables:void 0}}}});var TGt,A7l=h(()=>{"use strict";zn();sc();Uo();f7l();d7l();h7l();g7l();TGt=class extends tJ{constructor({context:t,breadcrumbs:r,audiences:n}){super({context:t,breadcrumbs:r,audiences:n})}async convert(){return this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.context.spec=await this.resolveAllExternalRefs({spec:this.context.spec}),this.isAsyncAPIV3(this.context)?this.convertChannelMessages():this.convertComponentMessages(),this.convertSchemas(),this.convertServers(),this.convertSecuritySchemes(),this.convertChannels(),this.finalizeIr()}isAsyncAPIV3(t){return parseFloat(t.spec.asyncapi)>=3}convertChannelMessages(){let t=this.context.spec;for(let[r,n]of Object.entries(t.channels??{}))for(let[i,o]of Object.entries(n.messages??{})){if(!this.context.isMessageWithPayload(o)&&!this.context.isReferenceObject(o))continue;let s=["channels",r,"messages",i],a=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:s});if(!this.context.isMessageWithPayload(a))continue;let c=this.context.resolveMaybeReference({schemaOrReference:a.payload,breadcrumbs:s});if(c==null)continue;let l=`${r}_${i}`;this.convertSchema({id:l,breadcrumbs:s,schema:c})}}convertComponentMessages(){for(let[t,r]of Object.entries(this.context.spec.components?.messages??{})){if(r.payload==null)continue;let n=["components","messages",t],i=this.context.resolveMaybeReference({schemaOrReference:r.payload,breadcrumbs:n});i!=null&&this.convertSchema({id:t,breadcrumbs:n,schema:i})}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{}))this.convertSchema({id:t,breadcrumbs:["components","schemas",t],schema:r})}convertSchema({id:t,breadcrumbs:r,schema:n}){let o=new Tm.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:r,schema:n}).convert();o!=null&&this.addSchemaOutputToIr(t,o)}convertServers(){let t;if(this.isAsyncAPIV3(this.context)){let r=this.context.spec.servers;t=new vKr({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}else{let r=this.context.spec.servers;t=new EKr({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}this.addEnvironmentsToIr({environmentConfig:t})}convertSecuritySchemes(){if(this.context.authOverrides){let r=G5t({rawApiFileSchema:this.context.authOverrides,casingsGenerator:this.context.casingsGenerator});this.addAuthToIR({requirement:r.requirement,schemes:r.schemes,docs:r.docs});return}let t=this.convertAsyncApiSecuritySchemes();t.length>0&&this.addAuthToIR({requirement:t.length===1?"ALL":"ANY",schemes:t,docs:void 0})}convertAsyncApiSecuritySchemes(){let t=[];for(let[r,n]of Object.entries(this.context.spec.components?.securitySchemes??{})){let i=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:["components","securitySchemes",r]});if(i==null)continue;let o=this.convertSecurityScheme({securityScheme:i,schemeId:r});o!=null&&t.push(o)}return t}convertSecurityScheme({securityScheme:t,schemeId:r}){switch(t.type){case"http":{if(t.scheme?.toLowerCase()==="bearer")return kp.bearer({key:r,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,tokenPlaceholder:void 0,docs:t.description,playgroundDocs:void 0});if(t.scheme?.toLowerCase()==="basic")return kp.basic({key:r,username:this.context.casingsGenerator.generateName("username"),password:this.context.casingsGenerator.generateName("password"),usernameEnvVar:void 0,passwordEnvVar:void 0,usernameOmit:!1,passwordOmit:!1,usernamePlaceholder:void 0,passwordPlaceholder:void 0,docs:t.description,playgroundDocs:void 0});break}case"apiKey":{if(t.in==="header")return kp.header({key:r,name:{name:this.context.casingsGenerator.generateName("apiKey"),wireValue:t.name},valueType:Ki.OPTIONAL_STRING,prefix:void 0,headerEnvVar:void 0,headerPlaceholder:void 0,docs:t.description,playgroundDocs:void 0});break}case"oauth2":return kp.bearer({key:r,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,tokenPlaceholder:void 0,docs:t.description,playgroundDocs:void 0})}}convertChannels(){for(let[t,r]of Object.entries(this.context.spec.channels??{})){let i=new vC.SdkGroupNameExtension({breadcrumbs:["channels",t],operation:r,context:this.context}).convert()?.groups,o;if(this.isAsyncAPIV3(this.context)){let a=this.context.spec.operations??{};o=new IKr({context:this.context,breadcrumbs:["channels",t],websocketGroup:i,channel:r,channelPath:t,operations:a}).convert()}else o=new bKr({context:this.context,breadcrumbs:["channels",t],websocketGroup:i,channel:r,channelPath:t}).convert();o!=null&&(this.addWebsocketChannelToIr({websocketChannel:o.channel,channelPath:t,audiences:o.audiences,websocketGroup:i}),this.addTypesToIr(o.inlinedTypes))}}}});var OGt,y7l=h(()=>{"use strict";zn();Uo();OGt=class extends Yb{isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}isMessageWithPayload(t){return t!=null&&typeof t=="object"&&"payload"in t}getTypeIdFromMessageReference(t){let r=t.$ref.match(/\/messages\/(.+)$/);if(!(!r||!r[1]))return r[1]}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i}){let o,s=t.$ref.match(/^.*\/schemas\/(.+)$/),a=t.$ref.match(/^.*\/channels\/([^/]+)\/messages\/(.+)$/),c=t.$ref.match(/^.*\/messages\/(.+)$/);if(s&&s[1])return o=s[1],this.convertSchemaReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o});if(a&&a[2]){let l=a[1],u=a[2];return o=`${l}_${u}`,this.convertV3MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o})}else return c&&c[1]?(o=c[1],this.convertV2MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o})):{ok:!1}}convertSchemaReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o}){let s=this.resolveReference({reference:t,breadcrumbs:r});if(!s.resolved)return{ok:!1};let a;if(i==="reference_identifier")a=n??s.value.title;else if(i==="discriminator_key")a=s.value.title??n;else{let c=t.$ref.split("/").pop()??o;a=s.value.title??c}return{ok:!0,reference:Hr.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}convertV3MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o}){let s=this.resolveReference({reference:t,breadcrumbs:r});if(!s.resolved)return{ok:!1};let a;if(i==="reference_identifier")a=n??s.value.name;else if(i==="discriminator_key")a=s.value.name??n;else{let c=t.$ref.split("/").pop()??o;a=s.value.name??c}return{ok:!0,reference:Hr.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}convertV2MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o}){let s=this.resolveReference({reference:t,breadcrumbs:r});if(!s.resolved)return{ok:!1};let a;if(i==="reference_identifier")a=n??s.value.messageId??s.value.name;else if(i==="discriminator_key")a=s.value.messageId??s.value.name??n;else{let c=t.$ref.split("/").pop()??o;a=s.value.messageId??s.value.name??c}return{ok:!0,reference:Hr.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}}});var b7l=h(()=>{"use strict";A7l();y7l()});function LGm(e){let t=new Set,r,n=new RegExp(MGm.source,"g");for(;(r=n.exec(e))!=null;)r[1]!=null&&t.add(r[1]);return t}var MGm,CKr,E7l=h(()=>{"use strict";Uo();MGm=/\{([^}]+)\}/g,CKr=class extends Vo{document;key="x-fern-base-path";constructor({breadcrumbs:t,document:r,context:n}){super({breadcrumbs:t,context:n}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(typeof t=="string")return this.parseString(t);if(typeof t=="object"&&!Array.isArray(t))return this.parseStructured(t);this.context.errorCollector.collect({message:"Expected `x-fern-base-path` to be a string or object",path:this.breadcrumbs})}}parseString(t){if(this.validatePath(t))return{path:t,parameters:[],pathsIncludeBasePath:!1}}parseStructured(t){let r=t.path;if(typeof r!="string"){this.context.errorCollector.collect({message:"`x-fern-base-path.path` must be a string",path:this.breadcrumbs});return}if(!this.validatePath(r))return;let n=LGm(r),i=t.parameters;if(i!=null&&(typeof i!="object"||Array.isArray(i))){this.context.errorCollector.collect({message:"`x-fern-base-path.parameters` must be an object map",path:[...this.breadcrumbs,"parameters"]});return}let o=i??{};for(let c of Object.keys(o))if(!n.has(c)){this.context.errorCollector.collect({message:`Parameter '${c}' does not appear in the base path '${r}'`,path:[...this.breadcrumbs,"parameters",c]});return}let s=[];for(let c of n){let l=o[c];if(l==null){s.push({name:c,type:"string",default:void 0,docs:void 0});continue}if(typeof l!="object"||Array.isArray(l)){this.context.errorCollector.collect({message:`Parameter '${c}' must be an object`,path:[...this.breadcrumbs,"parameters",c]});return}let u=l,p=typeof u.type=="string"?u.type:"string",d=typeof u.docs=="string"?u.docs:void 0;s.push({name:c,type:p,default:u.default,docs:d})}let a=t["paths-include-base-path"]===!0;return{path:r,parameters:s,pathsIncludeBasePath:a}}validatePath(t){return t.startsWith("/")?!0:(this.context.errorCollector.collect({message:"`x-fern-base-path` path must start with '/'",path:this.breadcrumbs}),!1)}}});var xKr,I7l=h(()=>{"use strict";Uo();xKr=class extends Vo{document;key="x-fern-base-url-env";constructor({breadcrumbs:t,document:r,context:n}){super({breadcrumbs:t,context:n}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(typeof t!="string"||t.length===0){this.context.errorCollector.collect({message:"Expected a non-empty string value for x-fern-base-url-env",path:this.breadcrumbs});return}return t}}}});var SKr,v7l=h(()=>{"use strict";Uo();SKr=class extends Vo{document;key="x-fern-global-headers";constructor({breadcrumbs:t,document:r,context:n}){super({breadcrumbs:t,context:n}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(!Array.isArray(t)){this.context.errorCollector.collect({message:"Received unexpected non-array value for x-fern-global-headers",path:this.breadcrumbs});return}return t}}}});function _Gm(e){let r=e["x-fern-default"]??e.default;if(typeof r=="string"||typeof r=="boolean"||typeof r=="number")return r}var wKr,C7l=h(()=>{"use strict";Uo();wKr=class extends Vo{document;key="x-fern-global-parameters";constructor({breadcrumbs:t,document:r,context:n}){super({breadcrumbs:t,context:n}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t==null)return;if(!Array.isArray(t)){this.context.errorCollector.collect({message:"Received unexpected non-array value for x-fern-global-parameters",path:this.breadcrumbs});return}let r=[];for(let[n,i]of t.entries()){if(typeof i!="object"||i==null||Array.isArray(i)){this.context.errorCollector.collect({message:`x-fern-global-parameters[${n}] must be an object`,path:[...this.breadcrumbs,`${n}`]});continue}let o=i;if(typeof o.name!="string"){this.context.errorCollector.collect({message:`x-fern-global-parameters[${n}].name is required and must be a string`,path:[...this.breadcrumbs,`${n}`,"name"]});continue}r.push({name:o.name,"parameter-name":typeof o["parameter-name"]=="string"?o["parameter-name"]:void 0,in:typeof o.in=="string"?o.in:void 0,target:typeof o.target=="string"?o.target:void 0,env:typeof o.env=="string"?o.env:void 0,default:_Gm(o),optional:typeof o.optional=="boolean"?o.optional:void 0,apply:typeof o.apply=="string"?o.apply:void 0,type:typeof o.type=="string"?o.type:void 0,docs:typeof o.docs=="string"?o.docs:void 0})}return r.length>0?r:void 0}}});function UGm(e){if(e!=null){if(typeof e=="string")return $t.Literal.string(e);if(typeof e=="boolean")return $t.Literal.boolean(e)}}function x7l({globalHeaderOverrides:e,context:t}){let r=[];for(let[n,i]of Object.entries(e.headers??{}))if(typeof i=="string")r.push({name:t.casingsGenerator.generateNameAndWireValue({name:n,wireValue:n}),valueType:Ki.STRING,env:void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}},availability:void 0,docs:void 0,clientDefault:void 0,defaultValue:void 0});else{let o=i.name??n;r.push({name:t.casingsGenerator.generateNameAndWireValue({name:o,wireValue:n}),valueType:Ki.STRING,env:i.env,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}},availability:void 0,docs:i.docs,clientDefault:UGm(i.default),defaultValue:i.default})}return r}var S7l=h(()=>{"use strict";zn();Uo()});function VGm(e){if(e!=null){if(typeof e=="string")return $t.Literal.string(e);if(typeof e=="boolean")return $t.Literal.boolean(e)}}function w7l({globalHeaders:e,context:t}){return e.map(r=>({name:t.casingsGenerator.generateNameAndWireValue({name:r.name??"",wireValue:r.header}),valueType:r.optional?Ki.OPTIONAL_STRING:Ki.STRING,env:r.env,v2Examples:r.optional?void 0:GGm({header:r,context:t}),availability:void 0,docs:void 0,clientDefault:VGm(r["x-fern-default"]),defaultValue:void 0}))}function GGm({header:e,context:t}){let r=new Bw({breadcrumbs:[],context:t,schema:{type:"string"},example:e.header}),{validExample:n}=r.convert();return{userSpecifiedExamples:{},autogeneratedExamples:{globalHeaderExample:n}}}var T7l=h(()=>{"use strict";zn();Uo()});function qGm(e,t,r,n){if(e!=null){if(typeof e=="boolean"){if(t!=null&&t!=="boolean"){n.errorCollector.collect({message:`Default value is a boolean but type is '${t}'; expected a ${t} value`,path:[...r,"default"]});return}return $t.Literal.boolean(e)}if(typeof e=="string"){if(t==="boolean"){n.errorCollector.collect({message:"Default value is a string but type is 'boolean'; expected a boolean value",path:[...r,"default"]});return}if(t==="integer"||t==="double"||t==="number"){n.errorCollector.collect({message:`Default value is a string but type is '${t}'; expected a numeric value`,path:[...r,"default"]});return}return $t.Literal.string(e)}if(typeof e=="number"){if(t==="boolean"){n.errorCollector.collect({message:"Default value is a number but type is 'boolean'; expected a boolean value",path:[...r,"default"]});return}if(t==="string"){n.errorCollector.collect({message:"Default value is a number but type is 'string'; expected a string value",path:[...r,"default"]});return}if(t==="integer"&&!Number.isInteger(e)){n.errorCollector.collect({message:`Default value ${e} is not an integer`,path:[...r,"default"]});return}return $t.Literal.string(String(e))}n.errorCollector.collect({message:`Default value has unsupported type '${typeof e}'; expected a string, number, or boolean`,path:[...r,"default"]})}}function WGm(e,t,r){switch(e){case void 0:case"body":return $t.GlobalParameterLocation.Body;case"query":return $t.GlobalParameterLocation.Query;case"header":return $t.GlobalParameterLocation.Header;case"path":return $t.GlobalParameterLocation.Path;default:return r.errorCollector.collect({message:`Invalid global parameter location '${e}'; expected one of: body, query, header, path`,path:t}),$t.GlobalParameterLocation.Body}}function HGm(e,t,r){switch(e){case void 0:return;case"explicit":return $t.GlobalParameterApplyMode.Explicit;case"auto":return $t.GlobalParameterApplyMode.Auto;default:r.errorCollector.collect({message:`Invalid global parameter apply mode '${e}'; expected one of: explicit, auto`,path:t});return}}function KGm(e,t){let r=JGm(e);return t===!0?$t.TypeReference.container($t.ContainerType.optional(r)):r}function JGm(e){switch(e){case"boolean":return $t.TypeReference.primitive({v1:"BOOLEAN",v2:$t.PrimitiveTypeV2.boolean({default:void 0})});case"integer":return $t.TypeReference.primitive({v1:"INTEGER",v2:$t.PrimitiveTypeV2.integer({default:void 0,validation:void 0})});case"double":case"number":return $t.TypeReference.primitive({v1:"DOUBLE",v2:$t.PrimitiveTypeV2.double({default:void 0,validation:void 0})});default:return Ki.STRING}}function YGm(e){return e.target!=null?e.target:e.name}function O7l({globalParameters:e,context:t}){let r=new Map;for(let[n,i]of e.entries()){let o=r.get(i.name);o!=null?t.errorCollector.collect({message:`Duplicate global parameter name '${i.name}' at index ${n} (first seen at index ${o}). Each global parameter must have a unique name.`,path:["x-fern-global-parameters",`${n}`,"name"]}):r.set(i.name,n)}return e.map((n,i)=>({param:n,index:i})).filter(({param:n,index:i})=>r.get(n.name)===i).map(({param:n,index:i})=>{let o=["x-fern-global-parameters",`${i}`],s=WGm(n.in,[...o,"in"],t),a=n["parameter-name"]??n.name;return{id:n.name,name:t.casingsGenerator.generateNameAndWireValue({name:a,wireValue:n.name}),location:s,target:YGm(n),valueType:KGm(n.type,n.optional),env:n.env,clientDefault:qGm(n.default,n.type,o,t),optional:n.optional,apply:HGm(n.apply,[...o,"apply"],t),docs:n.docs}})}var P7l=h(()=>{"use strict";zn();Uo()});var TKr,B7l=h(()=>{"use strict";mt();Uo();TKr=class extends Tm.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:n}){super({context:t,breadcrumbs:r,parameter:n})}convert(){let t,r={},n=this.getSchema();if(n!=null){let i=this.context.convertBreadcrumbsToName([...this.breadcrumbs,this.parameter.name]),s=new Tm.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,this.parameter.name,"schema"],schemaOrReference:n,wrapAsOptional:this.parameter.required==null||!this.parameter.required,schemaIdOverride:i}).convert();s!=null&&(t=s.type,r=s.inlinedTypes??{})}return this.convertToOutput({schema:n??{type:"string"},typeReference:t,inlinedTypes:r})}getSchema(){if(this.parameter.schema!=null)return this.parameter.schema;if(!(!this.context.settings.respectParameterContent||this.parameter.in!=="header"||this.parameter.content==null)){for(let[t,r]of Object.entries(this.parameter.content))if(r.schema!=null&&gp.parse(t)?.isJSON())return r.schema}}}});function ZGm({encoding:e}){if(e){if(e.explode)return"exploded";if(e.style==="form")return"form";if(e.contentType)return XGm[e.contentType]}}var OKr,XGm,D7l=h(()=>{"use strict";mt();zn();sc();Uo();OKr=class extends Tm.AbstractConverters.AbstractMediaTypeObjectConverter{contentType;mediaType;description;required;schemaId;streamingExtension;queryParameters;constructor({context:t,breadcrumbs:r,contentType:n,mediaType:i,description:o,required:s,group:a,method:c,streamingExtension:l,queryParameters:u}){super({context:t,breadcrumbs:r,group:a,method:c}),this.contentType=n,this.mediaType=i,this.description=o,this.required=s,this.schemaId=[...this.group,this.method,"Request"].join("_"),this.streamingExtension=l,this.queryParameters=u??[]}get bodyRequired(){return this.required===!1?!1:void 0}convert(){return this.streamingExtension?.type=="streamCondition"?this.convertStreamConditionRequestBody():this.convertNonStreamConditionRequestBody()}convertStreamConditionRequestBody(){if(this.isOrderedJsonOrFormContentType())return this.handleStreamConditionJsonOrFormContent({contentType:this.contentType})}convertNonStreamConditionRequestBody(){if(this.isOrderedJsonOrFormContentType())return this.handleJsonOrFormContent({contentType:this.contentType});if(gp.parse(this.contentType)?.isMultipart())return this.handleMultipartContent({contentType:this.contentType});if(this.isBinaryContentType())return this.handleBinaryContent({contentType:this.contentType})}isOrderedJsonOrFormContentType(){let t=gp.parse(this.contentType);return t?t.isJSON()||t.isURLEncoded()||t.isPlainText()||t.isCSV()||t.isHTML()||t.isXML()||t.isDNS()||t.isApplicationText():!1}isBinaryContentType(){let t=gp.parse(this.contentType);return t?t.isBinary():!1}handleJsonOrFormContent({contentType:t}){let r=this.mediaType;if(r==null)return;let n=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,contentType:t});if(n==null)return this.handleSchemalessJsonContent({contentType:t,mediaTypeObject:r});let i=n.schema?.typeDeclaration.shape;return i?.type==="object"?this.hasBodyQueryParameterOverlap(i.properties)?{requestBody:md.reference({contentType:t,docs:this.description,requestBodyType:n.type,required:this.bodyRequired,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:n.inlinedTypes??{}}:{requestBody:md.inlinedRequestBody({contentType:t,docs:this.description??n.schema?.typeDeclaration.docs,name:this.context.casingsGenerator.generateName(this.schemaId),extendedProperties:i.extendedProperties,extends:i.extends,properties:i.properties,extraProperties:i.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:n.inlinedTypes}),inlinedPropertiesByAudience:n.schema?.propertiesByAudience}:{requestBody:md.reference({contentType:t,docs:this.description,requestBodyType:n.type,required:this.bodyRequired,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:n.inlinedTypes??{}}}handleSchemalessJsonContent({contentType:t,mediaTypeObject:r}){if(!(r.example!=null||r.examples!=null&&Object.keys(r.examples).length>0))return;let i={userSpecifiedExamples:{},autogeneratedExamples:{}},o=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:r,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_example`}),s=new Set;for(let[a,c]of o){let l=this.context.resolveExampleWithValue(c),u=this.context.resolveExampleRecursively({example:c,breadcrumbs:this.breadcrumbs}),p=a;if(this.context.isExampleWithSummary(u)){let d=u.summary;s.has(d)||(p=d)}s.add(p),l!=null&&(i.userSpecifiedExamples[p]=l)}return{requestBody:md.reference({contentType:t,docs:this.description,requestBodyType:Hr.unknown(),required:this.bodyRequired,v2Examples:i}),streamRequestBody:void 0,inlinedTypes:{}}}handleMultipartContent({contentType:t}){let r=this.mediaType;if(r==null||r.schema==null)return;let n=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,resolveSchema:!0,contentType:t});if(n==null)return;let i=n.schema?.typeDeclaration.shape;if(i?.type==="object")return{requestBody:md.fileUpload({contentType:t,docs:this.description,name:this.context.casingsGenerator.generateName(this.schemaId),properties:i.properties.map(o=>{let s=r.encoding?.[cr(o.name)];return this.convertRequestBodyProperty({property:o,contentType:t,encoding:s})}),v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:n.inlinedTypes}),examples:n.examples}}handleBinaryContent({contentType:t}){let r=this.mediaType;if(r==null)return;let n=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,contentType:t});return{requestBody:md.bytes({contentType:t,isOptional:this.required===!1,docs:this.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:n?.inlinedTypes??{}}}convertRequestBodyProperty({property:t,contentType:r,encoding:n}){let{isFile:i,isOptional:o,isArray:s}=this.recursivelyCheckTypeReferenceIsFile({typeReference:t.valueType});return i?s?kx.file(eQ.fileArray({key:t.name,isOptional:o,contentType:r,docs:t.docs})):kx.file(eQ.file({key:t.name,isOptional:o,contentType:r,docs:t.docs})):kx.bodyProperty({...t,contentType:n?.contentType??r,style:ZGm({encoding:n}),name:t.name})}handleStreamConditionJsonOrFormContent({contentType:t}){if(this.streamingExtension?.type!=="streamCondition")return;let r=this.mediaType;if(r==null||r.schema==null)return;let n=this.context.resolveMaybeReference({schemaOrReference:r.schema,breadcrumbs:[...this.breadcrumbs,"content",t,"schema"]});if(n==null)return;let i=n.properties?.[this.streamingExtension.streamConditionProperty];if(i!=null&&this.context.isReferenceObject(i)&&(i=void 0),i==null){if(n.oneOf==null&&n.anyOf==null)return;i={type:"boolean"}}let o=this.buildStreamConditionRequestBody({streamConditionProperty:i,resolvedMediaTypeSchema:n,isStreaming:!0,contentType:t,mediaTypeObject:r}),s=this.buildStreamConditionRequestBody({streamConditionProperty:i,resolvedMediaTypeSchema:n,isStreaming:!1,contentType:t,mediaTypeObject:r});if(!(o==null||s==null))return{requestBody:s.requestBody,streamRequestBody:o.requestBody,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:{...o.inlinedTypes,...s.inlinedTypes}})}}buildStreamConditionRequestBody({streamConditionProperty:t,resolvedMediaTypeSchema:r,isStreaming:n,contentType:i,mediaTypeObject:o}){if(this.streamingExtension==null||this.streamingExtension.type!=="streamCondition")return;let s={...r,properties:{...r.properties,[this.streamingExtension.streamConditionProperty]:{...t,type:"boolean",const:n}},required:[...r.required??[],this.streamingExtension.streamConditionProperty]},a={...o,schema:s},c=this.parseMediaTypeObject({mediaTypeObject:a,schemaId:this.schemaId,contentType:i});if(c==null)return;let l=c.schema?.typeDeclaration.shape;return l?.type==="object"?{requestBody:md.inlinedRequestBody({contentType:i,docs:this.description??c.schema?.typeDeclaration.docs,name:this.context.casingsGenerator.generateName(n?this.streamingExtension?.streamRequestName??`${this.schemaId}_streaming`:this.schemaId),extendedProperties:l.extendedProperties,extends:l.extends,properties:l.properties,extraProperties:l.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:a,exampleGenerationStrategy:"request"})}),inlinedTypes:c.inlinedTypes}:{requestBody:md.reference({contentType:i,docs:this.description,requestBodyType:c.type,required:this.bodyRequired,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:a,exampleGenerationStrategy:"request"})}),inlinedTypes:c.inlinedTypes??{}}}recursivelyCheckTypeReferenceIsFile({typeReference:t,isOptional:r,isArray:n}){return this.context.isList(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.list,isOptional:r,isArray:!0}):this.context.isOptional(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.optional,isOptional:!0,isArray:n}):this.context.isNullable(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.nullable,isOptional:r,isArray:n}):{isFile:this.context.isFile(t),isOptional:r??!1,isArray:n??!1}}hasBodyQueryParameterOverlap(t){if(this.queryParameters.length===0)return!1;let r=new Set(this.queryParameters.map(n=>cr(n.name).toLowerCase()));return t.some(n=>r.has(cr(n.name).toLowerCase()))}},XGm={"application/json":"json"}});function t9m(e){return e?.header!=null}var $Gm,e9m,Uct,JGo=h(()=>{"use strict";mt();zn();sc();Uo();xo();B7l();D7l();$Gm=/{([^}]+)}/g,e9m=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]),Uct=class extends Ki{operation;method;path;pathItemParameters;inlinedTypes={};constructor({context:t,breadcrumbs:r,operation:n,method:i,path:o,pathItemParameters:s}){super({context:t,breadcrumbs:r}),this.operation=n,this.method=i,this.path=o,this.pathItemParameters=s??[]}convertHttpMethod(){switch(this.method){case"get":return gm.Get;case"post":return gm.Post;case"put":return gm.Put;case"delete":return gm.Delete;case"patch":return gm.Patch;case"head":return gm.Head;default:return}}convertParameters({breadcrumbs:t}){let r=[],n=[],i=[],o=this.mergeParameters(this.pathItemParameters,this.operation.parameters??[]);if(o.length===0)return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:n,headers:i};for(let s of o){let a=this.context.resolveMaybeReference({schemaOrReference:s,breadcrumbs:t});if(a==null)continue;let l=new TKr({context:this.context,breadcrumbs:t,parameter:a}).convert();if(l!=null)switch(this.inlinedTypes={...this.inlinedTypes,...l.inlinedTypes},l.type){case"path":r.push(l.parameter);break;case"query":n.push(l.parameter);break;case"header":{let u=jr(l.parameter.name),p=cr(l.parameter.name),d=!1,f=this.context.authOverrides?.["auth-schemes"];if(f!=null){for(let g of Object.values(f))if(t9m(g)&&g.header.toLowerCase()===p.toLowerCase()){d=!0;break}}let m=this.context.globalHeaderNames;if(m!=null){for(let g of m)if(g.toLowerCase()===p.toLowerCase()){d=!0;break}}!e9m.has(u.toLowerCase())&&!d&&i.push(l.parameter);break}}}return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:n,headers:i}}mergeParameters(t,r){if(t.length===0)return r;if(r.length===0)return t;let n=new Set;for(let o of r){let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:this.breadcrumbs});s!=null&&n.add(`${s.in}:${s.name}`)}return[...t.filter(o=>{let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:this.breadcrumbs});return s==null?!1:!n.has(`${s.in}:${s.name}`)}),...r]}checkMissingPathParameters(t){let n=[...this.path.matchAll($Gm)].map(i=>i[1]).filter(i=>!t.some(o=>jr(o.name)===i));for(let i of n){if(i==null)continue;let o=`${i}_example`;t.push({name:this.context.casingsGenerator.generateName(i),valueType:Ki.STRING,docs:void 0,location:"ENDPOINT",variable:void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{[o]:this.generateStringParameterExample({example:i})}},explode:void 0,clientDefault:void 0})}}convertRequestBody({breadcrumbs:t,group:r,method:n,streamingExtension:i,queryParameters:o}){if(this.operation.requestBody==null)return;let s=this.context.resolveMaybeReference({schemaOrReference:this.operation.requestBody,breadcrumbs:t});if(s==null)return null;let a=[];for(let[c,l]of Object.entries(s.content)){let p=new OKr({context:this.context,breadcrumbs:t,contentType:c,mediaType:l,description:s.description,required:s.required,group:r??[],method:n,streamingExtension:i,queryParameters:o}).convert();p!=null&&(this.inlinedTypes={...this.inlinedTypes,...p.inlinedTypes},a.push({requestBody:p.requestBody,streamRequestBody:p.streamRequestBody,examples:p.examples,inlinedPropertiesByAudience:p.inlinedPropertiesByAudience}))}return a}computeGroupNameAndLocationFromExtensions(){let r=new vC.SdkMethodNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.methodName,i=new vC.SdkGroupNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.groups??[];if(r!=null)return{group:i,method:r}}evaluateMethodNameFromOperation(){let t=this.operation.operationId;return t??(this.operation.summary!=null?ao(this.operation.summary):ao(`${this.method}_${this.path.split("/").join("_")}`))}sanitizeMethodName(t){return t.includes(".")?ao(t):t}computeGroupNameFromTagAndOperationId(){let t=this.operation.tags?.[0],r=this.evaluateMethodNameFromOperation();if(t==null)return{method:this.sanitizeMethodName(r)};let n=this.context.settings.respectOperationIdWordBoundaries,i=D7(t,n),o=D7(r,n);return qv(i,o)?{method:t}:this.computeGroupAndMethodFromTokens({tag:t,tagTokens:i,methodName:r,methodNameTokens:o})}computeGroupAndMethodFromTokens({tag:t,tagTokens:r,methodName:n,methodNameTokens:i}){if(r.some((a,c)=>a!==i[c]))return{group:[t],method:this.sanitizeMethodName(n)};let s=i.slice(r.length);return s[0]!=null&&/^\d/.test(s[0])?{group:[t],method:this.sanitizeMethodName(n)}:{group:[t],method:ao(s.join("_"))}}generateStringParameterExample({example:t}){let r=new Tm.ExampleConverter({breadcrumbs:this.breadcrumbs,context:this.context,schema:{type:"string"},example:t}),{validExample:n}=r.convert();return n}}});var Vct,YGo=h(()=>{"use strict";zn();JGo();Vct=class extends Uct{constructor({context:t,breadcrumbs:r,operation:n,method:i,path:o,pathItemParameters:s}){super({context:t,breadcrumbs:r,operation:n,method:i,path:o,pathItemParameters:s})}convert(){if(this.operation.requestBody==null){this.context.errorCollector.collect({message:"Skipping webhook because no request body present",path:this.breadcrumbs});return}let t=this.convertHttpMethod();if(t==null)return;if(t!=="POST"&&t!=="GET"){this.context.errorCollector.collect({message:"Skipping webhook because non-POST or GET method",path:this.breadcrumbs});return}let{group:r,method:n}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),i=[...this.breadcrumbs,"Payload"],{headers:o,queryParameters:s}=this.convertParameters({breadcrumbs:i}),a=this.convertRequestBody({breadcrumbs:i,group:r,method:n,streamingExtension:void 0,queryParameters:s});if(a==null)return;let c=a[0]?.requestBody;if(c==null)return;let l=c.type==="inlinedRequestBody"?a[0]?.inlinedPropertiesByAudience:void 0,u,p;if(c.type==="inlinedRequestBody")u=tT.inlinedPayload({name:c.name,extends:c.extends,properties:c.properties});else if(c.type==="reference")u=tT.reference({payloadType:c.requestBodyType,docs:c.docs});else if(c.type==="fileUpload")p={name:c.name,properties:c.properties,docs:c.docs,v2Examples:c.v2Examples,contentType:c.contentType},u=tT.inlinedPayload({name:c.name,extends:[],properties:[]});else return;let d=this.convertWebhookResponses();return{audiences:this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],group:r,inlinedPayloadPropertiesByAudience:l,webhook:{id:`${r?.join(".")??""}.${n}`,name:this.context.casingsGenerator.generateName(n),displayName:this.operation.summary,method:t,headers:o,payload:u,signatureVerification:void 0,fileUploadPayload:p,responses:d.length>0?d:void 0,examples:[],availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),docs:this.operation.description,v2Examples:{autogeneratedExamples:this.getWebhookV2ExamplesFromRequestBodyV2Examples(c.v2Examples?.autogeneratedExamples??{}),userSpecifiedExamples:this.getWebhookV2ExamplesFromRequestBodyV2Examples(c.v2Examples?.userSpecifiedExamples??{})}},inlinedTypes:this.inlinedTypes}}convertWebhookResponses(){let t=[];if(this.operation.responses==null)return t;for(let[r,n]of Object.entries(this.operation.responses)){let i=/^\d[Xx]{2}$/.test(r),o;if(i)o=parseInt(r.charAt(0))*100;else if(o=parseInt(r),isNaN(o))continue;let a=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:[...this.breadcrumbs,"responses",r]})?.description;t.push({statusCode:o,isWildcardStatusCode:i?!0:void 0,body:void 0,docs:a})}return t}getWebhookV2ExamplesFromRequestBodyV2Examples(t){return Object.fromEntries(Object.entries(t).map(([r,n])=>[r,{name:r,payload:n}]))}}});var R7l,k7l=h(()=>{"use strict";R7l=["get","post","put","delete","patch","head"]});var PKr,F7l=h(()=>{"use strict";Uo();PKr=class extends Vo{operation;key="x-fern-global-parameter";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;if(typeof t=="string")return[t];if(!Array.isArray(t)){this.context.errorCollector.collect({message:"Received unexpected value for x-fern-global-parameter; expected a string or array of strings",path:this.breadcrumbs});return}let r=[];for(let[n,i]of t.entries()){if(typeof i!="string"){this.context.errorCollector.collect({message:`x-fern-global-parameter[${n}] must be a string`,path:[...this.breadcrumbs,`${n}`]});continue}r.push(i)}return r.length>0?r:void 0}}});var BKr,N7l=h(()=>{"use strict";Uo();BKr=class extends Vo{operation;key="x-fern-idempotent";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-idempotent",path:this.breadcrumbs});return}return t}}}});var r9m,n9m,i9m,o9m,XGo,j7l=h(()=>{"use strict";nn();r9m=Xt.object({cursor:Xt.string(),next_cursor:Xt.string(),results:Xt.string()}),n9m=Xt.object({offset:Xt.string(),results:Xt.string(),step:Xt.string().optional(),"has-next-page":Xt.string().optional()}),i9m=Xt.object({next_uri:Xt.string(),results:Xt.string()}),o9m=Xt.object({next_path:Xt.string(),results:Xt.string()}),XGo=Xt.union([Xt.boolean(),r9m,n9m,i9m,o9m])});var ZGo,jSe,DKr,z7l=h(()=>{"use strict";Uo();j7l();ZGo="$request.",jSe="$response.",DKr=class extends Vo{operation;document;key="x-fern-pagination";constructor({breadcrumbs:t,operation:r,document:n,context:i}){super({breadcrumbs:t,context:i}),this.operation=r,this.document=n}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=XGo.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-pagination extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean"){let n=this.getExtensionValue(this.document);if(n==null)return;if(typeof n=="boolean"){this.context.errorCollector.collect({message:"Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.",path:this.breadcrumbs});return}let i=XGo.safeParse(n);if(!i.success){this.context.errorCollector.collect({message:`Invalid x-fern-pagination extension: ${i.error.message}`,path:this.breadcrumbs});return}if(typeof i.data=="boolean"){this.context.errorCollector.collect({message:"Global pagination extension is a boolean, expected an object.",path:this.breadcrumbs});return}return this.convertPaginationConfig({config:i.data})}if(typeof r.data=="boolean"){this.context.errorCollector.collect({message:"Pagination extension is a boolean with no global configuration.",path:this.breadcrumbs});return}return this.convertPaginationConfig({config:r.data})}convertPaginationConfig({config:t}){let r=t;if("cursor"in r)return{type:"cursor",cursor:Yb.maybeTrimPrefix(r.cursor,ZGo),nextCursor:Yb.maybeTrimPrefix(r.next_cursor,jSe),results:Yb.maybeTrimPrefix(r.results,jSe)};let n=t;if("next_uri"in n)return{type:"uri",nextUri:Yb.maybeTrimPrefix(n.next_uri,jSe),results:Yb.maybeTrimPrefix(n.results,jSe)};let i=t;if("next_path"in i)return{type:"path",nextPath:Yb.maybeTrimPrefix(i.next_path,jSe),results:Yb.maybeTrimPrefix(i.results,jSe)};let o=t;return{type:"offset",offset:Yb.maybeTrimPrefix(o.offset,ZGo),results:Yb.maybeTrimPrefix(o.results,jSe),step:o.step!=null?Yb.maybeTrimPrefix(o.step,ZGo):void 0,hasNextPage:o["has-next-page"]!=null?Yb.maybeTrimPrefix(o["has-next-page"],jSe):void 0}}}});function $Go(e){let t=e["x-fern-streaming"];if(t==null||typeof t=="boolean")return;let r=t.resumable;return typeof r=="boolean"?r:void 0}var s9m,a9m,c9m,RKr,Q7l=h(()=>{"use strict";Uo();nn();s9m="$request.",a9m=Xt.object({"stream-condition":Xt.string().optional(),format:Xt.enum(["sse","json"]).optional(),"stream-description":Xt.string().optional(),"stream-request-name":Xt.string().optional(),"response-stream":Xt.any(),response:Xt.any(),terminator:Xt.string().optional(),resumable:Xt.boolean().optional()}),c9m=Xt.union([Xt.boolean(),a9m]),RKr=class extends Vo{document;operation;key="x-fern-streaming";constructor({breadcrumbs:t,document:r,operation:n,context:i}){super({breadcrumbs:t,context:i}),this.document=r,this.operation=n}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=c9m.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-streaming extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean")return r.data?{type:"stream",format:"json",terminator:void 0,resumable:!1}:void 0;let n=r.data.resumable??$Go(this.document)??!1;if(r.data["stream-condition"]==null&&r.data.format!=null)return{type:"stream",format:r.data.format,terminator:r.data.terminator,resumable:n};if(r.data["stream-condition"]==null){this.context.errorCollector.collect({message:"Missing stream-condition property without specified format.",path:this.breadcrumbs});return}return{type:"streamCondition",format:r.data.format??"json",terminator:r.data.terminator,streamDescription:r.data["stream-description"],streamConditionProperty:Yb.maybeTrimPrefix(r.data["stream-condition"],s9m),streamRequestName:r.data["stream-request-name"],responseStream:r.data["response-stream"],response:r.data.response,resumable:n}}}});var kKr,M7l=h(()=>{"use strict";Uo();kKr=class extends Vo{operation;key="x-fern-subtitle";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="string"){this.context.errorCollector.collect({message:"Received unexpected non-string value for x-fern-subtitle",path:this.breadcrumbs});return}return t}}}});var FKr,L7l=h(()=>{"use strict";Uo();FKr=class extends Vo{operation;key="x-fern-webhook";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-webhook",path:this.breadcrumbs});return}return t}}}});function l9m(e){return oi(e)&&typeof e.$ref=="string"}function u9m(e,t){if(e!=null){if(typeof e=="string")return e;if(l9m(e)){let r=(0,_7l.resolve)(t??process.cwd(),e.$ref);if((0,jKr.existsSync)(r))try{return(0,jKr.readFileSync)(r,"utf-8")}catch{return}}}}var jKr,_7l,NKr,U7l=h(()=>{"use strict";mt();Uo();jKr=require("fs"),_7l=require("path");NKr=class extends Vo{operation;baseDir;key="x-codeSamples";constructor({context:t,breadcrumbs:r,operation:n,baseDir:i}){super({breadcrumbs:r,context:t}),this.operation=n,this.baseDir=i}convert(){let t=oi(this.operation)?this.operation:{},r=t["x-codeSamples"],n=t["x-code-samples"],i=Array.isArray(r)?r:[],o=Array.isArray(n)?n:[],s=[...i,...o];if(s.length===0)return;let a=[];for(let c of s){if(!oi(c))continue;let l=c,u=l.lang,p=l.label,d=l.source;if(typeof u!="string")continue;let f=u9m(d,this.baseDir);f!=null&&a.push({name:typeof p=="string"?p:u,language:u,code:f,install:void 0,docs:void 0})}if(a.length!==0)return[{"code-samples":a}]}}});function p9m(e){return oi(e)&&typeof e.$ref=="string"}function f9m(e,t){if(e!=null){if(typeof e=="string")return e;if(p9m(e)){let r=(0,V7l.resolve)(t??process.cwd(),e.$ref);if((0,QKr.existsSync)(r))try{return(0,QKr.readFileSync)(r,"utf-8")}catch{return}}}}function d9m(e,t){if(!Array.isArray(e))return[];let r=[];for(let n of e){if(!oi(n))continue;let o=f9m(n.code,t);o!=null&&r.push({...n,code:o})}return r}var QKr,V7l,zKr,G7l=h(()=>{"use strict";mt();lo();Uo();QKr=require("fs"),V7l=require("path");zKr=class extends Vo{operation;baseDir;key="x-fern-examples";constructor({context:t,breadcrumbs:r,operation:n,baseDir:i}){super({breadcrumbs:r,context:t}),this.operation=n,this.baseDir=i}convert(){let t=this.getExtensionValue(this.operation);return t==null?void 0:(Array.isArray(t)?t:[]).map(o=>{if(!oi(o))return o;let a=o["code-samples"];if(a!=null){let c=d9m(a,this.baseDir);return{...o,"code-samples":c}}return o}).filter(o=>{let s=Qd.serialization.ExampleEndpointCallSchema.parse(o);return s.ok||this.context.errorCollector.collect({message:`Failed to parse x-fern-example in ${this.breadcrumbs.join(".")}`,path:this.breadcrumbs}),s.ok})}}});var PGt,q7l=h(()=>{"use strict";Uo();PGt=class extends Vo{document;key="x-fern-explorer";constructor({breadcrumbs:t,document:r,context:n}){super({breadcrumbs:t,context:n}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-explorer",path:this.breadcrumbs});return}return t}}}});var BGt,W7l=h(()=>{"use strict";mt();zn();Uo();BGt=class extends Tm.AbstractConverters.AbstractMediaTypeObjectConverter{responseBody;statusCode;streamingExtension;convertedResponseHeaders;constructor({context:t,breadcrumbs:r,responseBody:n,group:i,method:o,statusCode:s,streamingExtension:a}){super({context:t,breadcrumbs:r,group:i,method:o}),this.responseBody=n,this.statusCode=s,this.streamingExtension=a}convert(){if(parseInt(this.statusCode)===204){this.responseBody.content!=null&&Object.keys(this.responseBody.content).length>0&&this.context.errorCollector.collect({message:"A 204 (No Content) response declares a body, but a 204 response cannot include one. Ignoring the declared body and treating the success response as optional.",path:this.breadcrumbs});return}return this.shouldConvertAsStreaming()?this.convertStreamingResponseBody():this.convertNonStreamingResponseBody()}convertStreamingResponseBody(){if(this.streamingExtension!=null){if(this.streamingExtension.type=="streamCondition"){let t=this.streamingExtension.responseStream,r=this.streamingExtension.response,n=[...this.group,this.method,"Response",this.statusCode].join("_"),i=`${n}_streaming`,o=this.parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:i}),s=this.parseMediaTypeSchemaOrReference({schemaOrReference:r,schemaId:n});return this.convertStreamConditionResponse({convertedStreamingSchema:o,convertedNonStreamingSchema:s})}if(this.streamingExtension.type==="stream"){let t=[...this.group,this.method,"Response",this.statusCode].join("_"),r=Object.keys(this.responseBody.content??{}),n=this.streamingExtension.format==="sse"?[...r.filter(i=>i.includes("text/event-stream")),...r.filter(i=>!i.includes("text/event-stream"))]:r;for(let i of n){let o=this.responseBody.content?.[i];if(o==null)continue;let s=this.parseMediaTypeObject({mediaTypeObject:o,schemaId:t,contentType:this.streamingExtension.format});if(s!=null)return this.convertStreamingResponse({mediaTypeObject:o,convertedSchema:s})}}}}convertNonStreamingResponseBody(){let t=[...this.group,this.method,"Response",this.statusCode].join("_"),r=Object.keys(this.responseBody.content??{}).filter(o=>o.includes("json"));for(let o of r){let s=this.responseBody.content?.[o];if(s==null)continue;let a=this.parseMediaTypeObject({mediaTypeObject:s,schemaId:t,contentType:o});if(a!=null&&this.shouldReturnJsonResponse(o))return this.returnJsonResponse({mediaTypeObject:s,convertedSchema:a})}let n=Object.keys(this.responseBody.content??{}).filter(o=>!o.includes("json"));for(let o of n){let s=this.responseBody.content?.[o];if(s==null)continue;let a=this.parseMediaTypeObject({mediaTypeObject:s,schemaId:t,contentType:o});if(a!=null){if(this.isBinarySchema(a))return this.shouldReturnBytesResponse()?this.returnBytesResponse({mediaTypeObject:s}):this.returnFileDownloadResponse({mediaTypeObject:s});if(this.shouldReturnTextResponse(o))return this.returnTextResponse({mediaTypeObject:s,contentType:o})}}let i=parseInt(this.statusCode);if(!isNaN(i)&&i>=200&&i<300&&i!==204){let o=r.map(c=>this.responseBody.content?.[c]).find(c=>c!=null),s={schema:{type:"object",description:"Empty response body"},...o?.examples!=null&&{examples:o.examples},...o?.example!=null&&{example:o.example}},a=this.parseMediaTypeObject({mediaTypeObject:s,schemaId:t,contentType:"application/json",resolveSchema:!0});if(a!=null)return this.returnJsonResponse({mediaTypeObject:s,convertedSchema:a})}}convertStreamConditionResponse({convertedStreamingSchema:t,convertedNonStreamingSchema:r}){if(t==null||r==null)return;let n=this.responseBody.description;return this.streamingExtension?.type==="streamCondition"&&this.streamingExtension.streamDescription!=null&&(n=this.streamingExtension.streamDescription),{responseBody:kl.json(K0.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:r.schema?.typeDeclaration.v2Examples})),streamResponseBody:kl.streaming(rv.json({docs:n,payload:t.type,terminator:this.streamingExtension?.terminator,v2Examples:t.schema?.typeDeclaration.v2Examples})),inlinedTypes:{...t.inlinedTypes,...r.inlinedTypes,...this.convertResponseHeaders().inlinedTypes},headers:this.convertResponseHeaders().headers}}convertStreamingResponse({mediaTypeObject:t,convertedSchema:r}){if(this.streamingExtension==null)return;switch(this.streamingExtension.format){case"json":return{responseBody:kl.streaming(rv.json({docs:this.responseBody.description,payload:r.type,terminator:this.streamingExtension?.terminator,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:{...r.inlinedTypes,...this.convertResponseHeaders().inlinedTypes},examples:r.examples,headers:this.convertResponseHeaders().headers};case"sse":return{responseBody:kl.streaming(rv.sse({docs:this.responseBody.description,payload:r.type,terminator:this.streamingExtension?.terminator,resumable:this.streamingExtension?.resumable,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:{...r.inlinedTypes,...this.convertResponseHeaders().inlinedTypes},examples:r.examples,headers:this.convertResponseHeaders().headers};default:return}}returnJsonResponse({mediaTypeObject:t,convertedSchema:r}){return{responseBody:kl.json(K0.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:{...r.inlinedTypes,...this.convertResponseHeaders().inlinedTypes},examples:r.examples,headers:this.convertResponseHeaders().headers}}returnBytesResponse({mediaTypeObject:t}){return{responseBody:kl.bytes({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:this.convertResponseHeaders().inlinedTypes,headers:this.convertResponseHeaders().headers}}returnFileDownloadResponse({mediaTypeObject:t}){return{responseBody:kl.fileDownload({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:this.convertResponseHeaders().inlinedTypes,headers:this.convertResponseHeaders().headers}}returnTextResponse({mediaTypeObject:t,contentType:r}){return{responseBody:kl.text({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"}),contentType:gp.parse(r)?.isPlainText()?void 0:r}),streamResponseBody:void 0,inlinedTypes:this.convertResponseHeaders().inlinedTypes,headers:this.convertResponseHeaders().headers}}isBinarySchema(t){let r=t.type;switch(r.type){case"container":case"named":case"unknown":return!1;case"primitive":return r.primitive.v2==null?!1:r.primitive.v2.type==="string"&&r.primitive.v2.validation?.format==="binary";default:return!1}}shouldConvertAsStreaming(){return this.streamingExtension!=null}shouldReturnJsonResponse(t){return t.includes("json")}shouldReturnBytesResponse(){return this.context.settings.useBytesForBinaryResponse&&this.streamingExtension==null}shouldReturnTextResponse(t){return gp.parse(t)?.isText()??!1}convertResponseHeaders(){return this.convertedResponseHeaders??=Mct({context:this.context,breadcrumbs:this.breadcrumbs,headers:this.responseBody.headers}),this.convertedResponseHeaders}}});var MKr,H7l=h(()=>{"use strict";mt();zn();Uo();MKr=class extends Tm.AbstractConverters.AbstractMediaTypeObjectConverter{responseError;statusCode;methodName;isWildcardStatusCode;convertedResponseHeaders;constructor({context:t,breadcrumbs:r,responseError:n,group:i,method:o,methodName:s,statusCode:a,isWildcardStatusCode:c}){super({context:t,breadcrumbs:r,group:i,method:o}),this.responseError=n,this.statusCode=a,this.methodName=s,this.isWildcardStatusCode=c}convert(){if(!this.responseError.content){let n=this.getErrorNameForStatusCode(this.statusCode,this.isWildcardStatusCode);if(n==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}let i=this.getErrorIdFromErrorName(n);return{error:{error:{name:this.context.casingsGenerator.generateName(i),fernFilepath:{allParts:[],packagePath:[],file:void 0},errorId:i},docs:this.responseError.description},errorType:Hr.unknown(),displayName:n,statusCode:this.statusCode,isWildcardStatusCode:this.isWildcardStatusCode,inlinedTypes:this.convertResponseHeaders().inlinedTypes,examples:{},headers:this.convertResponseHeaders().headers}}let t=Object.keys(this.responseError.content).filter(n=>n.includes("json")),r=this.getErrorNameForStatusCode(this.statusCode,this.isWildcardStatusCode);if(r==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}for(let n of[...t]){let i=this.responseError.content?.[n];if(i==null)continue;let o=this.parseMediaTypeObject({mediaTypeObject:i,schemaId:G6(`${this.methodName}Request${r}`),contentType:n});if(o==null)continue;let s=this.getErrorIdFromErrorName(r);if(o.schema!=null)return this.constructErrorConverterOutput({errorName:r,errorId:s,fernFilepath:o.schema.typeDeclaration.name.fernFilepath,convertedSchema:o,mediaTypeObject:i});if(o.type.type==="named")return this.constructErrorConverterOutput({errorName:r,errorId:s,fernFilepath:o.type.fernFilepath,convertedSchema:o,mediaTypeObject:i})}}constructErrorConverterOutput({errorName:t,errorId:r,fernFilepath:n,convertedSchema:i,mediaTypeObject:o}){return{error:{error:{name:this.context.casingsGenerator.generateName(r),fernFilepath:n,errorId:r},docs:this.responseError.description},errorType:i.type,displayName:t,statusCode:this.statusCode,isWildcardStatusCode:this.isWildcardStatusCode,inlinedTypes:{...i.inlinedTypes,...this.convertResponseHeaders().inlinedTypes},examples:this.convertErrorExamples({mediaTypeObject:o}),headers:this.convertResponseHeaders().headers}}convertErrorExamples({mediaTypeObject:t}){let r=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_error_example`});if(r.length===0)return;let n=new Set,i={};for(let[o,s]of r){let a=this.context.resolveExampleWithValue(s),c=this.context.resolveExampleRecursively({example:s,breadcrumbs:this.breadcrumbs}),l=this.getIdForErrorExample({key:o,example:c,usedExampleNames:n});n.add(l),a!=null&&(i[l]=a)}return Object.keys(i).length>0?i:void 0}getIdForErrorExample({key:t,example:r,usedExampleNames:n}){if(this.context.isExampleWithSummary(r)){let i=r.summary;if(!n.has(i))return i;let o=`${i} (${t})`;return n.has(o)?t:o}return t}getErrorNameForStatusCode(t,r){if(r){if(t===400)return"ClientRequestError";if(t===500)return"ServerError"}return hKr[t]}getErrorIdFromErrorName(t){return this.context.enableUniqueErrorsPerEndpoint?G6(`${this.methodName}Request${t}`):t}convertResponseHeaders(){return this.convertedResponseHeaders??=Mct({context:this.context,breadcrumbs:this.breadcrumbs,headers:this.responseError.headers}),this.convertedResponseHeaders}}});var LKr,K7l=h(()=>{"use strict";lo();zn();sc();W5();Uo();xo();U7l();G7l();q7l();W7l();H7l();JGo();LKr=class e extends Uct{idempotent;subtitle;globalParameterIds;idToAuthScheme;topLevelServers;pathLevelServers;streamingExtension;static AUTHORIZATION_HEADER="Authorization";constructor({context:t,breadcrumbs:r,operation:n,method:i,path:o,pathItemParameters:s,idempotent:a,subtitle:c,globalParameterIds:l,idToAuthScheme:u,topLevelServers:p,pathLevelServers:d,streamingExtension:f}){super({context:t,breadcrumbs:r,operation:n,method:i,path:o,pathItemParameters:s}),this.idempotent=a,this.subtitle=c,this.globalParameterIds=l,this.idToAuthScheme=u,this.topLevelServers=p,this.pathLevelServers=d,this.streamingExtension=f}convert(){let t=this.convertHttpMethod();if(t==null)return;let{group:r,method:n}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),i=this.getGroupDisplayName(r),o=this.getGroupDescription(r),{headers:s,pathParameters:a,queryParameters:c}=this.convertParameters({breadcrumbs:[...this.breadcrumbs,"parameters"]}),l=this.collectQueryParameterAudiences({breadcrumbs:[...this.breadcrumbs,"parameters"]}),u=this.convertRequestBody({breadcrumbs:[...this.breadcrumbs,"requestBody"],group:r,method:n,streamingExtension:this.streamingExtension,queryParameters:c}),p=u?.[0]?.requestBody,d=u?.[0]?.streamRequestBody,f=u?.[0]?.inlinedPropertiesByAudience,m={requestBodies:u?.map(ue=>ue.requestBody)},g=this.convertResponseBody({breadcrumbs:[...this.breadcrumbs,"responses"],group:r,method:n,streamingExtension:this.streamingExtension}),A=g?.response,b=g?.streamResponse,I=g!=null?g.errors:[],C={},x=I.map(ue=>ue.error),S=jy(this.path),P=this.context.perSpecBasePath,D=this.getEndpointBaseUrl(),R=this.getEndpointBaseUrls(),O=this.convertExamples({httpPath:S,httpMethod:t,baseUrl:D});if(Object.keys(O.examples).length===0&&Object.keys(O.streamExamples).length===0){let ue=this.synthesizeEndpointExamplesFromNativeRequestBody({httpPath:S,httpMethod:t,baseUrl:D});if(ue!=null)for(let[Pe,Ie]of Object.entries(ue))O.examples[Pe]=Ie}if(Object.keys(O.examples).length===0&&Object.keys(O.streamExamples).length===0&&u!=null&&u.length>1){let ue=this.synthesizeEndpointExamplesFromPerContentTypeRequestBodies({convertedRequestBodies:u,httpPath:S,httpMethod:t,baseUrl:D});if(ue!=null)for(let[Pe,Ie]of Object.entries(ue))O.examples[Pe]=Ie}let j=new Set(this.operation.security?.flatMap(ue=>Object.keys(ue))??[]),Y=this.authSchemeToHeaders(Array.from(j));Y.length>0&&s.push(...Y);for(let ue of I){let Pe=ue.error,Ie=ue.errorType,je=Pe.error.errorId,_e=ue.examples;C[je]={name:Pe.error,displayName:ue.displayName,discriminantValue:{name:Pe.error.name,wireValue:je},type:Ie,statusCode:ue.statusCode,isWildcardStatusCode:ue.isWildcardStatusCode,docs:Pe.docs,examples:[],v2Examples:{userSpecifiedExamples:_e??{},autogeneratedExamples:{}},headers:ue.headers}}let ee=this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],ce=new PGt({context:this.context,breadcrumbs:this.breadcrumbs,document:this.context.spec}).convert(),he=new PGt({context:this.context,breadcrumbs:this.breadcrumbs,document:this.operation}).convert()??ce,xe={displayName:this.operation.summary,subtitle:this.subtitle,method:t,baseUrl:D,v2BaseUrls:R,path:S,pathParameters:a,queryParameters:c,headers:s.filter((ue,Pe,Ie)=>Pe===Ie.findIndex(je=>cr(je.name)===cr(ue.name))),responseHeaders:g?.responseHeaders,sdkRequest:void 0,errors:x,auth:this.computeEndpointAuth(),security:this.computeEndpointSecurity(),availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),userSpecifiedExamples:[],autogeneratedExamples:[],idempotent:this.idempotent??!1,basePath:P!=null?jy(P):void 0,fullPath:P!=null?jy(`${P}${this.path}`):S,allPathParameters:a,pagination:void 0,transport:void 0,source:HD.openapi(),audiences:ee,retries:void 0,globalParameters:this.globalParameterIds,apiPlayground:he},Te=this.context.namespace!=null?[this.context.namespace]:[],pe=r?.map(ue=>ao(ue));return Te.push(...pe??[]),{audiences:ee,group:r,groupDisplayName:i,groupDescription:o,errors:C,endpoint:{...xe,id:`endpoint_${Te.join("/")}.${n}`,name:this.context.casingsGenerator.generateName(n),requestBody:p,v2RequestBodies:m,response:A,docs:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:O.examples},v2Responses:{responses:g?.v2Responses}},streamEndpoint:b!=null&&b.body!=null?{...xe,id:`endpoint_${Te.join("/")}.${n}_stream`,name:this.context.casingsGenerator.generateName(`${n}_stream`),requestBody:d,v2RequestBodies:void 0,response:b,docs:this.streamingExtension?.type==="streamCondition"?this.streamingExtension.streamDescription??this.operation.description:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:O.streamExamples},v2Responses:{responses:[{statusCode:200,isWildcardStatusCode:void 0,body:b.body,docs:b.docs}]}}:void 0,inlinedTypes:this.inlinedTypes,servers:this.filterOutTopLevelServers(this.operation.servers??this.pathLevelServers??[]),inlinedRequestPropertiesByAudience:f,queryParametersByAudience:l}}collectQueryParameterAudiences({breadcrumbs:t}){let r=this.mergeParameters(this.pathItemParameters,this.operation.parameters??[]);if(r.length===0)return;let n={},i=!1;for(let o of r){let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:t,skipErrorCollector:!0});if(s==null||s.in!=="query")continue;let a=this.context.getAudiences({operation:s,breadcrumbs:t})??[];if(a.length!==0){i=!0;for(let c of a)n[c]==null&&(n[c]=new Set),n[c].add(s.name)}}return i?n:void 0}convertResponseBody({breadcrumbs:t,group:r,method:n,streamingExtension:i}){if(this.operation.responses==null)return;let o,s=!1,a=!1;for(let[c,l]of Object.entries(this.operation.responses)){let u=/^[45]XX$/i.test(c),p,d=!1;if(u)p=parseInt(c.charAt(0))*100,d=!0;else{if(p=parseInt(c),isNaN(p)||p<200||p>=300&&p<400)continue;d=p>=400&&p<600}if(o==null&&(o={response:void 0,v2Responses:void 0,streamResponse:void 0,errors:[],examples:{},responseHeaders:[]}),p>=200&&p<300){let f=this.context.resolveMaybeReference({schemaOrReference:l,breadcrumbs:[...t,c]});if(f==null)continue;let g=new BGt({context:this.context,breadcrumbs:[...t,c],responseBody:f,group:r??[],method:n,statusCode:c,streamingExtension:i}).convert();if(g==null){a=!0,o.response==null&&(o.response={statusCode:p,isWildcardStatusCode:u?!0:void 0,body:void 0,docs:f.description});continue}g!=null&&(this.inlinedTypes={...this.inlinedTypes,...g.inlinedTypes},s||(s=!0,o.response={statusCode:p,isWildcardStatusCode:u?!0:void 0,body:g.responseBody,docs:f.description},o.streamResponse={statusCode:p,isWildcardStatusCode:u?!0:void 0,body:g.streamResponseBody,docs:f.description},g.headers!=null&&(o.responseHeaders=g.headers)),o.v2Responses=[...o.v2Responses??[],{statusCode:p,isWildcardStatusCode:u?!0:void 0,body:g.responseBody,docs:f.description}])}if(d){let f=this.context.resolveMaybeReference({schemaOrReference:l,breadcrumbs:[...t,c]});if(f==null)continue;let g=new MKr({context:this.context,breadcrumbs:[...t,c],responseError:f,group:r??[],method:n,methodName:this.evaluateMethodNameFromOperation(),statusCode:p,isWildcardStatusCode:u?!0:void 0}).convert();g!=null&&(this.inlinedTypes={...this.inlinedTypes,...g.inlinedTypes},o.errors.push(g))}}if(this.streamingExtension!=null){o==null&&(o={response:void 0,v2Responses:void 0,streamResponse:void 0,errors:[],examples:{},responseHeaders:[]});let l=new BGt({context:this.context,breadcrumbs:[...t,"stream"],responseBody:{description:""},group:r??[],method:n,statusCode:"stream",streamingExtension:i}).convert();l!=null&&(this.inlinedTypes={...this.inlinedTypes,...l.inlinedTypes},o.response={statusCode:200,isWildcardStatusCode:void 0,body:l.responseBody,docs:void 0},o.streamResponse={statusCode:200,isWildcardStatusCode:void 0,body:l.streamResponseBody,docs:void 0},o.v2Responses=[{statusCode:200,isWildcardStatusCode:void 0,body:l.responseBody,docs:void 0}])}if(a&&s&&o?.response?.body!=null){let c=o.response.body;if(c.type==="json"&&c.value.type==="response"){let l=c.value.responseBodyType;(l.type!=="container"||l.container.type!=="optional")&&(o.response={...o.response,body:kl.json(K0.response({...c.value,responseBodyType:Hr.container(As.optional(l))}))})}}return o}computeEndpointAuth(){return this.operation.security!=null&&this.operation.security.length===0?!1:this.operation.security!=null&&this.operation.security.length>0?!0:this.context.spec.security!=null&&this.context.spec.security.length>0||this.shouldApplyDefaultAuthOverrides()}computeEndpointSecurity(){return this.operation.security!=null&&this.operation.security.length===0?[]:this.context.authOverrides?.auth!=null&&!this.usesEndpointSecurity()?this.getDefaultSecurityFromAuthOverrides():UGo(this.operation.security??this.context.spec.security)}usesEndpointSecurity(){let t=this.context.authOverrides?.auth;return t!=null&&rnt(t)}shouldApplyDefaultAuthOverrides(){if(!this.context.authOverrides?.auth||this.usesEndpointSecurity())return!1;let t=this.context.spec.security!=null&&this.context.spec.security.length>0,r=this.operation.security!=null&&this.operation.security.length>0;return!(t||r)}getDefaultSecurityFromAuthOverrides(){if(!this.context.authOverrides?.auth)return;let t=this.context.authOverrides.auth;if(typeof t=="string"){let r={};return r[t]=[],[r]}if(typeof t=="object"&&"any"in t){let r=t.any;if(Array.isArray(r))return r.map(n=>{let i=typeof n=="string"?n:n.scheme,o={};return o[i]=[],o})}}authSchemeToHeaders(t){let r=[];for(let n of t){let i=this.idToAuthScheme?.[n];if(i==null)continue;let o={valueType:Ki.STRING,availability:void 0,docs:void 0,env:void 0,v2Examples:void 0,clientDefault:void 0,defaultValue:void 0};switch(i.type){case"bearer":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},...o});break;case"basic":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},...o});break;case"header":r.push({name:i.name,...o});break}}return r}convertExamples({httpPath:t,httpMethod:r,baseUrl:n}){let o=new zKr({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],a=new NKr({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],l=o.some(u=>Array.isArray(u["code-samples"])&&u["code-samples"].length>0)?o:[...o,...a];return l.length===0?{examples:{},streamExamples:{}}:this.streamingExtension?.type==="streamCondition"?this.convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:l}):{examples:this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:l}),streamExamples:{}}}synthesizeEndpointExamplesFromNativeRequestBody({httpPath:t,httpMethod:r,baseUrl:n}){if(this.operation.requestBody==null)return;let i=this.context.resolveMaybeReference({schemaOrReference:this.operation.requestBody,breadcrumbs:[...this.breadcrumbs,"requestBody"]});if(i==null)return;let o=this.extractNativeResponseExample(),s={};for(let[,a]of Object.entries(i.content)){if(a.schema!=null)continue;let c=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:a,breadcrumbs:[...this.breadcrumbs,"requestBody"],defaultExampleName:"Example"});for(let[l,u]of c){let p=this.context.resolveExampleWithValue(u);p!=null&&(s[l]={displayName:void 0,contentType:void 0,request:{docs:void 0,endpoint:{method:r,path:this.buildExamplePath(t,{})},baseUrl:void 0,environment:n,auth:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:p},response:o,codeSamples:void 0})}}return Object.keys(s).length>0?s:void 0}extractNativeResponseExample(){if(this.operation.responses!=null)for(let[t,r]of Object.entries(this.operation.responses)){let n=parseInt(t);if(isNaN(n)||n<200||n>=300)continue;let i=this.context.resolveMaybeReference({schemaOrReference:r,breadcrumbs:[...this.breadcrumbs,"responses",t]});if(i?.content!=null)for(let[,o]of Object.entries(i.content)){let s=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:o,breadcrumbs:[...this.breadcrumbs,"responses",t],defaultExampleName:"Example"});for(let[,a]of s){let c=this.context.resolveExampleWithValue(a);if(c!=null)return{docs:void 0,statusCode:n,body:$t.V2HttpEndpointResponseBody.json(c)}}}}}synthesizeEndpointExamplesFromPerContentTypeRequestBodies({convertedRequestBodies:t,httpPath:r,httpMethod:n,baseUrl:i}){let o={},s=this.extractNativeResponseExamplesByContentType();for(let a of t){let c=a.requestBody,l=c.contentType,u=c.v2Examples;if(u==null)continue;let p=u.userSpecifiedExamples;if(Object.keys(p).length===0)continue;let d=l!=null?s.get(l):void 0;for(let[f,m]of Object.entries(p)){let g=t.length>1&&l!=null?`${f} (${l})`:f;o[g]={displayName:t.length>1?g:void 0,contentType:l??void 0,request:{docs:void 0,endpoint:{method:n,path:this.buildExamplePath(r,{})},baseUrl:void 0,environment:i,auth:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:m},response:d??this.extractNativeResponseExample()??void 0,codeSamples:void 0}}}return Object.keys(o).length>0?o:void 0}extractNativeResponseExamplesByContentType(){let t=new Map;if(this.operation.responses==null)return t;for(let[r,n]of Object.entries(this.operation.responses)){let i=parseInt(r);if(isNaN(i)||i<200||i>=300)continue;let o=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:[...this.breadcrumbs,"responses",r]});if(o?.content!=null)for(let[s,a]of Object.entries(o.content)){if(t.has(s))continue;let c=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:a,breadcrumbs:[...this.breadcrumbs,"responses",r],defaultExampleName:"Example"});for(let[,l]of c){let u=this.context.resolveExampleWithValue(l);if(u!=null){t.set(s,{docs:void 0,statusCode:i,body:$t.V2HttpEndpointResponseBody.json(u)});break}}}}return t}convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:i}){let o=i.filter(l=>!(l.response!=null&&"stream"in l.response)),s=i.filter(l=>l.response!=null&&"stream"in l.response),a=this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:o}),c=this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:s});return{examples:a,streamExamples:c}}convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:i}){return Object.fromEntries(i.map((o,s)=>[this.getExampleName({example:o,exampleIndex:s}),{displayName:void 0,contentType:void 0,request:o.request!=null||o["path-parameters"]!=null||o["query-parameters"]!=null||o.headers!=null?{docs:void 0,endpoint:{method:r,path:this.buildExamplePath(t,o["path-parameters"]??{})},baseUrl:void 0,environment:n,auth:void 0,pathParameters:o["path-parameters"]??{},queryParameters:o["query-parameters"]??{},headers:o.headers??{},requestBody:o.request??void 0}:void 0,response:o.response!=null?{docs:void 0,statusCode:void 0,body:this.getExampleResponseBody({example:o})}:void 0,codeSamples:o["code-samples"]?.map(a=>{let c=("language"in a?a.language:a.sdk)??void 0;return{name:a.name,docs:void 0,language:c,code:a.code}})}]))}getExampleName({example:t,exampleIndex:r}){return t.name??t["code-samples"]?.[0]?.name??`Example_${r}`}getExampleResponseBody({example:t}){if(t.response!=null){if("stream"in t.response)return $t.V2HttpEndpointResponseBody.stream(t.response.stream);if("body"in t.response)return $t.V2HttpEndpointResponseBody.json(t.response.body)}}getEndpointBaseUrl(){let r=new vC.ServerFromOperationNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert();if(r!=null)return this.context.logger.debug(`[getEndpointBaseUrl] Endpoint ${this.method.toUpperCase()} ${this.path} specifies a server with "${un.SERVER_NAME_V2}" extension. Returning server type: ${r}`),r;let n=this.operation.servers?.[0]??this.pathLevelServers?.[0];if(n==null)return;let o=this.topLevelServers?.find(s=>s.url===n.url)??n;return l3.getServerName({server:o,context:this.context})}getEndpointBaseUrls(){if(new vC.ServerFromOperationNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()!=null)return;let n=this.operation.servers??this.pathLevelServers;return n?.map(o=>{let a=this.topLevelServers?.find(c=>c.url===o.url)??o;return l3.getServerName({server:a,context:this.context})})}buildExamplePath(t,r){return t.head+t.parts.map(n=>`${r[n.pathParameter]?.toString()??n.pathParameter}${n.tail}`).join("")}filterOutTopLevelServers(t){return t.filter(r=>!this.topLevelServers?.some(n=>n.url===r.url))}getGroupDisplayName(t){let r=this.operation.tags?.[0],n=t?.[t.length-1];if(r==null||n==null)return;let i=this.context.getDisplayNameForTag(r);if(i.toLowerCase().replaceAll(" ","")===n||this.context.hasExplicitDisplayNameForTag(r)&&ao(r)===ao(n))return i}getGroupDescription(t){let r=this.operation.tags?.[0],n=t?.[t.length-1];if(!(r==null||n==null)&&ao(r)===ao(n))return this.context.getDescriptionForTag(r)}}});var e9o,_Kr,J7l=h(()=>{"use strict";Uo();e9o=Ae(zUt(),1);k7l();F7l();N7l();z7l();Q7l();M7l();L7l();K7l();YGo();_Kr=class extends Ki{pathItem;path;idToAuthScheme;topLevelServers;declaredGlobalParameterIds;constructor({context:t,breadcrumbs:r,pathItem:n,path:i,idToAuthScheme:o,topLevelServers:s,declaredGlobalParameterIds:a}){super({context:t,breadcrumbs:r}),this.pathItem=n,this.path=i,this.idToAuthScheme=o,this.topLevelServers=s,this.declaredGlobalParameterIds=a}convert(){let t=[],r=[],n={};for(let i of R7l){let o=this.pathItem[i];if(o==null)continue;let s=[...this.breadcrumbs,i],a=this.tryParseAsWebhook({operationBreadcrumbs:s,operation:o,method:i,context:this.context});if(a!=null){r.push(a),Object.assign(n,a.inlinedTypes);continue}let l=new RKr({breadcrumbs:s,document:this.context.spec,operation:o,context:this.context}).convert();l==null&&this.operationHasTextEventStreamResponse(o)&&(l={type:"stream",format:"sse",terminator:void 0,resumable:$Go(this.context.spec)??!1});let u=this.tryParseAsHttpEndpoint({operationBreadcrumbs:s,operation:o,method:i,streamingExtension:l});u!=null&&(t.push(u),Object.assign(n,u.inlinedTypes))}return{endpoints:t,webhooks:r,inlinedTypes:n}}tryParseAsWebhook({operation:t,method:r,operationBreadcrumbs:n,context:i}){return new FKr({breadcrumbs:n,operation:t,context:i}).convert()?new Vct({context:this.context,breadcrumbs:n,operation:t,method:e9o.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path,pathItemParameters:this.pathItem.parameters}).convert():void 0}operationHasTextEventStreamResponse(t){if(t.responses==null)return!1;for(let[r,n]of Object.entries(t.responses)){let i=parseInt(r);if(isNaN(i)||i<200||i>=300)continue;let o=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:this.breadcrumbs});if(o?.content==null)continue;let s=Object.keys(o.content);if(s.length===1&&s[0]?.includes("text/event-stream"))return!0}return!1}tryParseAsHttpEndpoint({operation:t,method:r,operationBreadcrumbs:n,streamingExtension:i}){new DKr({breadcrumbs:n,operation:t,document:this.context.spec,context:this.context}).convert()!=null;let c=new BKr({breadcrumbs:n,operation:t,context:this.context}).convert(),u=new kKr({breadcrumbs:n,operation:t,context:this.context}).convert(),d=new PKr({breadcrumbs:n,operation:t,context:this.context}).convert();if(d!=null&&this.declaredGlobalParameterIds!=null){let m=[];for(let g of d)this.declaredGlobalParameterIds.has(g)?m.push(g):this.context.errorCollector.collect({message:`x-fern-global-parameter references undeclared global parameter '${g}'. Declared parameters: ${[...this.declaredGlobalParameterIds].join(", ")}`,path:[...n,"x-fern-global-parameter"]});d=m.length>0?m:void 0}return new LKr({context:this.context,breadcrumbs:n,operation:t,method:e9o.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path,pathItemParameters:this.pathItem.parameters,idempotent:c,subtitle:u,globalParameterIds:d,idToAuthScheme:this.idToAuthScheme,topLevelServers:this.topLevelServers,pathLevelServers:this.pathItem.servers,streamingExtension:i}).convert()}}});var UKr,Y7l=h(()=>{"use strict";zn();Uo();UKr=class extends Ki{securityScheme;schemeId;constructor({context:t,breadcrumbs:r,securityScheme:n,schemeId:i}){super({context:t,breadcrumbs:r}),this.securityScheme=n,this.schemeId=i}getExtension(t){return this.securityScheme[t]}convert(){let t=this.getExtension("x-fern-playground-description");switch(this.securityScheme.type){case"http":{if(this.securityScheme.scheme?.toLowerCase()==="bearer"){let r=this.getExtension("x-fern-bearer"),n=r?.name??"token",i=r?.env,o=r?.placeholder;return kp.bearer({key:this.schemeId,token:this.context.casingsGenerator.generateName(n),tokenEnvVar:i,tokenPlaceholder:o,docs:this.securityScheme.description,playgroundDocs:t})}if(this.securityScheme.scheme?.toLowerCase()==="basic"){let r=this.getExtension("x-fern-basic"),n=r?.username?.name??"username",i=r?.password?.name??"password",o=r?.username?.env,s=r?.password?.env,a=r?.username?.placeholder,c=r?.password?.placeholder;return kp.basic({key:this.schemeId,username:this.context.casingsGenerator.generateName(n),password:this.context.casingsGenerator.generateName(i),usernameEnvVar:o,passwordEnvVar:s,usernameOmit:!1,passwordOmit:!1,usernamePlaceholder:a,passwordPlaceholder:c,docs:this.securityScheme.description,playgroundDocs:t})}break}case"apiKey":{if(this.securityScheme.in==="header"){let r=this.getExtension("x-fern-header"),n=r?.name??"apiKey",i=r?.env,o=r?.prefix,s=r?.placeholder;return kp.header({key:this.schemeId,name:{name:this.context.casingsGenerator.generateName(n),wireValue:this.securityScheme.name},valueType:Ki.OPTIONAL_STRING,prefix:o,headerEnvVar:i,headerPlaceholder:s,docs:this.securityScheme.description,playgroundDocs:t})}break}case"oauth2":return kp.bearer({key:this.schemeId,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,tokenPlaceholder:void 0,docs:this.securityScheme.description,playgroundDocs:t})}}}});function m9m(e){if(e!=null){if(typeof e=="string")return kE.string(e);if(typeof e=="boolean")return kE.boolean(e)}}var X7l,DGt,Z7l=h(()=>{"use strict";mt();lo();zn();sc();W5();Uo();X7l=Ae(zUt(),1);E7l();I7l();v7l();C7l();S7l();T7l();P7l();YGo();J7l();Y7l();DGt=class extends tJ{constructor({breadcrumbs:t,context:r,audiences:n}){super({breadcrumbs:t,context:r,audiences:n})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.context.spec=await this.resolveAllExternalRefs({spec:this.context.spec}),this.context.spec=QUt({document:this.context.spec,options:this.context.settings,logger:this.context.logger}),_Go({spec:this.context.spec,errorCollector:this.context.errorCollector}),this.overrideOpenApiAuthWithGeneratorsAuth(),this.convertSecuritySchemes(),this.convertGlobalHeaders(),this.convertGlobalParameters(),this.convertBasePath(),this.convertSchemas(),this.convertWebhooks();let{endpointLevelServers:t,errors:r}=this.convertPaths();this.addErrorsToIr(r);let{defaultUrl:n}=this.convertServers({endpointLevelServers:t});this.updateEndpointsWithDefaultUrl(n);let i=this.context.spec.info?.title?.trim();return i&&i!=='""'&&(this.ir.apiDisplayName=i),this.finalizeIr()}convertGlobalHeaders(){if(this.context.globalHeaderOverrides){let n=x7l({globalHeaderOverrides:this.context.globalHeaderOverrides,context:this.context});this.addGlobalHeadersToIr(n),this.context.setGlobalHeaders(n);return}let r=new SKr({breadcrumbs:["x-fern-global-headers"],document:this.context.spec,context:this.context}).convert();if(r!=null){let n=w7l({globalHeaders:r,context:this.context});this.addGlobalHeadersToIr(n),this.context.setGlobalHeaders(n)}}convertGlobalParameters(){let r=new wKr({breadcrumbs:["x-fern-global-parameters"],document:this.context.spec,context:this.context}).convert();if(r!=null){let n=O7l({globalParameters:r,context:this.context});if(this.ir.globalParameters=n,this.ir.headers.length>0){let i=new Set(this.ir.headers.map(o=>{let s=o.name;return(typeof s=="string"?s:s.wireValue).toLowerCase()}));for(let o of r){let s=(o.target??o.name).toLowerCase();o.in==="header"&&i.has(s)&&this.context.logger.warn(`Global parameter "${o.name}" (in: header, target: "${o.target??o.name}") overlaps with an x-fern-global-headers entry. The x-fern-global-parameters definition takes precedence.`)}}}}convertBasePath(){let r=new CKr({breadcrumbs:["x-fern-base-path"],document:this.context.spec,context:this.context}).convert();if(r!=null){if(this.context.settings.respectPerSpecBasePath&&r.parameters.length===0){r.pathsIncludeBasePath||(this.context.perSpecBasePath=Xh(r.path));return}this.context.settings.respectPerSpecBasePath&&r.parameters.length>0&&this.context.errorCollector.collect({message:"respect-per-spec-base-path only applies to an x-fern-base-path without path parameters; this base path is used as the API-wide base path instead, which only one spec keeps when multiple specs are merged",path:["x-fern-base-path"]}),this.ir.basePath=jy(r.path);for(let n of r.parameters)n.type!=="string"&&this.context.errorCollector.collect({message:`x-fern-base-path parameter '${n.name}' uses type '${n.type}' which is not yet supported; treating as string`,path:["x-fern-base-path","parameters",n.name]}),this.ir.pathParameters.push({name:this.context.casingsGenerator.generateName(n.name),valueType:Ki.STRING,docs:n.docs,location:$t.PathParameterLocation.Root,variable:void 0,clientDefault:m9m(n.default),v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}},explode:void 0});if(r.pathsIncludeBasePath){let n=jUt({openApi:this.context.spec,basePath:r.path,rootPathParameterNames:new Set(r.parameters.map(i=>i.name))});for(let i of n)this.context.errorCollector.collect({message:i,path:["x-fern-base-path","paths-include-base-path"]})}}}convertSecuritySchemes(){let t=this.convertOpenApiSecuritySchemes();if(this.context.authOverrides){let r=new Map(t.map(n=>[n.key,n.docs]));this.convertAuthOverrides(r,this.context.authOverrides);return}t.length>0&&this.addAuthToIR({requirement:t.length===1?"ALL":"ANY",schemes:t,docs:void 0})}convertAuthOverrides(t,r){let n={...r,"auth-schemes":Object.fromEntries(Object.entries(r["auth-schemes"]??{}).map(([o,s])=>[o,{...s}]))};for(let[o,s]of Object.entries(n["auth-schemes"]))!s.docs&&t.has(o)&&(s.docs=t.get(o));let i=G5t({rawApiFileSchema:n,casingsGenerator:this.context.casingsGenerator});this.addAuthToIR({requirement:i.requirement,schemes:i.schemes,docs:i.docs})}convertOpenApiSecuritySchemes(){let t=[];for(let[r,n]of Object.entries(this.context.spec.components?.securitySchemes??{})){let i=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:["components","securitySchemes",r]});if(i==null)continue;let s=new UKr({context:this.context,breadcrumbs:["components","securitySchemes",r],securityScheme:i,schemeId:r}).convert();s!=null&&t.push(s)}return t}convertServers({endpointLevelServers:t}){let n=new xKr({breadcrumbs:["x-fern-base-url-env"],document:this.context.spec,context:this.context}).convert();if(this.context.environmentOverrides){let s=q5t({rawApiFileSchema:this.context.environmentOverrides,casingsGenerator:this.context.casingsGenerator});return s!=null&&this.addEnvironmentsToIr({environmentConfig:{...s.environmentsConfig,baseUrlEnvVar:s.environmentsConfig.baseUrlEnvVar??n},audiences:s.audiences}),{defaultUrl:this.context.environmentOverrides["default-url"]}}let o=new l3({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t,baseUrlEnvVar:n}).convert();return this.addEnvironmentsToIr({environmentConfig:o?.value}),{defaultUrl:o?.defaultUrl}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{})){let i=new Tm.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:["components","schemas",t],schema:r}).convert();i!=null&&this.addSchemaOutputToIr(t,i)}}convertWebhooks(){for(let[t,r]of Object.entries(this.context.spec.webhooks??{})){if(r==null){this.context.errorCollector.collect({message:"Skipping empty webhook",path:this.breadcrumbs});continue}if(!("post"in r)||r.post==null){this.context.errorCollector.collect({message:"Skipping webhook as it is not a POST method",path:this.breadcrumbs});continue}let n=r.post.operationId??t,i=r.post.operationId!=null?r.post:{...r.post,operationId:n},s=new Vct({context:this.context,breadcrumbs:["webhooks",n],operation:i,method:X7l.OpenAPIV3.HttpMethods.POST,path:n}).convert();s!=null&&(this.addWebhookToIr({webhook:s.webhook,operationId:n,audiences:s.audiences,group:s.group,inlinedPayloadPropertiesByAudience:s.inlinedPayloadPropertiesByAudience}),this.addTypesToIr(s.inlinedTypes))}}convertPaths(){let t=[],r={},n=this.ir.globalParameters!=null?new Set(this.ir.globalParameters.map(i=>i.id)):void 0;for(let[i,o]of Object.entries(this.context.spec.paths??{})){if(o==null)continue;let a=new _Kr({context:this.context,breadcrumbs:["paths",i],topLevelServers:this.context.spec.servers,pathItem:o,path:i,declaredGlobalParameterIds:n}).convert();if(a!=null){for(let c of a.endpoints){if(c.streamEndpoint!=null&&this.addEndpointToIr({endpoint:c.streamEndpoint,audiences:c.audiences,endpointGroup:c.group,endpointGroupDisplayName:c.groupDisplayName,endpointGroupDescription:c.groupDescription,inlinedRequestPropertiesByAudience:c.inlinedRequestPropertiesByAudience,queryParametersByAudience:c.queryParametersByAudience}),this.addEndpointToIr({endpoint:c.endpoint,audiences:c.audiences,endpointGroup:c.group,endpointGroupDisplayName:c.groupDisplayName,endpointGroupDescription:c.groupDescription,inlinedRequestPropertiesByAudience:c.inlinedRequestPropertiesByAudience,queryParametersByAudience:c.queryParametersByAudience}),c.servers)for(let l of c.servers)this.shouldAddServerToCollectedServers({server:l,currentServers:t})&&t.push(l);if(c.errors)for(let[l,u]of Object.entries(c.errors))r[l]=u}for(let c of a.webhooks){let l=this.context.getGroup({groupParts:c.group,namespace:this.context.namespace});this.addWebhookToIr({webhook:c.webhook,operationId:l.join("."),group:l,audiences:c.audiences,inlinedPayloadPropertiesByAudience:c.inlinedPayloadPropertiesByAudience})}this.addTypesToIr(a.inlinedTypes)}}return{endpointLevelServers:t,errors:r}}overrideOpenApiAuthWithGeneratorsAuth(){if(!this.context.authOverrides?.["auth-schemes"])return;let t=this.context.authOverrides.auth;if(t!=null&&rnt(t))return;let r={};for(let n of Object.keys(this.context.authOverrides["auth-schemes"]))r[n]=[];this.context.spec.security=[r],this.removeEndpointSpecificAuth()}removeEndpointSpecificAuth(){if(this.context.spec.paths)for(let t of Object.values(this.context.spec.paths)){if(!t)continue;let r=["get","post","put","patch","delete","options","head","trace"];for(let n of r){let i=t[n];i?.security!=null&&i.security.length>0&&delete i.security}}}}});var VKr,$7l=h(()=>{"use strict";Uo();VKr=class extends Vo{tag;key="x-displayName";constructor({breadcrumbs:t,tag:r,context:n}){super({breadcrumbs:t,context:n}),this.tag=r}convert(){if(typeof this.tag!="object"||this.tag==null)return;let t=this.tag[this.key];if(t!=null){if(typeof t!="string"){this.context.errorCollector.collect({message:"x-displayName extension must be a string",path:this.breadcrumbs});return}if(t.trim().length!==0)return{displayName:t}}}}});var wUe,eHl=h(()=>{"use strict";zn();sc();Uo();$7l();wUe=class extends Yb{perSpecBasePath;globalHeaderNames;tagToDisplayName={};tagsWithExplicitDisplayName=new Set;tagToDescription=new Map;tagDescriptionsIndexed=!1;isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i}){let o=this.getTypeIdFromSchemaReference(t);if(o==null)return{ok:!1};let s=t.$ref.split("/").pop()??o,a=this.resolveReference({reference:t,breadcrumbs:r});if(!a.resolved)return{ok:!1};let c;i==="reference_identifier"?c=n??a.value.title:i==="discriminator_key"?c=a.value.title??n:c=a.value.title??s;let l;if(o.includes("/")){let p=new Tm.SchemaConverters.SchemaConverter({context:this,breadcrumbs:r??[],schema:a.value,id:o}).convert();p!=null&&(l={[o]:p.convertedSchema})}return{ok:!0,reference:Hr.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(s),typeId:o,default:void 0,inline:!1,displayName:c}),inlinedTypes:l}}setGlobalHeaders(t){this.globalHeaderNames=t.map(r=>cr(r.name))}getDisplayNameForTag(t){if(Object.keys(this.tagToDisplayName).length===0)for(let r of this.spec.tags??[]){let i=new VKr({breadcrumbs:["tags",r.name],tag:r,context:this}).convert()?.displayName;i!=null&&this.tagsWithExplicitDisplayName.add(r.name),this.tagToDisplayName[r.name]=i??r.name}return this.tagToDisplayName[t]??t}hasExplicitDisplayNameForTag(t){return this.getDisplayNameForTag(t),this.tagsWithExplicitDisplayName.has(t)}getDescriptionForTag(t){if(!this.tagDescriptionsIndexed){this.tagDescriptionsIndexed=!0;for(let r of this.spec.tags??[])r.description!=null&&r.description.trim().length>0&&this.tagToDescription.set(r.name,r.description)}return this.tagToDescription.get(t)}}});function r9o({ir:e,authOverrides:t}){if(!t["auth-schemes"]||!e.auth)return e;let r=t["auth-schemes"],n=[];for(let i of e.auth.schemes){if(i.type!=="bearer"){n.push(i);continue}let o=r[i.key];if(o==null){n.push(i);continue}let s=Ode(o,{header:()=>{},basic:()=>{},tokenBearer:()=>{},inferredBearer:()=>{},oauth:a=>g9m({ir:e,key:i.key,oauthScheme:a})});n.push(s??i)}return{...e,auth:{...e.auth,schemes:n}}}function g9m({ir:e,key:t,oauthScheme:r}){if(r.type!=="client-credentials")return;let n=r["get-token"];if(n==null)return;let i=tHl({ir:e,endpointRef:n.endpoint});if(i==null)return;let{endpoint:o,serviceId:s,subpackageId:a}=i,c=n["request-properties"],l=n["response-properties"],u=t9o({ir:e,endpoint:o,wireValue:nJ(c?.["client-id"],"client_id")}),p=t9o({ir:e,endpoint:o,wireValue:nJ(c?.["client-secret"],"client_secret")}),d=Gct({ir:e,endpoint:o,wireValue:nJ(l?.["access-token"],"access_token")});if(!(u==null||p==null||d==null))return kp.oauth({key:t,docs:r.docs,playgroundDocs:r["playground-docs"],configuration:qD.clientCredentials({clientIdEnvVar:r["client-id-env"],clientSecretEnvVar:r["client-secret-env"],tokenPrefix:r["token-prefix"],tokenHeader:r["token-header"],scopes:r.scopes,tokenEndpoint:{endpointReference:{endpointId:o.id,serviceId:s,subpackageId:a},requestProperties:{clientId:u,clientSecret:p,scopes:void 0,customProperties:b9m({ir:e,endpoint:o,excludeWireValues:[nJ(c?.["client-id"],"client_id"),nJ(c?.["client-secret"],"client_secret")]})},responseProperties:{accessToken:d,expiresIn:Gct({ir:e,endpoint:o,wireValue:nJ(l?.["expires-in"],"expires_in")}),refreshToken:Gct({ir:e,endpoint:o,wireValue:nJ(l?.["refresh-token"],"refresh_token")})}},refreshEndpoint:r["refresh-token"]!=null?A9m({ir:e,refreshTokenConfig:r["refresh-token"]}):void 0})})}function A9m({ir:e,refreshTokenConfig:t}){let r=tHl({ir:e,endpointRef:t.endpoint});if(r==null)return;let{endpoint:n,serviceId:i,subpackageId:o}=r,s=t["request-properties"],a=t["response-properties"],c=t9o({ir:e,endpoint:n,wireValue:nJ(s?.["refresh-token"],"refresh_token")}),l=Gct({ir:e,endpoint:n,wireValue:nJ(a?.["access-token"],"access_token")});if(!(c==null||l==null))return{endpointReference:{endpointId:n.id,serviceId:i,subpackageId:o},requestProperties:{refreshToken:c},responseProperties:{accessToken:l,expiresIn:Gct({ir:e,endpoint:n,wireValue:nJ(a?.["expires-in"],"expires_in")}),refreshToken:Gct({ir:e,endpoint:n,wireValue:nJ(a?.["refresh-token"],"refresh_token")})}}}function tHl({ir:e,endpointRef:t}){let r=t.trim().split(/\s+/);if(r.length!==2)return;let n=h9m[r[0]?.toUpperCase()??""],i=Xh(r[1]);if(!(n==null||i==null))for(let[o,s]of Object.entries(e.services))for(let a of s.endpoints){if(a.method!==n)continue;if(y9m(a.fullPath)===i){let l=Object.entries(e.subpackages).find(([,u])=>u.service===o)?.[0];return{endpoint:a,serviceId:o,subpackageId:l}}}}function y9m(e){let t=e.head;for(let r of e.parts)t+=`{${r.pathParameter}}${r.tail}`;return Xh(t)}function nJ(e,t){return e==null?t:e.match(/^\$(?:request|response)\.(.+)$/)?.[1]??e}function rHl(e,t){return e.find(r=>cr(r.name)===t)}function n9o(e,t){let r=e.types[t];if(r?.shape.type==="object")return r.shape.properties}function t9o({ir:e,endpoint:t,wireValue:r}){if(t.requestBody==null)return;let n;t.requestBody.type==="inlinedRequestBody"?n=t.requestBody.properties.map(o=>({...o,xml:void 0})):t.requestBody.type==="reference"&&t.requestBody.requestBodyType.type==="named"&&(n=n9o(e,t.requestBody.requestBodyType.typeId));let i=n!=null?rHl(n,r):void 0;if(i!=null)return{propertyPath:void 0,property:YP.body({...i})}}function b9m({ir:e,endpoint:t,excludeWireValues:r}){if(t.requestBody==null)return;let n;if(t.requestBody.type==="inlinedRequestBody"?n=t.requestBody.properties.map(s=>({...s,xml:void 0})):t.requestBody.type==="reference"&&t.requestBody.requestBodyType.type==="named"&&(n=n9o(e,t.requestBody.requestBodyType.typeId)),n==null)return;let i=new Set(r),o=n.filter(s=>!i.has(cr(s.name))).map(s=>({propertyPath:void 0,property:YP.body({...s})}));return o.length>0?o:void 0}function Gct({ir:e,endpoint:t,wireValue:r}){if(t.response?.body?.type!=="json")return;let n=t.response.body.value.responseBodyType;if(n.type!=="named")return;let i=n9o(e,n.typeId),o=i!=null?rHl(i,r):void 0;if(o!=null)return{propertyPath:void 0,property:o}}var h9m,nHl=h(()=>{"use strict";mt();lo();zn();sc();h9m={GET:gm.Get,POST:gm.Post,PUT:gm.Put,PATCH:gm.Patch,DELETE:gm.Delete}});var i9o=h(()=>{"use strict";Z7l();eHl();nHl()});var qct,o9o=h(()=>{"use strict";Uo();qct=class extends Vo{document;key="x-fern-explorer";constructor({breadcrumbs:t,document:r,context:n}){super({breadcrumbs:t,context:n}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-explorer",path:this.breadcrumbs});return}return t}}}});var E9m,I9m,v9m,GKr,iHl=h(()=>{"use strict";mt();Uo();nn();E9m=Xt.object({description:Xt.string().optional(),required:Xt.boolean().optional(),deprecated:Xt.boolean().optional(),allowEmptyValue:Xt.boolean().optional(),style:Xt.string().optional(),explode:Xt.boolean().optional(),allowReserved:Xt.boolean().optional(),schema:Xt.any().optional(),example:Xt.any().optional(),examples:Xt.record(Xt.string(),Xt.any()).optional(),content:Xt.record(Xt.string(),Xt.any()).optional()}),I9m=E9m.extend({name:Xt.string(),in:Xt.string()}),v9m=Xt.array(I9m),GKr=class extends Vo{operation;key="x-fern-parameters";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null)try{return v9m.parse(t)}catch(r){this.context.errorCollector.collect({message:`Failed to parse x-fern-parameters extension: ${rn(r)}`,path:this.breadcrumbs});return}}}});var qKr,oHl=h(()=>{"use strict";zn();sc();Uo();o9o();qKr=class extends Ki{method;pathParameters;queryParameters;headers;topLevelServers;globalApiPlayground;constructor({context:t,breadcrumbs:r,method:n,pathParameters:i=[],queryParameters:o=[],headers:s=[],topLevelServers:a=[],globalApiPlayground:c}){super({context:t,breadcrumbs:r}),this.method=n,this.pathParameters=i,this.queryParameters=o,this.headers=s,this.topLevelServers=a,this.globalApiPlayground=c}convert(){let t={},r="";for(let l of this.pathParameters)r+=`/{${jr(l.name)}}`;let n=jy(r),i=[];for(let[l,u]of this.method.params.entries()){let p;if(this.context.isReferenceObject(u)){let g=this.context.resolveReference({reference:u});if(g.resolved)p=g.value;else continue}else p=u;let d=[this.method.name,"Param",p.name].join("_"),m=new Tm.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"Param",p.name],schemaIdOverride:d,context:this.context,schemaOrReference:p.schema,wrapAsOptional:!p.required}).convert();m!=null&&(i.push({docs:p.description,availability:this.context.getAvailability({node:u,breadcrumbs:[...this.breadcrumbs,"parameters"]}),name:this.context.casingsGenerator.generateNameAndWireValue({name:p.name,wireValue:p.name}),valueType:m.type,defaultValue:p.schema!=null&&typeof p.schema=="object"?p.schema.default:void 0,v2Examples:m.schema?.typeDeclaration.v2Examples,propertyAccess:void 0}),t={...m.inlinedTypes,...t,...m.schema!=null?{[d]:m.schema}:{}})}let o;if(this.method.result!=null){let l=this.context.resolveMaybeReference({schemaOrReference:this.method.result,breadcrumbs:[...this.breadcrumbs,"result"]});if(l!=null){let u=new Tm.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"result"],context:this.context,schemaOrReference:l.schema}),p=[this.method.name,"Result"].join("_"),d=u.convert();d!=null&&(o={docs:l.description,v2Examples:d.schema?.typeDeclaration.v2Examples,responseBodyType:d.type},t={...d.inlinedTypes,...t,...d.schema!=null?{[p]:d.schema}:{}})}}let s=this.getEndpointBaseUrls(),a=this.context.getAudiences({operation:this.method,breadcrumbs:this.breadcrumbs})??[];return{endpoint:{baseUrl:void 0,v2BaseUrls:s,basePath:void 0,auth:!1,security:void 0,method:"POST",id:this.method.name,docs:this.method.description,name:this.context.casingsGenerator.generateName(this.method.name),headers:this.headers,displayName:this.method.name,subtitle:void 0,pathParameters:this.pathParameters,queryParameters:this.queryParameters,allPathParameters:this.pathParameters,path:n,fullPath:n,requestBody:i.length>0?md.inlinedRequestBody({name:this.context.casingsGenerator.generateName([this.method.name,"Request"].join("_")),docs:void 0,properties:i,extends:[],extendedProperties:[],contentType:"application/json",extraProperties:!1,v2Examples:void 0}):void 0,v2RequestBodies:void 0,sdkRequest:void 0,response:o!=null?{body:kl.json(K0.response(o)),statusCode:void 0,isWildcardStatusCode:void 0,docs:o.docs}:void 0,v2Responses:void 0,errors:[],idempotent:!1,pagination:void 0,userSpecifiedExamples:[],autogeneratedExamples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples(r)},transport:void 0,availability:void 0,source:HD.openrpc({paramStructure:this.convertParamStructure()}),audiences:a,retries:void 0,globalParameters:void 0,apiPlayground:this.convertApiPlayground(),responseHeaders:[]},audiences:a,inlinedTypes:t,servers:this.filterOutTopLevelServers(this.method.servers??[])}}convertApiPlayground(){return new qct({breadcrumbs:[...this.breadcrumbs,this.method.name],document:this.method,context:this.context}).convert()??this.globalApiPlayground}convertParamStructure(){let t=this.method.paramStructure;switch(t){case"by-name":return $t.OpenRpcParamStructure.ByName;case"by-position":return $t.OpenRpcParamStructure.ByPosition;case"either":return $t.OpenRpcParamStructure.Either;case void 0:return;default:return}}convertExampleParams(t){return this.method.paramStructure==="by-name"?Object.fromEntries(t.map(r=>[r.name,r.value])):t.map(r=>r.value)}filterOutTopLevelServers(t){return t.filter(r=>!this.topLevelServers.some(n=>n.url===r.url))}getEndpointBaseUrls(){let t=this.method.servers;return t?.map(n=>{if(this.topLevelServers.find(a=>a.name===n.name&&a.url!==n.url)!=null)return n.url;let s=this.topLevelServers.find(a=>a.url===n.url)??n;return l3.getServerName({server:s,context:this.context})})}convertExamples(t){let r={},n={};for(let o of this.pathParameters){let s=Object.values(o.v2Examples?.userSpecifiedExamples??{})[0],a=Object.values(o.v2Examples?.autogeneratedExamples??{})[0],c=s!==void 0?s:a;c!==void 0&&(n[jr(o.name)]=c)}let i=0;if(this.method.examples&&this.method.examples.length>0){for(let o of this.method.examples??[]){let s;if(this.context.isReferenceObject(o)){let u=this.context.resolveReference({reference:o});if(u.resolved)s=u.value;else continue}else s=o;let a;if(s.result)if(this.context.isReferenceObject(s.result)){let u=this.context.resolveReference({reference:s.result});u.resolved&&(a=u.value)}else a=s.result;let c=s.name??`Example ${i+1}`,l=[];if(s.params&&Array.isArray(s.params)){l=[];for(let u of s.params)if(this.context.isReferenceObject(u)){let p=this.context.resolveReference({reference:u});if(p.resolved)l.push(p.value);else continue}else l.push(u)}r[c]={displayName:void 0,contentType:void 0,request:{docs:void 0,endpoint:{method:"POST",path:t},baseUrl:void 0,environment:void 0,auth:void 0,pathParameters:n,queryParameters:{},headers:{},requestBody:this.convertExampleParams(l)},response:{docs:void 0,statusCode:void 0,body:a?.value!==void 0?$t.V2HttpEndpointResponseBody.json({jsonrpc:"2.0",id:s.examplePairedRequest?.id||"1",result:a.value}):void 0},codeSamples:[]}}++i}return r}}});var WKr,sHl=h(()=>{"use strict";Uo();WKr=class extends Tm.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:n}){super({context:t,breadcrumbs:r,parameter:n})}convert(){let t,r={};if(this.parameter.schema!=null){let i=new Tm.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaOrReference:this.parameter.schema,wrapAsOptional:this.parameter.required==null||!this.parameter.required}).convert();i!=null&&(t=i.type,r=i.inlinedTypes??{})}return this.convertToOutput({schema:this.parameter.schema??{type:"string"},typeReference:t,inlinedTypes:r})}}});var RGt,aHl=h(()=>{"use strict";Uo();o9o();iHl();oHl();sHl();RGt=class extends tJ{constructor({context:t,breadcrumbs:r,audiences:n}){super({context:t,breadcrumbs:r,audiences:n})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.convertSchemas();let{endpointLevelServers:t}=this.convertMethods(),{defaultUrl:r}=this.convertServers({endpointLevelServers:t});return this.updateEndpointsWithDefaultUrl(r),this.finalizeIr()}convertServers({endpointLevelServers:t}){let n=new l3({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t}).convert();return this.addEnvironmentsToIr({environmentConfig:n?.value}),{defaultUrl:n?.defaultUrl}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{})){let i=new Tm.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:["components","schemas",t],schema:r}).convert();i!=null&&this.addSchemaOutputToIr(t,i)}}convertMethods(){let t=[],n=new GKr({context:this.context,breadcrumbs:["methods"],operation:this.context.spec}).convert(),i=[],o=[],s=[];if(n&&n.length>0)for(let[l,u]of n.entries()){let d=new WKr({context:this.context,breadcrumbs:[...this.breadcrumbs,`x-fern-parameters[${l}]`],parameter:u}).convert();if(d!=null)switch(d.type){case"path":{i.push(d.parameter);break}case"query":{o.push(d.parameter);break}case"header":{s.push(d.parameter);break}}}let a=this.context.getGroup({groupParts:[],namespace:this.context.namespace}),c=new qct({breadcrumbs:[],document:this.context.spec,context:this.context}).convert();for(let l of this.context.spec.methods??[]){let u=this.context.resolveMaybeReference({schemaOrReference:l,breadcrumbs:["methods"]});if(u==null)continue;let d=new qKr({context:this.context,breadcrumbs:["methods"],method:u,pathParameters:i,queryParameters:o,headers:s,topLevelServers:this.context.spec.servers,globalApiPlayground:c}).convert();if(d!=null&&(this.addEndpointToIr({endpoint:d.endpoint,audiences:d.audiences,endpointGroup:a,serviceName:"service_root"}),this.addTypesToIr(d.inlinedTypes),d.servers))for(let f of d.servers)this.shouldAddServerToCollectedServers({server:f,currentServers:t,specType:"openrpc"})&&t.push(this.maybeDeduplicateServerName(f))}return{endpointLevelServers:t}}maybeDeduplicateServerName(t){return this.context.spec.servers?.find(n=>n.name===t.name&&n.url!==t.url)?{...t,name:t.url}:t}}});var kGt,cHl=h(()=>{"use strict";zn();Uo();kGt=class extends Yb{isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i}){let o=this.getTypeIdFromSchemaReference(t);if(o==null)return{ok:!1};let s=this.resolveReference({reference:t,breadcrumbs:r});if(!s.resolved)return{ok:!1};let a;if(i==="reference_identifier")a=n??s.value.title;else if(i==="discriminator_key")a=s.value.title??n;else{let c=t.$ref.split("/").pop()??o;a=s.value.title??c}return{ok:!0,reference:Hr.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}}});var lHl=h(()=>{"use strict";aHl();cHl()});var uHl,pHl=h(()=>{"use strict";uHl=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i});function C9m(e){return typeof e=="string"&&uHl.test(e)}var s9o,fHl=h(()=>{"use strict";pHl();s9o=C9m});function dHl(e,t=0){return(bB[e[t+0]]+bB[e[t+1]]+bB[e[t+2]]+bB[e[t+3]]+"-"+bB[e[t+4]]+bB[e[t+5]]+"-"+bB[e[t+6]]+bB[e[t+7]]+"-"+bB[e[t+8]]+bB[e[t+9]]+"-"+bB[e[t+10]]+bB[e[t+11]]+bB[e[t+12]]+bB[e[t+13]]+bB[e[t+14]]+bB[e[t+15]]).toLowerCase()}var bB,mHl=h(()=>{"use strict";bB=[];for(let e=0;e<256;++e)bB.push((e+256).toString(16).slice(1))});function a9o(){return crypto.getRandomValues(x9m)}var x9m,hHl=h(()=>{"use strict";x9m=new Uint8Array(16)});function S9m(e,t,r){return!t&&!e&&crypto.randomUUID?crypto.randomUUID():w9m(e,t,r)}function w9m(e,t,r){e=e||{};let n=e.random??e.rng?.()??a9o();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){if(r=r||0,r<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let i=0;i<16;++i)t[r+i]=n[i];return t}return dHl(n)}var Dw,gHl=h(()=>{"use strict";hHl();mHl();Dw=S9m});var TUe=h(()=>{"use strict";gHl();fHl()});async function Wct({absoluteFilePathToOverrides:e,data:t,context:r,allowNullKeys:n}){let i=null;try{let o=(await(0,AHl.readFile)(e,"utf8")).toString();try{i=JSON.parse(o)}catch{i=Er.load(o,{json:!0})}}catch{return r.failAndThrow(`Failed to read overrides from file ${e}`,void 0,{code:T.Code.ParseError})}return QX({data:t,overrides:i,allowNullKeys:n})}var AHl,HKr=h(()=>{"use strict";mt();Bt();AHl=require("fs/promises");Ko()});async function c9o({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let n=(await(0,yHl.readFile)(t)).toString(),i;try{i=JSON.parse(n)}catch{i=Er.load(n)}let o=[];r!=null&&(Array.isArray(r)?o=r:o=[r]);let s=i;for(let a of o)s=await Wct({absoluteFilePathToOverrides:a,context:e,data:s});return s}var yHl,bHl=h(()=>{"use strict";yHl=require("fs/promises");Ko();HKr()});async function l9o({document:e,settings:t}){let r=t?.errorResponses;if(r==null)return{document:e,errorResponses:void 0};let n=typeof r.schema=="string"?await T9m(Zt.of(r.schema)):r.schema;return{document:Bjo({document:e,errorResponses:r,schema:n}),errorResponses:{...r,schema:n}}}async function T9m(e){let t=(await(0,EHl.readFile)(e)).toString(),r=Er.load(t);if(!gr(r))throw new T({message:`Expected ${e} to contain an OpenAPI schema object.`,code:T.Code.ConfigError});return r}var EHl,IHl=h(()=>{"use strict";vc();mt();tr();Bt();EHl=require("fs/promises");Ko()});var CHl=E((FUv,vHl)=>{"use strict";function O9m(){return typeof process=="object"&&typeof process.nextTick=="function"?process.nextTick:typeof setImmediate=="function"?setImmediate:function(t){setTimeout(t,0)}}vHl.exports=O9m()});var wHl=E((NUv,SHl)=>{"use strict";var xHl=CHl();SHl.exports=function(t,r){if(t){r.then(function(n){xHl(function(){t(null,n)})},function(n){xHl(function(){t(n)})});return}else return r}});var p9o=E((jUv,OHl)=>{"use strict";var u9o=class{constructor(t,r){this.cb=t,this.delay=r,this.timers={},this.pausers={}}setDelay(t){t>=0&&(this.delay=t)}pause(t){this.pausers[t]=this.pausers[t]||0,this.pausers[t]++}unpause(t){var r=this.pausers[t]||0;r>0&&r--,this.pausers[t]=r}unpauseAndTime(t){this.unpause(t),this.time(t)}time(t){var r=this,n=this.timers,i=this.timers[t];this.pausers[t]>0||(i&&clearTimeout(i),n[t]=setTimeout(function(){r.cb(t),delete n[t]},r.delay))}},KKr=class extends TypeError{constructor(t,r,n){let i=t.includes(".")?"property":"argument",o=`The "${t}" ${i} ${determiner} ${r}`}};function THl(e,t,r="Object"){if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e))){let n=new KKr(t,r,e);throw Error.captureStackTrace(n,THl),n}}OHl.exports={ERR_INVALID_ARG_TYPE:KKr,assertIsObject:THl,DebounceTimers:u9o}});var DHl=E((zUv,BHl)=>{"use strict";var{assertIsObject:PHl}=p9o();function P9m(e){return PHl(e,"options"),e=Object.assign({},e),e.allowHalfOpen=!0,e.rejectUnauthorized=!1,PHl(e.settings,"options.settings"),e.settings=Object.assign({},e.settings),e.Http1IncomingMessage=e.Http1IncomingMessage||this.http.IncomingMessage,e.Http1ServerResponse=e.Http1ServerResponse||this.http.ServerResponse,e.Http2ServerRequest=e.Http2ServerRequest||(this.http2||{}).Http2ServerRequest,e.Http2ServerResponse=e.Http2ServerResponse||(this.http2||{}).Http2ServerResponse,e}function B9m(e,t){e=P9m.call(this,e);var r=e.ALPNProtocols=[];return this.http2Support&&r.push("h2"),(e.allowHTTP1==!0||!this.http2Support)&&r.push("http/1.1"),t!==void 0&&e.servername===void 0&&(e.servername=t),e}BHl.exports={initializeTLSOptions:B9m}});var ZKr=E((MUv,NHl)=>{"use strict";var{URL:JKr}=require("url"),{EventEmitter:kHl}=require("events"),YKr=require("util")._extend,{DebounceTimers:D9m,assertIsObject:RHl,ERR_INVALID_ARG_TYPE:QUv}=p9o(),{initializeTLSOptions:R9m}=DHl(),FGt=require("http"),f9o=require("https"),{Stream:k9m}=require("stream");function XKr(e,t){let r=t.prototype;Object.keys(r).forEach(n=>{e.indexOf(n)==-1&&n.indexOf("_")!=0&&typeof r[n]=="function"&&e.push(n)})}var _me=[];XKr(_me,FGt.ClientRequest);XKr(_me,FGt.OutgoingMessage);XKr(_me,kHl);XKr(_me,k9m);var F9m=["httpVersionMajor","httpVersionMinor","httpVersion"],N9m=["host","connection"],zSe=Symbol("stubs");function NGt(){this.http2Mimic=!0,this[zSe]=[];for(var e=0;e<_me.length;e++){let l=_me[e];NGt.prototype[l]||(this[l]=function(){return this.genericStubber(l,arguments)}.bind(this))}var t,r,n,i;let o=arguments[0]instanceof jGt;var s,a;if(o){let l=arguments[0];l.method&&(s=l.method),l.protocol&&(a=l.protocol)}if(o?i=arguments[0].args:i=arguments,i[2]!=null?(n=i[0],t=i[1],r=i[2]):i[1]==null?t=i[0]:(t=i[0],r=i[1]),r=r||function(){},typeof t=="string"){if(t=d9o(new JKr(t)),!t.hostname)throw new Error("Unable to determine the domain name")}else n?t=YKr(d9o(new JKr(n)),t):t=YKr({},t);a!=a&&(t.protocol=a),t.protocol=="https:"&&!t.port&&t.port!=0&&(t.port=443),!t.port&&t.port!=0&&(t.port=80),s?t.method=s:t.method||(t.method="GET"),t.method=t.method.toUpperCase(),(t.requestManager||this.getGlobalManager(t)).handleClientRequest(this,t,r)}NGt.prototype={getGlobalManager(e){return e.agent?e.agent.protocol=="https:"?MSe.globalManager:LSe.globalManager:QSe.globalManager},genericStubber(e,t){return this[zSe]?(this[zSe].push([e,t]),!0):this[e](...arguments)},on(e,t){e=="response"&&(t.http2Safe||(e="http1.response",arguments[0]=e)),this._on?this._on(...arguments):this.genericStubber("on",arguments)},once(e,t){e=="response"&&(t.http2Safe||(e="http1.response")),this._once?this._once(...arguments):this.genericStubber("once",arguments)},emitError(e){if(this[zSe])this[zSe].forEach(([t,r])=>{(t==="on"||t==="once")&&r[0]==="error"&&r[1](e)});else return this.emit("error",e)},take(e){for(var t=0;t<_me.length;t++){let n=_me[t];e[n]&&(this[n]=e[n].bind(e))}this._on=e.on.bind(e),this._once=e.once.bind(e),this.proxyProps(e);for(let n=0;n<this[zSe].length;n++){var r=this[zSe][n];e[r[0]](...r[1])}this[zSe]=null},proxyProps(e){function t(){return e[this]}function r(c){e[this]=c}let n=["on","_on","_once","once","http2Mimic"].concat(_me),i=Object.keys(this),o=[].concat(F9m);i.forEach(function(l){n.indexOf(l)==-1&&o.indexOf(l)==-1&&o.push(l)});let s=Object.getOwnPropertyDescriptors(e);for(var a=0;a<o.length;a++){let c=o[a],l=s[c],u;l||(u=!0),l&&(l.writable||l)&&(u=!0),u&&(e[c]=this[c]),Object.defineProperty(this,c,{get:t.bind(c),set:r.bind(c)})}}};var QSe=class e extends kHl{constructor(t){super(),this.httpsAgent=f9o.globalAgent,this.httpAgent=FGt.globalAgent,this.init(t)}log(){}init(t){t=t||{},this.http2Clients={},this.cachedHTTP1Result={},this.setModules(),this.http2Debouncer=new D9m(function(n){this.log("stopping ",n);var i=this.http2Clients[n];i&&this.removeHttp2Client(n,i)}.bind(this),1e3),this.keepH1IdentificationCacheFor=t.keepH1IdentificationCacheFor||3e4,this.http2Debouncer.setDelay(t.keepH2ConnectionFor),t.useHttp?this.enforceProtocol="http:":t.useHttps&&(this.enforceProtocol="https:")}setModules(){this.http=require("http"),this.https=require("https"),this.tls=require("tls"),this.net=require("net"),this.http2Support=!1;try{this.http2=require("http2"),this.http2Support=!0}catch{}}handleClientRequest(t,r,n){let i=this,o=i.getClientKey(r);if(i.hasCachedConnection(o)){let s=i.getHttp2Client(o),a={createConnection(){return s}};process.nextTick(function(){i.makeRequest(t,o,r,n,a)}.bind(i))}else i.holdConnectionToIdentification(o,r,function(a,c){if(a){t.emitError(a);return}i.makeRequest(t,o,r,n,c)}.bind(i))}getClientKey(t){return`${t.protocol||this.enforceProtocol}${t.servername||t.host||t.hostname}:${t.port}`}getHttp2Client(t){return this.http2Clients[t]}setHttp2Client(t,r){let n=this,i=n.http2Clients[t];i&&n.removeHttp2Client(t,i),n.http2Clients[t]=r;function o(){n.removeHttp2Client(t,r)}r.on("close",o),r.on("goaway",o),r.on("error",o),r.on("frameError",o),r.on("timeout",o)}removeHttp2Client(t,r){try{delete this.http2Clients[t],r.closed||r.close()}catch{}r.removeAllListeners("close"),r.removeAllListeners("error"),r.removeAllListeners("frameError"),r.removeAllListeners("timeout")}request(t,r,n){var i=new jGt(arguments);return this.enforceProtocol&&(i.protocol=this.enforceProtocol),new NGt(i)}get(){var t=new jGt(arguments);t.method="GET";var r=this.request(t);return r.end(),r}hasCachedConnection(t){return this.getHttp2Client(t)?!0:this.cachedHTTP1Result[t]+this.keepH1IdentificationCacheFor<Date.now()}makeRequest(t,r,n,i,o){let s=this.getHttp2Client(r);return s?this.makeHttp2Request(r,t,s,Object.assign(o||{},n),i):(n.agent||(n.protocol=="https:"?n.agent=this.httpsAgent:n.agent=this.httpAgent),this.makeHttpRequest(r,t,n,i,o))}holdConnectionToIdentification(t,r,n){let i=`identify-${t}`;if(this._events[i])this.once(i,n);else{this.once(i,function(){});let o=this.identifyConnection(r,function(a,c){if(a)return n(a);var l={createConnection(){return o}};if(c=="h2"&&this.http2Support){var u=this.http2.connect(r,l);this.setHttp2Client(t,u)}else this.cachedHTTP1Result[t]=Date.now();n(null,l),this.emit(i,l)}.bind(this))}}makeHttpRequest(t,r,n,i,o){n instanceof JKr&&(n=d9o(n));let s=YKr({},n);o&&(s.createConnection=o.createConnection);let c=(s.protocol=="https:"?this.https:this.http).request(s,i);r.take(c),r._on("response",function(u){this.emit("http1.response",u)})}makeHttp2Request(t,r,n,i,o){var s=this.http2Debouncer;s.pause(t);var a=YKr({},i.headers||{});i.method&&(a[":method"]=i.method),i.path&&(a[":path"]=i.path),Object.keys(a).forEach(d=>{N9m.indexOf((d+"").toLowerCase())!=-1&&delete a[d]}),i.headers=a;var c=n.request(a);r.emit("socket",i.createConnection());let l,u=0;c.on("data",function(f){u+=f.length,u>=l&&s.unpauseAndTime(t)}),r.take(c);function p(d){l=parseInt(d["content-length"]),l<0&&this.http2Debouncer.unpauseAndTime(t),e.httpCompatibleResponse(c,i,d),r.emit("http1.response",c),o&&o(c)}p.http2Safe=!0,c.once("response",p.bind(this))}static httpCompatibleResponse(t,r,n){t.httpVersion="2.0",t.rawHeaders=n,t.headers=n,t.statusCode=n[":status"],delete n[":status"]}identifyConnection(t,r){var n=this.connect(t,{allowHTTP1:!0},function(){n.removeListener("error",r),n.alpnProtocol=="h2"?r(null,"h2"):(n.end(),r(null,"h1"))});return n.on("error",r),n}connect(t,r,n){typeof r=="function"&&(n=r,r=void 0),RHl(r,"options"),r=Object.assign({},r),typeof t=="string"&&(t=new JKr(t)),RHl(t,"authority",["string","Object","URL"]);var i=t.protocol||r.protocol||(this.enforceProtocol!="detect"?this.enforceProtocol:null)||"http:",o=""+(t.port!==""?t.port:t.protocol==="http:"?80:443),s=t.hostname||t.host||"localhost",a;if(typeof r.createConnection=="function")a=r.createConnection(t,r);else switch(i){case"http:":a=this.net.connect(o,s,n);break;case"https:":a=this.tls.connect(o,s,R9m.call(this,r,s),n);break;default:throw new Error("Not supprted"+i)}return a}};function d9o(e){var t={protocol:e.protocol,hostname:e.hostname,hash:e.hash,search:e.search,pathname:e.pathname,path:`${e.pathname}${e.search}`,href:e.href};return e.port!==""&&(t.port=Number(e.port)),(e.username||e.password)&&(t.auth=`${e.username}:${e.password}`),t}var jGt=class e{constructor(t){if(t[0]instanceof e)return t[0];this.args=t,this.method=null,this.protocol=null}},MSe=class extends QSe{constructor(){super(...arguments),this.Agent=f9o.Agent,this.globalAgent=f9o.globalAgent,this.enforceProtocol="https:"}},j9m=new MSe;MSe.globalManager=j9m;MSe.Manager=MSe;var LSe=class extends QSe{constructor(){super(...arguments),this.Agent=FGt.Agent,this.globalAgent=FGt.globalAgent,this.enforceProtocol="http:"}},z9m=new LSe;LSe.globalManager=z9m;LSe.Manager=LSe;var FHl=new QSe;FHl.enforceProtocol="detect";QSe.globalManager=FHl;NHl.exports={HttpRequest:LSe,HttpsRequest:MSe,HTTP2OutgoingMessage:NGt,ClientRequest:NGt,HttpRequestManager:QSe}});var zHl=E((LUv,jHl)=>{"use strict";var{HttpRequest:Q9m,ClientRequest:M9m}=ZKr(),zGt=Q9m.globalManager,L9m=zGt.request.bind(zGt),_9m=zGt.get.bind(zGt),U9m=Object.assign({},require("http"));jHl.exports=Object.assign(U9m,{ClientRequest:M9m,globalManager:zGt,request:L9m,get:_9m})});var MHl=E((_Uv,QHl)=>{"use strict";var{HttpsRequest:V9m,ClientRequest:G9m}=ZKr(),QGt=V9m.globalManager,q9m=QGt.request.bind(QGt),W9m=QGt.get.bind(QGt),H9m=Object.assign({},require("https"));QHl.exports=Object.assign(H9m,{ClientRequest:G9m,globalManager:QGt,request:q9m,get:W9m})});var _Hl=E((UUv,LHl)=>{"use strict";var{HttpRequestManager:m9o,HTTP2OutgoingMessage:K9m,ClientRequest:J9m}=ZKr(),Y9m=zHl(),X9m=MHl(),MGt=new m9o;m9o.globalManager=MGt;var Z9m=MGt.request.bind(MGt),$9m=MGt.get.bind(MGt);LHl.exports={HTTP2OutgoingMessage:K9m,ClientRequest:J9m,globalManager:m9o.globalManager,request:Z9m,get:$9m,http:Y9m,https:X9m}});var C9o={};ne(C9o,{FetchError:()=>yR,Headers:()=>d8,Request:()=>USe,Response:()=>vre,default:()=>uqm});function yR(e,t,r){Error.call(this,e),this.message=e,this.type=t,r&&(this.code=this.errno=r.code),Error.captureStackTrace(this,this.constructor)}function jT(e){var t=this,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=r.size;let i=n===void 0?0:n;var o=r.timeout;let s=o===void 0?0:o;e==null?e=null:HHl(e)?e=Buffer.from(e.toString()):e instanceof BUe?e=e[PUe]:Buffer.isBuffer(e)||(Object.prototype.toString.call(e)==="[object ArrayBuffer]"?e=Buffer.from(e):ArrayBuffer.isView(e)?e=Buffer.from(e.buffer,e.byteOffset,e.byteLength):e instanceof iJ.default||(e=Buffer.from(String(e)))),this[Vme]={body:e,disturbed:!1,error:null},this.size=i,this.timeout=s,e instanceof iJ.default&&e.on("error",function(a){let c=a.name==="AbortError"?a:new yR(`Invalid response body while trying to fetch ${t.url}: ${a.message}`,"system",a);t[Vme].error=c})}function Hct(){var e=this;if(this[Vme].disturbed)return jT.Promise.reject(new TypeError(`body used already for: ${this.url}`));if(this[Vme].disturbed=!0,this[Vme].error)return jT.Promise.reject(this[Vme].error);if(this.body===null)return jT.Promise.resolve(Buffer.alloc(0));if(Buffer.isBuffer(this.body))return jT.Promise.resolve(this.body);if(!(this.body instanceof iJ.default))return jT.Promise.resolve(Buffer.alloc(0));let t=[],r=0,n=!1;return new jT.Promise(function(i,o){let s;e.timeout&&(s=setTimeout(function(){n=!0,o(new yR(`Response timeout while trying to fetch ${e.url} (over ${e.timeout}ms)`,"body-timeout"))},e.timeout)),e.body.on("error",function(a){a.name==="AbortError"?(n=!0,o(a)):o(new yR(`Invalid response body while trying to fetch ${e.url}: ${a.message}`,"system",a))}),e.body.on("data",function(a){if(!(n||a===null)){if(e.size&&r+a.length>e.size){n=!0,o(new yR(`content size at ${e.url} over limit: ${e.size}`,"max-size"));return}r+=a.length,t.push(a)}}),e.body.on("end",function(){if(!n){clearTimeout(s);try{i(Buffer.concat(t))}catch(a){o(new yR(`Could not create Buffer from response body for ${e.url}: ${a.message}`,"system",a))}}})})}function eqm(e,t){if(typeof y9o!="function")throw new Error("The package `encoding` must be installed to use the textConverted() function");let r=t.get("content-type"),n="utf-8",i,o;return r&&(i=/charset=([^;]*)/i.exec(r)),o=e.slice(0,1024).toString(),!i&&o&&(i=/<meta.+?charset=(['"])(.+?)\1/i.exec(o)),!i&&o&&(i=/<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(o),i&&(i=/charset=(.*)/i.exec(i.pop()))),!i&&o&&(i=/<\?xml.+?encoding=(['"])(.+?)\1/i.exec(o)),i&&(n=i.pop(),(n==="gb2312"||n==="gbk")&&(n="gb18030")),y9o(e,"UTF-8",n).toString()}function HHl(e){return typeof e!="object"||typeof e.append!="function"||typeof e.delete!="function"||typeof e.get!="function"||typeof e.getAll!="function"||typeof e.has!="function"||typeof e.set!="function"?!1:e.constructor.name==="URLSearchParams"||Object.prototype.toString.call(e)==="[object URLSearchParams]"||typeof e.sort=="function"}function KHl(e){let t,r,n=e.body;if(e.bodyUsed)throw new Error("cannot clone body after it is used");return n instanceof iJ.default&&typeof n.getBoundary!="function"&&(t=new UHl,r=new UHl,n.pipe(t),n.pipe(r),e[Vme].body=t,n=r),n}function JHl(e){return e===null?null:typeof e=="string"?"text/plain;charset=UTF-8":HHl(e)?"application/x-www-form-urlencoded;charset=UTF-8":e instanceof BUe?e.type||null:Buffer.isBuffer(e)||Object.prototype.toString.call(e)==="[object ArrayBuffer]"||ArrayBuffer.isView(e)?null:typeof e.getBoundary=="function"?`multipart/form-data;boundary=${e.getBoundary()}`:e instanceof iJ.default?null:"text/plain;charset=UTF-8"}function YHl(e){let t=e.body;return t===null?0:Buffer.isBuffer(t)?t.length:t&&typeof t.getLengthSync=="function"&&(t._lengthRetrievers&&t._lengthRetrievers.length==0||t.hasKnownLength&&t.hasKnownLength())?t.getLengthSync():null}function tqm(e,t){let r=t.body;r===null?e.end():Buffer.isBuffer(r)?(e.write(r),e.end()):r.pipe(e)}function LGt(e){if(e=`${e}`,XHl.test(e))throw new TypeError(`${e} is not a legal HTTP header name`)}function VHl(e){if(e=`${e}`,b9o.test(e))throw new TypeError(`${e} is not a legal HTTP header value`)}function Jct(e,t){t=t.toLowerCase();for(let r in e)if(r.toLowerCase()===t)return r}function E9o(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"key+value";return Object.keys(e[CC]).sort().map(t==="key"?function(n){return n.toLowerCase()}:t==="value"?function(n){return e[CC][n].join(", ")}:function(n){return[n.toLowerCase(),e[CC][n].join(", ")]})}function g9o(e,t){let r=Object.create(v9o);return r[I9o]={target:e,kind:t,index:0},r}function rqm(e){let t=Object.assign({__proto__:null},e[CC]),r=Jct(e[CC],"Host");return r!==void 0&&(t[r]=t[r][0]),t}function nqm(e){let t=new d8;for(let r of Object.keys(e))if(!XHl.test(r))if(Array.isArray(e[r]))for(let n of e[r])b9o.test(n)||(t[CC][r]===void 0?t[CC][r]=[n]:t[CC][r].push(n));else b9o.test(e[r])||(t[CC][r]=[e[r]]);return t}function $Kr(e){return typeof e=="object"&&typeof e[Ume]=="object"}function aqm(e){let t=e&&typeof e=="object"&&Object.getPrototypeOf(e);return!!(t&&t.constructor.name==="AbortSignal")}function cqm(e){let t=e[Ume].parsedURL,r=new d8(e[Ume].headers);if(r.has("Accept")||r.set("Accept","*/*"),!t.protocol||!t.hostname)throw new TypeError("Only absolute URLs are supported");if(!/^https?:$/.test(t.protocol))throw new TypeError("Only HTTP(S) protocols are supported");if(e.signal&&e.body instanceof iJ.default.Readable&&!sqm)throw new Error("Cancellation of streamed requests with AbortSignal is not supported in node < 8");let n=null;if(e.body==null&&/^(POST|PUT)$/i.test(e.method)&&(n="0"),e.body!=null){let i=YHl(e);typeof i=="number"&&(n=String(i))}return n&&r.set("Content-Length",n),r.has("User-Agent")||r.set("User-Agent","node-fetch/1.0 (+https://github.com/bitinn/node-fetch)"),e.compress&&!r.has("Accept-Encoding")&&r.set("Accept-Encoding","gzip,deflate"),!r.has("Connection")&&!e.agent&&r.set("Connection","close"),Object.assign({},t,{method:e.method,headers:rqm(r),agent:e.agent})}function _Gt(e){Error.call(this,e),this.type="aborted",this.message=e,Error.captureStackTrace(this,this.constructor)}function _Se(e,t){if(!_Se.Promise)throw new Error("native promise missing, set fetch.Promise to your favorite alternative");return jT.Promise=_Se.Promise,new _Se.Promise(function(r,n){let i=new USe(e,t),o=cqm(i),s=WHl.default.request,a=i.signal,c=null,l=function(){let g=new _Gt("The user aborted a request.");n(g),i.body&&i.body instanceof iJ.default.Readable&&i.body.destroy(g),!(!c||!c.body)&&c.body.emit("error",g)};if(a&&a.aborted){l();return}let u=function(){l(),f()},p=s(o),d;a&&a.addEventListener("abort",u);function f(){p.abort(),a&&a.removeEventListener("abort",u),clearTimeout(d)}i.timeout&&p.once("socket",function(m){d=setTimeout(function(){n(new yR(`network timeout at: ${i.url}`,"request-timeout")),f()},i.timeout)}),p.on("error",function(m){n(new yR(`request to ${i.url} failed, reason: ${m.message}`,"system",m)),f()}),p.on("response",function(m){clearTimeout(d);let g=nqm(m.headers);if(_Se.isRedirect(m.statusCode)){let x=g.get("Location"),S=x===null?null:lqm(i.url,x);switch(i.redirect){case"error":n(new yR(`redirect mode is set to error: ${i.url}`,"no-redirect")),f();return;case"manual":if(S!==null)try{g.set("Location",S)}catch(D){n(D)}break;case"follow":if(S===null)break;if(i.counter>=i.follow){n(new yR(`maximum redirect reached at: ${i.url}`,"max-redirect")),f();return}let P={headers:new d8(i.headers),follow:i.follow,counter:i.counter+1,agent:i.agent,compress:i.compress,method:i.method,body:i.body,signal:i.signal};if(m.statusCode!==303&&i.body&&YHl(i)===null){n(new yR("Cannot follow redirect with body being a readable stream","unsupported-redirect")),f();return}(m.statusCode===303||(m.statusCode===301||m.statusCode===302)&&i.method==="POST")&&(P.method="GET",P.body=void 0,P.headers.delete("content-length")),r(_Se(new USe(S,P))),f();return}}m.once("end",function(){a&&a.removeEventListener("abort",u)});let A=m.pipe(new GHl),b={url:i.url,status:m.statusCode,statusText:m.statusMessage,headers:g,size:i.size,timeout:i.timeout},I=g.get("Content-Encoding");if(!i.compress||i.method==="HEAD"||I===null||m.statusCode===204||m.statusCode===304){c=new vre(A,b),r(c);return}let C={flush:Kct.default.Z_SYNC_FLUSH,finishFlush:Kct.default.Z_SYNC_FLUSH};if(I=="gzip"||I=="x-gzip"){A=A.pipe(Kct.default.createGunzip(C)),c=new vre(A,b),r(c);return}if(I=="deflate"||I=="x-deflate"){m.pipe(new GHl).once("data",function(S){(S[0]&15)===8?A=A.pipe(Kct.default.createInflate()):A=A.pipe(Kct.default.createInflateRaw()),c=new vre(A,b),r(c)});return}c=new vre(A,b),r(c)}),tqm(p,i)})}var iJ,qHl,eJr,WHl,Kct,PUe,h9o,BUe,y9o,Vme,UHl,XHl,b9o,CC,d8,I9o,v9o,OUe,iqm,vre,Ume,A9o,oqm,sqm,USe,GHl,lqm,uqm,x9o=h(()=>{"use strict";iJ=Ae(require("stream"),1),qHl=Ae(require("http"),1),eJr=Ae(require("url"),1),WHl=Ae(_Hl(),1),Kct=Ae(require("zlib"),1),PUe=Symbol("buffer"),h9o=Symbol("type"),BUe=class e{constructor(){this[h9o]="";let t=arguments[0],r=arguments[1],n=[];if(t){let o=t,s=Number(o.length);for(let a=0;a<s;a++){let c=o[a],l;c instanceof Buffer?l=c:ArrayBuffer.isView(c)?l=Buffer.from(c.buffer,c.byteOffset,c.byteLength):c instanceof ArrayBuffer?l=Buffer.from(c):c instanceof e?l=c[PUe]:l=Buffer.from(typeof c=="string"?c:String(c)),n.push(l)}}this[PUe]=Buffer.concat(n);let i=r&&r.type!==void 0&&String(r.type).toLowerCase();i&&!/[^\u0020-\u007E]/.test(i)&&(this[h9o]=i)}get size(){return this[PUe].length}get type(){return this[h9o]}slice(){let t=this.size,r=arguments[0],n=arguments[1],i,o;r===void 0?i=0:r<0?i=Math.max(t+r,0):i=Math.min(r,t),n===void 0?o=t:n<0?o=Math.max(t+n,0):o=Math.min(n,t);let s=Math.max(o-i,0),c=this[PUe].slice(i,i+s),l=new e([],{type:arguments[2]});return l[PUe]=c,l}};Object.defineProperties(BUe.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});Object.defineProperty(BUe.prototype,Symbol.toStringTag,{value:"Blob",writable:!1,enumerable:!1,configurable:!0});yR.prototype=Object.create(Error.prototype);yR.prototype.constructor=yR;yR.prototype.name="FetchError";try{y9o=require("encoding").convert}catch{}Vme=Symbol("Body internals"),UHl=iJ.default.PassThrough;jT.prototype={get body(){return this[Vme].body},get bodyUsed(){return this[Vme].disturbed},arrayBuffer(){return Hct.call(this).then(function(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)})},blob(){let e=this.headers&&this.headers.get("content-type")||"";return Hct.call(this).then(function(t){return Object.assign(new BUe([],{type:e.toLowerCase()}),{[PUe]:t})})},json(){var e=this;return Hct.call(this).then(function(t){try{return JSON.parse(t.toString())}catch(r){return jT.Promise.reject(new yR(`invalid json response body at ${e.url} reason: ${r.message}`,"invalid-json"))}})},text(){return Hct.call(this).then(function(e){return e.toString()})},buffer(){return Hct.call(this)},textConverted(){var e=this;return Hct.call(this).then(function(t){return eqm(t,e.headers)})}};Object.defineProperties(jT.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0}});jT.mixIn=function(e){for(let t of Object.getOwnPropertyNames(jT.prototype))if(!(t in e)){let r=Object.getOwnPropertyDescriptor(jT.prototype,t);Object.defineProperty(e,t,r)}};jT.Promise=global.Promise;XHl=/[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/,b9o=/[^\t\x20-\x7e\x80-\xff]/;CC=Symbol("map"),d8=class e{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:void 0;if(this[CC]=Object.create(null),t instanceof e){let r=t.raw(),n=Object.keys(r);for(let i of n)for(let o of r[i])this.append(i,o);return}if(t!=null)if(typeof t=="object"){let r=t[Symbol.iterator];if(r!=null){if(typeof r!="function")throw new TypeError("Header pairs must be iterable");let n=[];for(let i of t){if(typeof i!="object"||typeof i[Symbol.iterator]!="function")throw new TypeError("Each header pair must be iterable");n.push(Array.from(i))}for(let i of n){if(i.length!==2)throw new TypeError("Each header pair must be a name/value tuple");this.append(i[0],i[1])}}else for(let n of Object.keys(t)){let i=t[n];this.append(n,i)}}else throw new TypeError("Provided initializer must be an object")}get(t){t=`${t}`,LGt(t);let r=Jct(this[CC],t);return r===void 0?null:this[CC][r].join(", ")}forEach(t){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:void 0,n=E9o(this),i=0;for(;i<n.length;){var o=n[i];let s=o[0],a=o[1];t.call(r,a,s,this),n=E9o(this),i++}}set(t,r){t=`${t}`,r=`${r}`,LGt(t),VHl(r);let n=Jct(this[CC],t);this[CC][n!==void 0?n:t]=[r]}append(t,r){t=`${t}`,r=`${r}`,LGt(t),VHl(r);let n=Jct(this[CC],t);n!==void 0?this[CC][n].push(r):this[CC][t]=[r]}has(t){return t=`${t}`,LGt(t),Jct(this[CC],t)!==void 0}delete(t){t=`${t}`,LGt(t);let r=Jct(this[CC],t);r!==void 0&&delete this[CC][r]}raw(){return this[CC]}keys(){return g9o(this,"key")}values(){return g9o(this,"value")}[Symbol.iterator](){return g9o(this,"key+value")}};d8.prototype.entries=d8.prototype[Symbol.iterator];Object.defineProperty(d8.prototype,Symbol.toStringTag,{value:"Headers",writable:!1,enumerable:!1,configurable:!0});Object.defineProperties(d8.prototype,{get:{enumerable:!0},forEach:{enumerable:!0},set:{enumerable:!0},append:{enumerable:!0},has:{enumerable:!0},delete:{enumerable:!0},keys:{enumerable:!0},values:{enumerable:!0},entries:{enumerable:!0}});I9o=Symbol("internal");v9o=Object.setPrototypeOf({next(){if(!this||Object.getPrototypeOf(this)!==v9o)throw new TypeError("Value of `this` is not a HeadersIterator");var e=this[I9o];let t=e.target,r=e.kind,n=e.index,i=E9o(t,r),o=i.length;return n>=o?{value:void 0,done:!0}:(this[I9o].index=n+1,{value:i[n],done:!1})}},Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));Object.defineProperty(v9o,Symbol.toStringTag,{value:"HeadersIterator",writable:!1,enumerable:!1,configurable:!0});OUe=Symbol("Response internals"),iqm=qHl.default.STATUS_CODES,vre=class e{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};jT.call(this,t,r);let n=r.status||200,i=new d8(r.headers);if(t!=null&&!i.has("Content-Type")){let o=JHl(t);o&&i.append("Content-Type",o)}this[OUe]={url:r.url,status:n,statusText:r.statusText||iqm[n],headers:i}}get url(){return this[OUe].url}get status(){return this[OUe].status}get ok(){return this[OUe].status>=200&&this[OUe].status<300}get statusText(){return this[OUe].statusText}get headers(){return this[OUe].headers}clone(){return new e(KHl(this),{url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok})}};jT.mixIn(vre.prototype);Object.defineProperties(vre.prototype,{url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});Object.defineProperty(vre.prototype,Symbol.toStringTag,{value:"Response",writable:!1,enumerable:!1,configurable:!0});Ume=Symbol("Request internals"),A9o=eJr.default.parse,oqm=eJr.default.format,sqm="destroy"in iJ.default.Readable.prototype;USe=class e{constructor(t){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n;$Kr(t)?n=A9o(t.url):(t&&t.href?n=A9o(t.href):n=A9o(`${t}`),t={});let i=r.method||t.method||"GET";if(i=i.toUpperCase(),(r.body!=null||$Kr(t)&&t.body!==null)&&(i==="GET"||i==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let o=r.body!=null?r.body:$Kr(t)&&t.body!==null?KHl(t):null;jT.call(this,o,{timeout:r.timeout||t.timeout||0,size:r.size||t.size||0});let s=new d8(r.headers||t.headers||{});if(o!=null&&!s.has("Content-Type")){let c=JHl(o);c&&s.append("Content-Type",c)}let a=$Kr(t)?t.signal:null;if("signal"in r&&(a=r.signal),a!=null&&!aqm(a))throw new TypeError("Expected signal to be an instanceof AbortSignal");this[Ume]={method:i,redirect:r.redirect||t.redirect||"follow",headers:s,parsedURL:n,signal:a},this.follow=r.follow!==void 0?r.follow:t.follow!==void 0?t.follow:20,this.compress=r.compress!==void 0?r.compress:t.compress!==void 0?t.compress:!0,this.counter=r.counter||t.counter||0,this.agent=r.agent||t.agent}get method(){return this[Ume].method}get url(){return oqm(this[Ume].parsedURL)}get headers(){return this[Ume].headers}get redirect(){return this[Ume].redirect}get signal(){return this[Ume].signal}clone(){return new e(this)}};jT.mixIn(USe.prototype);Object.defineProperty(USe.prototype,Symbol.toStringTag,{value:"Request",writable:!1,enumerable:!1,configurable:!0});Object.defineProperties(USe.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0}});_Gt.prototype=Object.create(Error.prototype);_Gt.prototype.constructor=_Gt;_Gt.prototype.name="AbortError";GHl=iJ.default.PassThrough,lqm=eJr.default.resolve;_Se.isRedirect=function(e){return e===301||e===302||e===303||e===307||e===308};_Se.Promise=global.Promise;uqm=_Se});var RUe=E(GQ=>{"use strict";var Gme={ANCHOR:"&",COMMENT:"#",TAG:"!",DIRECTIVES_END:"-",DOCUMENT_END:"."},UGt={ALIAS:"ALIAS",BLANK_LINE:"BLANK_LINE",BLOCK_FOLDED:"BLOCK_FOLDED",BLOCK_LITERAL:"BLOCK_LITERAL",COMMENT:"COMMENT",DIRECTIVE:"DIRECTIVE",DOCUMENT:"DOCUMENT",FLOW_MAP:"FLOW_MAP",FLOW_SEQ:"FLOW_SEQ",MAP:"MAP",MAP_KEY:"MAP_KEY",MAP_VALUE:"MAP_VALUE",PLAIN:"PLAIN",QUOTE_DOUBLE:"QUOTE_DOUBLE",QUOTE_SINGLE:"QUOTE_SINGLE",SEQ:"SEQ",SEQ_ITEM:"SEQ_ITEM"},pqm="tag:yaml.org,2002:",fqm={MAP:"tag:yaml.org,2002:map",SEQ:"tag:yaml.org,2002:seq",STR:"tag:yaml.org,2002:str"};function ZHl(e){let t=[0],r=e.indexOf(`
|
|
550
|
+
`).reduce(s8m,Object.create(null)),s8m=(e,t)=>{let r=parseInt(t,10);if(r!==Buffer.byteLength(t)+1)return e;t=t.slice((r+" ").length);let n=t.split("="),i=n.shift();if(!i)return e;let o=i.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),s=n.join("=");return e[o]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(o)?new Date(Number(s)*1e3):/^[0-9]+$/.test(s)?+s:s,e},a8m=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,lf=a8m!=="win32"?e=>e:e=>e&&e.replaceAll(/\\/g,"/"),c8m=class extends EUe{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(e,t,r){switch(super({}),this.pause(),this.extended=t,this.globalExtended=r,this.header=e,this.remain=e.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=e.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!e.path)throw new Error("no path provided for tar.ReadEntry");this.path=lf(e.path),this.mode=e.mode,this.mode&&(this.mode=this.mode&4095),this.uid=e.uid,this.gid=e.gid,this.uname=e.uname,this.gname=e.gname,this.size=this.remain,this.mtime=e.mtime,this.atime=e.atime,this.ctime=e.ctime,this.linkpath=e.linkpath?lf(e.linkpath):void 0,this.uname=e.uname,this.gname=e.gname,t&&this.#e(t),r&&this.#e(r,!0)}write(e){let t=e.length;if(t>this.blockRemain)throw new Error("writing more to entry than is appropriate");let r=this.remain,n=this.blockRemain;return this.remain=Math.max(0,r-t),this.blockRemain=Math.max(0,n-t),this.ignore?!0:r>=t?super.write(e):super.write(e.subarray(0,r))}#e(e,t=!1){e.path&&(e.path=lf(e.path)),e.linkpath&&(e.linkpath=lf(e.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(e).filter(([r,n])=>!(n==null||r==="path"&&t))))}},WHr=(e,t,r,n={})=>{e.file&&(n.file=e.file),e.cwd&&(n.cwd=e.cwd),n.code=r instanceof Error&&r.code||t,n.tarCode=t,!e.strict&&n.recoverable!==!1?(r instanceof Error&&(n=Object.assign(r,n),r=r.message),e.emit("warn",t,r,n)):r instanceof Error?e.emit("error",Object.assign(r,n)):e.emit("error",Object.assign(new Error(`${t}: ${r}`),n))},l8m=1024*1024,U8o=Buffer.from([31,139]),V8o=Buffer.from([40,181,47,253]),u8m=Math.max(U8o.length,V8o.length),p8=Symbol("state"),pUe=Symbol("writeEntry"),zme=Symbol("readEntry"),O8o=Symbol("nextEntry"),cql=Symbol("processEntry"),yre=Symbol("extendedHeader"),rGt=Symbol("globalExtendedHeader"),ySe=Symbol("meta"),lql=Symbol("emitMeta"),Jb=Symbol("buffer"),Qme=Symbol("queue"),bSe=Symbol("ended"),P8o=Symbol("emittedEnd"),fUe=Symbol("emit"),Wx=Symbol("unzip"),bHr=Symbol("consumeChunk"),EHr=Symbol("consumeChunkSub"),B8o=Symbol("consumeBody"),uql=Symbol("consumeMeta"),pql=Symbol("consumeHeader"),nGt=Symbol("consuming"),D8o=Symbol("bufferConcat"),IHr=Symbol("maybeEnd"),bct=Symbol("writing"),ESe=Symbol("aborted"),vHr=Symbol("onDone"),dUe=Symbol("sawValidEntry"),CHr=Symbol("sawNullBlock"),xHr=Symbol("sawEOF"),fql=Symbol("closeStream"),p8m=()=>!0,yGt=class extends Qql.EventEmitter{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[Qme]=[];[Jb];[zme];[pUe];[p8]="begin";[ySe]="";[yre];[rGt];[bSe]=!1;[Wx];[ESe]=!1;[dUe];[CHr]=!1;[xHr]=!1;[bct]=!1;[nGt]=!1;[P8o]=!1;constructor(e={}){super(),this.file=e.file||"",this.on(vHr,()=>{(this[p8]==="begin"||this[dUe]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),e.ondone?this.on(vHr,e.ondone):this.on(vHr,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!e.strict,this.maxMetaEntrySize=e.maxMetaEntrySize||l8m,this.filter=typeof e.filter=="function"?e.filter:p8m;let t=e.file&&(e.file.endsWith(".tar.br")||e.file.endsWith(".tbr"));this.brotli=!(e.gzip||e.zstd)&&e.brotli!==void 0?e.brotli:t?void 0:!1;let r=e.file&&(e.file.endsWith(".tar.zst")||e.file.endsWith(".tzst"));this.zstd=!(e.gzip||e.brotli)&&e.zstd!==void 0?e.zstd:r?!0:void 0,this.on("end",()=>this[fql]()),typeof e.onwarn=="function"&&this.on("warn",e.onwarn),typeof e.onReadEntry=="function"&&this.on("entry",e.onReadEntry)}warn(e,t,r={}){WHr(this,e,t,r)}[pql](e,t){this[dUe]===void 0&&(this[dUe]=!1);let r;try{r=new bUe(e,t,this[yre],this[rGt])}catch(n){return this.warn("TAR_ENTRY_INVALID",n)}if(r.nullBlock)this[CHr]?(this[xHr]=!0,this[p8]==="begin"&&(this[p8]="header"),this[fUe]("eof")):(this[CHr]=!0,this[fUe]("nullBlock"));else if(this[CHr]=!1,!r.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:r});else if(!r.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:r});else{let n=r.type;if(/^(Symbolic)?Link$/.test(n)&&!r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:r});else if(!/^(Symbolic)?Link$/.test(n)&&!/^(Global)?ExtendedHeader$/.test(n)&&r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:r});else{let i=this[pUe]=new c8m(r,this[yre],this[rGt]);if(!this[dUe])if(i.remain){let o=()=>{i.invalid||(this[dUe]=!0)};i.on("end",o)}else this[dUe]=!0;i.meta?i.size>this.maxMetaEntrySize?(i.ignore=!0,this[fUe]("ignoredEntry",i),this[p8]="ignore",i.resume()):i.size>0&&(this[ySe]="",i.on("data",o=>this[ySe]+=o),this[p8]="meta"):(this[yre]=void 0,i.ignore=i.ignore||!this.filter(i.path,i),i.ignore?(this[fUe]("ignoredEntry",i),this[p8]=i.remain?"ignore":"header",i.resume()):(i.remain?this[p8]="body":(this[p8]="header",i.end()),this[zme]?this[Qme].push(i):(this[Qme].push(i),this[O8o]())))}}}[fql](){queueMicrotask(()=>this.emit("close"))}[cql](e){let t=!0;if(!e)this[zme]=void 0,t=!1;else if(Array.isArray(e)){let[r,...n]=e;this.emit(r,...n)}else this[zme]=e,this.emit("entry",e),e.emittedEnd||(e.on("end",()=>this[O8o]()),t=!1);return t}[O8o](){do;while(this[cql](this[Qme].shift()));if(this[Qme].length===0){let e=this[zme];!e||e.flowing||e.size===e.remain?this[bct]||this.emit("drain"):e.once("drain",()=>this.emit("drain"))}}[B8o](e,t){let r=this[pUe];if(!r)throw new Error("attempt to consume body without entry??");let n=r.blockRemain??0,i=n>=e.length&&t===0?e:e.subarray(t,t+n);return r.write(i),r.blockRemain||(this[p8]="header",this[pUe]=void 0,r.end()),i.length}[uql](e,t){let r=this[pUe],n=this[B8o](e,t);return!this[pUe]&&r&&this[lql](r),n}[fUe](e,t,r){this[Qme].length===0&&!this[zme]?this.emit(e,t,r):this[Qme].push([e,t,r])}[lql](e){switch(this[fUe]("meta",this[ySe]),e.type){case"ExtendedHeader":case"OldExtendedHeader":this[yre]=MHr.parse(this[ySe],this[yre],!1);break;case"GlobalExtendedHeader":this[rGt]=MHr.parse(this[ySe],this[rGt],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let t=this[yre]??Object.create(null);this[yre]=t,t.path=this[ySe].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let t=this[yre]||Object.create(null);this[yre]=t,t.linkpath=this[ySe].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+e.type)}}abort(e){this[ESe]=!0,this.emit("abort",e),this.warn("TAR_ABORT",e,{recoverable:!1})}write(e,t,r){if(typeof t=="function"&&(r=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,typeof t=="string"?t:"utf8")),this[ESe])return r?.(),!1;if((this[Wx]===void 0||this.brotli===void 0&&this[Wx]===!1)&&e){if(this[Jb]&&(e=Buffer.concat([this[Jb],e]),this[Jb]=void 0),e.length<u8m)return this[Jb]=e,r?.(),!0;for(let s=0;this[Wx]===void 0&&s<U8o.length;s++)e[s]!==U8o[s]&&(this[Wx]=!1);let i=!1;if(this[Wx]===!1&&this.zstd!==!1){i=!0;for(let s=0;s<V8o.length;s++)if(e[s]!==V8o[s]){i=!1;break}}let o=this.brotli===void 0&&!i;if(this[Wx]===!1&&o)if(e.length<512)if(this[bSe])this.brotli=!0;else return this[Jb]=e,r?.(),!0;else try{new bUe(e.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Wx]===void 0||this[Wx]===!1&&(this.brotli||i)){let s=this[bSe];this[bSe]=!1,this[Wx]=this[Wx]===void 0?new j5m({}):i?new L5m({}):new Q5m({}),this[Wx].on("data",c=>this[bHr](c)),this[Wx].on("error",c=>this.abort(c)),this[Wx].on("end",()=>{this[bSe]=!0,this[bHr]()}),this[bct]=!0;let a=!!this[Wx][s?"end":"write"](e);return this[bct]=!1,r?.(),a}}this[bct]=!0,this[Wx]?this[Wx].write(e):this[bHr](e),this[bct]=!1;let n=this[Qme].length>0?!1:this[zme]?this[zme].flowing:!0;return!n&&this[Qme].length===0&&this[zme]?.once("drain",()=>this.emit("drain")),r?.(),n}[D8o](e){e&&!this[ESe]&&(this[Jb]=this[Jb]?Buffer.concat([this[Jb],e]):e)}[IHr](){if(this[bSe]&&!this[P8o]&&!this[ESe]&&!this[nGt]){this[P8o]=!0;let e=this[pUe];if(e&&e.blockRemain){let t=this[Jb]?this[Jb].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${e.blockRemain} more bytes, only ${t} available)`,{entry:e}),this[Jb]&&e.write(this[Jb]),e.end()}this[fUe](vHr)}}[bHr](e){if(this[nGt]&&e)this[D8o](e);else if(!e&&!this[Jb])this[IHr]();else if(e){if(this[nGt]=!0,this[Jb]){this[D8o](e);let t=this[Jb];this[Jb]=void 0,this[EHr](t)}else this[EHr](e);for(;this[Jb]&&this[Jb]?.length>=512&&!this[ESe]&&!this[xHr];){let t=this[Jb];this[Jb]=void 0,this[EHr](t)}this[nGt]=!1}(!this[Jb]||this[bSe])&&this[IHr]()}[EHr](e){let t=0,r=e.length;for(;t+512<=r&&!this[ESe]&&!this[xHr];)switch(this[p8]){case"begin":case"header":this[pql](e,t),t+=512;break;case"ignore":case"body":t+=this[B8o](e,t);break;case"meta":t+=this[uql](e,t);break;default:throw new Error("invalid state: "+this[p8])}t<r&&(this[Jb]=this[Jb]?Buffer.concat([e.subarray(t),this[Jb]]):e.subarray(t))}end(e,t,r){return typeof e=="function"&&(r=e,t=void 0,e=void 0),typeof t=="function"&&(r=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,t)),r&&this.once("finish",r),this[ESe]||(this[Wx]?(e&&this[Wx].write(e),this[Wx].end()):(this[bSe]=!0,(this.brotli===void 0||this.zstd===void 0)&&(e=e||Buffer.alloc(0)),e&&this.write(e),this[IHr]())),this}},fGt=e=>{let t=e.length-1,r=-1;for(;t>-1&&e.charAt(t)==="/";)r=t,t--;return r===-1?e:e.slice(0,r)},f8m=e=>{let t=e.onReadEntry;e.onReadEntry=t?r=>{t(r),r.resume()}:r=>r.resume()},Kql=(e,t)=>{let r=new Map(t.map(o=>[fGt(o),!0])),n=e.filter,i=(o,s="")=>{let a=s||(0,GHr.parse)(o).root||".",c;if(o===a)c=!1;else{let l=r.get(o);c=l!==void 0?l:i((0,GHr.dirname)(o),a)}return r.set(o,c),c};e.filter=n?(o,s)=>n(o,s)&&i(fGt(o)):o=>i(fGt(o))},d8m=e=>{let t=new yGt(e),r=e.file,n;try{n=gUe.default.openSync(r,"r");let i=gUe.default.fstatSync(n),o=e.maxReadSize||16*1024*1024;if(i.size<o){let s=Buffer.allocUnsafe(i.size),a=gUe.default.readSync(n,s,0,i.size,0);t.end(a===s.byteLength?s:s.subarray(0,a))}else{let s=0,a=Buffer.allocUnsafe(o);for(;s<i.size;){let c=gUe.default.readSync(n,a,0,o,s);if(c===0)break;s+=c,t.write(a.subarray(0,c))}t.end()}}finally{if(typeof n=="number")try{gUe.default.closeSync(n)}catch{}}},m8m=(e,t)=>{let r=new yGt(e),n=e.maxReadSize||16*1024*1024,i=e.file;return new Promise((o,s)=>{r.on("error",s),r.on("end",o),gUe.default.stat(i,(a,c)=>{if(a)s(a);else{let l=new lGo(i,{readSize:n,size:c.size});l.on("error",s),l.pipe(r)}})})},HHr=IGt(d8m,m8m,e=>new yGt(e),e=>new yGt(e),(e,t)=>{t?.length&&Kql(e,t),e.noResume||f8m(e)}),Jql=(e,t,r)=>(e&=4095,r&&(e=(e|384)&-19),t&&(e&256&&(e|=64),e&32&&(e|=8),e&4&&(e|=1)),e),{isAbsolute:h8m,parse:dql}=Yql.win32,mGo=e=>{let t="",r=dql(e);for(;h8m(e)||r.root;){let n=e.charAt(0)==="/"&&e.slice(0,4)!=="//?/"?"/":r.root;e=e.slice(n.length),t+=n,r=dql(e)}return[t,e]},KHr=["|","<",">","?",":"],hGo=KHr.map(e=>String.fromCodePoint(61440+Number(e.codePointAt(0)))),g8m=new Map(KHr.map((e,t)=>[e,hGo[t]])),A8m=new Map(hGo.map((e,t)=>[e,KHr[t]])),mql=e=>KHr.reduce((t,r)=>t.split(r).join(g8m.get(r)),e),y8m=e=>hGo.reduce((t,r)=>t.split(r).join(A8m.get(r)),e),Xql=(e,t)=>t?(e=lf(e).replace(/^\.(\/|$)/,""),fGt(t)+"/"+e):lf(e),b8m=16*1024*1024,hql=Symbol("process"),gql=Symbol("file"),Aql=Symbol("directory"),q8o=Symbol("symlink"),yql=Symbol("hardlink"),iGt=Symbol("header"),BHr=Symbol("read"),W8o=Symbol("lstat"),DHr=Symbol("onlstat"),H8o=Symbol("onread"),K8o=Symbol("onreadlink"),J8o=Symbol("openfile"),Y8o=Symbol("onopenfile"),SSe=Symbol("close"),LHr=Symbol("mode"),X8o=Symbol("awaitDrain"),R8o=Symbol("ondrain"),bre=Symbol("prefix"),Zql=class extends EUe{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#e=!1;constructor(e,t={}){let r=pGo(t);super(),this.path=lf(e),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||b8m,this.linkCache=r.linkCache||new Map,this.statCache=r.statCache||new Map,this.preservePaths=!!r.preservePaths,this.cwd=lf(r.cwd||process.cwd()),this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.mtime=r.mtime,this.prefix=r.prefix?lf(r.prefix):void 0,this.onWriteEntry=r.onWriteEntry,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let n=!1;if(!this.preservePaths){let[o,s]=mGo(this.path);o&&typeof s=="string"&&(this.path=s,n=o)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=y8m(this.path.replaceAll(/\\/g,"/")),e=e.replaceAll(/\\/g,"/")),this.absolute=lf(r.absolute||G8o.default.resolve(this.cwd,e)),this.path===""&&(this.path="./"),n&&this.warn("TAR_ENTRY_INFO",`stripping ${n} from absolute path`,{entry:this,path:n+this.path});let i=this.statCache.get(this.absolute);i?this[DHr](i):this[W8o]()}warn(e,t,r={}){return WHr(this,e,t,r)}emit(e,...t){return e==="error"&&(this.#e=!0),super.emit(e,...t)}[W8o](){ZK.default.lstat(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[DHr](t)})}[DHr](e){this.statCache.set(this.absolute,e),this.stat=e,e.isFile()||(e.size=0),this.type=v8m(e),this.emit("stat",e),this[hql]()}[hql](){switch(this.type){case"File":return this[gql]();case"Directory":return this[Aql]();case"SymbolicLink":return this[q8o]();default:return this.end()}}[LHr](e){return Jql(e,this.type==="Directory",this.portable)}[bre](e){return Xql(e,this.prefix)}[iGt](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new bUe({path:this[bre](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[bre](this.linkpath):this.linkpath,mode:this[LHr](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new MHr({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[bre](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[bre](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let e=this.header?.block;if(!e)throw new Error("failed to encode header");super.write(e)}[Aql](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[iGt](),this.end()}[q8o](){ZK.default.readlink(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[K8o](t)})}[K8o](e){this.linkpath=lf(e),this[iGt](),this.end()}[yql](e){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=lf(G8o.default.relative(this.cwd,e)),this.stat.size=0,this[iGt](),this.end()}[gql](){if(!this.stat)throw new Error("cannot create file entry without stat");if(this.stat.nlink>1){let e=`${this.stat.dev}:${this.stat.ino}`,t=this.linkCache.get(e);if(t?.indexOf(this.cwd)===0)return this[yql](t);this.linkCache.set(e,this.absolute)}if(this[iGt](),this.stat.size===0)return this.end();this[J8o]()}[J8o](){ZK.default.open(this.absolute,"r",(e,t)=>{if(e)return this.emit("error",e);this[Y8o](t)})}[Y8o](e){if(this.fd=e,this.#e)return this[SSe]();if(!this.stat)throw new Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let t=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(t),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[BHr]()}[BHr](){let{fd:e,buf:t,offset:r,length:n,pos:i}=this;if(e===void 0||t===void 0)throw new Error("cannot read file without first opening");ZK.default.read(e,t,r,n,i,(o,s)=>{if(o)return this[SSe](()=>this.emit("error",o));this[H8o](s)})}[SSe](e=()=>{}){this.fd!==void 0&&ZK.default.close(this.fd,e)}[H8o](e){if(e<=0&&this.remain>0){let r=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[SSe](()=>this.emit("error",r))}if(e>this.remain){let r=Object.assign(new Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[SSe](()=>this.emit("error",r))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(e===this.remain)for(let r=e;r<this.length&&e<this.blockRemain;r++)this.buf[r+this.offset]=0,e++,this.remain++;let t=this.offset===0&&e===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+e);this.write(t)?this[R8o]():this[X8o](()=>this[R8o]())}[X8o](e){this.once("drain",e)}write(e,t,r){if(typeof t=="function"&&(r=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,typeof t=="string"?t:"utf8")),this.blockRemain<e.length){let n=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",n)}return this.remain-=e.length,this.blockRemain-=e.length,this.pos+=e.length,this.offset+=e.length,super.write(e,null,r)}[R8o](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[SSe](e=>e?this.emit("error",e):this.end());if(!this.buf)throw new Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[BHr]()}},E8m=class extends Zql{sync=!0;[W8o](){this[DHr](ZK.default.lstatSync(this.absolute))}[q8o](){this[K8o](ZK.default.readlinkSync(this.absolute))}[J8o](){this[Y8o](ZK.default.openSync(this.absolute,"r"))}[BHr](){let e=!0;try{let{fd:t,buf:r,offset:n,length:i,pos:o}=this;if(t===void 0||r===void 0)throw new Error("fd and buf must be set in READ method");let s=ZK.default.readSync(t,r,n,i,o);this[H8o](s),e=!1}finally{if(e)try{this[SSe](()=>{})}catch{}}}[X8o](e){e()}[SSe](e=()=>{}){this.fd!==void 0&&ZK.default.closeSync(this.fd),e()}},I8m=class extends EUe{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(e,t,r={}){return WHr(this,e,t,r)}constructor(e,t={}){let r=pGo(t);super(),this.preservePaths=!!r.preservePaths,this.portable=!!r.portable,this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.onWriteEntry=r.onWriteEntry,this.readEntry=e;let{type:n}=e;if(n==="Unsupported")throw new Error("writing entry that should be ignored");this.type=n,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=r.prefix,this.path=lf(e.path),this.mode=e.mode!==void 0?this[LHr](e.mode):void 0,this.uid=this.portable?void 0:e.uid,this.gid=this.portable?void 0:e.gid,this.uname=this.portable?void 0:e.uname,this.gname=this.portable?void 0:e.gname,this.size=e.size,this.mtime=this.noMtime?void 0:r.mtime||e.mtime,this.atime=this.portable?void 0:e.atime,this.ctime=this.portable?void 0:e.ctime,this.linkpath=e.linkpath!==void 0?lf(e.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let i=!1;if(!this.preservePaths){let[s,a]=mGo(this.path);s&&typeof a=="string"&&(this.path=a,i=s)}this.remain=e.size,this.blockRemain=e.startBlockSize,this.onWriteEntry?.(this),this.header=new bUe({path:this[bre](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[bre](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),i&&this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute path`,{entry:this,path:i+this.path}),this.header.encode()&&!this.noPax&&super.write(new MHr({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[bre](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[bre](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let o=this.header?.block;if(!o)throw new Error("failed to encode header");super.write(o),e.pipe(this)}[bre](e){return Xql(e,this.prefix)}[LHr](e){return Jql(e,this.type==="Directory",this.portable)}write(e,t,r){typeof t=="function"&&(r=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,typeof t=="string"?t:"utf8"));let n=e.length;if(n>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=n,super.write(e,r)}end(e,t,r){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof e=="function"&&(r=e,t=void 0,e=void 0),typeof t=="function"&&(r=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,t??"utf8")),r&&this.once("finish",r),e?super.end(e,r):super.end(r),this}},v8m=e=>e.isFile()?"File":e.isDirectory()?"Directory":e.isSymbolicLink()?"SymbolicLink":"Unsupported",C8m=class Sct{tail;head;length=0;static create(t=[]){return new Sct(t)}constructor(t=[]){for(let r of t)this.push(r)}*[Symbol.iterator](){for(let t=this.head;t;t=t.next)yield t.value}removeNode(t){if(t.list!==this)throw new Error("removing node which does not belong to this list");let r=t.next,n=t.prev;return r&&(r.prev=n),n&&(n.next=r),t===this.head&&(this.head=r),t===this.tail&&(this.tail=n),this.length--,t.next=void 0,t.prev=void 0,t.list=void 0,r}unshiftNode(t){if(t===this.head)return;t.list&&t.list.removeNode(t);let r=this.head;t.list=this,t.next=r,r&&(r.prev=t),this.head=t,this.tail||(this.tail=t),this.length++}pushNode(t){if(t===this.tail)return;t.list&&t.list.removeNode(t);let r=this.tail;t.list=this,t.prev=r,r&&(r.next=t),this.tail=t,this.head||(this.head=t),this.length++}push(...t){for(let r=0,n=t.length;r<n;r++)S8m(this,t[r]);return this.length}unshift(...t){for(var r=0,n=t.length;r<n;r++)w8m(this,t[r]);return this.length}pop(){if(!this.tail)return;let t=this.tail.value,r=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,r.list=void 0,this.length--,t}shift(){if(!this.head)return;let t=this.head.value,r=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,r.list=void 0,this.length--,t}forEach(t,r){r=r||this;for(let n=this.head,i=0;n;i++)t.call(r,n.value,i,this),n=n.next}forEachReverse(t,r){r=r||this;for(let n=this.tail,i=this.length-1;n;i--)t.call(r,n.value,i,this),n=n.prev}get(t){let r=0,n=this.head;for(;n&&r<t;r++)n=n.next;if(r===t&&n)return n.value}getReverse(t){let r=0,n=this.tail;for(;n&&r<t;r++)n=n.prev;if(r===t&&n)return n.value}map(t,r){r=r||this;let n=new Sct;for(let i=this.head;i;)n.push(t.call(r,i.value,this)),i=i.next;return n}mapReverse(t,r){r=r||this;var n=new Sct;for(let i=this.tail;i;)n.push(t.call(r,i.value,this)),i=i.prev;return n}reduce(t,r){let n,i=this.head;if(arguments.length>1)n=r;else if(this.head)i=this.head.next,n=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var o=0;i;o++)n=t(n,i.value,o),i=i.next;return n}reduceReverse(t,r){let n,i=this.tail;if(arguments.length>1)n=r;else if(this.tail)i=this.tail.prev,n=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let o=this.length-1;i;o--)n=t(n,i.value,o),i=i.prev;return n}toArray(){let t=new Array(this.length);for(let r=0,n=this.head;n;r++)t[r]=n.value,n=n.next;return t}toArrayReverse(){let t=new Array(this.length);for(let r=0,n=this.tail;n;r++)t[r]=n.value,n=n.prev;return t}slice(t=0,r=this.length){r<0&&(r+=this.length),t<0&&(t+=this.length);let n=new Sct;if(r<t||r<0)return n;t<0&&(t=0),r>this.length&&(r=this.length);let i=this.head,o=0;for(o=0;i&&o<t;o++)i=i.next;for(;i&&o<r;o++,i=i.next)n.push(i.value);return n}sliceReverse(t=0,r=this.length){r<0&&(r+=this.length),t<0&&(t+=this.length);let n=new Sct;if(r<t||r<0)return n;t<0&&(t=0),r>this.length&&(r=this.length);let i=this.length,o=this.tail;for(;o&&i>r;i--)o=o.prev;for(;o&&i>t;i--,o=o.prev)n.push(o.value);return n}splice(t,r=0,...n){t>this.length&&(t=this.length-1),t<0&&(t=this.length+t);let i=this.head;for(let s=0;i&&s<t;s++)i=i.next;let o=[];for(let s=0;i&&s<r;s++)o.push(i.value),i=this.removeNode(i);i?i!==this.tail&&(i=i.prev):i=this.tail;for(let s of n)i=x8m(this,i,s);return o}reverse(){let t=this.head,r=this.tail;for(let n=t;n;n=n.prev){let i=n.prev;n.prev=n.next,n.next=i}return this.head=r,this.tail=t,this}};gGo=class{list;next;prev;value;constructor(e,t,r,n){this.list=n,this.value=e,t?(t.next=this,this.prev=t):this.prev=void 0,r?(r.prev=this,this.next=r):this.next=void 0}},bql=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(e,t){this.path=e||"./",this.absolute=t}},Eql=Buffer.alloc(1024),RHr=Symbol("onStat"),oGt=Symbol("ended"),YK=Symbol("queue"),sGt=Symbol("pendingLinks"),ISe=Symbol("current"),mUe=Symbol("process"),aGt=Symbol("processing"),SHr=Symbol("processJob"),XK=Symbol("jobs"),k8o=Symbol("jobDone"),kHr=Symbol("addFSEntry"),Iql=Symbol("addTarEntry"),$8o=Symbol("stat"),eGo=Symbol("readdir"),FHr=Symbol("onreaddir"),NHr=Symbol("pipe"),vql=Symbol("entry"),F8o=Symbol("entryOpt"),jHr=Symbol("writeEntryClass"),$ql=Symbol("write"),N8o=Symbol("ondrain"),JHr=class extends EUe{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[jHr];onWriteEntry;[YK];[sGt]=new Map;[XK]=0;[aGt]=!1;[oGt]=!1;constructor(e={}){if(super(),this.opt=e,this.file=e.file||"",this.cwd=e.cwd||process.cwd(),this.maxReadSize=e.maxReadSize,this.preservePaths=!!e.preservePaths,this.strict=!!e.strict,this.noPax=!!e.noPax,this.prefix=lf(e.prefix||""),this.linkCache=e.linkCache||new Map,this.statCache=e.statCache||new Map,this.readdirCache=e.readdirCache||new Map,this.onWriteEntry=e.onWriteEntry,this[jHr]=Zql,typeof e.onwarn=="function"&&this.on("warn",e.onwarn),this.portable=!!e.portable,e.gzip||e.brotli||e.zstd){if((e.gzip?1:0)+(e.brotli?1:0)+(e.zstd?1:0)>1)throw new TypeError("gzip, brotli, zstd are mutually exclusive");if(e.gzip&&(typeof e.gzip!="object"&&(e.gzip={}),this.portable&&(e.gzip.portable=!0),this.zip=new N5m(e.gzip)),e.brotli&&(typeof e.brotli!="object"&&(e.brotli={}),this.zip=new z5m(e.brotli)),e.zstd&&(typeof e.zstd!="object"&&(e.zstd={}),this.zip=new M5m(e.zstd)),!this.zip)throw new Error("impossible");let t=this.zip;t.on("data",r=>super.write(r)),t.on("end",()=>super.end()),t.on("drain",()=>this[N8o]()),this.on("resume",()=>t.resume())}else this.on("drain",this[N8o]);this.noDirRecurse=!!e.noDirRecurse,this.follow=!!e.follow,this.noMtime=!!e.noMtime,e.mtime&&(this.mtime=e.mtime),this.filter=typeof e.filter=="function"?e.filter:()=>!0,this[YK]=new C8m,this[XK]=0,this.jobs=Number(e.jobs)||4,this[aGt]=!1,this[oGt]=!1}[$ql](e){return super.write(e)}add(e){return this.write(e),this}end(e,t,r){return typeof e=="function"&&(r=e,e=void 0),typeof t=="function"&&(r=t,t=void 0),e&&this.add(e),this[oGt]=!0,this[mUe](),r&&r(),this}write(e){if(this[oGt])throw new Error("write after end");return typeof e=="string"?this[kHr](e):this[Iql](e),this.flowing}[Iql](e){let t=lf(Z8o.default.resolve(this.cwd,e.path));if(!this.filter(e.path,e))e.resume();else{let r=new bql(e.path,t);r.entry=new I8m(e,this[F8o](r)),r.entry.on("end",()=>this[k8o](r)),this[XK]+=1,this[YK].push(r)}this[mUe]()}[kHr](e){let t=lf(Z8o.default.resolve(this.cwd,e));this[YK].push(new bql(e,t)),this[mUe]()}[$8o](e){e.pending=!0,this[XK]+=1;let t=this.follow?"stat":"lstat";bGt.default[t](e.absolute,(r,n)=>{e.pending=!1,this[XK]-=1,r?this.emit("error",r):this[RHr](e,n)})}[RHr](e,t){if(this.statCache.set(e.absolute,t),e.stat=t,!this.filter(e.path,t))e.ignore=!0;else if(t.isFile()&&t.nlink>1&&!this.linkCache.get(`${t.dev}:${t.ino}`)&&!this.sync)if(e===this[ISe])this[SHr](e);else{let r=`${t.dev}:${t.ino}`,n=this[sGt].get(r);n?n.push(e):this[sGt].set(r,[e]),e.pendingLink=!0,e.pending=!0}this[mUe]()}[eGo](e){e.pending=!0,this[XK]+=1,bGt.default.readdir(e.absolute,(t,r)=>{if(e.pending=!1,this[XK]-=1,t)return this.emit("error",t);this[FHr](e,r)})}[FHr](e,t){this.readdirCache.set(e.absolute,t),e.readdir=t,this[mUe]()}[mUe](){if(!this[aGt]){this[aGt]=!0;for(let e=this[YK].head;e&&this[XK]<this.jobs;e=e.next)if(this[SHr](e.value),e.value.ignore){let t=e.next;this[YK].removeNode(e),e.next=t}this[aGt]=!1,this[oGt]&&this[YK].length===0&&this[XK]===0&&(this.zip?this.zip.end(Eql):(super.write(Eql),super.end()))}}get[ISe](){return this[YK]&&this[YK].head&&this[YK].head.value}[k8o](e){this[YK].shift(),this[XK]-=1;let{stat:t}=e;if(t&&t.isFile()&&t.nlink>1){let r=`${t.dev}:${t.ino}`,n=this[sGt].get(r);if(n){this[sGt].delete(r);for(let i of n)i.pending=!1,this[SHr](i)}}this[mUe]()}[SHr](e){if(e.pending&&e.pendingLink&&e===this[ISe]&&(e.pending=!1,e.pendingLink=!1),!e.pending){if(e.entry){e===this[ISe]&&!e.piped&&this[NHr](e);return}if(!e.stat){let t=this.statCache.get(e.absolute);t?this[RHr](e,t):this[$8o](e)}if(e.stat&&!e.ignore){if(!this.noDirRecurse&&e.stat.isDirectory()&&!e.readdir){let t=this.readdirCache.get(e.absolute);if(t?this[FHr](e,t):this[eGo](e),!e.readdir)return}if(e.entry=this[vql](e),!e.entry){e.ignore=!0;return}e===this[ISe]&&!e.piped&&this[NHr](e)}}}[F8o](e){return{onwarn:(t,r,n)=>this.warn(t,r,n),noPax:this.noPax,cwd:this.cwd,absolute:e.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[vql](e){this[XK]+=1;try{return new this[jHr](e.path,this[F8o](e)).on("end",()=>this[k8o](e)).on("error",t=>this.emit("error",t))}catch(t){this.emit("error",t)}}[N8o](){this[ISe]&&this[ISe].entry&&this[ISe].entry.resume()}[NHr](e){e.piped=!0,e.readdir&&e.readdir.forEach(n=>{let i=e.path,o=i==="./"?"":i.replace(/\/*$/,"/");this[kHr](o+n)});let t=e.entry,r=this.zip;if(!t)throw new Error("cannot pipe without source");r?t.on("data",n=>{r.write(n)||t.pause()}):t.on("data",n=>{super.write(n)||t.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(e,t,r={}){WHr(this,e,t,r)}},AGo=class extends JHr{sync=!0;constructor(e){super(e),this[jHr]=E8m}pause(){}resume(){}[$8o](e){let t=this.follow?"statSync":"lstatSync";this[RHr](e,bGt.default[t](e.absolute))}[eGo](e){this[FHr](e,bGt.default.readdirSync(e.absolute))}[NHr](e){let t=e.entry,r=this.zip;if(e.readdir&&e.readdir.forEach(n=>{let i=e.path,o=i==="./"?"":i.replace(/\/*$/,"/");this[kHr](o+n)}),!t)throw new Error("Cannot pipe without source");r?t.on("data",n=>{r.write(n)}):t.on("data",n=>{super[$ql](n)})}},T8m=(e,t)=>{let r=new AGo(e),n=new zql(e.file,{mode:e.mode||438});r.pipe(n),eWl(r,t)},O8m=(e,t)=>{let r=new JHr(e),n=new VHr(e.file,{mode:e.mode||438});r.pipe(n);let i=new Promise((o,s)=>{n.on("error",s),n.on("close",o),r.on("error",s)});return tWl(r,t).catch(o=>r.emit("error",o)),i},eWl=(e,t)=>{t.forEach(r=>{r.charAt(0)==="@"?HHr({file:uGo.default.resolve(e.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r)}),e.end()},tWl=async(e,t)=>{for(let r of t)r.charAt(0)==="@"?await HHr({file:uGo.default.resolve(String(e.cwd),r.slice(1)),noResume:!0,onReadEntry:n=>{e.add(n)}}):e.add(r);e.end()},P8m=(e,t)=>{let r=new AGo(e);return eWl(r,t),r},B8m=(e,t)=>{let r=new JHr(e);return tWl(r,t).catch(n=>r.emit("error",n)),r},YHr=IGt(T8m,O8m,P8m,B8m,(e,t)=>{if(!t?.length)throw new TypeError("no paths specified to add to archive")}),D8m=process.env.__FAKE_PLATFORM__||process.platform,nWl=D8m==="win32",{O_CREAT:iWl,O_NOFOLLOW:Cql,O_TRUNC:oWl,O_WRONLY:sWl}=EGo.default.constants,aWl=Number(process.env.__FAKE_FS_O_FILENAME__)||EGo.default.constants.UV_FS_O_FILEMAP||0,R8m=nWl&&!!aWl,k8m=512*1024,F8m=aWl|oWl|iWl|sWl,xql=!nWl&&typeof Cql=="number"?Cql|oWl|iWl|sWl:null,cWl=xql!==null?()=>xql:R8m?e=>e<k8m?F8m:"w":()=>"w",tGo=(e,t,r)=>{try{return vGt.default.lchownSync(e,t,r)}catch(n){if(n?.code!=="ENOENT")throw n}},_Hr=(e,t,r,n)=>{vGt.default.lchown(e,t,r,i=>{n(i&&i?.code!=="ENOENT"?i:null)})},N8m=(e,t,r,n,i)=>{if(t.isDirectory())lWl(Tct.default.resolve(e,t.name),r,n,o=>{if(o)return i(o);let s=Tct.default.resolve(e,t.name);_Hr(s,r,n,i)});else{let o=Tct.default.resolve(e,t.name);_Hr(o,r,n,i)}},lWl=(e,t,r,n)=>{vGt.default.readdir(e,{withFileTypes:!0},(i,o)=>{if(i){if(i.code==="ENOENT")return n();if(i.code!=="ENOTDIR"&&i.code!=="ENOTSUP")return n(i)}if(i||!o.length)return _Hr(e,t,r,n);let s=o.length,a=null,c=l=>{if(!a){if(l)return n(a=l);if(--s===0)return _Hr(e,t,r,n)}};for(let l of o)N8m(e,l,t,r,c)})},j8m=(e,t,r,n)=>{t.isDirectory()&&uWl(Tct.default.resolve(e,t.name),r,n),tGo(Tct.default.resolve(e,t.name),r,n)},uWl=(e,t,r)=>{let n;try{n=vGt.default.readdirSync(e,{withFileTypes:!0})}catch(i){let o=i;if(o?.code==="ENOENT")return;if(o?.code==="ENOTDIR"||o?.code==="ENOTSUP")return tGo(e,t,r);throw o}for(let i of n)j8m(e,i,t,r);return tGo(e,t,r)},fWl=class extends Error{path;code;syscall="chdir";constructor(e,t){super(`${t}: Cannot cd into '${e}'`),this.path=e,this.code=t}get name(){return"CwdError"}},XHr=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(e,t){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=e,this.path=t}get name(){return"SymlinkError"}},z8m=(e,t)=>{VQ.default.stat(e,(r,n)=>{(r||!n.isDirectory())&&(r=new fWl(e,r?.code||"ENOTDIR")),t(r)})},Q8m=(e,t,r)=>{e=lf(e);let n=t.umask??18,i=t.mode|448,o=(i&n)!==0,s=t.uid,a=t.gid,c=typeof s=="number"&&typeof a=="number"&&(s!==t.processUid||a!==t.processGid),l=t.preserve,u=t.unlink,p=lf(t.cwd),d=(m,g)=>{m?r(m):g&&c?lWl(g,s,a,A=>d(A)):o?VQ.default.chmod(e,i,r):r()};if(e===p)return z8m(e,d);if(l)return pWl.default.mkdir(e,{mode:i,recursive:!0}).then(m=>d(null,m??void 0),d);let f=lf(EGt.default.relative(p,e)).split("/");rGo(p,f,i,u,p,void 0,d)},rGo=(e,t,r,n,i,o,s)=>{if(t.length===0)return s(null,o);let a=t.shift(),c=lf(EGt.default.resolve(e+"/"+a));VQ.default.mkdir(c,r,dWl(c,t,r,n,i,o,s))},dWl=(e,t,r,n,i,o,s)=>a=>{a?VQ.default.lstat(e,(c,l)=>{if(c)c.path=c.path&&lf(c.path),s(c);else if(l.isDirectory())rGo(e,t,r,n,i,o,s);else if(n)VQ.default.unlink(e,u=>{if(u)return s(u);VQ.default.mkdir(e,r,dWl(e,t,r,n,i,o,s))});else{if(l.isSymbolicLink())return s(new XHr(e,e+"/"+t.join("/")));s(a)}}):(o=o||e,rGo(e,t,r,n,i,o,s))},M8m=e=>{let t=!1,r;try{t=VQ.default.statSync(e).isDirectory()}catch(n){r=n?.code}finally{if(!t)throw new fWl(e,r??"ENOTDIR")}},L8m=(e,t)=>{e=lf(e);let r=t.umask??18,n=t.mode|448,i=(n&r)!==0,o=t.uid,s=t.gid,a=typeof o=="number"&&typeof s=="number"&&(o!==t.processUid||s!==t.processGid),c=t.preserve,l=t.unlink,u=lf(t.cwd),p=m=>{m&&a&&uWl(m,o,s),i&&VQ.default.chmodSync(e,n)};if(e===u)return M8m(u),p();if(c)return p(VQ.default.mkdirSync(e,{mode:n,recursive:!0})??void 0);let d=lf(EGt.default.relative(u,e)).split("/"),f;for(let m=d.shift(),g=u;m&&(g+="/"+m);m=d.shift()){g=lf(EGt.default.resolve(g));try{VQ.default.mkdirSync(g,n),f=f||g}catch{let A=VQ.default.lstatSync(g);if(A.isDirectory())continue;if(l){VQ.default.unlinkSync(g),VQ.default.mkdirSync(g,n),f=f||g;continue}else if(A.isSymbolicLink())return new XHr(g,g+"/"+d.join("/"))}}return p(f)},j8o=Object.create(null),Sql=1e4,Ect=new Set,_8m=e=>{Ect.has(e)?Ect.delete(e):j8o[e]=e.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Ect.add(e);let t=j8o[e],r=Ect.size-Sql;if(r>Sql/10){for(let n of Ect)if(Ect.delete(n),delete j8o[n],--r<=0)break}return t},U8m=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,V8m=U8m==="win32",G8m=e=>e.split("/").slice(0,-1).reduce((t,r)=>{let n=t.at(-1);return n!==void 0&&(r=(0,IGo.join)(n,r)),t.push(r||"/"),t},[]),q8m=class{#e=new Map;#t=new Map;#r=new Set;reserve(e,t){e=V8m?["win32 parallelization disabled"]:e.map(n=>fGt((0,IGo.join)(_8m(n))));let r=new Set(e.map(n=>G8m(n)).reduce((n,i)=>n.concat(i)));this.#t.set(t,{dirs:r,paths:e});for(let n of e){let i=this.#e.get(n);i?i.push(t):this.#e.set(n,[t])}for(let n of r){let i=this.#e.get(n);if(!i)this.#e.set(n,[new Set([t])]);else{let o=i.at(-1);o instanceof Set?o.add(t):i.push(new Set([t]))}}return this.#i(t)}#n(e){let t=this.#t.get(e);if(!t)throw new Error("function does not have any path reservations");return{paths:t.paths.map(r=>this.#e.get(r)),dirs:[...t.dirs].map(r=>this.#e.get(r))}}check(e){let{paths:t,dirs:r}=this.#n(e);return t.every(n=>n&&n[0]===e)&&r.every(n=>n&&n[0]instanceof Set&&n[0].has(e))}#i(e){return this.#r.has(e)||!this.check(e)?!1:(this.#r.add(e),e(()=>this.#o(e)),!0)}#o(e){if(!this.#r.has(e))return!1;let t=this.#t.get(e);if(!t)throw new Error("invalid reservation");let{paths:r,dirs:n}=t,i=new Set;for(let o of r){let s=this.#e.get(o);if(!s||s?.[0]!==e)continue;let a=s[1];if(!a){this.#e.delete(o);continue}if(s.shift(),typeof a=="function")i.add(a);else for(let c of a)i.add(c)}for(let o of n){let s=this.#e.get(o),a=s?.[0];if(!(!s||!(a instanceof Set)))if(a.size===1&&s.length===1){this.#e.delete(o);continue}else if(a.size===1){s.shift();let c=s[0];typeof c=="function"&&i.add(c)}else a.delete(e)}return this.#r.delete(e),i.forEach(o=>this.#i(o)),!0}},W8m=()=>process.umask(),wql=Symbol("onEntry"),nGo=Symbol("checkFs"),Tql=Symbol("checkFs2"),iGo=Symbol("isReusable"),f8=Symbol("makeFs"),oGo=Symbol("file"),sGo=Symbol("directory"),zHr=Symbol("link"),Oql=Symbol("symlink"),Pql=Symbol("hardlink"),uGt=Symbol("ensureNoSymlink"),Bql=Symbol("unsupported"),Dql=Symbol("checkPath"),z8o=Symbol("stripAbsolutePath"),TSe=Symbol("mkdir"),FT=Symbol("onError"),wHr=Symbol("pending"),Rql=Symbol("pend"),Ict=Symbol("unpend"),Q8o=Symbol("ended"),M8o=Symbol("maybeClose"),aGo=Symbol("skip"),dGt=Symbol("doChown"),mGt=Symbol("uid"),hGt=Symbol("gid"),gGt=Symbol("checkedCwd"),H8m=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,AGt=H8m==="win32",K8m=1024,J8m=(e,t)=>{if(!AGt)return Ed.default.unlink(e,t);let r=e+".DELETE."+(0,bGo.randomBytes)(16).toString("hex");Ed.default.rename(e,r,n=>{if(n)return t(n);Ed.default.unlink(r,t)})},Y8m=e=>{if(!AGt)return Ed.default.unlinkSync(e);let t=e+".DELETE."+(0,bGo.randomBytes)(16).toString("hex");Ed.default.renameSync(e,t),Ed.default.unlinkSync(t)},kql=(e,t,r)=>e!==void 0&&e===e>>>0?e:t!==void 0&&t===t>>>0?t:r,vGo=class extends yGt{[Q8o]=!1;[gGt]=!1;[wHr]=0;reservations=new q8m;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(e={}){if(e.ondone=()=>{this[Q8o]=!0,this[M8o]()},super(e),this.transform=e.transform,this.chmod=!!e.chmod,typeof e.uid=="number"||typeof e.gid=="number"){if(typeof e.uid!="number"||typeof e.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(e.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=e.uid,this.gid=e.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;this.preserveOwner=e.preserveOwner===void 0&&typeof e.uid!="number"?!!(process.getuid&&process.getuid()===0):!!e.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof e.maxDepth=="number"?e.maxDepth:K8m,this.forceChown=e.forceChown===!0,this.win32=!!e.win32||AGt,this.newer=!!e.newer,this.keep=!!e.keep,this.noMtime=!!e.noMtime,this.preservePaths=!!e.preservePaths,this.unlink=!!e.unlink,this.cwd=lf(Hx.default.resolve(e.cwd||process.cwd())),this.strip=Number(e.strip)||0,this.processUmask=this.chmod?typeof e.processUmask=="number"?e.processUmask:W8m():0,this.umask=typeof e.umask=="number"?e.umask:this.processUmask,this.dmode=e.dmode||511&~this.umask,this.fmode=e.fmode||438&~this.umask,this.on("entry",t=>this[wql](t))}warn(e,t,r={}){return(e==="TAR_BAD_ARCHIVE"||e==="TAR_ABORT")&&(r.recoverable=!1),super.warn(e,t,r)}[M8o](){this[Q8o]&&this[wHr]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[z8o](e,t){let r=e[t],{type:n}=e;if(!r||this.preservePaths)return!0;let[i,o]=mGo(r),s=o.replaceAll(/\\/g,"/").split("/");if(s.includes("..")||AGt&&/^[a-z]:\.\.$/i.test(s[0]??"")){if(t==="path"||n==="Link")return this.warn("TAR_ENTRY_ERROR",`${t} contains '..'`,{entry:e,[t]:r}),!1;let a=Hx.default.posix.dirname(e.path),c=Hx.default.posix.normalize(Hx.default.posix.join(a,s.join("/")));if(c.startsWith("../")||c==="..")return this.warn("TAR_ENTRY_ERROR",`${t} escapes extraction directory`,{entry:e,[t]:r}),!1}return i&&(e[t]=String(o),this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute ${t}`,{entry:e,[t]:r})),!0}[Dql](e){let t=lf(e.path),r=t.split("/");if(this.strip){if(r.length<this.strip)return!1;if(e.type==="Link"){let n=lf(String(e.linkpath)).split("/");if(n.length>=this.strip)e.linkpath=n.slice(this.strip).join("/");else return!1}r.splice(0,this.strip),e.path=r.join("/")}if(isFinite(this.maxDepth)&&r.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:e,path:t,depth:r.length,maxDepth:this.maxDepth}),!1;if(!this[z8o](e,"path")||!this[z8o](e,"linkpath"))return!1;if(e.absolute=Hx.default.isAbsolute(e.path)?lf(Hx.default.resolve(e.path)):lf(Hx.default.resolve(this.cwd,e.path)),!this.preservePaths&&typeof e.absolute=="string"&&e.absolute.indexOf(this.cwd+"/")!==0&&e.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:e,path:lf(e.path),resolvedPath:e.absolute,cwd:this.cwd}),!1;if(e.absolute===this.cwd&&e.type!=="Directory"&&e.type!=="GNUDumpDir")return!1;if(this.win32){let{root:n}=Hx.default.win32.parse(String(e.absolute));e.absolute=n+mql(String(e.absolute).slice(n.length));let{root:i}=Hx.default.win32.parse(e.path);e.path=i+mql(e.path.slice(i.length))}return!0}[wql](e){if(!this[Dql](e))return e.resume();switch(rWl.default.equal(typeof e.absolute,"string"),e.type){case"Directory":case"GNUDumpDir":e.mode&&(e.mode=e.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[nGo](e);default:return this[Bql](e)}}[FT](e,t){e.name==="CwdError"?this.emit("error",e):(this.warn("TAR_ENTRY_ERROR",e,{entry:t}),this[Ict](),t.resume())}[TSe](e,t,r){Q8m(lf(e),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:t},r)}[dGt](e){return this.forceChown||this.preserveOwner&&(typeof e.uid=="number"&&e.uid!==this.processUid||typeof e.gid=="number"&&e.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[mGt](e){return kql(this.uid,e.uid,this.processUid)}[hGt](e){return kql(this.gid,e.gid,this.processGid)}[oGo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.fmode,n=new VHr(String(e.absolute),{flags:cWl(e.size),mode:r,autoClose:!1});n.on("error",a=>{n.fd&&Ed.default.close(n.fd,()=>{}),n.write=()=>!0,this[FT](a,e),t()});let i=1,o=a=>{if(a){n.fd&&Ed.default.close(n.fd,()=>{}),this[FT](a,e),t();return}--i===0&&n.fd!==void 0&&Ed.default.close(n.fd,c=>{c?this[FT](c,e):this[Ict](),t()})};n.on("finish",()=>{let a=String(e.absolute),c=n.fd;if(typeof c=="number"&&e.mtime&&!this.noMtime){i++;let l=e.atime||new Date,u=e.mtime;Ed.default.futimes(c,l,u,p=>p?Ed.default.utimes(a,l,u,d=>o(d&&p)):o())}if(typeof c=="number"&&this[dGt](e)){i++;let l=this[mGt](e),u=this[hGt](e);typeof l=="number"&&typeof u=="number"&&Ed.default.fchown(c,l,u,p=>p?Ed.default.chown(a,l,u,d=>o(d&&p)):o())}o()});let s=this.transform&&this.transform(e)||e;s!==e&&(s.on("error",a=>{this[FT](a,e),t()}),e.pipe(s)),s.pipe(n)}[sGo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.dmode;this[TSe](String(e.absolute),r,n=>{if(n){this[FT](n,e),t();return}let i=1,o=()=>{--i===0&&(t(),this[Ict](),e.resume())};e.mtime&&!this.noMtime&&(i++,Ed.default.utimes(String(e.absolute),e.atime||new Date,e.mtime,o)),this[dGt](e)&&(i++,Ed.default.chown(String(e.absolute),Number(this[mGt](e)),Number(this[hGt](e)),o)),o()})}[Bql](e){e.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${e.type}`,{entry:e}),e.resume()}[Oql](e,t){let r=lf(Hx.default.relative(this.cwd,Hx.default.resolve(Hx.default.dirname(String(e.absolute)),String(e.linkpath)))).split("/");this[uGt](e,this.cwd,r,()=>this[zHr](e,String(e.linkpath),"symlink",t),n=>{this[FT](n,e),t()})}[Pql](e,t){let r=lf(Hx.default.resolve(this.cwd,String(e.linkpath))),n=lf(String(e.linkpath)).split("/");this[uGt](e,this.cwd,n,()=>this[zHr](e,r,"link",t),i=>{this[FT](i,e),t()})}[uGt](e,t,r,n,i){let o=r.shift();if(this.preservePaths||o===void 0)return n();let s=Hx.default.resolve(t,o);Ed.default.lstat(s,(a,c)=>{if(a)return n();if(c?.isSymbolicLink())return i(new XHr(s,Hx.default.resolve(s,r.join("/"))));this[uGt](e,s,r,n,i)})}[Rql](){this[wHr]++}[Ict](){this[wHr]--,this[M8o]()}[aGo](e){this[Ict](),e.resume()}[iGo](e,t){return e.type==="File"&&!this.unlink&&t.isFile()&&t.nlink<=1&&!AGt}[nGo](e){this[Rql]();let t=[e.path];e.linkpath&&t.push(e.linkpath),this.reservations.reserve(t,r=>this[Tql](e,r))}[Tql](e,t){let r=s=>{t(s)},n=()=>{this[TSe](this.cwd,this.dmode,s=>{if(s){this[FT](s,e),r();return}this[gGt]=!0,i()})},i=()=>{if(e.absolute!==this.cwd){let s=lf(Hx.default.dirname(String(e.absolute)));if(s!==this.cwd)return this[TSe](s,this.dmode,a=>{if(a){this[FT](a,e),r();return}o()})}o()},o=()=>{Ed.default.lstat(String(e.absolute),(s,a)=>{if(a&&(this.keep||this.newer&&a.mtime>(e.mtime??a.mtime))){this[aGo](e),r();return}if(s||this[iGo](e,a))return this[f8](null,e,r);if(a.isDirectory()){if(e.type==="Directory"){let c=this.chmod&&e.mode&&(a.mode&4095)!==e.mode,l=u=>this[f8](u??null,e,r);return c?Ed.default.chmod(String(e.absolute),Number(e.mode),l):l()}if(e.absolute!==this.cwd)return Ed.default.rmdir(String(e.absolute),c=>this[f8](c??null,e,r))}if(e.absolute===this.cwd)return this[f8](null,e,r);J8m(String(e.absolute),c=>this[f8](c??null,e,r))})};this[gGt]?i():n()}[f8](e,t,r){if(e){this[FT](e,t),r();return}switch(t.type){case"File":case"OldFile":case"ContiguousFile":return this[oGo](t,r);case"Link":return this[Pql](t,r);case"SymbolicLink":return this[Oql](t,r);case"Directory":case"GNUDumpDir":return this[sGo](t,r)}}[zHr](e,t,r,n){Ed.default[r](t,String(e.absolute),i=>{i?this[FT](i,e):(this[Ict](),e.resume()),n()})}},cGt=e=>{try{return[null,e()]}catch(t){return[t,null]}},mWl=class extends vGo{sync=!0;[f8](e,t){return super[f8](e,t,()=>{})}[nGo](e){if(!this[gGt]){let i=this[TSe](this.cwd,this.dmode);if(i)return this[FT](i,e);this[gGt]=!0}if(e.absolute!==this.cwd){let i=lf(Hx.default.dirname(String(e.absolute)));if(i!==this.cwd){let o=this[TSe](i,this.dmode);if(o)return this[FT](o,e)}}let[t,r]=cGt(()=>Ed.default.lstatSync(String(e.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(e.mtime??r.mtime)))return this[aGo](e);if(t||this[iGo](e,r))return this[f8](null,e);if(r.isDirectory()){if(e.type==="Directory"){let o=this.chmod&&e.mode&&(r.mode&4095)!==e.mode,[s]=o?cGt(()=>{Ed.default.chmodSync(String(e.absolute),Number(e.mode))}):[];return this[f8](s,e)}let[i]=cGt(()=>Ed.default.rmdirSync(String(e.absolute)));this[f8](i,e)}let[n]=e.absolute===this.cwd?[]:cGt(()=>Y8m(String(e.absolute)));this[f8](n,e)}[oGo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.fmode,n=s=>{let a;try{Ed.default.closeSync(i)}catch(c){a=c}(s||a)&&this[FT](s||a,e),t()},i;try{i=Ed.default.openSync(String(e.absolute),cWl(e.size),r)}catch(s){return n(s)}let o=this.transform&&this.transform(e)||e;o!==e&&(o.on("error",s=>this[FT](s,e)),e.pipe(o)),o.on("data",s=>{try{Ed.default.writeSync(i,s,0,s.length)}catch(a){n(a)}}),o.on("end",()=>{let s=null;if(e.mtime&&!this.noMtime){let a=e.atime||new Date,c=e.mtime;try{Ed.default.futimesSync(i,a,c)}catch(l){try{Ed.default.utimesSync(String(e.absolute),a,c)}catch{s=l}}}if(this[dGt](e)){let a=this[mGt](e),c=this[hGt](e);try{Ed.default.fchownSync(i,Number(a),Number(c))}catch(l){try{Ed.default.chownSync(String(e.absolute),Number(a),Number(c))}catch{s=s||l}}}n(s)})}[sGo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.dmode,n=this[TSe](String(e.absolute),r);if(n){this[FT](n,e),t();return}if(e.mtime&&!this.noMtime)try{Ed.default.utimesSync(String(e.absolute),e.atime||new Date,e.mtime)}catch{}if(this[dGt](e))try{Ed.default.chownSync(String(e.absolute),Number(this[mGt](e)),Number(this[hGt](e)))}catch{}t(),e.resume()}[TSe](e,t){try{return L8m(lf(e),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:t})}catch(r){return r}}[uGt](e,t,r,n,i){if(this.preservePaths||r.length===0)return n();let o=t;for(let s of r){o=Hx.default.resolve(o,s);let[a,c]=cGt(()=>Ed.default.lstatSync(o));if(a)return n();if(c.isSymbolicLink())return i(new XHr(o,Hx.default.resolve(t,r.join("/"))))}n()}[zHr](e,t,r,n){let i=`${r}Sync`;try{Ed.default[i](t,String(e.absolute)),n(),e.resume()}catch(o){return this[FT](o,e)}}},X8m=e=>{let t=new mWl(e),r=e.file,n=yGo.default.statSync(r),i=e.maxReadSize||16*1024*1024;new x5m(r,{readSize:i,size:n.size}).pipe(t)},Z8m=(e,t)=>{let r=new vGo(e),n=e.maxReadSize||16*1024*1024,i=e.file;return new Promise((o,s)=>{r.on("error",s),r.on("close",o),yGo.default.stat(i,(a,c)=>{if(a)s(a);else{let l=new lGo(i,{readSize:n,size:c.size});l.on("error",s),l.pipe(r)}})})},hWl=IGt(X8m,Z8m,e=>new mWl(e),e=>new vGo(e),(e,t)=>{t?.length&&Kql(e,t)}),$8m=(e,t)=>{let r=new AGo(e),n=!0,i,o;try{try{i=UQ.default.openSync(e.file,"r+")}catch(c){if(c?.code==="ENOENT")i=UQ.default.openSync(e.file,"w+");else throw c}let s=UQ.default.fstatSync(i),a=Buffer.alloc(512);e:for(o=0;o<s.size;o+=512){for(let u=0,p=0;u<512;u+=p){if(p=UQ.default.readSync(i,a,u,a.length-u,o+u),o===0&&a[0]===31&&a[1]===139)throw new Error("cannot append to compressed archives");if(!p)break e}let c=new bUe(a);if(!c.cksumValid)break;let l=512*Math.ceil((c.size||0)/512);if(o+l+512>s.size)break;o+=l,e.mtimeCache&&c.mtime&&e.mtimeCache.set(String(c.path),c.mtime)}n=!1,eGm(e,r,o,i,t)}finally{if(n)try{UQ.default.closeSync(i)}catch{}}},eGm=(e,t,r,n,i)=>{let o=new zql(e.file,{fd:n,start:r});t.pipe(o),rGm(t,i)},tGm=(e,t)=>{t=Array.from(t);let r=new JHr(e),n=(i,o,s)=>{let a=(d,f)=>{d?UQ.default.close(i,m=>s(d)):s(null,f)},c=0;if(o===0)return a(null,0);let l=0,u=Buffer.alloc(512),p=(d,f)=>{if(d||f===void 0)return a(d);if(l+=f,l<512&&f)return UQ.default.read(i,u,l,u.length-l,c+l,p);if(c===0&&u[0]===31&&u[1]===139)return a(new Error("cannot append to compressed archives"));if(l<512)return a(null,c);let m=new bUe(u);if(!m.cksumValid)return a(null,c);let g=512*Math.ceil((m.size??0)/512);if(c+g+512>o||(c+=g+512,c>=o))return a(null,c);e.mtimeCache&&m.mtime&&e.mtimeCache.set(String(m.path),m.mtime),l=0,UQ.default.read(i,u,0,512,c,p)};UQ.default.read(i,u,0,512,c,p)};return new Promise((i,o)=>{r.on("error",o);let s="r+",a=(c,l)=>{if(c&&c.code==="ENOENT"&&s==="r+")return s="w+",UQ.default.open(e.file,s,a);if(c||!l)return o(c);UQ.default.fstat(l,(u,p)=>{if(u)return UQ.default.close(l,()=>o(u));n(l,p.size,(d,f)=>{if(d)return o(d);let m=new VHr(e.file,{fd:l,start:f});r.pipe(m),m.on("error",o),m.on("close",i),nGm(r,t)})})};UQ.default.open(e.file,s,a)})},rGm=(e,t)=>{t.forEach(r=>{r.charAt(0)==="@"?HHr({file:CGo.default.resolve(e.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r)}),e.end()},nGm=async(e,t)=>{for(let r of t)r.charAt(0)==="@"?await HHr({file:CGo.default.resolve(String(e.cwd),r.slice(1)),noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r);e.end()},lGt=IGt($8m,tGm,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(e,t)=>{if(!B5m(e))throw new TypeError("file is required");if(e.gzip||e.brotli||e.zstd||e.file.endsWith(".br")||e.file.endsWith(".tbr"))throw new TypeError("cannot append to compressed archives");if(!t?.length)throw new TypeError("no paths specified to add/replace")}),czv=IGt(lGt.syncFile,lGt.asyncFile,lGt.syncNoFile,lGt.asyncNoFile,(e,t=[])=>{lGt.validate?.(e,t),iGm(e)}),iGm=e=>{let t=e.filter;e.mtimeCache||(e.mtimeCache=new Map),e.filter=t?(r,n)=>t(r,n)&&!((e.mtimeCache?.get(r)??n.mtime??0)>(n.mtime??0)):(r,n)=>!((e.mtimeCache?.get(r)??n.mtime??0)>(n.mtime??0))}});var Ki,$Hr=h(()=>{"use strict";zn();Ki=class e{breadcrumbs=[];context;static STRING=$t.TypeReference.primitive({v1:"STRING",v2:$t.PrimitiveTypeV2.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=$t.TypeReference.container($t.ContainerType.optional(e.STRING));constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r}}});var xGo,gWl,AWl=h(()=>{"use strict";xGo=class{_map;_path;_lastScalar;_fragments;_count;constructor(){this._map={},this._path=[],this._lastScalar="",this._fragments=[],this._count=0}get map(){return this._map}resolveNode(t,r){if(t.path==="."&&(r="."),!this._map[r]){let{line:n,position:i,lineStart:o}=t;this._map[r]={line:n,position:i,lineStart:o}}t.children&&t.children.length>0&&t.children.forEach(n=>{this.resolveNode(n,(r==="."?"":r)+"."+n.path)})}iterFragments(t,r){for(let n=this._fragments.length-1;n>=0;n--){if(!this._fragments[n].path.startsWith(t)||this._fragments[n].path===t)continue;let i=this._fragments.pop();r(i)}}handleState(t,r){if(t==="close"){let n=r.result,i=r.kind,o=this._path.join(".");if(i==="scalar"){this._path.pop(),this._lastScalar=`${n}`;let{line:s,position:a,lineStart:c}=r;this._path.length===0?this._map["."+n]={line:s,position:a,lineStart:c}:this._fragments.push({path:this._path.join(".")+"."+n,line:s,position:a,lineStart:c})}else if(i==="mapping"){let s={path:o,children:[],line:0,position:0,lineStart:0},a=0;this.iterFragments(o,c=>{a++,!((!c.children||c.children.length===0)&&a%2===1)&&(this._path.length===1?this.resolveNode(c,c.path):(s.children.push({...c,path:c.path.slice(o.length+1)}),s.line=c.line,s.position=c.position,s.lineStart=c.lineStart))}),s.children&&s.children.length>0&&this._fragments.push(s),this._path.pop()}else if(i==="sequence"){let s={path:o,children:[],line:0,position:0,lineStart:0},a=new Set,c=n.length;this.iterFragments(o,l=>{a.has(l.position)||(c--,a.add(l.position),this._path.length===1?this.resolveNode(l,`${o}.${c}`):(s.children.push({...l,path:c.toString()}),s.line=l.line,s.position=l.position,s.lineStart=l.lineStart))}),s.children&&s.children.length>0&&this._fragments.push(s),this._path.pop()}else this._path.pop()}if(t==="open"){if(this._count===0){let{line:n,position:i,lineStart:o}=r;this._map["."]={line:n,position:i,lineStart:o}}this._path.push(this._lastScalar),this._count++}}listen(){return this.handleState.bind(this)}lookup(t){let r=t instanceof Array?t.map(i=>`${i}`).join("."):`${t}`;r.startsWith(".")||(r="."+r),r.startsWith("..")&&(r=r.slice(1)),r=r.replace(/\[/g,".").replace(/\]/g,"");let n=this._map[r];if(n)return{line:n.line+1,column:n.position-n.lineStart+1,position:n.position}}},gWl=xGo});var yWl,HE,Ire,SGo,CGt=h(()=>{"use strict";tr();Ey();yWl=require("fs/promises");Ko();AWl();(function(e){e.WARNING="warning",e.ERROR="error"})(HE||(HE={}));Ire=class{errors=[];logger;breadcrumbToLineNumberMapper;relativeFilepathToSpec;constructor({logger:t,relativeFilepathToSpec:r}){this.logger=t,this.relativeFilepathToSpec=r,r&&(this.breadcrumbToLineNumberMapper=new SGo({logger:t,relativePathToFile:be.of(r)}))}collect(t){this.errors.push(t)}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}dedupe(){let t=[],r=new Set,n=0;for(let i of this.errors){let o=i.path?i.path.join("->"):"",s=`${i.message}|${i.level||HE.WARNING}|${o}`;r.has(s)?n++:(r.add(s),t.push(i))}return this.errors=t,n}getErrorStats(){this.dedupe();let t=0,r=0;for(let n of this.errors)n.level===HE.ERROR?t++:(n.level===HE.WARNING||n.level===void 0)&&r++;return{numErrors:t,numWarnings:r}}async logErrors({logWarnings:t}){this.dedupe();for(let r of this.errors){let n=r.level??HE.WARNING;if(!(n===HE.WARNING&&!t))switch(n){case HE.ERROR:if(this.logger.log(Un.Debug,r.message),r.path&&r.path.length>0){let i=await this.breadcrumbToLineNumberMapper?.getSourceLocation(r.path),o=i?`${this.relativeFilepathToSpec}:${i.line}:${i.column}`:r.path.join(" -> ");this.logger.log(Un.Debug,` - at location (${o})`)}break;case HE.WARNING:if(this.logger.log(Un.Warn,r.message),r.path&&r.path.length>0){let i=await this.breadcrumbToLineNumberMapper?.getSourceLocation(r.path),o=i?`${this.relativeFilepathToSpec}:${i.line}:${i.column}`:r.path.join(" -> ");this.logger.log(Un.Warn,` - at location (${o})`)}r.resolution&&this.logger.log(Un.Warn,` - resolution: ${r.resolution}`);break}}}},SGo=class{logger;relativePathToFile;map=new gWl;initialized=!1;constructor({relativePathToFile:t,logger:r}){this.relativePathToFile=t,this.logger=r}async initialize(){if(!this.initialized)try{let t=await(0,yWl.readFile)(this.relativePathToFile,"utf-8");Er.load(t,{listener:this.map.listen()}),this.initialized=!0}catch(t){this.logger.log(Un.Warn,`Failed to initialize line number mapping for ${this.relativePathToFile}: ${JSON.stringify(t)}`)}}async getSourceLocation(t){return this.initialized||await this.initialize(),this.map.lookup(t)}}});function sGm(e){return"deprecated"in e&&e.deprecated===!0}async function aGm(e){let t=await fetch(e);if(t.ok)try{let r=await t.text();try{return JSON.parse(r)}catch{return Er.load(r)}}catch{return}}var Yb,bWl=h(()=>{"use strict";QK();mt();zn();Ko();xo();CGt();Uo();Yb=class e{args;spec;settings;errorCollector;logger;generationLanguage;smartCasing;casingsGenerator;namespace;exampleGenerationArgs;authOverrides;environmentOverrides;globalHeaderOverrides;enableUniqueErrorsPerEndpoint;generateV1Examples;documentBaseDir;externalDocuments=new Map;discriminatedVariantsInProgress=new Set;constructor(t){this.args=t,this.spec=t.spec,this.settings=t.settings,this.errorCollector=t.errorCollector,this.logger=t.logger,this.generationLanguage=t.generationLanguage,this.smartCasing=t.smartCasing,this.namespace=t.namespace,this.casingsGenerator=Tw({generationLanguage:t.generationLanguage,keywords:void 0,smartCasing:t.smartCasing}),this.exampleGenerationArgs=t.exampleGenerationArgs,this.authOverrides=t.authOverrides,this.environmentOverrides=t.environmentOverrides,this.globalHeaderOverrides=t.globalHeaderOverrides,this.enableUniqueErrorsPerEndpoint=t.enableUniqueErrorsPerEndpoint,this.generateV1Examples=t.generateV1Examples,this.documentBaseDir=t.documentBaseDir}static BREADCRUMBS_TO_IGNORE=["properties","allOf","anyOf"];convertBreadcrumbsToName(t){let r=e.getPropertyNameIndices(t),n=t.filter((o,s)=>r.has(s)?!0:!(/^\d+$/.test(o)||e.BREADCRUMBS_TO_IGNORE.includes(o)||s===0&&o==="components"||s===1&&o==="schemas"||t[0]==="paths"&&(s===0||s===1&&["get","post","put","delete","patch"].includes(o)||s===2&&t[1]!=null&&["get","post","put","delete","patch"].includes(t[1])&&o==="parameters"))),i=ao(n.join("_"));return G6(i)}static getPropertyNameIndices(t){let r=new Set;for(let[n,i]of t.entries())i==="properties"&&!r.has(n)&&n+1<t.length&&r.add(n+1);return r}createFernFilepath(t={}){let r=this.namespace!=null?[this.casingsGenerator.generateName(this.namespace)]:[],n=t.name!=null?this.casingsGenerator.generateName(t.name):void 0;return{allParts:n?[...r,n]:r,packagePath:r,file:n}}resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:n}){let i=this.spec,o=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(s=>s.replace(/~1/g,"/"));for(let s of o){if(typeof i!="object"||i==null)return n||this.errorCollector.collect({level:HE.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1};i=i[s]}return i==null?(n||this.errorCollector.collect({level:HE.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1}):{resolved:!0,value:i}}getErrorMessageForMissingRef({reference:t}){let r=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/");return r.length>=3&&r[0]==="components"&&r[1]==="schemas"?`Schema ${r[2]} does not exist`:`${t.$ref} does not exist`}async resolveMaybeExternalReference(t){let r=this.spec,n,i=!1,o=null,s;if(this.isExternalReference(t.$ref)){i=!0;let l=t.$ref.split("#"),u=l[0];if(n=l[1],!u)return{resolved:!1};if(s=u,o=await this.loadExternalDocument(u),r=o,r==null)return{resolved:!1};if(!n)return{resolved:!0,value:r}}let a=n??t.$ref;if(a==null||typeof a!="string")return{resolved:!1};let c=a.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(l=>l.replace(/~1/g,"/"));for(let l of c){if(typeof r!="object"||r==null)return{resolved:!1};r=r[l]}if(r==null)return{resolved:!1};if(i&&typeof r=="object"&&r!==null){let l=new Set;l.add(t.$ref),r=await this.resolveNestedExternalReferences(r,o,l,s)}return{resolved:!0,value:r}}async loadExternalDocument(t){let r=this.externalDocuments.get(t);r==null&&(r=aGm(t),this.externalDocuments.set(t,r));try{let n=await r;return n==null&&this.forgetExternalDocument(t,r),structuredClone(n)}catch(n){throw this.forgetExternalDocument(t,r),n}}forgetExternalDocument(t,r){this.externalDocuments.get(t)===r&&this.externalDocuments.delete(t)}async resolveNestedExternalReferences(t,r,n,i){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){let s=[];for(let a of t)s.push(await this.resolveNestedExternalReferences(a,r,n,i));return s}if(this.isReferenceObject(t)){let s=t.$ref;if(this.isExternalReference(s)){if(n.has(s))return t;n.add(s);let a=await this.resolveMaybeExternalReference({$ref:s});if(n.delete(s),a.resolved)return a.value}else{let a=`${i}${s}`;if(n.has(a))return t;n.add(a);let c=r,l=s.substring(2).split("/").map(D0);for(let u of l){if(typeof c!="object"||c===null)return t;c=c[u]}if(c!=null){let u=await this.resolveNestedExternalReferences(c,r,n,i);return n.delete(s),u}n.delete(s)}return t}let o={};for(let[s,a]of Object.entries(t))typeof a=="object"&&a!==null?o[s]=await this.resolveNestedExternalReferences(a,r,n,i):o[s]=a;return o}getExamplesFromSchema({schema:t,breadcrumbs:r}){if(t==null)return[];let n=t.example!=null?[t.example]:[];return t.examples!=null&&(Array.isArray(t.examples)?n.push(...t.examples):this.errorCollector.collect({message:"Received non-array schema examples",path:r})),n}getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:r,defaultExampleName:n}){if(t==null)return[];let i=[];if(t.example!=null){let o=this.generateUniqueName({prefix:n??`${r.join("_")}_example`,existingNames:[]});i.push([o,{value:t.example}])}return t.examples!=null&&i.push(...Object.entries(t.examples)),i}resolveMaybeReference({schemaOrReference:t,breadcrumbs:r,skipErrorCollector:n}){if(this.isReferenceObject(t)){let i=this.resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:n});return i.resolved?i.value:void 0}return t}resolveExampleRecursively({example:t,breadcrumbs:r,maxDepth:n=10}){let i=t,o=0;for(;this.isReferenceObject(i);){if(o>=n){this.errorCollector.collect({message:`Maximum reference depth (${n}) exceeded while resolving example reference`,path:r});return}let s=this.resolveReference({reference:i,breadcrumbs:r,skipErrorCollector:!0});if(!s.resolved)return;i=s.value,o++}return i}resolveExample(t){if(!this.isReferenceObject(t))return t;let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}resolveExampleWithValue(t){if(!this.isReferenceObject(t))return this.returnExampleValue(t);let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}returnExampleValue(t){return this.isExampleWithValue(t)?t.value:t}getPropertyAccess(t){let r=t;for(;this.isReferenceObject(r);){let o=this.resolveReference({reference:r});if(!o.resolved)return;r=o.value}let{readOnly:n,writeOnly:i}=this.getReadOnlyWriteOnlyFromSchema(r);if(!(n&&i)){if(n)return $t.ObjectPropertyAccess.ReadOnly;if(i)return $t.ObjectPropertyAccess.WriteOnly}}getReadOnlyWriteOnlyFromSchema(t){if(t.allOf&&t.allOf.length>0){let r=!0,n=!0;for(let i of t.allOf){let o=i;if(this.isReferenceObject(i)){let a=this.resolveReference({reference:i});if(!a.resolved)continue;o=a.value}let s=this.getReadOnlyWriteOnlyFromSchema(o);r=r&&s.readOnly,n=n&&s.writeOnly}return{readOnly:r,writeOnly:n}}else return{readOnly:!!t.readOnly,writeOnly:!!t.writeOnly}}getAudiences({operation:t,breadcrumbs:r}){let i=new vC.AudienceExtension({operation:t,breadcrumbs:r,context:this}).convert();if(i!=null)return i.audiences}getAvailability({node:t,breadcrumbs:r}){let n=new Set;for(;this.isReferenceObject(t);){let i=this.getDeclaredAvailability({node:t,breadcrumbs:r});if(i!=null)return i;if(n.has(t.$ref))return;n.add(t.$ref);let o=this.resolveReference({reference:t});if(!o.resolved)return;t=o.value}return this.getDeclaredAvailability({node:t,breadcrumbs:r})}getDeclaredAvailability({node:t,breadcrumbs:r}){let i=new vC.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(i!=null)return{status:i,message:void 0};if(sGm(t))return{status:eh.Deprecated,message:void 0}}getNamespacedSchemaId(t){if(this.namespace==null)return t;let r=`${this.namespace}:`;return t.startsWith(r)?t:`${r}${t}`}getRawSchemaId(t){if(this.namespace==null)return t;let r=`${this.namespace}:`;return t.startsWith(r)?t.slice(r.length):t}getTypeIdFromSchemaReference(t){let r=t.$ref.match(/\/schemas\/(.+)$/);if(!(!r||!r[1]))return this.getNamespacedSchemaId(r[1])}getRawSchemaNameFromReference(t){let r=t.$ref.match(/\/schemas\/([^/]+)/);if(!(!r||!r[1]))return r[1]}createNamedTypeReference(t,r){return Hr.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(t),typeId:this.getNamespacedSchemaId(t),displayName:r,default:void 0,inline:!1})}typeReferenceToDeclaredTypeName(t){if(t.type==="named")return{typeId:t.typeId,fernFilepath:{allParts:[],packagePath:[],file:void 0},name:t.name,displayName:t.displayName}}removeSchemaFromInlinedTypes({id:t,inlinedTypes:r}){let n=this.getNamespacedSchemaId(t);return Object.fromEntries(Object.entries(r).filter(([i])=>i!==n))}static maybeTrimPrefix(t,r){return t.startsWith(r)?t.slice(r.length):t}generateUniqueName({prefix:t,existingNames:r}){if(!r.includes(t))return t;let n=0;for(;r.includes(`${t}_${n}`);)n++;return`${t}_${n}`}isReferenceObject(t){return typeof t=="object"&&t!==null&&"$ref"in t}isExternalReference(t){return typeof t=="string"&&Yh(t)}isReferenceObjectWithIdentifier(t){return this.isReferenceObject(t)&&("title"in t||"name"in t||"messageId"in t||"summary"in t)}isExampleWithSummary(t){return typeof t=="object"&&t!=null&&"summary"in t&&typeof t.summary=="string"&&t.summary.length>0}isExampleWithValue(t){return typeof t=="object"&&t!=null&&"value"in t}isOptional(t){return t.type==="container"&&t.container.type==="optional"}isNullable(t){return t.type==="container"&&t.container.type==="nullable"}isList(t){return t.type==="container"&&t.container.type==="list"}isFile(t){return t.type==="primitive"&&t.primitive.v2?.type==="string"&&t.primitive.v2.validation?.format==="binary"}getAsString(t){if(typeof t=="string")return t}getAsInteger(t){if(typeof t=="number"&&Number.isInteger(t))return t}getAsNumber(t){if(typeof t=="number")return t}getAsBoolean(t){if(typeof t=="boolean")return t}getAsArray(t){if(Array.isArray(t))return t}getAsObject(t){if(gr(t))return t}getGroup({groupParts:t,namespace:r}){let n=[];return r!=null&&n.push(r),n.push(...t??[]),n}isObjectSchemaType(t){return t.type==="object"||t.properties!=null}}});var Vo,AR=h(()=>{"use strict";Vo=class{breadcrumbs;context;constructor(t){this.breadcrumbs=t.breadcrumbs,this.context=t.context}getExtensionValue(t,r){if(typeof t!="object"||t==null)return;let n=t[this.key];if(n!=null)return n;if(r!=null)return t[r]}}});var Pct,wGo=h(()=>{"use strict";AR();Pct=class extends Vo{operation;key="x-fern-audiences";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(n=>typeof n=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{audiences:r}}}});var eKr,EWl=h(()=>{"use strict";zn();AR();eKr=class extends Vo{node;key="x-fern-availability";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t==null||typeof t!="string")return;switch(t.toUpperCase().replace(/[-_\s]/g,"_")){case"IN_DEVELOPMENT":return eh.InDevelopment;case"PRE_RELEASE":return eh.PreRelease;case"GENERAL_AVAILABILITY":case"GENERALLY_AVAILABLE":case"GA":case"STABLE":return eh.GeneralAvailability;case"DEPRECATED":return eh.Deprecated;case"ALPHA":return eh.Alpha;case"BETA":return eh.Beta;case"PREVIEW":return eh.Preview;case"LEGACY":return eh.Legacy;default:return}}}});var Bct,TGo=h(()=>{"use strict";AR();Bct=class extends Vo{node;key="x-fern-discriminated";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t!=null&&typeof t=="boolean")return t}}});var Dct,OGo=h(()=>{"use strict";AR();Dct=class extends Vo{node;key="x-fern-discriminator-context";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t==="data"||t==="protocol")return t}}});var cGm,lGm,IWl,vWl=h(()=>{"use strict";nn();cGm=Xt.object({snake:Xt.string().optional(),camel:Xt.string().optional(),screamingSnake:Xt.string().optional(),pascal:Xt.string().optional()}),lGm=Xt.object({description:Xt.string().optional(),name:Xt.string().optional(),casing:cGm.optional()}),IWl=Xt.record(lGm)});var Rct,PGo=h(()=>{"use strict";AR();vWl();Rct=class extends Vo{schema;key="x-fern-enum";constructor({breadcrumbs:t,schema:r,context:n}){super({breadcrumbs:t,context:n}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t==null)return;let r=IWl.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-enum extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data}}});var IUe,CWl=h(()=>{"use strict";AR();IUe=class extends Vo{operation;key="x-fern-ignore";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-ignore",path:this.breadcrumbs});return}return t}}}});var tKr,xWl=h(()=>{"use strict";AR();tKr=class extends Vo{parameter;key="x-fern-optional";constructor({breadcrumbs:t,parameter:r,context:n}){super({breadcrumbs:t,context:n}),this.parameter=r}convert(){let t=this.getExtensionValue(this.parameter);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-optional",path:this.breadcrumbs});return}return t}}}});var rKr,SWl=h(()=>{"use strict";AR();rKr=class extends Vo{operation;key="x-fern-sdk-group-name";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(n=>typeof n=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{groups:r}}}});var nKr,wWl=h(()=>{"use strict";AR();nKr=class extends Vo{operation;key="x-fern-sdk-method-name";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null&&typeof t=="string")return{methodName:t}}}});var iKr,TWl=h(()=>{"use strict";AR();iKr=class extends Vo{operation;key="x-fern-server-name";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation,"x-name");if(!(t==null||typeof t!="string"))return t}}});var oKr,OWl=h(()=>{"use strict";AR();oKr=class extends Vo{schema;key="x-fern-type";constructor({breadcrumbs:t,schema:r,context:n}){super({breadcrumbs:t,context:n}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t!=null&&typeof t=="string")return t}}});var sKr,PWl=h(()=>{"use strict";AR();sKr=class extends Vo{schema;key="x-fern-type-name";constructor({breadcrumbs:t,schema:r,context:n}){super({breadcrumbs:t,context:n}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(typeof t=="string")return t}}});function uGm({isText:e,isAttribute:t}){return e?rQ.Text:t?rQ.Attribute:rQ.Element}function RWl(e){return typeof e=="object"&&e!=null}function aKr(e,t){if(!(typeof e!="object"||e==null))return e[t]}function BGo(...e){return e.find(t=>t!=null)}var BWl,DWl,kct,Fct,cKr=h(()=>{"use strict";zn();AR();BWl="x-fern-xml-text",DWl="x-fern-xml-list-separator",kct=class extends Vo{schema;fallbackName;key="xml";constructor({breadcrumbs:t,schema:r,fallbackName:n,context:i}){super({breadcrumbs:t,context:i}),this.schema=r,this.fallbackName=n}convert(){let t=this.getExtensionValue(this.schema);if(RWl(t))return{name:typeof t.name=="string"?t.name:this.fallbackName,namespace:typeof t.namespace=="string"?t.namespace:void 0,prefix:typeof t.prefix=="string"?t.prefix:void 0}}},Fct=class extends Vo{propertySchema;resolvedPropertySchema;key="xml";constructor({breadcrumbs:t,propertySchema:r,resolvedPropertySchema:n,context:i}){super({breadcrumbs:t,context:i}),this.propertySchema=r,this.resolvedPropertySchema=n}convert(){let t=this.propertySchema,r=this.resolvedPropertySchema,n=BGo(this.getExtensionValue(t),this.getExtensionValue(r)),i=BGo(aKr(t,BWl),aKr(r,BWl)),o=BGo(aKr(t,DWl),aKr(r,DWl)),s=RWl(n)?n:{};return{kind:uGm({isText:i===!0,isAttribute:s.attribute===!0}),name:typeof s.name=="string"?s.name:void 0,wrapped:typeof s.wrapped=="boolean"?s.wrapped:void 0,listSeparator:typeof o=="string"?o:void 0}}}});var vC={};ne(vC,{AudienceExtension:()=>Pct,FernAvailabilityExtension:()=>eKr,FernDiscriminatedExtension:()=>Bct,FernDiscriminatorContextExtension:()=>Dct,FernEnumExtension:()=>Rct,FernIgnoreExtension:()=>IUe,FernOptionalExtension:()=>tKr,FernTypeExtension:()=>oKr,FernTypeNameExtension:()=>sKr,SdkGroupNameExtension:()=>rKr,SdkMethodNameExtension:()=>nKr,ServerFromOperationNameExtension:()=>iKr,XmlPropertyExtension:()=>Fct,XmlSchemaExtension:()=>kct});var DGo=h(()=>{"use strict";wGo();EWl();TGo();OGo();PGo();CWl();xWl();SWl();wWl();TWl();OWl();PWl();cKr()});function FWl(e){let t=new Map,r=(i,o)=>{if(t.has(i))return t.get(i);let s=e[i];if(s==null||o.has(i))return;o.add(i);let a=n(s,o);return o.delete(i),t.set(i,a),a},n=(i,o)=>{let s=a=>dw.named({name:i.name,shape:a});switch(i.shape.type){case"object":return s(KD.Object);case"enum":return s(KD.Enum);case"union":return s(KD.Union);case"undiscriminatedUnion":return s(KD.UndiscriminatedUnion);case"alias":{let{resolvedType:a}=i.shape,c=kWl(a);return c!=null?r(c,o):a}default:return}};for(let[i,o]of Object.entries(e)){if(o.shape.type!=="alias"||kWl(o.shape.resolvedType)==null)continue;let s=r(i,new Set);s!=null&&(e[i]={...o,shape:ic.alias({aliasOf:o.shape.aliasOf,resolvedType:s})})}}function kWl(e){if(e.type!=="named")return;let t=e;return e.shape==null&&typeof t.typeId=="string"?t.typeId:void 0}var NWl=h(()=>{"use strict";zn()});var tJ,jWl=h(()=>{"use strict";zn();sc();xo();$Hr();DGo();NWl();tJ=class extends Ki{ir;audiences;irGraph;constructor({breadcrumbs:t=[],context:r,audiences:n}){super({breadcrumbs:t,context:r}),this.audiences=n,this.irGraph=new M4e(n),this.ir={auth:{docs:void 0,requirement:$t.AuthSchemesRequirement.All,schemes:[]},selfHosted:!1,types:{},services:{},errors:{},webhookGroups:{},websocketChannels:void 0,headers:[],idempotencyHeaders:[],apiVersion:void 0,apiDisplayName:void 0,apiDocs:void 0,basePath:void 0,pathParameters:[],errorDiscriminationStrategy:$t.ErrorDiscriminationStrategy.statusCode(),variables:[],globalParameters:void 0,serviceTypeReferenceInfo:{sharedTypes:[],typesReferencedOnlyByService:{}},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0,environments:void 0,fdrApiDefinitionId:void 0,rootPackage:this.createPackage(),subpackages:{},sdkConfig:{hasFileDownloadEndpoints:!1,hasPaginatedEndpoints:!1,hasStreamingEndpoints:!1,isAuthMandatory:!0,idempotencyKeyGeneration:void 0,webhookSignatureVerification:void 0,platformHeaders:{language:"",sdkName:"",sdkVersion:"",userAgent:void 0}},audiences:void 0,generationMetadata:void 0,apiPlayground:void 0,casingsConfig:void 0,specVersion:void 0}}removeXFernIgnores({document:t,breadcrumbs:r=[]}){return Array.isArray(t)?t.filter((n,i)=>!new IUe({breadcrumbs:[...r,String(i)],operation:n,context:this.context}).convert()).map((n,i)=>this.removeXFernIgnores({document:n,breadcrumbs:[...r,String(i)]})):t!=null&&typeof t=="object"?Object.fromEntries(Object.entries(t).filter(([n,i])=>!new IUe({breadcrumbs:[...r,n],operation:i,context:this.context}).convert()).map(([n,i])=>[n,this.removeXFernIgnores({document:i,breadcrumbs:[...r,n]})])):t}finalizeIr(){let t=Object.values(this.ir.services).some(a=>a.endpoints.some(c=>c.response?.body?.type==="streaming")),r=Object.values(this.ir.services).some(a=>a.endpoints.some(c=>c.pagination!=null)),n=Object.values(this.ir.services).some(a=>a.endpoints.some(c=>c.response?.body?.type==="fileDownload"));this.ir.sdkConfig={...this.ir.sdkConfig,hasStreamingEndpoints:t,hasPaginatedEndpoints:r,hasFileDownloadEndpoints:n},$5t(this.ir,{onWarning:a=>this.context.logger.warn(a)}),FWl(this.ir.types);let i={...this.ir,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})},audiences:this.audiences.type==="select"?this.audiences.audiences:void 0};this.irGraph.hasNoAudiences()||(i=this.filterIrForAudiences(i)),K5t({ir:i});let o=this.context.exampleGenerationArgs,s=d4o({ir:i,exampleGeneration:o,logger:this.context.logger});if(this.context.generateV1Examples){let a=Y5t({ir:i,exampleGeneration:o});return{...i,...a,...s}}return{...i,...s}}filterIrForAudiences(t){return{...Z5t(t,this.irGraph.build()),sdkConfig:t.sdkConfig,subpackages:t.subpackages,rootPackage:t.rootPackage}}async resolveAllExternalRefs({spec:t}){let r=[t];for(let n=0;n<r.length;n++){let i=r[n];i!=null&&(Array.isArray(i)?await this.resolveExternalRefsInArray(i,r):typeof i=="object"&&await this.resolveExternalRefsInObject(i,r))}return t}async resolveExternalRefsInArray(t,r){for(let n=0;n<t.length;n++)t[n]=await this.resolveReferenceChain(t[n],r)}async resolveExternalRefsInObject(t,r){for(let[n,i]of Object.entries(t))t[n]=await this.resolveReferenceChain(i,r)}async resolveReferenceChain(t,r){let n=t;if(!this.context.isReferenceObject(n))return r.push(n),t;for(;this.context.isReferenceObject(n);){let i=this.context.isExternalReference(n.$ref),o=await this.context.resolveMaybeExternalReference(n);if(o.resolved){if(n=o.value,i)return n}else return t}return t}shouldAddServerToCollectedServers({server:t,currentServers:r,specType:n="openapi"}){return n==="openapi"?!r.some(i=>i.url===t.url&&"x-fern-server-name"in i&&"x-fern-server-name"in t&&i["x-fern-server-name"]===t["x-fern-server-name"]):!r.some(i=>i.url===t.url&&"name"in i&&"name"in t&&i.name===t.name)}addEndpointToIr({endpoint:t,audiences:r,endpointGroup:n,endpointGroupDisplayName:i,endpointGroupDescription:o,serviceName:s,inlinedRequestPropertiesByAudience:a,queryParametersByAudience:c}){let l=this.context.getGroup({groupParts:n,namespace:this.context.namespace}),u=this.getOrCreatePackage({group:n});u!==this.ir.rootPackage&&u.docs==null&&o!=null&&(u.docs=o);let p=[...l].map(m=>this.context.casingsGenerator.generateName(m)),d=p[p.length-1];u.service==null&&(u.service=s??`service_${l.map(m=>ao(m)).join("/")}`),this.ir.services[u.service]==null&&(this.ir.services[u.service]=this.createNewService({allParts:p,finalpart:d,endpointGroupDisplayName:i})),this.ir.services[u.service]?.endpoints.push(t);let f=this.ir.services[u.service];f!=null&&(this.irGraph.addEndpoint(f,t),this.irGraph.markEndpointForAudience(f.name,[t],r),a!=null&&Object.keys(a).length>0&&this.irGraph.markInlinedRequestPropertiesForAudiences(t.id,a),c!=null&&Object.keys(c).length>0&&this.irGraph.markQueryParametersForAudiences(t.id,c))}addWebhookToIr({webhook:t,operationId:r,audiences:n,group:i,inlinedPayloadPropertiesByAudience:o}){let s=i?.join(".")??r,a=this.getOrCreatePackage({group:i});this.ir.webhookGroups[s]==null&&(this.ir.webhookGroups[s]=[]),this.ir.webhookGroups[s].push(t),a.webhooks=s;let c=this.context.createFernFilepath();this.irGraph.addWebhook(c,t),n!=null&&this.irGraph.markWebhookForAudiences(c,t,n),t.id!=null&&o!=null&&Object.keys(o).length>0&&this.irGraph.markInlinedWebhookPayloadPropertiesForAudiences(t.id,o)}addWebsocketChannelToIr({websocketChannel:t,channelPath:r,audiences:n,websocketGroup:i}){let o=ao(i?.join(".")),s=ao(r),a=this.context.namespace?`${ao(this.context.namespace)}/`:"",c=o?`channel_${a}${o}`:`channel_${a}${s}`,l=i?this.getOrCreatePackage({group:i}):this.getOrCreatePackage({group:[s]});this.ir.websocketChannels={...this.ir.websocketChannels,[c]:t},c!==""?l.websocket==null&&(l.websocket=c):this.ir.rootPackage.websocket="";let u=this.context.createFernFilepath();this.irGraph.addChannel(u,c,t),n!=null&&this.irGraph.markChannelForAudiences(u,c,n)}addAuthToIR(t){this.ir.auth=t}addErrorsToIr(t){this.ir.errors=t;for(let r of Object.values(t))this.irGraph.addError(r)}addGlobalHeadersToIr(t){this.ir.headers=t}addEnvironmentsToIr({environmentConfig:t,audiences:r}){if(this.ir.environments=t,t==null)return;let n=t.environments.environments,i=r==null||n.every(o=>o.audiences==null);for(let o of n)this.irGraph.markEnvironmentForAudiences(o,r?.[o.id]??[],i)}addTypeToRootPackage(t){this.ir.rootPackage.types.push(t)}addSchemaOutputToIr(t,r){let{convertedSchema:n,inlinedTypes:i}=r,o=this.context.getNamespacedSchemaId(t),a=Object.keys(i).some(c=>c===o)?`${o}Wrapper`:o;this.addTypeToPackage(a),this.addTypesToIr({...i,[a]:n})}addTypeToPackage(t){let r=this.context.getGroup({groupParts:[],namespace:this.context.namespace});this.getOrCreatePackage({group:r}).types.push(t)}addTypesToIr(t){Object.assign(this.ir.types,Object.fromEntries(Object.entries(t).map(([r,n])=>[r,n.typeDeclaration])));for(let r of Object.values(t))this.irGraph.addType({declaredTypeName:r.typeDeclaration.name,descendantTypeIds:r.typeDeclaration.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:r.propertiesByAudience,descendantFilepaths:new Set}),this.irGraph.markTypeForAudiences(r.typeDeclaration.name,r.audiences)}updateEndpointsWithDefaultUrl(t){if(t!=null)for(let r of Object.values(this.ir.services))for(let n of r.endpoints)n.baseUrl==null&&(n.baseUrl=t)}createNewService({allParts:t,finalpart:r,endpointGroupDisplayName:n}){return{name:{fernFilepath:{allParts:t,packagePath:t.slice(0,-1),file:r}},displayName:n,basePath:jy(""),headers:[],pathParameters:[],availability:void 0,endpoints:[],transport:void 0,encoding:void 0,audiences:void 0}}createPackage(t={}){return{fernFilepath:this.context.createFernFilepath(t),service:void 0,types:[],errors:[],subpackages:[],docs:void 0,webhooks:void 0,websocket:void 0,hasEndpointsInTree:!1,hasWebSocketInTree:void 0,navigationConfig:void 0}}getOrCreatePackage({group:t}){let r=[];if(this.context.namespace!=null&&r.push(this.context.namespace),r.push(...(t??[]).map(i=>ao(i))),r.length==0)return this.ir.rootPackage;let n=this.ir.rootPackage;for(let i=0;i<r.length;i++){let o=r[i]??"",a=`subpackage_${r.slice(0,i+1).join("/")}`;this.ir.subpackages[a]==null&&(this.ir.subpackages[a]={name:this.context.casingsGenerator.generateName(o),displayName:void 0,...this.createPackage({name:o})});let c=this.ir.subpackages[a];n.subpackages.includes(a)||n.subpackages.push(a),n=c}return n}}});function vUe(e){return typeof e=="object"&&e!==null&&!("$ref"in e)}function dGm(e){if(!vUe(e))return!1;if("nullable"in e&&e.nullable===!0)return!0;let t=r=>Array.isArray(r)&&r.some(n=>vUe(n)&&n.type==="null");return t(e.anyOf)||t(e.oneOf)}function mGm(e){return e.type==="array"||e.properties||e.oneOf||e.anyOf||e.allOf||e.additionalProperties?!1:!!(e.type==="string"||e.type==="number"||e.type==="integer"||e.type==="boolean"||e.const!==void 0||Array.isArray(e.enum)&&e.enum.length>0)}function QWl(e){if(e.const!==void 0)return e.const;if(Array.isArray(e.enum)&&e.enum.length>0)return e.enum[0]}var pGm,zWl,fGm,Bw,BSe=h(()=>{"use strict";mt();Uo();pGm=/^literal<\s*(?:"(.*)"|(true|false))\s*>$/,zWl=new WeakMap,fGm=new Set(["type","properties","required","allOf","description","title","deprecated","readOnly","writeOnly","xml","externalDocs","discriminator"]);Bw=class e extends Ki{MAX_DEPTH=12;EXAMPLE_STRING=Mo.STRING;EXAMPLE_NUMBER=Mo.DOUBLE;EXAMPLE_BOOLEAN=Mo.BOOLEAN;EXAMPLE_INTEGER=Mo.INT;EXAMPLE_DATE=Mo.DATE;EXAMPLE_DATE_TIME=Mo.DATE_TIME;schema;example;depth;exampleGenerationStrategy;generateOptionalProperties;seenRefs;sharedState;constructor({breadcrumbs:t,context:r,schema:n,example:i,depth:o=0,exampleGenerationStrategy:s,generateOptionalProperties:a=!1,seenRefs:c=new Set}){super({breadcrumbs:t,context:r}),this.example=i,this.schema=n,this.depth=o,this.exampleGenerationStrategy=s,this.generateOptionalProperties=a,this.seenRefs=c;let l=zWl.get(r);l!=null?this.sharedState=l:(this.sharedState={mergedAllOfProperties:new WeakMap,mergeOnlyAllOfSchemas:new WeakMap},zWl.set(r,this.sharedState))}convert(){if(this.depth>this.MAX_DEPTH)return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:typeof this.example<"u"?this.example:{},errors:[]};if(this.context.isReferenceObject(this.schema)){let n=this.schema.$ref;if(this.seenRefs.has(n))return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}}let t=this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(t!=null&&this.context.isReferenceObject(t))return new e({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(t==null)return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:"Schema is not resolvable",path:this.breadcrumbs}]};if(typeof t!="object")return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Schema should be an object: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]};if("nullable"in t&&t.nullable===!0&&this.example===null)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let r=this.maybeConvertLiteralFernType(t);return r??(Array.isArray(t.type)?this.convertSchemaTypeArray({resolvedSchema:t}):t.type=="null"?this.convertNull():t.type=="boolean"?this.convertBoolean():t.enum!=null?this.convertEnum(t):t.type=="number"?this.convertNumber():t.type=="string"?this.convertString():t.type=="integer"?this.convertInteger():t.type=="array"?this.convertArray({resolvedSchema:t}):"oneOf"in t&&t.oneOf!=null?this.convertOneOf({resolvedSchema:t}):"anyOf"in t&&t.anyOf!=null?this.convertAnyOf({resolvedSchema:t}):t.type=="object"||t.properties!=null||t.allOf!=null?this.convertObject({resolvedSchema:t}):typeof t=="object"&&Object.keys(t).length===0?{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Unsupported schema type: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]})}convertNull(){let t=this.example===null;return t?{isValid:t,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Example is not null: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertBoolean(){let t=typeof this.example=="boolean";if(t)return{isValid:t,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.default:this.schema.default,n=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.const:this.schema.const;return typeof r=="boolean"||typeof n=="boolean"?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n??r,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_BOOLEAN,errors:[{message:`Example is not a boolean: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertEnum(t){let r=t.enum?.includes(this.example)??!1;if(r)return{isValid:r,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let n=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return n!==void 0&&t.enum?.includes(n)?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n,errors:[]}:{isValid:r,coerced:!1,usedProvidedExample:!1,validExample:t.enum?.[0],errors:[{message:`Example is not one of the allowed enum values: ${JSON.stringify(t.enum,null,2)}`,path:this.breadcrumbs}]}}convertNumber(){if(typeof this.example=="number")return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let t=Number(this.example);if(!isNaN(t))return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):this.schema,n=r?.default;return typeof n=="number"?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.adjustNumberToConstraints(this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_NUMBER,r),errors:[{message:`Example is not a number: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}adjustNumberToConstraints(t,r){if(r==null)return this.context.logger.debug("[ExampleConverter.adjustNumberToConstraints] Schema object is null, returning original number","number:",t.toString()),t;let{minimum:n,maximum:i,exclusiveMinimum:o,exclusiveMaximum:s}=r,a;o!=null?typeof o=="boolean"?a=n!=null?n+Math.max(Number.EPSILON,Math.abs(n)*1e-10):void 0:a=o+Math.max(Number.EPSILON,Math.abs(o)*1e-10):n!=null&&(a=n);let c;return s!=null?typeof s=="boolean"?c=i!=null?i-Math.max(Number.EPSILON,Math.abs(i)*Number.EPSILON):void 0:c=s-Math.max(Number.EPSILON,Math.abs(s)*Number.EPSILON):i!=null&&(c=i),a!==void 0&&c!==void 0?(t<a||t>c)&&(t=a+(c-a)/2):a!==void 0&&t<a?t=a+Math.abs(a*.1):c!==void 0&&t>c&&(t=c-Math.abs(c*.1)),Number(Number(t).toPrecision(3))}convertString(){if(typeof this.example=="string")return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};if(typeof this.example!="object"&&!Array.isArray(this.example)&&this.example!=null)return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:String(this.example),errors:[]};let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;if(typeof t=="string")return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):this.schema,n=r?.format==="date"?this.EXAMPLE_DATE:r?.format==="date-time"?this.EXAMPLE_DATE_TIME:this.EXAMPLE_STRING;return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??n,errors:[{message:`Example cannot be converted to string: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertInteger(){if(typeof this.example=="number"&&Number.isInteger(this.example))return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};if(typeof this.example=="string"){let r=Number(this.example);if(!isNaN(r)&&Number.isInteger(r))return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:r,errors:[]}}let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return typeof t=="number"&&Number.isInteger(t)?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:t,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_INTEGER,errors:[{message:`Example is not an integer: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertArray({resolvedSchema:t}){if(t.type!="array")return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};t.items==null&&(t.items={type:"string"});let r=this.example==null,n=this.example??t.example,o=(Array.isArray(n)?n:[n]).map(c=>new e({breadcrumbs:[...this.breadcrumbs,"items"],context:this.context,schema:t.items,example:c,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),s=o.every(c=>c?.isValid??!1)&&!r,a=!r&&o.some(c=>c.usedProvidedExample);return{isValid:s,coerced:!1,usedProvidedExample:a,validExample:o.map(c=>c.validExample),errors:s?[]:o.flatMap(c=>c.errors)}}convertObject({resolvedSchema:t}){if(t.type=="object"&&t.properties==null&&t.allOf==null)return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example??{},errors:[]};let r=typeof this.example!="object"||this.example==null?{}:this.example,n=this.example===void 0&&this.canGenerateFromMergedAllOf(t),{mergedProperties:i,mergedRequired:o}=this.mergeAllOfProperties(t,new Set,0,n),s=Object.entries(i).map(([b,I])=>{if(typeof I!="object")return{key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if(this.isDeprecatedProperty(I)&&!this.isRequiredProperty({key:b,resolvedSchema:t}))return{key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("readOnly"in I&&I.readOnly===!0&&"writeOnly"in I&&I.writeOnly===!0)return{key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("readOnly"in I&&I.readOnly===!0&&this.exampleGenerationStrategy==="request")return{key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("writeOnly"in I&&I.writeOnly===!0&&this.exampleGenerationStrategy==="response")return{key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};let C=dGm(I),x=!(b in r)||!C&&r[b]==null||C&&r[b]===void 0,S=!o.includes(b);if(x&&S){if(this.example===void 0&&this.generateOptionalProperties){let P=this.maybeResolveSchemaExample(I),D=new e({breadcrumbs:[...this.breadcrumbs,b],context:this.context,schema:I,example:P,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()});return{key:b,result:D.convert()}}return{key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}}}else{let P=r[b],D=P!==void 0?P:this.maybeResolveSchemaExample(I),O=new e({breadcrumbs:[...this.breadcrumbs,b],context:this.context,schema:I,example:D,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();return{key:b,result:O}}}),a=n?[]:(t.allOf??[]).map((b,I)=>{let C=this.context.resolveMaybeReference({schemaOrReference:b,breadcrumbs:[...this.breadcrumbs,`allOf[${I}]`],skipErrorCollector:!0});return C&&this.isConstraintOnlySchema(C)?{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}:new e({breadcrumbs:[...this.breadcrumbs,`allOf[${I}]`],context:this.context,schema:{...t,...b,allOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()}),c=this.example!==void 0&&(s.some(({result:b})=>b.usedProvidedExample)||a.some(b=>b.usedProvidedExample)),l=Object.fromEntries(s.map(({key:b,result:I})=>[b,I.validExample]).filter(([b,I])=>I!==void 0));for(let b of a)if(typeof b.validExample=="object"&&b.validExample!==null){let I=b.validExample,C=Object.fromEntries(Object.entries(I).filter(([x,S])=>S!==void 0));for(let[x,S]of Object.entries(C))(!(x in l)||l[x]==null)&&(l[x]=S)}let u=[],p=this.collectAllPropertyKeys(t),d=Object.keys(r).filter(b=>!p.has(b)),f=this.schemaHasPatternProperties(t),m=f?d:[],g=f?[]:d;if(m.forEach(b=>{u.push({key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:r[b],errors:[]}})}),g.length>0)if(t.additionalProperties===!1)g.forEach(b=>{let I=[...this.breadcrumbs,b].join("."),C={message:`Found unexpected property '${b}' in example. This property does not exist in the schema${I?` at path: ${I}`:""}`,path:[...this.breadcrumbs,b]};u.push({key:b,result:{isValid:!1,coerced:!1,usedProvidedExample:!0,validExample:void 0,errors:[C]}})});else if(t.additionalProperties===!0||t.additionalProperties===void 0)g.forEach(b=>{u.push({key:b,result:{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:r[b],errors:[]}})});else{let b=t.additionalProperties;g.forEach(I=>{let x=new e({breadcrumbs:[...this.breadcrumbs,I],context:this.context,schema:b,example:r[I],depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();u.push({key:I,result:x})})}for(let{key:b,result:I}of u)I.validExample!==void 0&&l[b]===void 0&&(l[b]=I.validExample);let A=s.every(b=>b.result.isValid)&&a.every(b=>b.isValid)&&u.every(({result:b})=>b.isValid);if(Object.keys(l).length===0){let b=a.find(I=>I.validExample!==void 0&&(typeof I.validExample!="object"||I.validExample===null));b&&(l=b.validExample)}return{isValid:A,coerced:!1,usedProvidedExample:c,validExample:l,errors:[...s.flatMap(({result:b})=>b.errors),...a.flatMap(b=>b.errors),...u.flatMap(({result:b})=>b.errors)]}}convertSchemaTypeArray({resolvedSchema:t}){if(!Array.isArray(t.type))return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};if(t.type.length===1)return new e({breadcrumbs:this.breadcrumbs,context:this.context,schema:{...t,type:t.type[0]},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();let r=t.type.map((a,c)=>new e({breadcrumbs:[...this.breadcrumbs,`type[${c}]`],context:this.context,schema:{...t,type:a},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),n=r.some(a=>a?.isValid??!1),o=r.find(a=>a.isValid)?.validExample??r[0]?.validExample??null,s=r.some(a=>a.usedProvidedExample);return{isValid:n,coerced:!1,usedProvidedExample:s,validExample:o,errors:n?[]:r.flatMap(a=>a?.errors??[])}}convertUnion({resolvedSchema:t,unionType:r}){let n=r==="oneOf"?t.oneOf:t.anyOf;if(!(r in t)||n==null)return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};let i=this.example!==void 0?this.example:this.maybeResolveSchemaExample(t);if(this.example===void 0){let d=[];for(let m of n){if(!m)continue;let g=this.context.resolveMaybeReference({schemaOrReference:m,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});g&&d.push(g)}if(d.length>0&&d.every(m=>mGm(m))){let m=d.findIndex(g=>QWl(g)!==void 0);if(m!==-1){let g=n[m],A=d[m];if(g&&A){let b=QWl(A),C=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${m}]`],context:this.context,schema:r==="oneOf"?{...t,...g,oneOf:void 0}:g,example:b,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(C.isValid)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:C.validExample,errors:[]}}}}}let o=[],s=null,a=null;for(let d=0;d<n.length;d++){let f=n[d];if(!f)continue;let m=r==="oneOf"?{...t,...f,oneOf:void 0}:f,g=i!==void 0?i:this.maybeResolveSchemaExample(m),b=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${d}]`],context:this.context,schema:m,example:g,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(b.isValid&&!b.coerced&&b.usedProvidedExample)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:b.validExample,errors:[]};if(b.isValid&&!b.coerced&&this.example===void 0)return{isValid:!0,coerced:!1,usedProvidedExample:b.usedProvidedExample,validExample:b.validExample,errors:[]};o.push(b),b.isValid&&b.usedProvidedExample&&a===null&&(a=b),b.isValid&&s===null&&(s=b)}let c=a??s,l=c!==null,u=c?.validExample??o[0]?.validExample,p=c?.usedProvidedExample??!1;return{isValid:l,coerced:!1,usedProvidedExample:p,validExample:u,errors:l?[]:o.flatMap(d=>d.errors)}}convertOneOf({resolvedSchema:t}){return this.convertUnion({resolvedSchema:t,unionType:"oneOf"})}convertAnyOf({resolvedSchema:t}){return this.convertUnion({resolvedSchema:t,unionType:"anyOf"})}getMaybeUpdatedSeenRefs(){let t=new Set(this.seenRefs);return this.context.isReferenceObject(this.schema)&&t.add(this.schema.$ref),t}maybeResolveSchemaExample(t){if("example"in t)return t.example;if("examples"in t){let n=t.examples;if(Array.isArray(n)&&n.length>0)return n[0];if(n!=null&&typeof n=="object")return Object.values(n)[0]}let r=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(r!=null){if("example"in r)return r.example;if("examples"in r){let n=r.examples;return Array.isArray(n)&&n.length>0?n[0]:Object.values(n??{})[0]}}}maybeConvertLiteralFernType(t){let r=t["x-fern-type"];if(typeof r!="string")return;let n=r.match(pGm);if(n!=null){if(n[1]!=null)return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n[1],errors:[]};if(n[2]!=null)return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n[2]==="true",errors:[]}}}mergeAllOfProperties(t,r=new Set,n=0,i=!1){if(i){let p=this.sharedState.mergedAllOfProperties.get(t)?.get(n);if(p!=null)return p}let o=t.properties??{},s=t.required??[];if(n>this.MAX_DEPTH||t.allOf==null||t.allOf.length===0){let p={mergedProperties:o,mergedRequired:s};return i&&this.cacheMergedAllOfProperties(t,n,p),p}let a={},c=new Set(s);for(let p of t.allOf){let d=this.context.resolveMaybeReference({schemaOrReference:p,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(d==null)continue;let f=this.context.isReferenceObject(p)?p.$ref:void 0;if(!(f!=null&&r.has(f))){if(d.allOf!=null&&d.allOf.length>0){let m=new Set(r);f!=null&&m.add(f);let g=this.mergeAllOfProperties(d,m,n+1,i);for(let A of g.mergedRequired)c.add(A);for(let[A,b]of Object.entries(g.mergedProperties))if(typeof b=="object"&&b!==null){let I=a[A];I!=null&&vUe(I)&&vUe(b)?a[A]={...I,...b}:a[A]=b}continue}if(d.required!=null)for(let m of d.required)c.add(m);if(d.properties!=null){for(let[m,g]of Object.entries(d.properties))if(typeof g=="object"&&g!==null){let A=a[m];A!=null&&vUe(A)&&vUe(g)?a[m]={...A,...g}:a[m]=g}}}}let l={...o};for(let[p,d]of Object.entries(l)){let f=a[p];if(f==null||!vUe(d))continue;let m="$ref"in f?this.context.resolveMaybeReference({schemaOrReference:f,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):f;m!=null&&(l[p]={...m,...d})}for(let[p,d]of Object.entries(a))p in l||(l[p]=d);let u={mergedProperties:l,mergedRequired:[...c]};return i&&this.cacheMergedAllOfProperties(t,n,u),u}cacheMergedAllOfProperties(t,r,n){let i=this.sharedState.mergedAllOfProperties.get(t);i!=null?i.set(r,n):this.sharedState.mergedAllOfProperties.set(t,new Map([[r,n]]))}canGenerateFromMergedAllOf(t,r=new WeakSet){if(t.allOf==null||t.allOf.length===0||!this.isMergeOnlyObjectSchema(t))return!1;let n=this.sharedState.mergeOnlyAllOfSchemas.get(t);if(n!=null)return n;if(r.has(t))return!1;r.add(t);let i=t.allOf.every(o=>{let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});return s==null||!this.isMergeOnlyObjectSchema(s)?!1:s.allOf==null||s.allOf.length===0?!0:this.canGenerateFromMergedAllOf(s,r)});return r.delete(t),this.sharedState.mergeOnlyAllOfSchemas.set(t,i),i}isMergeOnlyObjectSchema(t){return t.type!=null&&t.type!=="object"||t.type==null&&t.properties==null&&t.allOf==null?!1:Object.keys(t).every(r=>fGm.has(r))}isConstraintOnlySchema(t){if(typeof t!="object"||t===null||t.type!==void 0||t.properties!==void 0||t.allOf!==void 0||t.oneOf!==void 0||t.anyOf!==void 0||"items"in t||t.additionalProperties!==void 0||t.enum!==void 0||t.const!==void 0)return!1;let r=new Set(["required","description","title","deprecated","readOnly","writeOnly","nullable","example","examples","default","minLength","maxLength","minimum","maximum","exclusiveMinimum","exclusiveMaximum","minItems","maxItems","uniqueItems","pattern","format"]),n=Object.keys(t);return n.length>0&&n.every(i=>r.has(i))}isDeprecatedProperty(t){return t!=null&&"availability"in t&&t.availability==="deprecated"}isRequiredProperty({key:t,resolvedSchema:r}){return r.required?.includes(t)??!1}collectAllPropertyKeys(t,r=new Set){let n=new Set;if(t.properties)for(let i of Object.keys(t.properties))n.add(i);for(let i of t.allOf??[]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)){r.add(s);let a=this.collectAllPropertyKeys(o,r);for(let c of a)n.add(c)}}}for(let i of[...t.oneOf??[],...t.anyOf??[]]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)){r.add(s);let a=this.collectAllPropertyKeys(o,r);for(let c of a)n.add(c)}}}return n}schemaHasPatternProperties(t,r=new Set){let n=t.patternProperties;if(n&&typeof n=="object"&&Object.keys(n).length>0)return!0;for(let i of[...t.allOf??[],...t.oneOf??[],...t.anyOf??[]]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)&&(r.add(s),this.schemaHasPatternProperties(o,r)))return!0}}return!1}}});function MWl(e){return fC({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return Hr.primitive({v1:"BASE_64",v2:di.base64({})});case"BOOLEAN":return Hr.primitive({v1:"BOOLEAN",v2:di.boolean({default:void 0})});case"DATE":return Hr.primitive({v1:"DATE",v2:di.date({})});case"DATE_TIME":return Hr.primitive({v1:"DATE_TIME",v2:di.dateTime({})});case"DATE_TIME_RFC_2822":return Hr.primitive({v1:"DATE_TIME_RFC_2822",v2:di.dateTimeRfc2822({})});case"FLOAT":return Hr.primitive({v1:"FLOAT",v2:di.float({default:void 0,validation:void 0})});case"DOUBLE":return Hr.primitive({v1:"DOUBLE",v2:di.double({default:void 0,validation:void 0})});case"UINT":return Hr.primitive({v1:"UINT",v2:di.uint({default:void 0,validation:void 0})});case"UINT_64":return Hr.primitive({v1:"UINT_64",v2:di.uint64({default:void 0,validation:void 0})});case"INTEGER":return Hr.primitive({v1:"INTEGER",v2:di.integer({default:void 0,validation:void 0})});case"LONG":return Hr.primitive({v1:"LONG",v2:di.long({default:void 0,validation:void 0})});case"STRING":return Hr.primitive({v1:"STRING",v2:di.string({default:void 0,validation:void 0})});case"UUID":return Hr.primitive({v1:"UUID",v2:di.uuid({})});case"BIG_INTEGER":return Hr.primitive({v1:"BIG_INTEGER",v2:di.bigInteger({default:void 0})});default:return}},unknown:()=>Hr.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return Hr.container(As.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return Hr.container(As.list(t))},optional:t=>{if(t!=null)return Hr.container(As.optional(t))},nullable:t=>{if(t!=null)return Hr.container(As.nullable(t))},set:t=>{if(t!=null)return Hr.container(As.set(t))},literal:t=>Hr.container(As.literal(t._visit({string:r=>kE.string(r),boolean:r=>kE.boolean(r),_other:()=>{throw new T({message:"Unexpected literal type",code:T.Code.InternalError})}}))),named:()=>{}}})}var LWl=h(()=>{"use strict";lo();zn();Bt()});var DSe,lKr=h(()=>{"use strict";zn();sc();Uo();DSe=class extends Ki{schema;maybeFernEnum;forwardCompatible;constructor({context:t,breadcrumbs:r,schema:n,maybeFernEnum:i,forwardCompatible:o}){super({context:t,breadcrumbs:r}),this.schema=n,this.maybeFernEnum=i,this.forwardCompatible=o??!1}convert(){if(!this.schema.enum)return;let r=this.schema.enum.filter(i=>typeof i=="string"||typeof i=="number").map(i=>{let o=i.toString(),s=this.maybeFernEnum?.[o],a=s?.name??o;return{name:this.context.casingsGenerator.generateNameAndWireValue({name:a,wireValue:o}),docs:s?.description,availability:void 0,casing:s?.casing}});if(r.length===0){this.context.errorCollector.collect({message:`Received enum schema with no valid values: ${JSON.stringify(this.schema)}`,path:this.breadcrumbs});return}let n=this.context.getAsString(this.schema.default);return{type:ic.enum({default:n!=null?r.find(i=>cr(i.name)===n):void 0,values:r,forwardCompatible:this.forwardCompatible||void 0})}}}});var uKr,_Wl=h(()=>{"use strict";zn();Uo();Nct();CUe();uKr=class extends Ki{schemaOrReferenceOrBoolean;constructor({context:t,breadcrumbs:r,schemaOrReferenceOrBoolean:n}){super({context:t,breadcrumbs:r}),this.schemaOrReferenceOrBoolean=n}convert(){let t=this.tryConvertUnknownMap();if(t!=null)return t;let r=this.tryConvertTypedMap();if(r!=null)return r}tryConvertUnknownMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean"){let t=Hr.container(As.map({keyType:Ki.STRING,valueType:Hr.unknown()}));return{type:ic.alias({aliasOf:t,resolvedType:t}),referencedTypes:new Set,inlinedTypes:{}}}}tryConvertTypedMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean")return;let r=new NT({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schemaOrReferenceOrBoolean}).convert();if(r!=null){let n=Hr.container(As.map({keyType:Ki.STRING,valueType:r.type})),i=new Set;for(let o of r.schema?.typeDeclaration.referencedTypes??[])i.add(o);for(let o of Object.keys(r.inlinedTypes))i.add(o);return c3(r.type,i),{type:ic.alias({aliasOf:n,resolvedType:n}),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}}});function GWl(e,t,r){let n=qWl(t,r),i={};for(let o of n)i=RGo(i,o);return EGm(i,e),i}function qWl(e,t,r){let n=r??new Set,i=[];for(let o of e)if(Array.isArray(o.allOf)&&o.allOf.length>0){let{allOf:s,...a}=o,c=[];for(let l of s)if("$ref"in l){if(t==null)continue;let u=l.$ref;if(n.has(u))continue;n.add(u);let p=t(l);p!=null&&c.push(p)}else c.push(l);i.push(...qWl(c,t,n)),Object.keys(a).length>0&&i.push(a)}else i.push(o);return i}function RGo(e,t){let r={...e};for(let[n,i]of Object.entries(t)){if(i===void 0||yGm.includes(n))continue;let o=r[n];if(n==="required"){let s=Array.isArray(o)?o:[],a=Array.isArray(i)?i:[];r[n]=[...new Set([...s,...a])];continue}if(n==="properties"){r[n]=bGm(o??{},i);continue}if(n==="items"){gr(o)&&gr(i)?r[n]=RGo(o,i):r[n]=i;continue}if(UWl.includes(n)){gr(o)&&gr(i)?r[n]=WWl(o,i):r[n]=i;continue}if(VWl.includes(n)){r[n]=!!o||!!i;continue}if(gGm.includes(n)){typeof o=="number"&&typeof i=="number"?r[n]=Math.max(o,i):r[n]=i;continue}if(AGm.includes(n)){typeof o=="number"&&typeof i=="number"?r[n]=Math.min(o,i):r[n]=i;continue}r[n]=i}return r}function bGm(e,t){let r={...e};for(let[n,i]of Object.entries(t)){let o=r[n];gr(o)&&gr(i)?r[n]=RGo(o,i):r[n]=i}return r}function WWl(e,t){let r={...e};for(let[n,i]of Object.entries(t)){let o=r[n];gr(o)&&gr(i)?r[n]=WWl(o,i):r[n]=i}return r}function EGm(e,t){for(let r of hGm){let n=t[r];n!=null&&(e[r]=n)}for(let r of UWl){let n=t[r];n!=null&&(e[r]=n)}for(let r of VWl)t[r]===!0&&(e[r]=!0)}var hGm,UWl,VWl,gGm,AGm,yGm,HWl=h(()=>{"use strict";mt();hGm=["description","title","format","type","discriminator","xml","externalDocs","extensions"],UWl=["example","default"],VWl=["deprecated","readOnly","writeOnly","uniqueItems","nullable"],gGm=["minimum","exclusiveMinimum","minLength","minItems","minProperties"],AGm=["maximum","exclusiveMaximum","maxLength","maxItems","maxProperties"],yGm=["allOf","oneOf","anyOf"]});var jct,kGo=h(()=>{"use strict";mt();zn();sc();cKr();Uo();Nct();jct=class extends Ki{schema;xmlEncoding;constructor({context:t,breadcrumbs:r,schema:n,id:i}){super({context:t,breadcrumbs:r}),this.schema=n,this.xmlEncoding=new kct({breadcrumbs:this.breadcrumbs,schema:n,fallbackName:i,context:t}).convert()}convert(){let t=typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties;if(!this.schema.properties&&!this.schema.allOf)return{type:ic.object({properties:[],extends:[],extendedProperties:[],extraProperties:t,deferredUnionBaseProperties:void 0}),propertiesByAudience:{},inlinedTypes:{},referencedTypes:new Set,xmlEncoding:this.xmlEncoding};let{convertedProperties:r,inlinedTypesFromProperties:n,referencedTypes:i,propertiesByAudience:o}=xUe({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector,withinXmlElement:this.xmlEncoding!=null}),s=[],a=i,c=this.schema.required!=null&&this.schema.required.length>0,l=n,u=o,p={};for(let d of this.schema.allOf??[])if(this.context.isReferenceObject(d)){let f=this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:this.breadcrumbs});if(f?.properties!=null)for(let[m,g]of Object.entries(f.properties))!this.context.isReferenceObject(g)&&p[m]==null&&(p[m]=g)}for(let[d,f]of(this.schema.allOf??[]).entries()){let m=[...this.breadcrumbs,"allOf",d.toString()],g,A=!1;if(this.context.isReferenceObject(f)){let D=this.context.resolveMaybeReference({schemaOrReference:f,breadcrumbs:m});if(D==null){this.context.logger.debug?.(`[ObjectSchemaConverter] allOf[${d}] reference could not be resolved. Skipping: ${JSON.stringify(f)}`);continue}if(g=D,typeof g.additionalProperties=="boolean"&&g.additionalProperties&&(t=!0),!c||Object.keys(g.properties??{}).every(R=>!this.schema.required?.includes(R))){this.addTypeReferenceToExtends({reference:f,breadcrumbs:m,extends_:s,referencedTypes:a});continue}}else g=f,A=!0;typeof g.additionalProperties=="boolean"&&g.additionalProperties&&(t=!0);let b=g.oneOf??g.anyOf;if(b!=null&&g.type==null&&g.properties==null){let D=new Set(r.map(R=>cr(R.name)));for(let[R,O]of b.entries()){let j=[...m,g.oneOf!=null?"oneOf":"anyOf",R.toString()],Y=this.context.isReferenceObject(O)?this.context.resolveMaybeReference({schemaOrReference:O,breadcrumbs:j}):O;if(Y==null)continue;let ee={};for(let[Te,pe]of Object.entries(Y.properties??{}))!this.context.isReferenceObject(pe)&&"not"in pe||(ee[Te]=pe);let te=Object.keys(ee).filter(Te=>!D.has(Te));if(te.length===0)continue;let ce={};for(let Te of te){let pe=ee[Te];pe!=null&&(ce[Te]=pe,D.add(Te))}let{convertedProperties:le,inlinedTypesFromProperties:ae,referencedTypes:he,propertiesByAudience:xe}=xUe({properties:ce,required:[],breadcrumbs:j,context:this.context,errorCollector:this.context.errorCollector,withinXmlElement:this.xmlEncoding!=null});r.push(...le),l={...l,...ae},u={...u,...xe},he.forEach(Te=>{a.add(Te)})}continue}let I=g.properties??{};if(A){I={};for(let[D,R]of Object.entries(g.properties??{})){let O=p[D];O!=null&&!this.context.isReferenceObject(R)?I[D]={...O,...R}:I[D]=R}}let{convertedProperties:C,inlinedTypesFromProperties:x,referencedTypes:S,propertiesByAudience:P}=xUe({properties:I,required:[...this.schema.required??[],...g.required??[],...Hue(g)],breadcrumbs:m,context:this.context,errorCollector:this.context.errorCollector,withinXmlElement:this.xmlEncoding!=null});r.push(...C),l={...l,...x},u={...u,...P},S.forEach(D=>{a.add(D)})}for(let d of Object.keys(l))a.add(d);return{type:ic.object({properties:r,extends:s.map(d=>this.context.typeReferenceToDeclaredTypeName(d)).filter(gs),extendedProperties:[],extraProperties:t,deferredUnionBaseProperties:void 0}),propertiesByAudience:u,referencedTypes:a,inlinedTypes:l,xmlEncoding:this.xmlEncoding}}addTypeReferenceToExtends({reference:t,breadcrumbs:r,extends_:n,referencedTypes:i}){let o=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:r});o.ok&&n.push(o.reference);let s=this.context.getTypeIdFromSchemaReference(t);s!=null&&i.add(s)}}});function IGm(e){return e.type==="union"&&e.types.length===0}function vGm({schema:e,discriminantProperty:t}){let r=e.properties?.[t];if(r==null||"$ref"in r)return;let n=r.const;if(typeof n=="string")return n;if(r.enum?.length===1&&typeof r.enum[0]=="string")return r.enum[0]}var SUe,FGo=h(()=>{"use strict";zn();TGo();OGo();PGo();Uo();Nct();lKr();pKr();CUe();SUe=class extends Ki{schema;id;constructor({context:t,breadcrumbs:r,schema:n,id:i,inlinedTypes:o}){super({context:t,breadcrumbs:r}),this.schema=n,this.id=i}convert(){if(this.shouldConvertAsNullableSchemaOrReference())return this.convertAsNullableSchemaOrReference();if(new Bct({context:this.context,breadcrumbs:this.breadcrumbs,node:this.schema}).convert()===!1)return this.convertAsUndiscriminatedUnion();if(this.schema.discriminator!=null){let n=this.convertAsDiscriminatedUnion();return n!=null&&!IGm(n.type)?n:this.convertAsUndiscriminatedUnion()??n}if(this.context.settings.inferForwardCompatible){let n=this.convertAsOpenEndedEnum();if(n!=null)return n}return this.convertAsUndiscriminatedUnion()}convertAsOpenEndedEnum(){let t=this.schema.oneOf??this.schema.anyOf;if(t==null||t.length!==2)return;let r,n=!1;for(let c of t){let l;if(this.context.isReferenceObject(c)){let u=this.context.resolveReference({reference:c,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});u.resolved&&(l=u.value)}else l=c;l!=null&&(l.enum!=null&&l.enum.length>1&&(l.type==="string"||l.type==null)?r=l:l.type==="string"&&l.enum==null&&(n=!0))}if(r==null||!n)return;let o=new Rct({breadcrumbs:this.breadcrumbs,schema:r,context:this.context}).convert(),a=new DSe({context:this.context,breadcrumbs:this.breadcrumbs,schema:r,maybeFernEnum:o,forwardCompatible:!0}).convert();if(a!=null)return{...a,referencedTypes:new Set,inlinedTypes:{}}}getEnclosingComponentRef(){let[t,r,n]=this.breadcrumbs;return t==="components"&&r==="schemas"&&n!=null?`#/components/schemas/${n}`:void 0}filterDiscriminantFromSchema(t,r){if(t.properties==null||!(r in t.properties))return t;let{[r]:n,...i}=t.properties,o=t.required?.filter(s=>s!==r);return{...t,properties:i,required:o}}getVariants(t){let r=this.schema.discriminator?.mapping;if(r!=null){let o=[];for(let[s,a]of Object.entries(r)){let c=this.context.getTypeIdFromSchemaReference({$ref:a});c!=null&&o.push({discriminant:s,typeId:c,ref:a,schema:this.resolveVariantSchema({$ref:a}),breadcrumbs:[...this.breadcrumbs,"discriminator","mapping",s]})}return o}let n=this.schema.oneOf??this.schema.anyOf??[],i=[];for(let[o,s]of n.entries()){let a=this.resolveVariantSchema(s),c=a!=null?vGm({schema:a,discriminantProperty:t}):void 0;if(!this.context.isReferenceObject(s)){if(c==null)return[];i.push({discriminant:c,typeId:this.context.convertBreadcrumbsToName([`${this.id}_${o}`]),schema:a,breadcrumbs:[...this.breadcrumbs,`oneOf[${o}]`]});continue}let l=s.$ref,u=l.split("/").pop(),p=this.context.getTypeIdFromSchemaReference(s),d=c??u;if(p==null||d==null)return[];i.push({discriminant:d,typeId:p,ref:l,schema:a,breadcrumbs:[...this.breadcrumbs,"discriminator","mapping",d]})}return i}resolveVariantSchema(t){if(!this.context.isReferenceObject(t))return t;let r=this.context.resolveReference({reference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});return r.resolved?r.value:void 0}convertAsDiscriminatedUnion(){if(this.schema.discriminator==null)return;let t=this.schema.discriminator.propertyName,r=[],n=new Set,i={};for(let{discriminant:u,typeId:p,ref:d,schema:f,breadcrumbs:m}of this.getVariants(t)){let g=d!=null?{$ref:d}:f,A=p!=null&&this.context.discriminatedVariantsInProgress.has(p),b=d!=null&&d===this.getEnclosingComponentRef(),I=f?.properties!=null&&t in f.properties&&!((A||b)&&d!=null);if(I&&f!=null&&(g=this.filterDiscriminantFromSchema(f,t)),g==null)continue;let C=new NT({context:this.context,schemaOrReference:g,schemaIdOverride:p??void 0,breadcrumbs:m});p!=null&&n.add(p);let x=I&&p!=null&&!A;x&&this.context.discriminatedVariantsInProgress.add(p);let S;try{S=C.convert()}finally{x&&this.context.discriminatedVariantsInProgress.delete(p)}if(S?.type!=null&&p!=null){for(let Y of Object.keys(S?.inlinedTypes??{}))n.add(Y);for(let Y of S.schema?.typeDeclaration.referencedTypes??[])n.add(Y);let P=this.context.casingsGenerator.generateNameAndWireValue({name:u,wireValue:u}),D=d?.split("/").pop()??p,R=f?.title,O=f?.description,j=R??u??D;S.schema?.typeDeclaration!=null&&R!=null&&(S.schema.typeDeclaration.name.displayName=R),r.push({docs:O,discriminantValue:P,availability:S.availability,displayName:j,shape:eT.samePropertiesAsObject({typeId:p,name:this.context.casingsGenerator.generateName(D),fernFilepath:{allParts:[],packagePath:[],file:void 0},displayName:j})}),i={...i,...S.inlinedTypes}}}let{convertedProperties:o,referencedTypes:s,inlinedTypesFromProperties:a}=xUe({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector});n=new Set([...n,...s]);let c=[];for(let[u,p]of(this.schema.allOf??[]).entries()){let d=[...this.breadcrumbs,"allOf",u.toString()];if(this.context.isReferenceObject(p)){let f=this.context.convertReferenceToTypeReference({reference:p,breadcrumbs:d});if(f.ok){let g=this.context.typeReferenceToDeclaredTypeName(f.reference);g!=null&&c.push(g)}let m=this.context.getTypeIdFromSchemaReference(p);m!=null&&n.add(m);continue}}for(let u of Object.keys({...i,...a}))n.add(u);let l=new Dct({context:this.context,breadcrumbs:[...this.breadcrumbs,"discriminator"],node:this.schema.discriminator});return{type:ic.union({baseProperties:o,inheritedBaseProperties:[],discriminant:this.context.casingsGenerator.generateNameAndWireValue({name:this.schema.discriminator.propertyName,wireValue:this.schema.discriminator.propertyName}),extends:c,types:r,default:void 0,discriminatorContext:l.convert()}),referencedTypes:n,inlinedTypes:{...i,...a}}}convertAsUndiscriminatedUnion(){if(!this.schema.oneOf&&!this.schema.anyOf||this.schema.anyOf?.length===0&&this.schema.oneOf?.length===0)return;let t=[],r=new Set,n={};for(let[a,c]of[...(this.schema.oneOf??[]).entries(),...(this.schema.anyOf??[]).entries()]){if(this.context.isReferenceObject(c)){let g;if(this.context.isReferenceObjectWithIdentifier(c))g=this.context.convertReferenceToTypeReference({reference:c,displayNameOverride:c.summary??c.title??c.name??c.messageId,displayNameOverrideSource:"reference_identifier"});else{let b=this.getDiscriminatorKeyForRef(c);b!=null?g=this.context.convertReferenceToTypeReference({reference:c,displayNameOverride:b,displayNameOverrideSource:"discriminator_key"}):g=this.context.convertReferenceToTypeReference({reference:c,breadcrumbs:this.breadcrumbs})}if(g.ok){let b=this.context.resolveReference({reference:c,breadcrumbs:this.breadcrumbs}),I=b.resolved?b.value.description:void 0;t.push({type:g.reference,docs:I})}let A=this.context.getTypeIdFromSchemaReference(c);A!=null&&r.add(A);continue}let u=Object.keys(this.schema.properties??{}).length>0?void 0:this.extendSubSchema(c),p=this.context.convertBreadcrumbsToName([`${this.id}_${a}`]),d=c.title,m=new RSe({context:this.context,id:p,nameOverride:d,breadcrumbs:[...this.breadcrumbs,`oneOf[${a}]`],schema:u??c}).convert();if(m!=null){let g=m.convertedSchema.typeDeclaration.shape;if(g.type==="alias"&&this.typeReferenceIsWrappedPrimitive(g.aliasOf))t.push({type:g.aliasOf,docs:c.description});else if(g.type==="object"&&g.properties.length===0&&g.extends.length===0)t.push({type:Hr.container(As.map({keyType:Ki.STRING,valueType:Hr.unknown()})),docs:c.description});else{t.push({type:this.context.createNamedTypeReference(p,d),docs:c.description});let A=this.context.getNamespacedSchemaId(p);n={...n,...m.inlinedTypes,[A]:m.convertedSchema},r.add(A);for(let b of Object.keys(m.inlinedTypes))r.add(b)}m.convertedSchema.typeDeclaration.referencedTypes.forEach(A=>{r.add(A)})}}let{convertedProperties:i,referencedTypes:o,inlinedTypesFromProperties:s}=xUe({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector});for(let a of Object.keys(s))r.add(a);for(let a of o)r.add(a);return{type:ic.undiscriminatedUnion({members:t,baseProperties:i.length>0?i:void 0}),referencedTypes:r,inlinedTypes:{...n,...s}}}shouldConvertAsNullableSchemaOrReference(){return this.schema.oneOf!=null?this.schema.oneOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):this.schema.anyOf!=null?this.schema.anyOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):!1}removeNullFromOneOfOrAnyOf(){let t=this.schema.oneOf??this.schema.anyOf,r=this.schema.oneOf!=null?"oneOf":"anyOf";if(t==null)return;let n=t.filter(i=>!(typeof i=="object"&&i!==null&&"type"in i&&i.type==="null"));if(n.length===0){this.context.errorCollector.collect({message:`Received ${r} schema with no valid non-null types`,path:this.breadcrumbs});return}return n.length===1?{...this.schema,[r]:void 0,...n[0]}:{...this.schema,[r]:n}}convertAsNullableSchemaOrReference(){let t=this.removeNullFromOneOfOrAnyOf();if(t==null)return;let n=new NT({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(n==null)return;let i=this.wrapInNullable(n.type);return{type:ic.alias({aliasOf:i,resolvedType:i}),referencedTypes:n.schema?.typeDeclaration.referencedTypes??new Set,inlinedTypes:n.inlinedTypes}}typeReferenceIsWrappedPrimitive(t){switch(t.type){case"container":return this.containerTypeIsWrappedPrimitive(t.container);case"named":return!1;case"primitive":return!0;case"unknown":return!0;default:return!1}}containerTypeIsWrappedPrimitive(t){switch(t.type){case"list":return this.typeReferenceIsWrappedPrimitive(t.list);case"map":return this.typeReferenceIsWrappedPrimitive(t.keyType)&&this.typeReferenceIsWrappedPrimitive(t.valueType);case"nullable":return this.typeReferenceIsWrappedPrimitive(t.nullable);case"optional":return this.typeReferenceIsWrappedPrimitive(t.optional);case"set":return this.typeReferenceIsWrappedPrimitive(t.set);case"literal":return!0;default:return!1}}wrapInNullable(t){return Hr.container(As.nullable(t))}mergeIntoObjectSchema(t,r){return{...t,properties:{...r,...t.properties??{}}}}extendSubSchema(t){if(Object.entries(this.schema.properties??{}).length===0)return t;if(t.type==="object")return this.mergeIntoObjectSchema(t,this.schema.properties??{});this.context.isObjectSchemaType(t)||this.context.errorCollector.collect({message:"Received additional object properties for oneOf/anyOf that are not objects",path:this.breadcrumbs})}getDiscriminatorKeyForRef(t){return Object.entries(this.schema.discriminator?.mapping??{}).find(([r,n])=>n===t.$ref)?.[0]}}});var zct,NGo=h(()=>{"use strict";zn();Uo();zct=class extends Ki{schema;constructor({context:t,breadcrumbs:r,schema:n}){super({context:t,breadcrumbs:r}),this.schema=n}convert(){switch(this.schema.type){case"string":{let t=this.context.getAsString(this.schema.const);if(t!=null)return Hr.container(As.literal(kE.string(t)));if(this.schema.format==="date-time-rfc-2822")return Hr.primitive({v1:ss.DateTimeRfc2822,v2:di.dateTimeRfc2822({})});if(this.context.settings.typeDatesAsStrings===!1){if(this.schema.format==="date")return Hr.primitive({v1:ss.Date,v2:di.date({})});if(this.schema.format==="date-time")return Hr.primitive({v1:ss.DateTime,v2:di.dateTime({})})}return Hr.primitive({v1:"STRING",v2:di.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":switch(this.schema.format){case"double":return Hr.primitive({v1:"DOUBLE",v2:di.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return Hr.primitive({v1:"FLOAT",v2:di.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return Hr.primitive({v1:"INTEGER",v2:di.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return Hr.primitive({v1:"LONG",v2:di.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return Hr.primitive({v1:"UINT",v2:di.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return Hr.primitive({v1:"UINT_64",v2:di.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return Hr.primitive({v1:"DOUBLE",v2:di.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"integer":switch(this.schema.format){case"double":return Hr.primitive({v1:"DOUBLE",v2:di.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return Hr.primitive({v1:"FLOAT",v2:di.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return Hr.primitive({v1:"INTEGER",v2:di.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return Hr.primitive({v1:"LONG",v2:di.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return Hr.primitive({v1:"UINT",v2:di.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return Hr.primitive({v1:"UINT_64",v2:di.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return Hr.primitive({v1:"INTEGER",v2:di.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"boolean":{let t=this.context.getAsBoolean(this.schema.const);return t!=null?Hr.container(As.literal(kE.boolean(t))):Hr.primitive({v1:"BOOLEAN",v2:di.boolean({default:this.context.getAsBoolean(this.schema.default)})})}default:return}}getNumberValidation(t){let r=t.minimum,n=t.maximum,i,o;return typeof t.exclusiveMinimum=="boolean"?i=t.exclusiveMinimum:typeof t.exclusiveMinimum=="number"&&(r=t.exclusiveMinimum,i=!0),typeof t.exclusiveMaximum=="boolean"?o=t.exclusiveMaximum:typeof t.exclusiveMaximum=="number"&&(n=t.exclusiveMaximum,o=!0),{max:n,min:r,exclusiveMax:o,exclusiveMin:i,multipleOf:t.multipleOf}}getStringValidation(t){let r=t.format??(t.contentMediaType==="application/octet-stream"?"binary":void 0);return{minLength:t.minLength,maxLength:t.maxLength,pattern:t.pattern,format:r}}}});function xGm(e){let t=Hue(e);return t.length===0?e:{...e,required:[...new Set([...e.required??[],...t])]}}var CGm,RSe,pKr=h(()=>{"use strict";mt();zn();Uo();Nct();LWl();BSe();jGo();lKr();_Wl();HWl();kGo();FGo();NGo();CGm=["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],RSe=class e extends Ki{static MAX_DISTRIBUTED_VARIANTS=64;schema;id;inlined;audiences;nameOverride;visitedRefs;constructor({context:t,breadcrumbs:r,schema:n,id:i,inlined:o=!1,nameOverride:s,visitedRefs:a}){super({context:t,breadcrumbs:r}),this.schema=n,this.id=i,this.inlined=o,this.nameOverride=s,this.visitedRefs=a??new Set,this.audiences=this.context.getAudiences({operation:this.schema,breadcrumbs:this.breadcrumbs})??[]}convert(){let t=this.tryConvertFernTypeDeclaration();if(t!=null)return t;let r=this.tryConvertReferenceSchema();if(r!=null)return r;let n=this.tryConvertEnumSchema();if(n!=null)return n;let i=this.tryDistributeAllOfOverOneOf();if(i!=null)return i;let o=this.tryConvertSingularAllOfSchema();if(o!=null)return o;let s=this.tryConvertPrimitiveSchema();if(s!=null)return s;let a=this.tryConvertArraySchema();if(a!=null)return a;let c=this.tryConvertTypeArraySchema();if(c!=null)return c;let l=this.tryConvertSiblingAnyOfConstraint();if(l!=null)return l;let u=this.tryConvertSiblingOneOfConstraint();if(u!=null)return u;let p=this.tryConvertOneOfAnyOfSchema();if(p!=null)return p;let d=this.tryConvertMapSchema();if(d!=null)return d;let f=this.tryConvertDiscriminatorMappingSchema();if(f!=null)return f;let m=this.tryConvertObjectAllOfSchema();if(m!=null)return m;let g=this.tryConvertUntypedSchema();if(g!=null)return g;this.context.errorCollector.collect({message:`Failed to convert schema object: ${JSON.stringify(this.schema,null,2)}`,path:this.breadcrumbs})}tryConvertReferenceSchema(){if(!this.context.isReferenceObject(this.schema))return;let t=this.schema;if(this.visitedRefs.has(t.$ref)||t.$ref===`#/components/schemas/${this.id}`)return;let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(!r.ok)return;let n=new Set;return c3(r.reference,n),{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:ic.alias({aliasOf:r.reference,resolvedType:r.reference}),referencedTypes:n}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes??{}}}tryConvertEnumSchema(){if(!this.schema.enum?.length)return;let r=new vC.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),i=new DSe({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,maybeFernEnum:r}).convert();if(i!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:i.type,referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertSingularAllOfSchema(){if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&this.schema.allOf?.length===1&&this.schema.allOf[0]!=null){let r=this.schema.allOf[0];if(this.context.isReferenceObject(r)){let i=r.$ref;if(this.visitedRefs.has(i))return}let n=this.context.resolveMaybeReference({schemaOrReference:r,breadcrumbs:this.breadcrumbs});if(n!=null){let i=this.context.isReferenceObject(r)?new Set([...this.visitedRefs,r.$ref]):this.visitedRefs,s=new e({context:this.context,breadcrumbs:[...this.breadcrumbs,"allOf","0"],schema:n,id:this.id,inlined:this.inlined,visitedRefs:i}).convert();if(s?.convertedSchema.typeDeclaration?.shape.type!=="object"){if(s!=null){let a=s.convertedSchema.typeDeclaration;this.schema.description!=null&&a.docs==null&&(a.docs=this.schema.description);let c=this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs});c!=null&&a.availability==null&&(a.availability=c)}return s}}}if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&Array.isArray(this.schema.allOf)&&this.schema.allOf.length>=1){let r=new Set,n=[],i=!1;for(let c of this.schema.allOf??[]){let l;if(this.context.isReferenceObject(c)){let p=c.$ref;if(this.visitedRefs.has(p)){i=!0;break}if(r.has(p))continue;r.add(p);let d=this.context.resolveMaybeReference({schemaOrReference:c,breadcrumbs:this.breadcrumbs});if(d==null)return;l=d}else l=c;let u=l.oneOf??l.anyOf;if(!this.context.isReferenceObject(c)&&u!=null&&l.type==null&&l.properties==null){let p={};for(let d of u){let f=this.context.isReferenceObject(d)?this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:this.breadcrumbs}):d;if(f!=null)for(let[m,g]of Object.entries(f.properties??{}))!this.context.isReferenceObject(g)&&"not"in g||m in p||(p[m]=g)}Object.keys(p).length>0&&n.push({properties:p});continue}n.push(xGm(l))}if(i)return;let o=GWl(this.schema,n,c=>{let l=this.context.resolveMaybeReference({schemaOrReference:c,breadcrumbs:this.breadcrumbs});if(!(l!=null&&this.context.isReferenceObject(l)))return l}),s=new Set([...this.visitedRefs,...r]);return new e({context:this.context,breadcrumbs:this.breadcrumbs,schema:o,id:this.id,inlined:this.inlined,visitedRefs:s}).convert()}}tryDistributeAllOfOverOneOf(){if(!this.context.settings.preserveOneOfInAllOf)return;let t=this.schema.allOf;if(!Array.isArray(t)||t.length===0||this.schema.oneOf!=null||this.schema.anyOf!=null)return;let r=this.getDistributableUnions(t),n=r[0];if(n==null)return;let i=r.reduce((c,l)=>c*l.variants.length,1);if(i>e.MAX_DISTRIBUTED_VARIANTS){this.context.logger.warn(`Not distributing allOf over its ${r.length} unions at ${this.breadcrumbs.join(".")}: it would produce ${i} variants (max ${e.MAX_DISTRIBUTED_VARIANTS}).`);return}let o=t.filter((c,l)=>l!==n.index);(this.schema.properties!=null||this.schema.required!=null)&&o.push({type:"object",properties:this.schema.properties,required:this.schema.required});let s={...this.schema};return delete s.allOf,delete s.properties,delete s.required,new e({context:this.context,breadcrumbs:this.breadcrumbs,schema:{...s,oneOf:n.variants.map(c=>{let l=this.getVariantTitle(c);return{...l!=null?{title:l}:{},allOf:[c,...o]}})},id:this.id,inlined:this.inlined,nameOverride:this.nameOverride,visitedRefs:this.visitedRefs}).convert()}getVariantTitle(t){return this.context.isReferenceObject(t)?this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs})?.title??t.$ref.split("/").pop():t.title}getDistributableUnions(t){let r=[];for(let[n,i]of t.entries()){let o=this.context.isReferenceObject(i)?this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:this.breadcrumbs}):i;if(o==null||o.properties!=null||o.type!=null&&o.type!=="object"||o.discriminator!=null)continue;let s=o.oneOf??o.anyOf;s==null||s.length===0||r.push({index:n,variants:s})}return r}tryConvertPrimitiveSchema(){let r=new zct({context:this.context,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:ic.alias({aliasOf:r,resolvedType:r}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertArraySchema(){if(this.schema.type==="array"){let r=new Qct({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:ic.alias({aliasOf:r.typeReference,resolvedType:r.typeReference}),referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertTypeArraySchema(){if(Array.isArray(this.schema.type)&&this.schema.type.length>0)return this.schema.type.length===1?this.schema.type=this.schema.type[0]:(this.schema.oneOf=this.schema.type.map(t=>({type:t})),this.schema.type=void 0),this.convert()}tryConvertSiblingAnyOfConstraint(){if(!this.context.settings.anyOfSiblingPropertiesAsObject||!Sze(this.schema))return;this.context.logger.debug(`Treating the anyOf at ${this.breadcrumbs.join(".")} as an "at least one of" constraint over its sibling properties rather than a union, and converting the schema as an object.`);let{anyOf:t,...r}=this.schema;return new e({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:r,inlined:this.inlined,nameOverride:this.nameOverride,visitedRefs:this.visitedRefs}).convert()}tryConvertSiblingOneOfConstraint(){if(!wze(this.schema)||new vC.FernDiscriminatedExtension({context:this.context,breadcrumbs:this.breadcrumbs,node:this.schema}).convert()===!0)return;this.context.logger.debug(`Treating the oneOf at ${this.breadcrumbs.join(".")} as an "exactly one of" constraint over its sibling properties rather than a union, and converting the schema as an object.`);let r=Hue(this.schema),{oneOf:n,...i}=this.schema;return r.length>0&&(i.required=[...new Set([...i.required??[],...r])]),new e({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:i,inlined:this.inlined,nameOverride:this.nameOverride,visitedRefs:this.visitedRefs}).convert()}tryConvertOneOfAnyOfSchema(){if(this.schema.oneOf!=null||this.schema.anyOf!=null){let r=new SUe({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,inlinedTypes:{}}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertMapSchema(){if((typeof this.schema.additionalProperties=="object"||typeof this.schema.additionalProperties=="boolean")&&this.schema.additionalProperties!=null&&!this.schema.properties&&!this.schema.allOf){if(typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties===!1)return;let r=new uKr({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReferenceOrBoolean:this.schema.additionalProperties}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertDiscriminatorMappingSchema(){if(this.schema.discriminator?.mapping!=null&&Object.keys(this.schema.discriminator.mapping).length>0&&this.schema.oneOf==null&&this.schema.anyOf==null){let t={...this.schema,oneOf:Object.values(this.schema.discriminator.mapping).map(i=>({$ref:i}))},n=new SUe({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:t,inlinedTypes:{}}).convert();if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:n.type,referencedTypes:n.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:n.inlinedTypes}}}tryConvertObjectAllOfSchema(){if(this.schema.type==="object"||this.schema.properties!=null||this.schema.allOf!=null){let r=new jct({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,id:this.id}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes,encoding:r.xmlEncoding!=null?{json:void 0,proto:void 0,xml:r.xmlEncoding}:void 0}),audiences:this.audiences,propertiesByAudience:r.propertiesByAudience},inlinedTypes:r.inlinedTypes}}}tryConvertUntypedSchema(){if(this.isUntypedSchema())return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:ic.alias({aliasOf:Hr.unknown(),resolvedType:Hr.unknown()}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertFernTypeDeclaration(){let r=new vC.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r==null)return;let n=MWl(r);if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:ic.alias({aliasOf:n,resolvedType:n}),referencedTypes:new Set,omitV2Examples:!0}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}createTypeDeclaration({shape:t,referencedTypes:r,omitV2Examples:n,encoding:i}){return{name:this.convertDeclaredTypeName(),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:i,availability:this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs}),docs:this.schema.description,referencedTypes:r,source:void 0,inline:this.inlined,v2Examples:n?void 0:this.convertSchemaExamples()}}convertDeclaredTypeName(){let t=this.context.getRawSchemaId(this.id);return{typeId:this.context.getNamespacedSchemaId(this.id),fernFilepath:this.context.createFernFilepath(),name:this.context.casingsGenerator.generateName(t),displayName:this.nameOverride}}schemaOnlyHasAllowedKeys(t){let r=[...CGm,...t];return Object.keys(this.schema).every(i=>r.includes(i))}isUntypedSchema(){return!!(this.schema&&typeof this.schema=="object"&&!("oneOf"in this.schema)&&!("anyOf"in this.schema)&&!("allOf"in this.schema)&&!("items"in this.schema)&&!("properties"in this.schema))}convertSchemaExamples(){let t={userSpecifiedExamples:{},autogeneratedExamples:{}},r=this.context.getExamplesFromSchema({schema:this.schema,breadcrumbs:this.breadcrumbs});if(r.length===0){let n=this.generateOrValidateExample({example:void 0,ignoreErrors:!0});return t.autogeneratedExamples={[`${this.id}_example_autogenerated`]:n},t}return t.userSpecifiedExamples=this.convertUserSpecifiedExamples(r),t}convertUserSpecifiedExamples(t){let r={};for(let[n,i]of t.entries()){let o=this.context.resolveExample(i),s=`${this.id}_example_${n}`,a=this.generateOrValidateExample({example:o,exampleName:s});r[s]=a}return r}generateOrValidateExample({example:t}){let r=new Bw({breadcrumbs:this.breadcrumbs,context:this.context,schema:this.schema,example:t}),{validExample:n}=r.convert();return n}}});function wGm(e){return Object.keys(e).every(t=>SGm.has(t))}var NT,SGm,CUe=h(()=>{"use strict";zn();Uo();pKr();NT=class extends Ki{schemaOrReference;schemaIdOverride;wrapAsOptional;wrapAsNullable;constructor({context:t,breadcrumbs:r,schemaOrReference:n,schemaIdOverride:i,wrapAsOptional:o=!1,wrapAsNullable:s=!1}){super({context:t,breadcrumbs:r}),this.schemaOrReference=n,this.schemaIdOverride=i,this.wrapAsOptional=o,this.wrapAsNullable=s}convert(){let t=this.maybeConvertReferenceObject({schemaOrReference:this.schemaOrReference});if(t!=null)return t;let r=this.maybeConvertSingularAllOfReferenceObject();return r??this.convertSchemaObject({schema:this.schemaOrReference})}maybeConvertReferenceObject({schemaOrReference:t}){if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:r.inlinedTypes??{},availability:this.context.getAvailability({node:t,breadcrumbs:this.breadcrumbs})}}}maybeConvertSingularAllOfReferenceObject(){if(this.context.isReferenceObject(this.schemaOrReference)||this.schemaOrReference.allOf==null)return;if(this.schemaOrReference.allOf.length===1){let i=this.schemaOrReference.allOf[0];if(this.context.isReferenceObject(i)){let o=this.context.convertReferenceToTypeReference({reference:i,breadcrumbs:this.breadcrumbs});if(o.ok)return{type:this.wrapTypeReference(o.reference),inlinedTypes:o.inlinedTypes??{},availability:this.getAvailabilityOfSelfOrReference(i)}}return}let t=this.schemaOrReference.allOf.filter(i=>this.context.isReferenceObject(i)),r=this.schemaOrReference.allOf.filter(i=>typeof i=="object"&&i!==null&&!this.context.isReferenceObject(i)),n=t.length===1?t[0]:void 0;if(n!=null&&r.every(i=>wGm(i))){let i=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:this.breadcrumbs});if(i!=null&&i.type!=="object"&&!i.properties&&!i.allOf&&!i.oneOf&&!i.anyOf&&!i.format){let o=this.context.convertReferenceToTypeReference({reference:n,breadcrumbs:this.breadcrumbs});if(o.ok)return{type:this.wrapTypeReference(o.reference),inlinedTypes:o.inlinedTypes??{},availability:this.getAvailabilityOfSelfOrReference(n)}}}}getAvailabilityOfSelfOrReference(t){for(let r of[...this.getSelfAndInlineAllOfElements(),t]){let n=this.context.getAvailability({node:r,breadcrumbs:this.breadcrumbs});if(n!=null)return n}}getSelfAndInlineAllOfElements(){return this.context.isReferenceObject(this.schemaOrReference)||this.schemaOrReference.allOf==null?[this.schemaOrReference]:[this.schemaOrReference,...this.schemaOrReference.allOf.filter(t=>!this.context.isReferenceObject(t))]}convertSchemaObject({schema:t}){let r=this.schemaIdOverride??this.context.convertBreadcrumbsToName(this.breadcrumbs),n=this.context.getNamespacedSchemaId(r),i=new RSe({context:this.context,breadcrumbs:this.breadcrumbs,schema:t,id:r}),o=this.context.getAvailability({node:t,breadcrumbs:this.breadcrumbs}),s=i.convert();if(s!=null){let a=s.convertedSchema.typeDeclaration.shape;return a.type==="alias"?{type:this.wrapTypeReference(a.aliasOf),schema:s.convertedSchema,inlinedTypes:s.inlinedTypes,availability:o}:{type:this.wrapTypeReference(this.context.createNamedTypeReference(r)),schema:s.convertedSchema,inlinedTypes:{...s.inlinedTypes,[n]:s.convertedSchema},availability:o}}}wrapTypeReference(t){return this.wrapAsOptional&&this.wrapAsNullable?this.wrapInOptional(this.wrapInNullable(t)):this.wrapAsOptional?this.wrapInOptional(t):this.wrapAsNullable?this.wrapInNullable(t):t}wrapInOptional(t){return Hr.container(As.optional(t))}wrapInNullable(t){return Hr.container(As.nullable(t))}},SGm=new Set(["description","title","deprecated","readOnly","writeOnly","xml","externalDocs","x-fern-type-name"])});function xUe({properties:e,required:t,breadcrumbs:r,context:n,errorCollector:i,withinXmlElement:o=!1}){let s=[],a={},c={},l=new Set;for(let[u,p]of Object.entries(e??{})){let d=[...r,"properties",u];if(typeof p!="object"){i.collect({message:`Schema property ${u} should be an object`,path:d});continue}let f=OGm(r,p,n)??n.convertBreadcrumbsToName(d),m="nullable"in p?p.nullable:!1,A=new NT({context:n,breadcrumbs:d,schemaOrReference:p,schemaIdOverride:f,wrapAsOptional:!t.includes(u),wrapAsNullable:m}).convert();if(A!=null){let b=n.resolveMaybeReference({schemaOrReference:p,breadcrumbs:d,skipErrorCollector:!0});s.push({name:n.casingsGenerator.generateNameAndWireValue({name:u,wireValue:u}),valueType:A.type,docs:p.description??A.schema?.typeDeclaration.docs,availability:A.availability,propertyAccess:n.getPropertyAccess(p),defaultValue:b?.default,xml:o?new Fct({breadcrumbs:d,propertySchema:p,resolvedPropertySchema:b??void 0,context:n}).convert():void 0,v2Examples:A.schema?.typeDeclaration?.v2Examples??TGm({propertySchema:p,breadcrumbs:d,context:n,propertyId:f})}),a={...a,...A.inlinedTypes},A.schema?.typeDeclaration.referencedTypes!=null&&A.schema.typeDeclaration.referencedTypes.forEach(I=>{l.add(I)}),c3(A.type,l);for(let I of A.schema?.audiences??[])c[I]==null&&(c[I]=new Set),c[I].add(u)}}for(let u of Object.keys(a))l.add(u);return{convertedProperties:s,propertiesByAudience:c,inlinedTypesFromProperties:a,referencedTypes:l}}function TGm({propertySchema:e,breadcrumbs:t,context:r,propertyId:n}){let i=r.resolveMaybeReference({schemaOrReference:e,breadcrumbs:t,skipErrorCollector:!0}),o=r.getExamplesFromSchema({schema:i??void 0,breadcrumbs:t});if(o.length>0){let l={};for(let[u,p]of o.entries()){let d=r.resolveExample(p),f=`${n}_example_${u}`,m=new Bw({breadcrumbs:t,context:r,schema:e,example:d}),{validExample:g}=m.convert();l[f]=g}return{userSpecifiedExamples:l,autogeneratedExamples:{}}}let s=`${n}_example_autogenerated`,a=new Bw({breadcrumbs:t,context:r,schema:e,example:void 0,generateOptionalProperties:!0}),{validExample:c}=a.convert();return{userSpecifiedExamples:{},autogeneratedExamples:{[s]:c}}}function OGm(e,t,r){return r.isReferenceObject(t)?void 0:new vC.FernTypeNameExtension({breadcrumbs:e,schema:t,context:r}).convert()}function c3(e,t){switch(e.type){case"named":t.add(e.typeId);return;case"primitive":case"unknown":return;case"container":PGm(e.container,t);return}}function PGm(e,t){switch(e.type){case"list":c3(e.list,t);return;case"set":c3(e.set,t);return;case"optional":c3(e.optional,t);return;case"nullable":c3(e.nullable,t);return;case"map":c3(e.keyType,t),c3(e.valueType,t);return;case"literal":return}}var Nct=h(()=>{"use strict";BSe();CUe();cKr();Uo()});var Qct,jGo=h(()=>{"use strict";zn();Uo();Nct();CUe();Qct=class e extends Ki{static LIST_UNKNOWN=Hr.container(As.list(Hr.unknown()));schema;constructor({context:t,breadcrumbs:r,schema:n}){super({context:t,breadcrumbs:r}),this.schema=n}convert(){if(this.schema.items!=null){Array.isArray(this.schema.items)&&(this.schema.items={oneOf:this.schema.items});let r=new NT({context:this.context,breadcrumbs:[...this.breadcrumbs,"items"],schemaOrReference:this.schema.items}).convert();if(r!=null){let n=new Set;for(let i of r.schema?.typeDeclaration.referencedTypes??[])n.add(i);return r.inlinedTypes!=null&&Object.values(r.inlinedTypes).forEach(i=>{i.typeDeclaration.referencedTypes.forEach(o=>{n.add(o)})}),c3(r.type,n),{typeReference:Hr.container(As.list(r.type)),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}}});var zGo={};ne(zGo,{ArraySchemaConverter:()=>Qct,EnumSchemaConverter:()=>DSe,ObjectSchemaConverter:()=>jct,OneOfSchemaConverter:()=>SUe,PrimitiveSchemaConverter:()=>zct,SchemaConverter:()=>RSe,SchemaOrReferenceConverter:()=>NT});var QGo=h(()=>{"use strict";jGo();lKr();kGo();FGo();NGo();pKr();CUe()});var fKr,KWl=h(()=>{"use strict";xo();Uo();BSe();QGo();fKr=class extends Ki{group;method;constructor({context:t,breadcrumbs:r,group:n,method:i}){super({context:t,breadcrumbs:r}),this.group=n,this.method=i}parseMediaTypeObject({mediaTypeObject:t,resolveSchema:r,contentType:n,schemaId:i}){if(t.schema==null)return;if(r){let c=this.context.resolveMaybeReference({schemaOrReference:t.schema,breadcrumbs:[...this.breadcrumbs,"content",n]});if(c==null)return;t.schema=c}let s=new NT({context:this.context,breadcrumbs:[...this.breadcrumbs,"content",n,"schema"],schemaOrReference:t.schema,schemaIdOverride:i}).convert();if(s==null)return;let a=t.examples!=null?Object.fromEntries(Object.entries(t.examples).map(([c,l])=>{if(this.context.isReferenceObject(l)){let u=this.context.resolveReference({reference:l,breadcrumbs:[...this.breadcrumbs,"content",n,"examples"],skipErrorCollector:!0});return u.resolved?[c,u.value.value??u.value]:null}return[c,l.value??l]}).filter(c=>c!=null)):void 0;return{...s,examples:a}}parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:r}){let i=new NT({context:this.context,breadcrumbs:[...this.breadcrumbs],schemaOrReference:t,schemaIdOverride:r}).convert();if(i!=null)return{...i,examples:void 0}}getIdForExample({key:t,example:r,usedExampleNames:n}){if(this.context.isExampleWithSummary(r)){let i=r.summary;if(!n.has(i))return i;let o=`${i} (${t})`;return n.has(o)?t:o}return t}convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:r,exampleGenerationStrategy:n}){let i={userSpecifiedExamples:{},autogeneratedExamples:{}},o=t?.schema,s=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_example`}),a=new Set;for(let[c,l]of s){let u=this.context.resolveExampleWithValue(l),p=this.context.resolveExampleRecursively({example:l,breadcrumbs:this.breadcrumbs}),d=this.getIdForExample({key:c,example:p,usedExampleNames:a});a.add(d),u!=null&&(o!=null?i.userSpecifiedExamples[d]=this.generateOrValidateExample({schema:o,example:u,exampleGenerationStrategy:n,exampleName:d}):i.userSpecifiedExamples[d]=u)}if(o!=null&&Object.keys(i.userSpecifiedExamples).length===0){let c=this.getExamplesFromSchemaOrReference(o);c.length>1&&c.forEach((l,u)=>{let p=`Example ${u+1}`;i.userSpecifiedExamples[p]=this.generateOrValidateExample({schema:o,example:l,exampleGenerationStrategy:n,exampleName:p})})}if(Object.keys(i.userSpecifiedExamples).length===0&&o!=null){let c=ao(`${[...this.group,this.method].join("_")}_example`);i.autogeneratedExamples[c]=this.generateOrValidateExample({schema:o,example:void 0,ignoreErrors:!0,generateOptionalProperties:r,exampleGenerationStrategy:n,exampleName:c})}return i}getExamplesFromSchemaOrReference(t){let r=new Set,n=t;for(;this.context.isReferenceObject(n);){if(r.has(n.$ref))return[];r.add(n.$ref);let i=this.context.resolveReference({reference:n,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(!i.resolved)return[];n=i.value}return this.context.getExamplesFromSchema({schema:n,breadcrumbs:this.breadcrumbs})}generateOrValidateExample({schema:t,example:r,generateOptionalProperties:n,exampleGenerationStrategy:i}){let o=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(o==null)return;let s=this.context.getExamplesFromSchema({schema:o,breadcrumbs:this.breadcrumbs}),a=new Bw({breadcrumbs:this.breadcrumbs,context:this.context,schema:o,example:r??s[0],generateOptionalProperties:n??!1,exampleGenerationStrategy:i}),{validExample:c}=a.convert();return c}}});var dKr,JWl=h(()=>{"use strict";Uo();BSe();dKr=class extends Ki{parameter;constructor({context:t,breadcrumbs:r,parameter:n}){super({context:t,breadcrumbs:r}),this.parameter=n}convertToOutput({schema:t,typeReference:r,inlinedTypes:n}){let i=this.context.getAvailability({node:this.parameter,breadcrumbs:this.breadcrumbs}),o=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs}),s=this.getParameterSchemaWithExampleOverride({schema:o}),a=o?.default,c=this.getParameterDescription({schema:t});switch(this.parameter.in){case"query":return{type:"query",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:c,valueType:r??Ki.OPTIONAL_STRING,allowMultiple:this.parameter.explode??!1,clientDefault:void 0,defaultValue:a,v2Examples:this.convertParameterExamples({schema:s??t,originalSchema:t}),availability:i,explode:this.getExplodeForQueryParameter()},inlinedTypes:n};case"header":return{type:"header",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:c,valueType:r??Ki.OPTIONAL_STRING,env:void 0,clientDefault:void 0,defaultValue:a,v2Examples:this.convertParameterExamples({schema:s??t,originalSchema:t}),availability:i},inlinedTypes:n};case"path":return{type:"path",parameter:{name:this.context.casingsGenerator.generateName(this.parameter.name),docs:c,valueType:r??Ki.STRING,location:"ENDPOINT",variable:void 0,clientDefault:void 0,v2Examples:this.convertParameterExamples({schema:s??t,originalSchema:t}),explode:this.getExplodeForPathParameter()},inlinedTypes:n};default:return}}getParameterDescription({schema:t}){if(this.parameter.description!=null)return this.parameter.description;if("description"in t&&typeof t.description=="string")return t.description}getParameterSchemaWithExampleOverride({schema:t}){if(t!=null)return t.type==="string"&&t.example==null?{...t,example:this.parameter.name}:t}convertParameterExamples({schema:t,originalSchema:r}){let n={userSpecifiedExamples:{},autogeneratedExamples:{}},i=this.parameter.example,o=this.parameter.examples;for(let[s,a]of Object.entries(o??{})){let c=this.context.resolveExampleWithValue(a);c!=null&&(n.userSpecifiedExamples[s]=this.generateOrValidateExample({schema:t,example:c,exampleName:s}))}if(i!=null){let s=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(n.userSpecifiedExamples)});n.userSpecifiedExamples[s]=this.generateOrValidateExample({schema:t,example:i,exampleName:s})}if(Object.keys(n.userSpecifiedExamples).length===0){let s=this.context.getExamplesFromSchema({schema:this.resolveSchemaChain(r),breadcrumbs:this.breadcrumbs});for(let a of s){let c=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(n.userSpecifiedExamples)});n.userSpecifiedExamples[c]=this.generateOrValidateExample({schema:t,example:this.context.resolveExample(a),exampleName:c})}}if(Object.keys(n.userSpecifiedExamples).length===0){let s=`${this.parameter.name}_example`;n.autogeneratedExamples[s]=this.generateOrValidateExample({schema:t,example:void 0,ignoreErrors:!0,exampleName:s})}return n}resolveSchemaChain(t){let r=new Set,n=t;for(;this.context.isReferenceObject(n);){if(r.has(n.$ref))return;r.add(n.$ref);let i=this.context.resolveReference({reference:n,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(!i.resolved)return;n=i.value}return n}generateOrValidateExample({schema:t,example:r}){let n=new Bw({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:r}),{validExample:i}=n.convert();return i}getExplodeForQueryParameter(){let t=this.parameter.style??"form",r=this.parameter.explode;if(r!==void 0)return t==="form"||t==="deepObject"?r===!0?void 0:r:r===!1?void 0:r}getExplodeForPathParameter(){let t=this.parameter.explode;if(t!==void 0)return t===!1?void 0:t}}});var MGo={};ne(MGo,{AbstractMediaTypeObjectConverter:()=>fKr,AbstractParameterConverter:()=>dKr});var YWl=h(()=>{"use strict";KWl();JWl()});function Mct({context:e,breadcrumbs:t,headers:r}){let n=[],i={},o=t??[];if(r==null)return{headers:n,inlinedTypes:i};for(let[s,a]of Object.entries(r)){let c=e.resolveMaybeReference({schemaOrReference:a,breadcrumbs:[...o,"headers",s]});if(c==null)continue;let l=BGm({context:e,header:c}),u=l?.schema,p=c.required===!0,d=b=>p?b:Hr.container(As.optional(b)),f=d(Ki.STRING),m,g=e.getAvailability({node:c,breadcrumbs:[...o,"headers",s]});if(u!=null)if(m=e.resolveMaybeReference({schemaOrReference:u,breadcrumbs:[...o,"headers",s,"schema"]}),m?.type==="number"||m?.type==="integer")f=d(Hr.primitive({v1:m.type==="integer"?"INTEGER":"DOUBLE",v2:m.type==="integer"?di.integer({default:void 0,validation:void 0}):di.double({default:void 0,validation:void 0})}));else if(m?.type==="boolean")f=d(Hr.primitive({v1:"BOOLEAN",v2:di.boolean({default:void 0})}));else{let b=new NT({context:e,breadcrumbs:[...o,"headers",s,"schema"],schemaOrReference:u,wrapAsOptional:!p,schemaIdOverride:e.convertBreadcrumbsToName([...o,"headers",s])}).convert();if(b!=null){f=b.type;for(let[I,C]of Object.entries(b.inlinedTypes))i[I]=C}}let A=DGm({context:e,breadcrumbs:o,header:c,headerName:s,schema:u,mediaTypeObject:l?.mediaTypeObject});n.push({name:e.casingsGenerator.generateNameAndWireValue({name:s,wireValue:s}),docs:c.description,valueType:f,env:void 0,v2Examples:A,availability:g,clientDefault:void 0,defaultValue:m?.default})}return{headers:n,inlinedTypes:i}}function BGm({context:e,header:t}){if(t.schema!=null)return{schema:t.schema};if(!(!e.settings.respectParameterContent||t.content==null)){for(let[r,n]of Object.entries(t.content))if(n.schema!=null&&gp.parse(r)?.isJSON())return{schema:n.schema,mediaTypeObject:n}}}function DGm({context:e,breadcrumbs:t,header:r,headerName:n,schema:i,mediaTypeObject:o}){let s={userSpecifiedExamples:{},autogeneratedExamples:{}},a=r.example,c=r.examples;for(let[l,u]of Object.entries(c??{})){let p=e.resolveExampleWithValue(u);p!=null&&(s.userSpecifiedExamples[l]=xGt({context:e,breadcrumbs:t,schema:i,example:p}))}if(a!=null){let l=e.generateUniqueName({prefix:`${n}_example`,existingNames:Object.keys(s.userSpecifiedExamples)});s.userSpecifiedExamples[l]=xGt({context:e,breadcrumbs:t,schema:i,example:a})}if(Object.keys(s.userSpecifiedExamples).length===0&&o!=null)for(let[l,u]of e.getNamedExamplesFromMediaTypeObject({mediaTypeObject:o,breadcrumbs:[...t,"headers",n,"content"],defaultExampleName:`${n}_example`})){let p=e.resolveExampleWithValue(u);if(p!=null){let d=e.generateUniqueName({prefix:l,existingNames:Object.keys(s.userSpecifiedExamples)});s.userSpecifiedExamples[d]=xGt({context:e,breadcrumbs:t,schema:i,example:p})}}if(Object.keys(s.userSpecifiedExamples).length===0&&i!=null){let l=e.getExamplesFromSchema({schema:RGm({context:e,schema:i,breadcrumbs:[...t,"headers",n,"schema"]}),breadcrumbs:[...t,"headers",n,"schema"]});for(let u of l){let p=e.generateUniqueName({prefix:`${n}_example`,existingNames:Object.keys(s.userSpecifiedExamples)});s.userSpecifiedExamples[p]=xGt({context:e,breadcrumbs:t,schema:i,example:e.resolveExample(u)})}}if(Object.keys(s.userSpecifiedExamples).length===0&&i!=null){let l=`${n}_example`;s.autogeneratedExamples[l]=xGt({context:e,breadcrumbs:t,schema:i,example:void 0,ignoreErrors:!0})}return s}function RGm({context:e,schema:t,breadcrumbs:r}){let n=new Set,i=t;for(;e.isReferenceObject(i);){if(n.has(i.$ref))return;n.add(i.$ref);let o=e.resolveReference({reference:i,breadcrumbs:r,skipErrorCollector:!0});if(!o.resolved)return;i=o.value}return i}function xGt({context:e,breadcrumbs:t,schema:r,example:n,ignoreErrors:i}){if(r==null)return n;let o=new Bw({breadcrumbs:t,context:e,schema:r,example:n}),{validExample:s,errors:a}=o.convert();return i||a.forEach(c=>{e.errorCollector.collect({message:c.message,path:c.path})}),s}var XWl=h(()=>{"use strict";mt();zn();$Hr();BSe();CUe()});var mKr,ZWl=h(()=>{"use strict";AR();mKr=class extends Vo{server;key="x-fern-server-name";constructor({breadcrumbs:t,server:r,context:n}){super({breadcrumbs:t,context:n}),this.server=r}convert(){let t=this.getExtensionValue(this.server,"x-name");if(!(t==null||typeof t!="string"))return t}}});var $Wl,kGm,l3,e7l=h(()=>{"use strict";mt();zn();wGo();ZWl();Uo();$Wl="Base",kGm="x-fern-default-url",l3=class e extends Ki{servers;endpointLevelServers;baseUrlEnvVar;constructor({breadcrumbs:t,context:r,servers:n,endpointLevelServers:i,baseUrlEnvVar:o}){super({breadcrumbs:t,context:r}),this.servers=n,this.endpointLevelServers=i,this.baseUrlEnvVar=o}convert(){if(this.servers==null||this.servers.length===0||this.servers[0]==null)return;if(this.endpointLevelServers!=null&&this.endpointLevelServers.length>0){let n=this.getDefaultBaseUrlName(),i={id:n,name:this.context.casingsGenerator.generateName(n)},o=this.endpointLevelServers.map(c=>{let l=e.getServerName({server:c,context:this.context});return{id:l,name:this.context.casingsGenerator.generateName(l)}}).filter((c,l,u)=>u.findIndex(p=>p.id===c.id)===l),s=[i,...o],a=this.servers.map(c=>{let l=e.getServerName({server:c,context:this.context}),u=this.endpointLevelServers?.map(g=>[e.getServerName({server:g,context:this.context}),this.getServerUrl(g)]),p=e.getServerAudiences({server:c,context:this.context}),{defaultUrls:d,urlTemplates:f,urlVariables:m}=this.buildMultiUrlTemplateFields({defaultBaseUrlId:n,topLevelServer:c,endpointServers:this.endpointLevelServers??[]});return{id:l,name:this.context.casingsGenerator.generateName(l),urls:{[n]:this.getServerUrl(c),...Object.fromEntries(u??[])},docs:c.description,audiences:p,defaultUrls:d,urlTemplates:f,urlVariables:m}});return{value:{defaultEnvironment:a[0]?.id,baseUrlEnvVar:this.baseUrlEnvVar,environments:DE.multipleBaseUrls({baseUrls:s,environments:a})},defaultUrl:i.id}}let t=this.extractFernDefaultUrl(),r=this.servers.map(n=>{let i=e.getServerName({server:n,context:this.context}),o=e.getServerAudiences({server:n,context:this.context});return n.variables!=null&&Object.keys(n.variables).length>0&&n.variables!=null?{id:i,name:this.context.casingsGenerator.generateName(i),url:this.maybeRemoveTrailingSlashIfNotEmpty(this.getServerUrl(n)),audiences:o,defaultUrl:t,urlTemplate:this.maybeRemoveTrailingSlashIfNotEmpty(n.url),urlVariables:this.convertServerVariables(n.variables),docs:n.description}:{id:i,name:this.context.casingsGenerator.generateName(i),url:this.maybeRemoveTrailingSlashIfNotEmpty(this.getServerUrl(n)),audiences:o,defaultUrl:void 0,urlTemplate:void 0,urlVariables:void 0,docs:n.description}}).filter(gs);return{value:{defaultEnvironment:r[0]?.id,baseUrlEnvVar:this.baseUrlEnvVar,environments:DE.singleBaseUrl({environments:r})},defaultUrl:r[0]?.id}}convertServerVariables(t){return Object.entries(t).map(([r,n])=>({id:r,name:this.context.casingsGenerator.generateName(r),default:n.default,values:n.enum}))}static getServerExtensionName({server:t,context:r}){return new mKr({breadcrumbs:[],server:t,context:r}).convert()}static getServerAudiences({server:t,context:r}){return new Pct({breadcrumbs:[],operation:t,context:r}).convert()?.audiences}static getServerName({server:t,context:r}){return t.name!=null?t.name:e.getServerExtensionName({server:t,context:r})??t.description??t.url}getServerUrl(t){if(t.variables==null)return t.url;let r=t.url;for(let[n,i]of Object.entries(t.variables))i.default!=null&&(r=r.replace(`{${n}}`,encodeURIComponent(i.default)));return r}getDefaultBaseUrlName(){return this.servers==null||this.servers.length===0||this.servers[0]==null?$Wl:e.getServerExtensionName({server:this.servers[0],context:this.context})??$Wl}maybeRemoveTrailingSlashIfNotEmpty(t){return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}buildMultiUrlTemplateFields({defaultBaseUrlId:t,topLevelServer:r,endpointServers:n}){let i={},o={},s={},a=!1;if(r.variables!=null&&Object.keys(r.variables).length>0){a=!0;let c=this.extractFernDefaultUrlFromServer(r);c!=null&&(i[t]=c),o[t]=this.maybeRemoveTrailingSlashIfNotEmpty(r.url),s[t]=this.convertServerVariables(r.variables)}for(let c of n){let l=e.getServerName({server:c,context:this.context});if(c.variables!=null&&Object.keys(c.variables).length>0){a=!0;let u=this.extractFernDefaultUrlFromServer(c);u!=null&&(i[l]=u),o[l]=this.maybeRemoveTrailingSlashIfNotEmpty(c.url),s[l]=this.convertServerVariables(c.variables)}}return a?{defaultUrls:Object.keys(i).length>0?i:void 0,urlTemplates:o,urlVariables:s}:{defaultUrls:void 0,urlTemplates:void 0,urlVariables:void 0}}extractFernDefaultUrlFromServer(t){let r=t[kGm];if(typeof r=="string")return this.maybeRemoveTrailingSlashIfNotEmpty(r)}extractFernDefaultUrl(){if(this.servers!=null)for(let t of this.servers){let r=this.extractFernDefaultUrlFromServer(t);if(r!=null)return r}}}});var Tm={};ne(Tm,{AbstractConverters:()=>MGo,ExampleConverter:()=>Bw,SchemaConverters:()=>zGo,ServersConverter:()=>l3,convertResponseHeaders:()=>Mct});var LGo=h(()=>{"use strict";YWl();BSe();XWl();QGo();e7l()});var SGt,t7l=h(()=>{"use strict";BSe();CGt();SGt=class{context;constructor({context:t}){this.context=t}validateExample({example:t,schema:r,breadcrumbs:n,exampleGenerationStrategy:i}){return new Bw({breadcrumbs:n,context:this.context,schema:r,example:t,depth:0,exampleGenerationStrategy:i,generateOptionalProperties:!1}).convert()}validateEndpointExample({exampleToValidate:t}){let r=[],n=[],i=!0,o=!1,s,a=[t.endpointPath,t.method];if(t.requestExample!==void 0&&t.requestSchema!==void 0){let l=this.validateExample({example:t.requestExample,schema:t.requestSchema,breadcrumbs:[...a,"request"],exampleGenerationStrategy:"request"});if(!l.isValid){i=!1;let u=t.exampleSource==="human"?HE.WARNING:HE.ERROR;r.push(...l.errors.map(p=>({...p,level:u,message:`Invalid request example: ${p.message}`})))}l.coerced&&(o=!0,n.push({level:HE.WARNING,message:"Request example was coerced to match schema",path:[...a,"request"]})),s={request:l.validExample}}let c=this.getResponseSchemaForValidation(t);if(t.responseExample!==void 0&&c!==void 0){let l=this.validateExample({example:t.responseExample,schema:c,breadcrumbs:[...a,"response"],exampleGenerationStrategy:"response"});if(!l.isValid){i=!1;let u=t.exampleSource==="human"?HE.WARNING:HE.ERROR;r.push(...l.errors.map(p=>({...p,level:u,message:`Invalid response example: ${p.message}`})))}l.coerced&&(o=!0,n.push({level:HE.WARNING,message:"Response example was coerced to match schema",path:[...a,"response"]})),s={...typeof s=="object"&&s!==null?s:{},response:l.validExample}}return{isValid:i,errors:r,warnings:n,endpointPath:t.endpointPath,method:t.method,exampleSource:t.exampleSource,exampleName:t.exampleName,validExample:s,coerced:o}}getResponseSchemaForValidation(t){let{responseStatusCode:r,responseSchemas:n,responseSchema:i}=t;return n&&Object.keys(n).length>0?r&&n[r]?n[r]:n[200]??n[201]:i}validateAiExamples({aiExamples:t,spec:r}){let n=[],i=[];for(let o of t){let{requestSchema:s,responseSchema:a,responseSchemas:c}=this.getSchemasForEndpoint({spec:r,endpointPath:o.endpointPath,method:o.method}),l={endpointPath:o.endpointPath,method:o.method,exampleSource:"ai",requestExample:o.request?.body,responseExample:o.response?.body,requestSchema:s,responseSchema:a,responseSchemas:c},u=this.validateEndpointExample({exampleToValidate:l}),p=this.hasUnexpectedProperties({requestExample:o.request?.body,responseExample:o.response?.body,requestSchema:s,responseSchema:a}),d=u.errors.length>0||u.warnings.length>0;!u.isValid||d||p?i.push({example:o,validationResult:u}):n.push(o)}return{validExamples:n,invalidExamples:i}}hasUnexpectedProperties({requestExample:t,responseExample:r,requestSchema:n,responseSchema:i}){return!!(t&&n&&this.exampleHasUnexpectedProperties(t,n)||r&&i&&this.exampleHasUnexpectedProperties(r,i))}exampleHasUnexpectedProperties(t,r){if(!t||typeof t!="object"||t===null)return!1;let n=this.context.resolveMaybeReference({schemaOrReference:r,breadcrumbs:[],skipErrorCollector:!0});if(!n||!n.properties&&!n.allOf&&!n.oneOf&&!n.anyOf||this.schemaHasPatternProperties(n))return!1;let i=t,o=this.collectAllPropertyKeys(n);return Object.keys(i).some(a=>!o.has(a))}collectAllPropertyKeys(t,r=new Set){let n=new Set;if(t.properties)for(let i of Object.keys(t.properties))n.add(i);for(let i of t.allOf??[]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:[],skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)){r.add(s);let a=this.collectAllPropertyKeys(o,r);for(let c of a)n.add(c)}}}for(let i of[...t.oneOf??[],...t.anyOf??[]]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:[],skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)){r.add(s);let a=this.collectAllPropertyKeys(o,r);for(let c of a)n.add(c)}}}return n}schemaHasPatternProperties(t,r=new Set){let n=t.patternProperties;if(n&&typeof n=="object"&&Object.keys(n).length>0)return!0;for(let i of[...t.allOf??[],...t.oneOf??[],...t.anyOf??[]]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:[],skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)&&(r.add(s),this.schemaHasPatternProperties(o,r)))return!0}}return!1}validateHumanExamples({spec:t}){let r=[],n=0,i=0,o=0,s=[],a=[];if(!t.paths)return{endpoints:r,totalExamples:n,validExamples:i,invalidExamples:o,hasInvalidHumanExamples:!1,hasInvalidAiExamples:!1,invalidHumanExamples:s,invalidAiExamples:a};for(let[c,l]of Object.entries(t.paths)){if(!l)continue;let u=["get","post","put","delete","patch","options","head","trace"];for(let p of u){let d=l[p];if(!d)continue;let f=[],{requestSchema:m,responseSchema:g,responseSchemas:A}=this.getSchemasForOperation({operation:d}),b=this.extractExamplesFromOperation({operation:d,path:c,method:p});for(let I of b){n++;let C={endpointPath:c,method:p,exampleName:I.name,exampleSource:I.source,requestExample:I.request,responseExample:I.response,requestSchema:m,responseSchema:g,responseStatusCode:I.statusCode,responseSchemas:A},x=this.validateEndpointExample({exampleToValidate:C});f.push(x),x.isValid?i++:(o++,I.source==="human"?s.push(x):I.source==="ai"&&a.push(x))}f.length>0&&r.push({endpointPath:c,method:p,results:f,hasInvalidExamples:f.some(I=>!I.isValid),invalidExampleCount:f.filter(I=>!I.isValid).length})}}return{endpoints:r,totalExamples:n,validExamples:i,invalidExamples:o,hasInvalidHumanExamples:s.length>0,hasInvalidAiExamples:a.length>0,invalidHumanExamples:s,invalidAiExamples:a}}getSchemasForEndpoint({spec:t,endpointPath:r,method:n}){let i=t.paths?.[r];if(!i)return{responseSchemas:{}};let o=i[n.toLowerCase()];return!o||typeof o!="object"||!("responses"in o)?{responseSchemas:{}}:this.getSchemasForOperation({operation:o})}getSchemasForOperation({operation:t}){let r,n,i={};if(t.requestBody&&!this.context.isReferenceObject(t.requestBody)){let s=t.requestBody.content?.["application/json"];s?.schema&&(r=s.schema)}if(t.responses){for(let[o,s]of Object.entries(t.responses)){if(!s||this.context.isReferenceObject(s))continue;let c=s.content?.["application/json"];c?.schema&&(i[o]=c.schema)}n=i[200]??i[201]}return{requestSchema:r,responseSchema:n,responseSchemas:i}}extractExamplesFromOperation({operation:t,path:r,method:n}){let i=[];if(t.requestBody&&!this.context.isReferenceObject(t.requestBody)){let a=t.requestBody.content?.["application/json"];if(a?.example!==void 0&&i.push({name:`${n}_${r}_request_example`,source:"openapi",request:a.example}),a?.examples)for(let[c,l]of Object.entries(a.examples)){let u=this.context.isReferenceObject(l)?this.context.resolveExample(l):l;u&&typeof u=="object"&&"value"in u&&i.push({name:c,source:"human",request:u.value})}}if(t.responses)for(let[s,a]of Object.entries(t.responses)){if(!a||this.context.isReferenceObject(a))continue;let l=a.content?.["application/json"];if(l?.example!==void 0){let u=i.find(p=>p.request!==void 0&&p.response===void 0);u?(u.response=l.example,u.statusCode=s):i.push({name:`${n}_${r}_response_${s}_example`,source:"openapi",response:l.example,statusCode:s})}if(l?.examples)for(let[u,p]of Object.entries(l.examples)){let d=this.context.isReferenceObject(p)?this.context.resolveExample(p):p;if(d&&typeof d=="object"&&"value"in d){let f=i.find(m=>m.name===u);f?(f.response=d.value,f.statusCode=s):i.push({name:u,source:"human",response:d.value,statusCode:s})}}}let o=t["x-fern-examples"];if(Array.isArray(o)){for(let s of o)if(typeof s=="object"&&s!==null){let a=s;i.push({name:a.name,source:"human",request:a.request?.body,response:a.response?.body})}}return i}}});function r7l({tags:e,errorCollector:t}){for(let r of e)if(Lct.test(r.name)){let n=[...r.name].filter(i=>Lct.test(i));t.collect({level:HE.ERROR,message:`Tag name "${r.name}" contains non-ASCII characters: ${n.join(", ")}. Non-ASCII characters in tag names will be included in URL paths and HTTP headers, which only support ASCII characters. This will cause runtime errors (ERR_INVALID_CHAR).`,path:["tags",r.name],resolution:`Remove non-ASCII characters from the tag name. For example, rename "${r.name}" to "${r.name.replace(Lct,"").trim()}".`})}}function n7l({description:e,path:t,errorCollector:r}){FGm.test(e)&&r.collect({level:HE.ERROR,message:'Description contains "---" frontmatter delimiters which will cause YAML parsing failures in the generated docs site. The docs renderer interprets content between "---" delimiters as YAML frontmatter, which will fail if the content is not valid YAML.',path:t,resolution:'Remove the "---" delimiters from the description.'})}function _Go({spec:e,errorCollector:t}){if(Array.isArray(e.tags)){let n=e.tags.filter(i=>typeof i=="object"&&i!=null&&"name"in i&&typeof i.name=="string");r7l({tags:n,errorCollector:t})}let r=["get","post","put","delete","patch","options","head","trace"];if(e.paths!=null&&typeof e.paths=="object"){let n=new Set;for(let[i,o]of Object.entries(e.paths)){if(o==null||typeof o!="object")continue;let s=o;for(let a of r){let c=s[a];if(c==null||typeof c!="object")continue;let l=c;if(typeof l.description=="string"&&n7l({description:l.description,path:["paths",i,a,"description"],errorCollector:t}),Array.isArray(l.tags)&&!Array.isArray(e.tags)){for(let u of l.tags)if(typeof u=="string"&&!n.has(u)&&Lct.test(u)){n.add(u);let p=[...u].filter(d=>Lct.test(d));t.collect({level:HE.ERROR,message:`Tag name "${u}" contains non-ASCII characters: ${p.join(", ")}. Non-ASCII characters in tag names will be included in URL paths and HTTP headers, which only support ASCII characters. This will cause runtime errors (ERR_INVALID_CHAR).`,path:["paths",i,a,"tags"],resolution:`Remove non-ASCII characters from the tag name. For example, rename "${u}" to "${u.replace(Lct,"").trim()}".`})}}}}}}var Lct,FGm,i7l=h(()=>{"use strict";CGt();Lct=new RegExp("[^\\x00-\\x7F]"),FGm=/(?:^|\n)\s*---\s*(?:\n|$)/});var hKr,NGm,o7l=h(()=>{"use strict";hKr={400:"BadRequestError",401:"UnauthorizedError",402:"PaymentRequiredError",403:"ForbiddenError",404:"NotFoundError",405:"MethodNotAllowedError",406:"NotAcceptableError",407:"ProxyAuthenticationRequiredError",408:"RequestTimeoutError",409:"ConflictError",410:"GoneError",411:"LengthRequiredError",412:"PreconditionFailedError",413:"ContentTooLargeError",414:"URITooLongError",415:"UnsupportedMediaTypeError",416:"RangeNotSatisfiableError",417:"ExpectationFailedError",418:"ImATeapotError",419:"AuthenticationTimeoutError",420:"MethodFailureError",421:"MisdirectedRequestError",422:"UnprocessableEntityError",423:"LockedError",424:"FailedDependencyError",425:"TooEarlyError",426:"UpgradeRequiredError",428:"PreconditionError",429:"TooManyRequestsError",430:"RequestHeaderFieldsTooLargeError",431:"RequestHeaderFieldsTooLargeError",444:"NoResponseError",449:"RetryWithError",450:"BlockedByWindowsParentalControlsError",451:"UnavailableForLegalReasonsError",498:"InvalidTokenError",499:"ClientClosedRequestError",500:"InternalServerError",501:"NotImplementedError",502:"BadGatewayError",503:"ServiceUnavailableError",504:"GatewayTimeoutError",505:"HTTPVersionNotSupportedError",506:"VariantAlsoNegotiatesError",507:"InsufficientStorageError",508:"LoopDetectedError",509:"BandwidthLimitExceededError",510:"NotExtendedError",511:"NetworkAuthenticationRequiredError"},NGm=new Set(Object.values(hKr))});function UGo(e){if(e!=null)return e.map(t=>Object.fromEntries(Object.entries(t).map(([r,n])=>[r,n??[]])))}var s7l=h(()=>{"use strict"});var Uo=h(()=>{"use strict";$Hr();bWl();AR();jWl();LGo();LGo();CGt();t7l();DGo();i7l();o7l();s7l()});var jGm,zGm,a7l,c7l=h(()=>{"use strict";nn();jGm=Xt.object({type:Xt.string(),channelId:Xt.string().optional(),messageId:Xt.string(),value:Xt.any()}),zGm=Xt.object({summary:Xt.string().optional(),description:Xt.string().optional(),"query-parameters":Xt.record(Xt.string()).optional(),headers:Xt.record(Xt.string()).optional(),messages:Xt.array(jGm)}),a7l=Xt.array(zGm)});var gKr,l7l=h(()=>{"use strict";Uo();c7l();gKr=class extends Vo{channel;baseDir;key="x-fern-examples";constructor({breadcrumbs:t,channel:r,context:n,baseDir:i}){super({breadcrumbs:t??[],context:n}),this.channel=r,this.baseDir=i}convert(){let t=this.getExtensionValue(this.channel);if(t==null)return;let r=a7l.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-examples extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data.map(n=>({summary:n.summary,description:n.description,queryParameters:n["query-parameters"],headers:n.headers,messages:n.messages.map(i=>({type:i.type,channelId:i.channelId,messageId:i.messageId,value:i.value}))}))}}});var _ct,VGo=h(()=>{"use strict";Uo();l7l();_ct=class extends Ki{channel;channelPath;inlinedTypes={};websocketGroup;constructor({context:t,breadcrumbs:r,websocketGroup:n,channel:i,channelPath:o}){super({context:t,breadcrumbs:r}),this.websocketGroup=n,this.channel=i,this.channelPath=o}convertExamples({fullPath:t,baseUrl:r,asyncApiVersion:n}){let o=new gKr({context:this.context,breadcrumbs:this.breadcrumbs,channel:this.channel,baseDir:this.context.documentBaseDir}).convert();return o==null?{}:Object.fromEntries(o.map((s,a)=>[a.toString(),{channel:{method:"GET",path:t},baseUrl:t,environment:r,auth:void 0,pathParameters:{},queryParameters:s.queryParameters,headers:s.headers,messages:s.messages.map(c=>({type:n==="v2"?c.type:c.messageId,body:c.value}))}]))}transformToValidPath(t){return t.startsWith("/")?t:"/"+t}}});var QGm,rJ,wGt=h(()=>{"use strict";zn();Uo();QGm="x-fern-server-name",rJ=class e extends Ki{servers;constructor({context:t,breadcrumbs:r,servers:n}){super({context:t,breadcrumbs:r}),this.servers=n}convert(){if(this.servers==null||Object.keys(this.servers).length===0)return;let t=[],r;for(let[n,i]of Object.entries(this.servers)){let o=e.getServerName(n,i),s=this.buildSingleBaseUrlEnvironment(this.context,o,i);t.push(s),r==null&&(r=s.id)}return{defaultEnvironment:r,baseUrlEnvVar:void 0,environments:DE.singleBaseUrl({environments:t})}}static getServerName(t,r){if(r!=null&&typeof r=="object"){let n=r[QGm];if(typeof n=="string"&&n.length>0)return n}return t}constructServerUrl(t,r){return r.includes("://")?r:`${t}://${r}`}}});var kSe,GGo=h(()=>{"use strict";Uo();kSe=class extends Tm.AbstractConverters.AbstractParameterConverter{parameterNamePrefix;constructor({context:t,breadcrumbs:r,parameter:n,parameterNamePrefix:i}){super({context:t,breadcrumbs:r,parameter:n}),this.parameterNamePrefix=i}convert(){let t,r={},i=new vC.FernOptionalExtension({breadcrumbs:this.breadcrumbs,parameter:this.parameter,context:this.context}).convert()??this.parameter.required===!1,o=this.parameter.schema??{...this.parameter,type:"string",enum:this.parameter.enum,default:this.parameter.default,example:this.parameter.example??this.parameter.name,examples:Object.values(this.parameter.examples??{}),deprecated:this.parameter.deprecated,required:void 0},a=new Tm.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaIdOverride:this.parameterNamePrefix?`${this.parameterNamePrefix}_${this.parameter.name}`:this.parameter.name,schemaOrReference:o,wrapAsOptional:i}).convert();return a!=null&&(t=a.type,r=a.inlinedTypes??{}),this.convertToOutput({schema:o,typeReference:t,inlinedTypes:r})}}});var AKr,u7l=h(()=>{"use strict";Uo();AKr=class extends Vo{channel;key="x-fern-address";constructor({breadcrumbs:t,channel:r,context:n}){super({breadcrumbs:t,context:n}),this.channel=r}convert(){let t=this.getExtensionValue(this.channel);if(!(t==null||typeof t!="string"))return t}}});var FSe,qGo=h(()=>{"use strict";Uo();FSe=class extends Vo{node;key="x-fern-display-name";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(!(t==null||typeof t!="string"))return t}}});var NSe,WGo=h(()=>{"use strict";Uo();NSe=class extends Vo{node;key="x-fern-explorer";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-explorer",path:this.breadcrumbs});return}return t}}}});var yKr,p7l=h(()=>{"use strict";Uo();yKr=class extends Vo{operation;key="x-fern-sdk-method-name";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(!(t==null||typeof t!="string"))return t}}});var bKr,f7l=h(()=>{"use strict";zn();sc();Uo();xo();VGo();wGt();GGo();u7l();qGo();WGo();p7l();bKr=class extends _ct{inlinedTypes={};constructor({context:t,breadcrumbs:r,websocketGroup:n,channel:i,channelPath:o}){super({context:t,breadcrumbs:r,websocketGroup:n,channel:i,channelPath:o})}convert(){let t=[],r=[],n=[],o=new FSe({breadcrumbs:this.breadcrumbs,node:this.channel,context:this.context}).convert()??this.websocketGroup?.join(".");this.channel.parameters&&this.convertPathParameters({context:this.context,pathParameters:t}),this.channel.bindings?.ws!=null&&(this.convertHeaders({context:this.context,headers:n}),this.convertBindingQueryParameters({context:this.context,queryParameters:r}));let s;this.channel.subscribe!=null&&(s=this.convertMessage({context:this.context,operation:this.channel.subscribe,origin:"server"}));let a;this.channel.publish!=null&&(a=this.convertMessage({context:this.context,operation:this.channel.publish,origin:"client"}));let c=[];s!=null&&c.push(s),a!=null&&c.push(a);let u=new AKr({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert(),p=this.transformToValidPath(u??this.channelPath),d=this.resolveServerName(this.channel.servers?.[0])??this.resolveServerName(Object.keys(this.context.spec.servers??{})[0]),f=jy(p),m=ao(this.channelPath),g=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[],A=this.hasServerSecurity()||this.context.authOverrides?.auth!=null,b=new NSe({context:this.context,breadcrumbs:this.breadcrumbs,node:this.context.spec}).convert(),C=new NSe({context:this.context,breadcrumbs:this.breadcrumbs,node:this.channel}).convert()??b;return{channel:{name:this.context.casingsGenerator.generateName(m),displayName:o,connectMethodName:void 0,baseUrl:d,path:f,auth:A,headers:n,queryParameters:r,pathParameters:t,messages:c,availability:this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({fullPath:p,baseUrl:d,asyncApiVersion:"v2"})},apiPlayground:C},audiences:g,inlinedTypes:this.inlinedTypes}}hasServerSecurity(){let t=this.context.spec.servers??{};if(this.channel.servers&&this.channel.servers.length>0){for(let r of this.channel.servers){let n=t[r];if(n?.security&&n.security.length>0)return!0}return!1}for(let r of Object.values(t)){let n=r;if(n.security&&n.security.length>0)return!0}return!1}convertMessage({context:t,operation:r,origin:n}){let i,o=n==="server"?"subscribe":"publish",s=[...this.breadcrumbs,o],a=t.resolveMaybeReference({schemaOrReference:r.message,breadcrumbs:s});a!=null&&(r.message=a);let c=Qze(ao(`${this.channelPath}_${o}`)).replace(/ /g,"");if("oneOf"in r.message){let u=new Tm.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:s,schemaOrReference:r.message,schemaIdOverride:c}).convert();u!=null&&u.schema!=null&&(i=u.schema,this.inlinedTypes={...this.inlinedTypes,...u.inlinedTypes})}else if(t.isMessageWithPayload(r.message)){let l=t.resolveMaybeReference({schemaOrReference:r.message.payload,breadcrumbs:s});if(l!=null){let p=new Tm.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:s,schemaOrReference:l,schemaIdOverride:c}).convert();p!=null&&p.schema!=null&&(i=p.schema,this.inlinedTypes={...this.inlinedTypes,...p.inlinedTypes})}}if(i!=null){let l=i,u=Hr.named({fernFilepath:t.createFernFilepath(),name:l.typeDeclaration.name.name,typeId:l.typeDeclaration.name.typeId,displayName:void 0,default:void 0,inline:!1}),p=ZP.reference({bodyType:u,docs:r.description}),d=n==="server"?"subscribe":"publish",m=new FSe({breadcrumbs:[...this.breadcrumbs,d],node:r,context:this.context}).convert()??d;return{type:d,displayName:m,origin:n,body:p,availability:t.getAvailability({node:r,breadcrumbs:this.breadcrumbs}),docs:r.description,methodName:this.getOperationMethodName(r)}}}convertPathParameters({context:t,pathParameters:r}){for(let[n,i]of Object.entries(this.channel.parameters??{})){let o=t.resolveMaybeReference({schemaOrReference:i,breadcrumbs:this.breadcrumbs});if(o==null)continue;let a=new kSe({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...o,name:n,in:"path",description:o.description,required:o.required??!0},parameterNamePrefix:this.channelPath}).convert();a!=null&&(this.inlinedTypes={...this.inlinedTypes,...a.inlinedTypes},a.type==="path"&&r.push(a.parameter))}}convertHeaders({context:t,headers:r}){if(this.channel.bindings?.ws?.headers!=null){let n=this.channel.bindings.ws.headers.required??[];for(let[i,o]of Object.entries(this.channel.bindings.ws.headers.properties??{})){let s=t.resolveMaybeReference({schemaOrReference:o,breadcrumbs:[...this.breadcrumbs,i]});if(s==null)continue;let c=new kSe({context:this.context,breadcrumbs:[...this.breadcrumbs,i],parameter:{name:i,in:"header",required:n.includes(i),schema:s,description:"description"in s?s.description:void 0},parameterNamePrefix:this.channelPath}).convert();c!=null&&c.type==="header"&&(this.inlinedTypes={...this.inlinedTypes,...c.inlinedTypes},r.push(c.parameter))}}}resolveServerName(t){if(t==null)return;let r=this.context.spec.servers;if(r!=null&&t in r){let n=r[t];return rJ.getServerName(t,n)}return t}getOperationMethodName(t){return new yKr({breadcrumbs:this.breadcrumbs,operation:t,context:this.context}).convert()}convertBindingQueryParameters({context:t,queryParameters:r}){if(this.channel.bindings?.ws?.query!=null){let n=this.channel.bindings.ws.query.required??[];for(let[i,o]of Object.entries(this.channel.bindings.ws.query.properties??{})){let s=t.resolveMaybeReference({schemaOrReference:o,breadcrumbs:[...this.breadcrumbs,i]});if(s==null)continue;let c=new kSe({context:this.context,breadcrumbs:[...this.breadcrumbs,i],parameter:{name:i,in:"query",required:n.includes(i),schema:s,description:"description"in s?s.description:void 0,deprecated:s.deprecated??!1},parameterNamePrefix:this.channelPath}).convert();c!=null&&c.type==="query"&&(this.inlinedTypes={...this.inlinedTypes,...c.inlinedTypes},r.push(c.parameter))}}}}});var EKr,d7l=h(()=>{"use strict";wGt();EKr=class extends rJ{constructor({context:t,breadcrumbs:r,servers:n}){super({context:t,breadcrumbs:r,servers:n})}buildSingleBaseUrlEnvironment(t,r,n){return{id:r,name:t.casingsGenerator.generateName(r),url:this.constructServerUrl(n.protocol,n.url),docs:void 0,audiences:void 0,defaultUrl:void 0,urlTemplate:void 0,urlVariables:void 0}}}});var HGo,m7l,KGo,IKr,h7l=h(()=>{"use strict";zn();sc();Bt();VGo();wGt();GGo();qGo();WGo();HGo="$message.",m7l="#/channels/",KGo="#/servers/",IKr=class extends _ct{operations;inlinedTypes={};constructor({context:t,breadcrumbs:r,websocketGroup:n,channel:i,channelPath:o,operations:s}){super({context:t,breadcrumbs:r,websocketGroup:n,channel:i,channelPath:o}),this.operations=s}convert(){let t=[],r=[],n=[],o=new FSe({breadcrumbs:this.breadcrumbs,node:this.channel,context:this.context}).convert()??this.websocketGroup?.join(".")??this.channelPath;this.channel.parameters&&this.convertChannelParameters({pathParameters:t,queryParameters:r,headers:n,channelPath:this.channelPath});let s=Object.entries(this.operations).reduce((A,[b,I])=>{try{this.getChannelPathFromOperation(I)===this.channelPath&&(A[b]=I)}catch{}return A},{}),a=[];for(let[A,b]of Object.entries(s)){let C=new FSe({breadcrumbs:[...this.breadcrumbs,A],node:b,context:this.context}).convert()??A;for(let x of b.messages){let S=this.context.convertReferenceToTypeReference({reference:x});if(S.ok){let P=this.resolveMessageDocs(x)??b.description,D=ZP.reference({bodyType:S.reference,docs:P});a.push({type:A,displayName:C,origin:b.action==="send"?"client":"server",body:D,availability:this.context.getAvailability({node:b,breadcrumbs:this.breadcrumbs}),docs:P,methodName:void 0})}}}let c=this.resolveChannelServersFromReference(this.channel.servers??[])??this.resolveFirstServerName(),l=this.transformToValidPath(this.channel.address??this.channelPath),u=jy(l),p=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[],d=this.hasServerSecurity()||this.context.authOverrides?.auth!=null,f=new NSe({context:this.context,breadcrumbs:this.breadcrumbs,node:this.context.spec}).convert(),g=new NSe({context:this.context,breadcrumbs:this.breadcrumbs,node:this.channel}).convert()??f;return{channel:{name:this.context.casingsGenerator.generateName(o),displayName:o,connectMethodName:void 0,baseUrl:c,path:u,auth:d,headers:n,queryParameters:r,pathParameters:t,messages:a,availability:this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({fullPath:l,baseUrl:c,asyncApiVersion:"v3"})},apiPlayground:g},audiences:p,inlinedTypes:this.inlinedTypes}}hasServerSecurity(){let r=this.context.spec.servers??{};if(this.channel.servers&&this.channel.servers.length>0){for(let n of this.channel.servers){let i=n.$ref.replace(KGo,""),o=r[i];if(o?.security&&o.security.length>0)return!0}return!1}for(let n of Object.values(r))if(n.security&&n.security.length>0)return!0;return!1}convertChannelParameters({pathParameters:t,queryParameters:r,headers:n,channelPath:i}){for(let o of Object.values(this.channel.parameters??{})){let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:[...this.breadcrumbs,"parameters"]});if(s==null)continue;let a=this.convertChannelParameterLocation(s.location);if(a==null)continue;let{type:c,parameterKey:l}=a,p=new kSe({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...s,name:l,in:c},parameterNamePrefix:this.channelPath}).convert();if(p!=null)switch(this.inlinedTypes={...this.inlinedTypes,...p.inlinedTypes},p.type){case"path":t.push(p.parameter);break;case"query":r.push(p.parameter);break;case"header":n.push(p.parameter);break}}}convertChannelParameterLocation(t){try{let[r,n]=t.split("#/");if(r==null||n==null){this.context.errorCollector.collect({message:`Invalid location format: ${t}; unable to parse message type and parameter key`,path:this.breadcrumbs});return}if(!r.startsWith(HGo)){this.context.errorCollector.collect({message:`Invalid location format: ${t}; expected ${HGo} prefix`,path:this.breadcrumbs});return}let i=r.substring(HGo.length);if(i!=="header"&&i!=="path"&&i!=="payload"){this.context.errorCollector.collect({message:`Invalid message type: ${i}. Must be one of: header, path, payload`,path:this.breadcrumbs});return}return i==="payload"?{type:"query",parameterKey:n}:{type:i,parameterKey:n}}catch{this.context.errorCollector.collect({message:`Invalid location format: ${t}; see here for more details: https://www.asyncapi.com/docs/reference/specification/v3.0.0#runtimeExpression`,path:this.breadcrumbs});return}}resolveMessageDocs(t){let r=t,n=new Set;for(;this.context.isReferenceObject(r);){if(n.has(r.$ref))return;n.add(r.$ref);let i=this.context.resolveReference({reference:r,breadcrumbs:this.breadcrumbs});if(!i.resolved)return;r=i.value}return r.description??r.summary}resolveChannelServersFromReference(t){if(t==null||t.length===0||t[0]==null)return;let r=t[0];if(!r.$ref.startsWith(KGo)){this.context.errorCollector.collect({message:`Failed to resolve server name from server ref ${r.$ref}`,path:this.breadcrumbs});return}let n=r.$ref.substring(KGo.length);if(n==null){this.context.errorCollector.collect({message:`Failed to find server with name ${n}`,path:this.breadcrumbs});return}let i=this.context.spec.servers;if(i!=null&&n in i){let o=i[n];return rJ.getServerName(n,o)}return n}resolveFirstServerName(){let t=this.context.spec.servers;if(t==null)return;let r=Object.keys(t)[0];if(r==null)return;let n=t[r];return rJ.getServerName(r,n)}getChannelPathFromOperation(t){if(!t.channel.$ref.startsWith(m7l))throw new T({message:`Failed to resolve channel path from operation ${t.channel.$ref}`,code:T.Code.ReferenceError});return t.channel.$ref.substring(m7l.length)}}});var vKr,g7l=h(()=>{"use strict";wGt();vKr=class extends rJ{constructor({context:t,breadcrumbs:r,servers:n}){super({context:t,breadcrumbs:r,servers:n})}buildSingleBaseUrlEnvironment(t,r,n){return{id:r,name:t.casingsGenerator.generateName(r),url:this.constructServerUrl(n.protocol,n.host),docs:void 0,audiences:void 0,defaultUrl:void 0,urlTemplate:void 0,urlVariables:void 0}}}});var TGt,A7l=h(()=>{"use strict";zn();sc();Uo();f7l();d7l();h7l();g7l();TGt=class extends tJ{constructor({context:t,breadcrumbs:r,audiences:n}){super({context:t,breadcrumbs:r,audiences:n})}async convert(){return this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.context.spec=await this.resolveAllExternalRefs({spec:this.context.spec}),this.isAsyncAPIV3(this.context)?this.convertChannelMessages():this.convertComponentMessages(),this.convertSchemas(),this.convertServers(),this.convertSecuritySchemes(),this.convertChannels(),this.finalizeIr()}isAsyncAPIV3(t){return parseFloat(t.spec.asyncapi)>=3}convertChannelMessages(){let t=this.context.spec;for(let[r,n]of Object.entries(t.channels??{}))for(let[i,o]of Object.entries(n.messages??{})){if(!this.context.isMessageWithPayload(o)&&!this.context.isReferenceObject(o))continue;let s=["channels",r,"messages",i],a=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:s});if(!this.context.isMessageWithPayload(a))continue;let c=this.context.resolveMaybeReference({schemaOrReference:a.payload,breadcrumbs:s});if(c==null)continue;let l=`${r}_${i}`;this.convertSchema({id:l,breadcrumbs:s,schema:c})}}convertComponentMessages(){for(let[t,r]of Object.entries(this.context.spec.components?.messages??{})){if(r.payload==null)continue;let n=["components","messages",t],i=this.context.resolveMaybeReference({schemaOrReference:r.payload,breadcrumbs:n});i!=null&&this.convertSchema({id:t,breadcrumbs:n,schema:i})}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{}))this.convertSchema({id:t,breadcrumbs:["components","schemas",t],schema:r})}convertSchema({id:t,breadcrumbs:r,schema:n}){let o=new Tm.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:r,schema:n}).convert();o!=null&&this.addSchemaOutputToIr(t,o)}convertServers(){let t;if(this.isAsyncAPIV3(this.context)){let r=this.context.spec.servers;t=new vKr({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}else{let r=this.context.spec.servers;t=new EKr({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}this.addEnvironmentsToIr({environmentConfig:t})}convertSecuritySchemes(){if(this.context.authOverrides){let r=G5t({rawApiFileSchema:this.context.authOverrides,casingsGenerator:this.context.casingsGenerator});this.addAuthToIR({requirement:r.requirement,schemes:r.schemes,docs:r.docs});return}let t=this.convertAsyncApiSecuritySchemes();t.length>0&&this.addAuthToIR({requirement:t.length===1?"ALL":"ANY",schemes:t,docs:void 0})}convertAsyncApiSecuritySchemes(){let t=[];for(let[r,n]of Object.entries(this.context.spec.components?.securitySchemes??{})){let i=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:["components","securitySchemes",r]});if(i==null)continue;let o=this.convertSecurityScheme({securityScheme:i,schemeId:r});o!=null&&t.push(o)}return t}convertSecurityScheme({securityScheme:t,schemeId:r}){switch(t.type){case"http":{if(t.scheme?.toLowerCase()==="bearer")return kp.bearer({key:r,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,tokenPlaceholder:void 0,docs:t.description,playgroundDocs:void 0});if(t.scheme?.toLowerCase()==="basic")return kp.basic({key:r,username:this.context.casingsGenerator.generateName("username"),password:this.context.casingsGenerator.generateName("password"),usernameEnvVar:void 0,passwordEnvVar:void 0,usernameOmit:!1,passwordOmit:!1,usernamePlaceholder:void 0,passwordPlaceholder:void 0,docs:t.description,playgroundDocs:void 0});break}case"apiKey":{if(t.in==="header")return kp.header({key:r,name:{name:this.context.casingsGenerator.generateName("apiKey"),wireValue:t.name},valueType:Ki.OPTIONAL_STRING,prefix:void 0,headerEnvVar:void 0,headerPlaceholder:void 0,docs:t.description,playgroundDocs:void 0});break}case"oauth2":return kp.bearer({key:r,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,tokenPlaceholder:void 0,docs:t.description,playgroundDocs:void 0})}}convertChannels(){for(let[t,r]of Object.entries(this.context.spec.channels??{})){let i=new vC.SdkGroupNameExtension({breadcrumbs:["channels",t],operation:r,context:this.context}).convert()?.groups,o;if(this.isAsyncAPIV3(this.context)){let a=this.context.spec.operations??{};o=new IKr({context:this.context,breadcrumbs:["channels",t],websocketGroup:i,channel:r,channelPath:t,operations:a}).convert()}else o=new bKr({context:this.context,breadcrumbs:["channels",t],websocketGroup:i,channel:r,channelPath:t}).convert();o!=null&&(this.addWebsocketChannelToIr({websocketChannel:o.channel,channelPath:t,audiences:o.audiences,websocketGroup:i}),this.addTypesToIr(o.inlinedTypes))}}}});var OGt,y7l=h(()=>{"use strict";zn();Uo();OGt=class extends Yb{isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}isMessageWithPayload(t){return t!=null&&typeof t=="object"&&"payload"in t}getTypeIdFromMessageReference(t){let r=t.$ref.match(/\/messages\/(.+)$/);if(!(!r||!r[1]))return r[1]}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i}){let o,s=t.$ref.match(/^.*\/schemas\/(.+)$/),a=t.$ref.match(/^.*\/channels\/([^/]+)\/messages\/(.+)$/),c=t.$ref.match(/^.*\/messages\/(.+)$/);if(s&&s[1])return o=s[1],this.convertSchemaReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o});if(a&&a[2]){let l=a[1],u=a[2];return o=`${l}_${u}`,this.convertV3MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o})}else return c&&c[1]?(o=c[1],this.convertV2MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o})):{ok:!1}}convertSchemaReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o}){let s=this.resolveReference({reference:t,breadcrumbs:r});if(!s.resolved)return{ok:!1};let a;if(i==="reference_identifier")a=n??s.value.title;else if(i==="discriminator_key")a=s.value.title??n;else{let c=t.$ref.split("/").pop()??o;a=s.value.title??c}return{ok:!0,reference:Hr.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}convertV3MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o}){let s=this.resolveReference({reference:t,breadcrumbs:r});if(!s.resolved)return{ok:!1};let a;if(i==="reference_identifier")a=n??s.value.name;else if(i==="discriminator_key")a=s.value.name??n;else{let c=t.$ref.split("/").pop()??o;a=s.value.name??c}return{ok:!0,reference:Hr.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}convertV2MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o}){let s=this.resolveReference({reference:t,breadcrumbs:r});if(!s.resolved)return{ok:!1};let a;if(i==="reference_identifier")a=n??s.value.messageId??s.value.name;else if(i==="discriminator_key")a=s.value.messageId??s.value.name??n;else{let c=t.$ref.split("/").pop()??o;a=s.value.messageId??s.value.name??c}return{ok:!0,reference:Hr.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}}});var b7l=h(()=>{"use strict";A7l();y7l()});function LGm(e){let t=new Set,r,n=new RegExp(MGm.source,"g");for(;(r=n.exec(e))!=null;)r[1]!=null&&t.add(r[1]);return t}var MGm,CKr,E7l=h(()=>{"use strict";Uo();MGm=/\{([^}]+)\}/g,CKr=class extends Vo{document;key="x-fern-base-path";constructor({breadcrumbs:t,document:r,context:n}){super({breadcrumbs:t,context:n}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(typeof t=="string")return this.parseString(t);if(typeof t=="object"&&!Array.isArray(t))return this.parseStructured(t);this.context.errorCollector.collect({message:"Expected `x-fern-base-path` to be a string or object",path:this.breadcrumbs})}}parseString(t){if(this.validatePath(t))return{path:t,parameters:[],pathsIncludeBasePath:!1}}parseStructured(t){let r=t.path;if(typeof r!="string"){this.context.errorCollector.collect({message:"`x-fern-base-path.path` must be a string",path:this.breadcrumbs});return}if(!this.validatePath(r))return;let n=LGm(r),i=t.parameters;if(i!=null&&(typeof i!="object"||Array.isArray(i))){this.context.errorCollector.collect({message:"`x-fern-base-path.parameters` must be an object map",path:[...this.breadcrumbs,"parameters"]});return}let o=i??{};for(let c of Object.keys(o))if(!n.has(c)){this.context.errorCollector.collect({message:`Parameter '${c}' does not appear in the base path '${r}'`,path:[...this.breadcrumbs,"parameters",c]});return}let s=[];for(let c of n){let l=o[c];if(l==null){s.push({name:c,type:"string",default:void 0,docs:void 0});continue}if(typeof l!="object"||Array.isArray(l)){this.context.errorCollector.collect({message:`Parameter '${c}' must be an object`,path:[...this.breadcrumbs,"parameters",c]});return}let u=l,p=typeof u.type=="string"?u.type:"string",d=typeof u.docs=="string"?u.docs:void 0;s.push({name:c,type:p,default:u.default,docs:d})}let a=t["paths-include-base-path"]===!0;return{path:r,parameters:s,pathsIncludeBasePath:a}}validatePath(t){return t.startsWith("/")?!0:(this.context.errorCollector.collect({message:"`x-fern-base-path` path must start with '/'",path:this.breadcrumbs}),!1)}}});var xKr,I7l=h(()=>{"use strict";Uo();xKr=class extends Vo{document;key="x-fern-base-url-env";constructor({breadcrumbs:t,document:r,context:n}){super({breadcrumbs:t,context:n}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(typeof t!="string"||t.length===0){this.context.errorCollector.collect({message:"Expected a non-empty string value for x-fern-base-url-env",path:this.breadcrumbs});return}return t}}}});var SKr,v7l=h(()=>{"use strict";Uo();SKr=class extends Vo{document;key="x-fern-global-headers";constructor({breadcrumbs:t,document:r,context:n}){super({breadcrumbs:t,context:n}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(!Array.isArray(t)){this.context.errorCollector.collect({message:"Received unexpected non-array value for x-fern-global-headers",path:this.breadcrumbs});return}return t}}}});function _Gm(e){let r=e["x-fern-default"]??e.default;if(typeof r=="string"||typeof r=="boolean"||typeof r=="number")return r}var wKr,C7l=h(()=>{"use strict";Uo();wKr=class extends Vo{document;key="x-fern-global-parameters";constructor({breadcrumbs:t,document:r,context:n}){super({breadcrumbs:t,context:n}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t==null)return;if(!Array.isArray(t)){this.context.errorCollector.collect({message:"Received unexpected non-array value for x-fern-global-parameters",path:this.breadcrumbs});return}let r=[];for(let[n,i]of t.entries()){if(typeof i!="object"||i==null||Array.isArray(i)){this.context.errorCollector.collect({message:`x-fern-global-parameters[${n}] must be an object`,path:[...this.breadcrumbs,`${n}`]});continue}let o=i;if(typeof o.name!="string"){this.context.errorCollector.collect({message:`x-fern-global-parameters[${n}].name is required and must be a string`,path:[...this.breadcrumbs,`${n}`,"name"]});continue}r.push({name:o.name,"parameter-name":typeof o["parameter-name"]=="string"?o["parameter-name"]:void 0,in:typeof o.in=="string"?o.in:void 0,target:typeof o.target=="string"?o.target:void 0,env:typeof o.env=="string"?o.env:void 0,default:_Gm(o),optional:typeof o.optional=="boolean"?o.optional:void 0,apply:typeof o.apply=="string"?o.apply:void 0,type:typeof o.type=="string"?o.type:void 0,docs:typeof o.docs=="string"?o.docs:void 0})}return r.length>0?r:void 0}}});function UGm(e){if(e!=null){if(typeof e=="string")return $t.Literal.string(e);if(typeof e=="boolean")return $t.Literal.boolean(e)}}function x7l({globalHeaderOverrides:e,context:t}){let r=[];for(let[n,i]of Object.entries(e.headers??{}))if(typeof i=="string")r.push({name:t.casingsGenerator.generateNameAndWireValue({name:n,wireValue:n}),valueType:Ki.STRING,env:void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}},availability:void 0,docs:void 0,clientDefault:void 0,defaultValue:void 0});else{let o=i.name??n;r.push({name:t.casingsGenerator.generateNameAndWireValue({name:o,wireValue:n}),valueType:Ki.STRING,env:i.env,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}},availability:void 0,docs:i.docs,clientDefault:UGm(i.default),defaultValue:i.default})}return r}var S7l=h(()=>{"use strict";zn();Uo()});function VGm(e){if(e!=null){if(typeof e=="string")return $t.Literal.string(e);if(typeof e=="boolean")return $t.Literal.boolean(e)}}function w7l({globalHeaders:e,context:t}){return e.map(r=>({name:t.casingsGenerator.generateNameAndWireValue({name:r.name??"",wireValue:r.header}),valueType:r.optional?Ki.OPTIONAL_STRING:Ki.STRING,env:r.env,v2Examples:r.optional?void 0:GGm({header:r,context:t}),availability:void 0,docs:void 0,clientDefault:VGm(r["x-fern-default"]),defaultValue:void 0}))}function GGm({header:e,context:t}){let r=new Bw({breadcrumbs:[],context:t,schema:{type:"string"},example:e.header}),{validExample:n}=r.convert();return{userSpecifiedExamples:{},autogeneratedExamples:{globalHeaderExample:n}}}var T7l=h(()=>{"use strict";zn();Uo()});function qGm(e,t,r,n){if(e!=null){if(typeof e=="boolean"){if(t!=null&&t!=="boolean"){n.errorCollector.collect({message:`Default value is a boolean but type is '${t}'; expected a ${t} value`,path:[...r,"default"]});return}return $t.Literal.boolean(e)}if(typeof e=="string"){if(t==="boolean"){n.errorCollector.collect({message:"Default value is a string but type is 'boolean'; expected a boolean value",path:[...r,"default"]});return}if(t==="integer"||t==="double"||t==="number"){n.errorCollector.collect({message:`Default value is a string but type is '${t}'; expected a numeric value`,path:[...r,"default"]});return}return $t.Literal.string(e)}if(typeof e=="number"){if(t==="boolean"){n.errorCollector.collect({message:"Default value is a number but type is 'boolean'; expected a boolean value",path:[...r,"default"]});return}if(t==="string"){n.errorCollector.collect({message:"Default value is a number but type is 'string'; expected a string value",path:[...r,"default"]});return}if(t==="integer"&&!Number.isInteger(e)){n.errorCollector.collect({message:`Default value ${e} is not an integer`,path:[...r,"default"]});return}return $t.Literal.string(String(e))}n.errorCollector.collect({message:`Default value has unsupported type '${typeof e}'; expected a string, number, or boolean`,path:[...r,"default"]})}}function WGm(e,t,r){switch(e){case void 0:case"body":return $t.GlobalParameterLocation.Body;case"query":return $t.GlobalParameterLocation.Query;case"header":return $t.GlobalParameterLocation.Header;case"path":return $t.GlobalParameterLocation.Path;default:return r.errorCollector.collect({message:`Invalid global parameter location '${e}'; expected one of: body, query, header, path`,path:t}),$t.GlobalParameterLocation.Body}}function HGm(e,t,r){switch(e){case void 0:return;case"explicit":return $t.GlobalParameterApplyMode.Explicit;case"auto":return $t.GlobalParameterApplyMode.Auto;default:r.errorCollector.collect({message:`Invalid global parameter apply mode '${e}'; expected one of: explicit, auto`,path:t});return}}function KGm(e,t){let r=JGm(e);return t===!0?$t.TypeReference.container($t.ContainerType.optional(r)):r}function JGm(e){switch(e){case"boolean":return $t.TypeReference.primitive({v1:"BOOLEAN",v2:$t.PrimitiveTypeV2.boolean({default:void 0})});case"integer":return $t.TypeReference.primitive({v1:"INTEGER",v2:$t.PrimitiveTypeV2.integer({default:void 0,validation:void 0})});case"double":case"number":return $t.TypeReference.primitive({v1:"DOUBLE",v2:$t.PrimitiveTypeV2.double({default:void 0,validation:void 0})});default:return Ki.STRING}}function YGm(e){return e.target!=null?e.target:e.name}function O7l({globalParameters:e,context:t}){let r=new Map;for(let[n,i]of e.entries()){let o=r.get(i.name);o!=null?t.errorCollector.collect({message:`Duplicate global parameter name '${i.name}' at index ${n} (first seen at index ${o}). Each global parameter must have a unique name.`,path:["x-fern-global-parameters",`${n}`,"name"]}):r.set(i.name,n)}return e.map((n,i)=>({param:n,index:i})).filter(({param:n,index:i})=>r.get(n.name)===i).map(({param:n,index:i})=>{let o=["x-fern-global-parameters",`${i}`],s=WGm(n.in,[...o,"in"],t),a=n["parameter-name"]??n.name;return{id:n.name,name:t.casingsGenerator.generateNameAndWireValue({name:a,wireValue:n.name}),location:s,target:YGm(n),valueType:KGm(n.type,n.optional),env:n.env,clientDefault:qGm(n.default,n.type,o,t),optional:n.optional,apply:HGm(n.apply,[...o,"apply"],t),docs:n.docs}})}var P7l=h(()=>{"use strict";zn();Uo()});var TKr,B7l=h(()=>{"use strict";mt();Uo();TKr=class extends Tm.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:n}){super({context:t,breadcrumbs:r,parameter:n})}convert(){let t,r={},n=this.getSchema();if(n!=null){let i=this.context.convertBreadcrumbsToName([...this.breadcrumbs,this.parameter.name]),s=new Tm.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,this.parameter.name,"schema"],schemaOrReference:n,wrapAsOptional:this.parameter.required==null||!this.parameter.required,schemaIdOverride:i}).convert();s!=null&&(t=s.type,r=s.inlinedTypes??{})}return this.convertToOutput({schema:n??{type:"string"},typeReference:t,inlinedTypes:r})}getSchema(){if(this.parameter.schema!=null)return this.parameter.schema;if(!(!this.context.settings.respectParameterContent||this.parameter.in!=="header"||this.parameter.content==null)){for(let[t,r]of Object.entries(this.parameter.content))if(r.schema!=null&&gp.parse(t)?.isJSON())return r.schema}}}});function ZGm({encoding:e}){if(e){if(e.explode)return"exploded";if(e.style==="form")return"form";if(e.contentType)return XGm[e.contentType]}}var OKr,XGm,D7l=h(()=>{"use strict";mt();zn();sc();Uo();OKr=class extends Tm.AbstractConverters.AbstractMediaTypeObjectConverter{contentType;mediaType;description;required;schemaId;streamingExtension;queryParameters;constructor({context:t,breadcrumbs:r,contentType:n,mediaType:i,description:o,required:s,group:a,method:c,streamingExtension:l,queryParameters:u}){super({context:t,breadcrumbs:r,group:a,method:c}),this.contentType=n,this.mediaType=i,this.description=o,this.required=s,this.schemaId=[...this.group,this.method,"Request"].join("_"),this.streamingExtension=l,this.queryParameters=u??[]}get bodyRequired(){return this.required===!1?!1:void 0}convert(){return this.streamingExtension?.type=="streamCondition"?this.convertStreamConditionRequestBody():this.convertNonStreamConditionRequestBody()}convertStreamConditionRequestBody(){if(this.isOrderedJsonOrFormContentType())return this.handleStreamConditionJsonOrFormContent({contentType:this.contentType})}convertNonStreamConditionRequestBody(){if(this.isOrderedJsonOrFormContentType())return this.handleJsonOrFormContent({contentType:this.contentType});if(gp.parse(this.contentType)?.isMultipart())return this.handleMultipartContent({contentType:this.contentType});if(this.isBinaryContentType())return this.handleBinaryContent({contentType:this.contentType})}isOrderedJsonOrFormContentType(){let t=gp.parse(this.contentType);return t?t.isJSON()||t.isURLEncoded()||t.isPlainText()||t.isCSV()||t.isHTML()||t.isXML()||t.isDNS()||t.isApplicationText():!1}isBinaryContentType(){let t=gp.parse(this.contentType);return t?t.isBinary():!1}handleJsonOrFormContent({contentType:t}){let r=this.mediaType;if(r==null)return;let n=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,contentType:t});if(n==null)return this.handleSchemalessJsonContent({contentType:t,mediaTypeObject:r});let i=n.schema?.typeDeclaration.shape;return i?.type==="object"?this.hasBodyQueryParameterOverlap(i.properties)?{requestBody:md.reference({contentType:t,docs:this.description,requestBodyType:n.type,required:this.bodyRequired,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:n.inlinedTypes??{}}:{requestBody:md.inlinedRequestBody({contentType:t,docs:this.description??n.schema?.typeDeclaration.docs,name:this.context.casingsGenerator.generateName(this.schemaId),extendedProperties:i.extendedProperties,extends:i.extends,properties:i.properties,extraProperties:i.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:n.inlinedTypes}),inlinedPropertiesByAudience:n.schema?.propertiesByAudience}:{requestBody:md.reference({contentType:t,docs:this.description,requestBodyType:n.type,required:this.bodyRequired,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:n.inlinedTypes??{}}}handleSchemalessJsonContent({contentType:t,mediaTypeObject:r}){if(!(r.example!=null||r.examples!=null&&Object.keys(r.examples).length>0))return;let i={userSpecifiedExamples:{},autogeneratedExamples:{}},o=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:r,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_example`}),s=new Set;for(let[a,c]of o){let l=this.context.resolveExampleWithValue(c),u=this.context.resolveExampleRecursively({example:c,breadcrumbs:this.breadcrumbs}),p=a;if(this.context.isExampleWithSummary(u)){let d=u.summary;s.has(d)||(p=d)}s.add(p),l!=null&&(i.userSpecifiedExamples[p]=l)}return{requestBody:md.reference({contentType:t,docs:this.description,requestBodyType:Hr.unknown(),required:this.bodyRequired,v2Examples:i}),streamRequestBody:void 0,inlinedTypes:{}}}handleMultipartContent({contentType:t}){let r=this.mediaType;if(r==null||r.schema==null)return;let n=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,resolveSchema:!0,contentType:t});if(n==null)return;let i=n.schema?.typeDeclaration.shape;if(i?.type==="object")return{requestBody:md.fileUpload({contentType:t,docs:this.description,name:this.context.casingsGenerator.generateName(this.schemaId),properties:i.properties.map(o=>{let s=r.encoding?.[cr(o.name)];return this.convertRequestBodyProperty({property:o,contentType:t,encoding:s})}),v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:n.inlinedTypes}),examples:n.examples}}handleBinaryContent({contentType:t}){let r=this.mediaType;if(r==null)return;let n=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,contentType:t});return{requestBody:md.bytes({contentType:t,isOptional:this.required===!1,docs:this.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:n?.inlinedTypes??{}}}convertRequestBodyProperty({property:t,contentType:r,encoding:n}){let{isFile:i,isOptional:o,isArray:s}=this.recursivelyCheckTypeReferenceIsFile({typeReference:t.valueType});return i?s?kx.file(eQ.fileArray({key:t.name,isOptional:o,contentType:r,docs:t.docs})):kx.file(eQ.file({key:t.name,isOptional:o,contentType:r,docs:t.docs})):kx.bodyProperty({...t,contentType:n?.contentType??r,style:ZGm({encoding:n}),name:t.name})}handleStreamConditionJsonOrFormContent({contentType:t}){if(this.streamingExtension?.type!=="streamCondition")return;let r=this.mediaType;if(r==null||r.schema==null)return;let n=this.context.resolveMaybeReference({schemaOrReference:r.schema,breadcrumbs:[...this.breadcrumbs,"content",t,"schema"]});if(n==null)return;let i=n.properties?.[this.streamingExtension.streamConditionProperty];if(i!=null&&this.context.isReferenceObject(i)&&(i=void 0),i==null){if(n.oneOf==null&&n.anyOf==null)return;i={type:"boolean"}}let o=this.buildStreamConditionRequestBody({streamConditionProperty:i,resolvedMediaTypeSchema:n,isStreaming:!0,contentType:t,mediaTypeObject:r}),s=this.buildStreamConditionRequestBody({streamConditionProperty:i,resolvedMediaTypeSchema:n,isStreaming:!1,contentType:t,mediaTypeObject:r});if(!(o==null||s==null))return{requestBody:s.requestBody,streamRequestBody:o.requestBody,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:{...o.inlinedTypes,...s.inlinedTypes}})}}buildStreamConditionRequestBody({streamConditionProperty:t,resolvedMediaTypeSchema:r,isStreaming:n,contentType:i,mediaTypeObject:o}){if(this.streamingExtension==null||this.streamingExtension.type!=="streamCondition")return;let s={...r,properties:{...r.properties,[this.streamingExtension.streamConditionProperty]:{...t,type:"boolean",const:n}},required:[...r.required??[],this.streamingExtension.streamConditionProperty]},a={...o,schema:s},c=this.parseMediaTypeObject({mediaTypeObject:a,schemaId:this.schemaId,contentType:i});if(c==null)return;let l=c.schema?.typeDeclaration.shape;return l?.type==="object"?{requestBody:md.inlinedRequestBody({contentType:i,docs:this.description??c.schema?.typeDeclaration.docs,name:this.context.casingsGenerator.generateName(n?this.streamingExtension?.streamRequestName??`${this.schemaId}_streaming`:this.schemaId),extendedProperties:l.extendedProperties,extends:l.extends,properties:l.properties,extraProperties:l.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:a,exampleGenerationStrategy:"request"})}),inlinedTypes:c.inlinedTypes}:{requestBody:md.reference({contentType:i,docs:this.description,requestBodyType:c.type,required:this.bodyRequired,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:a,exampleGenerationStrategy:"request"})}),inlinedTypes:c.inlinedTypes??{}}}recursivelyCheckTypeReferenceIsFile({typeReference:t,isOptional:r,isArray:n}){return this.context.isList(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.list,isOptional:r,isArray:!0}):this.context.isOptional(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.optional,isOptional:!0,isArray:n}):this.context.isNullable(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.nullable,isOptional:r,isArray:n}):{isFile:this.context.isFile(t),isOptional:r??!1,isArray:n??!1}}hasBodyQueryParameterOverlap(t){if(this.queryParameters.length===0)return!1;let r=new Set(this.queryParameters.map(n=>cr(n.name).toLowerCase()));return t.some(n=>r.has(cr(n.name).toLowerCase()))}},XGm={"application/json":"json"}});function t9m(e){return e?.header!=null}var $Gm,e9m,Uct,JGo=h(()=>{"use strict";mt();zn();sc();Uo();xo();B7l();D7l();$Gm=/{([^}]+)}/g,e9m=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]),Uct=class extends Ki{operation;method;path;pathItemParameters;inlinedTypes={};constructor({context:t,breadcrumbs:r,operation:n,method:i,path:o,pathItemParameters:s}){super({context:t,breadcrumbs:r}),this.operation=n,this.method=i,this.path=o,this.pathItemParameters=s??[]}convertHttpMethod(){switch(this.method){case"get":return gm.Get;case"post":return gm.Post;case"put":return gm.Put;case"delete":return gm.Delete;case"patch":return gm.Patch;case"head":return gm.Head;default:return}}convertParameters({breadcrumbs:t}){let r=[],n=[],i=[],o=this.mergeParameters(this.pathItemParameters,this.operation.parameters??[]);if(o.length===0)return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:n,headers:i};for(let s of o){let a=this.context.resolveMaybeReference({schemaOrReference:s,breadcrumbs:t});if(a==null)continue;let l=new TKr({context:this.context,breadcrumbs:t,parameter:a}).convert();if(l!=null)switch(this.inlinedTypes={...this.inlinedTypes,...l.inlinedTypes},l.type){case"path":r.push(l.parameter);break;case"query":n.push(l.parameter);break;case"header":{let u=jr(l.parameter.name),p=cr(l.parameter.name),d=!1,f=this.context.authOverrides?.["auth-schemes"];if(f!=null){for(let g of Object.values(f))if(t9m(g)&&g.header.toLowerCase()===p.toLowerCase()){d=!0;break}}let m=this.context.globalHeaderNames;if(m!=null){for(let g of m)if(g.toLowerCase()===p.toLowerCase()){d=!0;break}}!e9m.has(u.toLowerCase())&&!d&&i.push(l.parameter);break}}}return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:n,headers:i}}mergeParameters(t,r){if(t.length===0)return r;if(r.length===0)return t;let n=new Set;for(let o of r){let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:this.breadcrumbs});s!=null&&n.add(`${s.in}:${s.name}`)}return[...t.filter(o=>{let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:this.breadcrumbs});return s==null?!1:!n.has(`${s.in}:${s.name}`)}),...r]}checkMissingPathParameters(t){let n=[...this.path.matchAll($Gm)].map(i=>i[1]).filter(i=>!t.some(o=>jr(o.name)===i));for(let i of n){if(i==null)continue;let o=`${i}_example`;t.push({name:this.context.casingsGenerator.generateName(i),valueType:Ki.STRING,docs:void 0,location:"ENDPOINT",variable:void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{[o]:this.generateStringParameterExample({example:i})}},explode:void 0,clientDefault:void 0})}}convertRequestBody({breadcrumbs:t,group:r,method:n,streamingExtension:i,queryParameters:o}){if(this.operation.requestBody==null)return;let s=this.context.resolveMaybeReference({schemaOrReference:this.operation.requestBody,breadcrumbs:t});if(s==null)return null;let a=[];for(let[c,l]of Object.entries(s.content)){let p=new OKr({context:this.context,breadcrumbs:t,contentType:c,mediaType:l,description:s.description,required:s.required,group:r??[],method:n,streamingExtension:i,queryParameters:o}).convert();p!=null&&(this.inlinedTypes={...this.inlinedTypes,...p.inlinedTypes},a.push({requestBody:p.requestBody,streamRequestBody:p.streamRequestBody,examples:p.examples,inlinedPropertiesByAudience:p.inlinedPropertiesByAudience}))}return a}computeGroupNameAndLocationFromExtensions(){let r=new vC.SdkMethodNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.methodName,i=new vC.SdkGroupNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.groups??[];if(r!=null)return{group:i,method:r}}evaluateMethodNameFromOperation(){let t=this.operation.operationId;return t??(this.operation.summary!=null?ao(this.operation.summary):ao(`${this.method}_${this.path.split("/").join("_")}`))}sanitizeMethodName(t){return t.includes(".")?ao(t):t}computeGroupNameFromTagAndOperationId(){let t=this.operation.tags?.[0],r=this.evaluateMethodNameFromOperation();if(t==null)return{method:this.sanitizeMethodName(r)};let n=this.context.settings.respectOperationIdWordBoundaries,i=D7(t,n),o=D7(r,n);return qv(i,o)?{method:t}:this.computeGroupAndMethodFromTokens({tag:t,tagTokens:i,methodName:r,methodNameTokens:o})}computeGroupAndMethodFromTokens({tag:t,tagTokens:r,methodName:n,methodNameTokens:i}){if(r.some((a,c)=>a!==i[c]))return{group:[t],method:this.sanitizeMethodName(n)};let s=i.slice(r.length);return s[0]!=null&&/^\d/.test(s[0])?{group:[t],method:this.sanitizeMethodName(n)}:{group:[t],method:ao(s.join("_"))}}generateStringParameterExample({example:t}){let r=new Tm.ExampleConverter({breadcrumbs:this.breadcrumbs,context:this.context,schema:{type:"string"},example:t}),{validExample:n}=r.convert();return n}}});var Vct,YGo=h(()=>{"use strict";zn();JGo();Vct=class extends Uct{constructor({context:t,breadcrumbs:r,operation:n,method:i,path:o,pathItemParameters:s}){super({context:t,breadcrumbs:r,operation:n,method:i,path:o,pathItemParameters:s})}convert(){if(this.operation.requestBody==null){this.context.errorCollector.collect({message:"Skipping webhook because no request body present",path:this.breadcrumbs});return}let t=this.convertHttpMethod();if(t==null)return;if(t!=="POST"&&t!=="GET"){this.context.errorCollector.collect({message:"Skipping webhook because non-POST or GET method",path:this.breadcrumbs});return}let{group:r,method:n}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),i=[...this.breadcrumbs,"Payload"],{headers:o,queryParameters:s}=this.convertParameters({breadcrumbs:i}),a=this.convertRequestBody({breadcrumbs:i,group:r,method:n,streamingExtension:void 0,queryParameters:s});if(a==null)return;let c=a[0]?.requestBody;if(c==null)return;let l=c.type==="inlinedRequestBody"?a[0]?.inlinedPropertiesByAudience:void 0,u,p;if(c.type==="inlinedRequestBody")u=tT.inlinedPayload({name:c.name,extends:c.extends,properties:c.properties});else if(c.type==="reference")u=tT.reference({payloadType:c.requestBodyType,docs:c.docs});else if(c.type==="fileUpload")p={name:c.name,properties:c.properties,docs:c.docs,v2Examples:c.v2Examples,contentType:c.contentType},u=tT.inlinedPayload({name:c.name,extends:[],properties:[]});else return;let d=this.convertWebhookResponses();return{audiences:this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],group:r,inlinedPayloadPropertiesByAudience:l,webhook:{id:`${r?.join(".")??""}.${n}`,name:this.context.casingsGenerator.generateName(n),displayName:this.operation.summary,method:t,headers:o,payload:u,signatureVerification:void 0,fileUploadPayload:p,responses:d.length>0?d:void 0,examples:[],availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),docs:this.operation.description,v2Examples:{autogeneratedExamples:this.getWebhookV2ExamplesFromRequestBodyV2Examples(c.v2Examples?.autogeneratedExamples??{}),userSpecifiedExamples:this.getWebhookV2ExamplesFromRequestBodyV2Examples(c.v2Examples?.userSpecifiedExamples??{})}},inlinedTypes:this.inlinedTypes}}convertWebhookResponses(){let t=[];if(this.operation.responses==null)return t;for(let[r,n]of Object.entries(this.operation.responses)){let i=/^\d[Xx]{2}$/.test(r),o;if(i)o=parseInt(r.charAt(0))*100;else if(o=parseInt(r),isNaN(o))continue;let a=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:[...this.breadcrumbs,"responses",r]})?.description;t.push({statusCode:o,isWildcardStatusCode:i?!0:void 0,body:void 0,docs:a})}return t}getWebhookV2ExamplesFromRequestBodyV2Examples(t){return Object.fromEntries(Object.entries(t).map(([r,n])=>[r,{name:r,payload:n}]))}}});var R7l,k7l=h(()=>{"use strict";R7l=["get","post","put","delete","patch","head"]});var PKr,F7l=h(()=>{"use strict";Uo();PKr=class extends Vo{operation;key="x-fern-global-parameter";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;if(typeof t=="string")return[t];if(!Array.isArray(t)){this.context.errorCollector.collect({message:"Received unexpected value for x-fern-global-parameter; expected a string or array of strings",path:this.breadcrumbs});return}let r=[];for(let[n,i]of t.entries()){if(typeof i!="string"){this.context.errorCollector.collect({message:`x-fern-global-parameter[${n}] must be a string`,path:[...this.breadcrumbs,`${n}`]});continue}r.push(i)}return r.length>0?r:void 0}}});var BKr,N7l=h(()=>{"use strict";Uo();BKr=class extends Vo{operation;key="x-fern-idempotent";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-idempotent",path:this.breadcrumbs});return}return t}}}});var r9m,n9m,i9m,o9m,XGo,j7l=h(()=>{"use strict";nn();r9m=Xt.object({cursor:Xt.string(),next_cursor:Xt.string(),results:Xt.string()}),n9m=Xt.object({offset:Xt.string(),results:Xt.string(),step:Xt.string().optional(),"has-next-page":Xt.string().optional()}),i9m=Xt.object({next_uri:Xt.string(),results:Xt.string()}),o9m=Xt.object({next_path:Xt.string(),results:Xt.string()}),XGo=Xt.union([Xt.boolean(),r9m,n9m,i9m,o9m])});var ZGo,jSe,DKr,z7l=h(()=>{"use strict";Uo();j7l();ZGo="$request.",jSe="$response.",DKr=class extends Vo{operation;document;key="x-fern-pagination";constructor({breadcrumbs:t,operation:r,document:n,context:i}){super({breadcrumbs:t,context:i}),this.operation=r,this.document=n}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=XGo.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-pagination extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean"){let n=this.getExtensionValue(this.document);if(n==null)return;if(typeof n=="boolean"){this.context.errorCollector.collect({message:"Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.",path:this.breadcrumbs});return}let i=XGo.safeParse(n);if(!i.success){this.context.errorCollector.collect({message:`Invalid x-fern-pagination extension: ${i.error.message}`,path:this.breadcrumbs});return}if(typeof i.data=="boolean"){this.context.errorCollector.collect({message:"Global pagination extension is a boolean, expected an object.",path:this.breadcrumbs});return}return this.convertPaginationConfig({config:i.data})}if(typeof r.data=="boolean"){this.context.errorCollector.collect({message:"Pagination extension is a boolean with no global configuration.",path:this.breadcrumbs});return}return this.convertPaginationConfig({config:r.data})}convertPaginationConfig({config:t}){let r=t;if("cursor"in r)return{type:"cursor",cursor:Yb.maybeTrimPrefix(r.cursor,ZGo),nextCursor:Yb.maybeTrimPrefix(r.next_cursor,jSe),results:Yb.maybeTrimPrefix(r.results,jSe)};let n=t;if("next_uri"in n)return{type:"uri",nextUri:Yb.maybeTrimPrefix(n.next_uri,jSe),results:Yb.maybeTrimPrefix(n.results,jSe)};let i=t;if("next_path"in i)return{type:"path",nextPath:Yb.maybeTrimPrefix(i.next_path,jSe),results:Yb.maybeTrimPrefix(i.results,jSe)};let o=t;return{type:"offset",offset:Yb.maybeTrimPrefix(o.offset,ZGo),results:Yb.maybeTrimPrefix(o.results,jSe),step:o.step!=null?Yb.maybeTrimPrefix(o.step,ZGo):void 0,hasNextPage:o["has-next-page"]!=null?Yb.maybeTrimPrefix(o["has-next-page"],jSe):void 0}}}});function $Go(e){let t=e["x-fern-streaming"];if(t==null||typeof t=="boolean")return;let r=t.resumable;return typeof r=="boolean"?r:void 0}var s9m,a9m,c9m,RKr,Q7l=h(()=>{"use strict";Uo();nn();s9m="$request.",a9m=Xt.object({"stream-condition":Xt.string().optional(),format:Xt.enum(["sse","json"]).optional(),"stream-description":Xt.string().optional(),"stream-request-name":Xt.string().optional(),"response-stream":Xt.any(),response:Xt.any(),terminator:Xt.string().optional(),resumable:Xt.boolean().optional()}),c9m=Xt.union([Xt.boolean(),a9m]),RKr=class extends Vo{document;operation;key="x-fern-streaming";constructor({breadcrumbs:t,document:r,operation:n,context:i}){super({breadcrumbs:t,context:i}),this.document=r,this.operation=n}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=c9m.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-streaming extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean")return r.data?{type:"stream",format:"json",terminator:void 0,resumable:!1}:void 0;let n=r.data.resumable??$Go(this.document)??!1;if(r.data["stream-condition"]==null&&r.data.format!=null)return{type:"stream",format:r.data.format,terminator:r.data.terminator,resumable:n};if(r.data["stream-condition"]==null){this.context.errorCollector.collect({message:"Missing stream-condition property without specified format.",path:this.breadcrumbs});return}return{type:"streamCondition",format:r.data.format??"json",terminator:r.data.terminator,streamDescription:r.data["stream-description"],streamConditionProperty:Yb.maybeTrimPrefix(r.data["stream-condition"],s9m),streamRequestName:r.data["stream-request-name"],responseStream:r.data["response-stream"],response:r.data.response,resumable:n}}}});var kKr,M7l=h(()=>{"use strict";Uo();kKr=class extends Vo{operation;key="x-fern-subtitle";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="string"){this.context.errorCollector.collect({message:"Received unexpected non-string value for x-fern-subtitle",path:this.breadcrumbs});return}return t}}}});var FKr,L7l=h(()=>{"use strict";Uo();FKr=class extends Vo{operation;key="x-fern-webhook";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-webhook",path:this.breadcrumbs});return}return t}}}});function l9m(e){return oi(e)&&typeof e.$ref=="string"}function u9m(e,t){if(e!=null){if(typeof e=="string")return e;if(l9m(e)){let r=(0,_7l.resolve)(t??process.cwd(),e.$ref);if((0,jKr.existsSync)(r))try{return(0,jKr.readFileSync)(r,"utf-8")}catch{return}}}}var jKr,_7l,NKr,U7l=h(()=>{"use strict";mt();Uo();jKr=require("fs"),_7l=require("path");NKr=class extends Vo{operation;baseDir;key="x-codeSamples";constructor({context:t,breadcrumbs:r,operation:n,baseDir:i}){super({breadcrumbs:r,context:t}),this.operation=n,this.baseDir=i}convert(){let t=oi(this.operation)?this.operation:{},r=t["x-codeSamples"],n=t["x-code-samples"],i=Array.isArray(r)?r:[],o=Array.isArray(n)?n:[],s=[...i,...o];if(s.length===0)return;let a=[];for(let c of s){if(!oi(c))continue;let l=c,u=l.lang,p=l.label,d=l.source;if(typeof u!="string")continue;let f=u9m(d,this.baseDir);f!=null&&a.push({name:typeof p=="string"?p:u,language:u,code:f,install:void 0,docs:void 0})}if(a.length!==0)return[{"code-samples":a}]}}});function p9m(e){return oi(e)&&typeof e.$ref=="string"}function f9m(e,t){if(e!=null){if(typeof e=="string")return e;if(p9m(e)){let r=(0,V7l.resolve)(t??process.cwd(),e.$ref);if((0,QKr.existsSync)(r))try{return(0,QKr.readFileSync)(r,"utf-8")}catch{return}}}}function d9m(e,t){if(!Array.isArray(e))return[];let r=[];for(let n of e){if(!oi(n))continue;let o=f9m(n.code,t);o!=null&&r.push({...n,code:o})}return r}var QKr,V7l,zKr,G7l=h(()=>{"use strict";mt();lo();Uo();QKr=require("fs"),V7l=require("path");zKr=class extends Vo{operation;baseDir;key="x-fern-examples";constructor({context:t,breadcrumbs:r,operation:n,baseDir:i}){super({breadcrumbs:r,context:t}),this.operation=n,this.baseDir=i}convert(){let t=this.getExtensionValue(this.operation);return t==null?void 0:(Array.isArray(t)?t:[]).map(o=>{if(!oi(o))return o;let a=o["code-samples"];if(a!=null){let c=d9m(a,this.baseDir);return{...o,"code-samples":c}}return o}).filter(o=>{let s=Qd.serialization.ExampleEndpointCallSchema.parse(o);return s.ok||this.context.errorCollector.collect({message:`Failed to parse x-fern-example in ${this.breadcrumbs.join(".")}`,path:this.breadcrumbs}),s.ok})}}});var PGt,q7l=h(()=>{"use strict";Uo();PGt=class extends Vo{document;key="x-fern-explorer";constructor({breadcrumbs:t,document:r,context:n}){super({breadcrumbs:t,context:n}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-explorer",path:this.breadcrumbs});return}return t}}}});var BGt,W7l=h(()=>{"use strict";mt();zn();Uo();BGt=class extends Tm.AbstractConverters.AbstractMediaTypeObjectConverter{responseBody;statusCode;streamingExtension;convertedResponseHeaders;constructor({context:t,breadcrumbs:r,responseBody:n,group:i,method:o,statusCode:s,streamingExtension:a}){super({context:t,breadcrumbs:r,group:i,method:o}),this.responseBody=n,this.statusCode=s,this.streamingExtension=a}convert(){if(parseInt(this.statusCode)===204){this.responseBody.content!=null&&Object.keys(this.responseBody.content).length>0&&this.context.errorCollector.collect({message:"A 204 (No Content) response declares a body, but a 204 response cannot include one. Ignoring the declared body and treating the success response as optional.",path:this.breadcrumbs});return}return this.shouldConvertAsStreaming()?this.convertStreamingResponseBody():this.convertNonStreamingResponseBody()}convertStreamingResponseBody(){if(this.streamingExtension!=null){if(this.streamingExtension.type=="streamCondition"){let t=this.streamingExtension.responseStream,r=this.streamingExtension.response,n=[...this.group,this.method,"Response",this.statusCode].join("_"),i=`${n}_streaming`,o=this.parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:i}),s=this.parseMediaTypeSchemaOrReference({schemaOrReference:r,schemaId:n});return this.convertStreamConditionResponse({convertedStreamingSchema:o,convertedNonStreamingSchema:s})}if(this.streamingExtension.type==="stream"){let t=[...this.group,this.method,"Response",this.statusCode].join("_"),r=Object.keys(this.responseBody.content??{}),n=this.streamingExtension.format==="sse"?[...r.filter(i=>i.includes("text/event-stream")),...r.filter(i=>!i.includes("text/event-stream"))]:r;for(let i of n){let o=this.responseBody.content?.[i];if(o==null)continue;let s=this.parseMediaTypeObject({mediaTypeObject:o,schemaId:t,contentType:this.streamingExtension.format});if(s!=null)return this.convertStreamingResponse({mediaTypeObject:o,convertedSchema:s})}}}}convertNonStreamingResponseBody(){let t=[...this.group,this.method,"Response",this.statusCode].join("_"),r=Object.keys(this.responseBody.content??{}).filter(o=>o.includes("json"));for(let o of r){let s=this.responseBody.content?.[o];if(s==null)continue;let a=this.parseMediaTypeObject({mediaTypeObject:s,schemaId:t,contentType:o});if(a!=null&&this.shouldReturnJsonResponse(o))return this.returnJsonResponse({mediaTypeObject:s,convertedSchema:a})}let n=Object.keys(this.responseBody.content??{}).filter(o=>!o.includes("json"));for(let o of n){let s=this.responseBody.content?.[o];if(s==null)continue;let a=this.parseMediaTypeObject({mediaTypeObject:s,schemaId:t,contentType:o});if(a!=null){if(this.isBinarySchema(a))return this.shouldReturnBytesResponse()?this.returnBytesResponse({mediaTypeObject:s}):this.returnFileDownloadResponse({mediaTypeObject:s});if(this.shouldReturnTextResponse(o))return this.returnTextResponse({mediaTypeObject:s,contentType:o})}}let i=parseInt(this.statusCode);if(!isNaN(i)&&i>=200&&i<300&&i!==204){let o=r.map(c=>this.responseBody.content?.[c]).find(c=>c!=null),s={schema:{type:"object",description:"Empty response body"},...o?.examples!=null&&{examples:o.examples},...o?.example!=null&&{example:o.example}},a=this.parseMediaTypeObject({mediaTypeObject:s,schemaId:t,contentType:"application/json",resolveSchema:!0});if(a!=null)return this.returnJsonResponse({mediaTypeObject:s,convertedSchema:a})}}convertStreamConditionResponse({convertedStreamingSchema:t,convertedNonStreamingSchema:r}){if(t==null||r==null)return;let n=this.responseBody.description;return this.streamingExtension?.type==="streamCondition"&&this.streamingExtension.streamDescription!=null&&(n=this.streamingExtension.streamDescription),{responseBody:kl.json(K0.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:r.schema?.typeDeclaration.v2Examples})),streamResponseBody:kl.streaming(rv.json({docs:n,payload:t.type,terminator:this.streamingExtension?.terminator,v2Examples:t.schema?.typeDeclaration.v2Examples})),inlinedTypes:{...t.inlinedTypes,...r.inlinedTypes,...this.convertResponseHeaders().inlinedTypes},headers:this.convertResponseHeaders().headers}}convertStreamingResponse({mediaTypeObject:t,convertedSchema:r}){if(this.streamingExtension==null)return;switch(this.streamingExtension.format){case"json":return{responseBody:kl.streaming(rv.json({docs:this.responseBody.description,payload:r.type,terminator:this.streamingExtension?.terminator,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:{...r.inlinedTypes,...this.convertResponseHeaders().inlinedTypes},examples:r.examples,headers:this.convertResponseHeaders().headers};case"sse":return{responseBody:kl.streaming(rv.sse({docs:this.responseBody.description,payload:r.type,terminator:this.streamingExtension?.terminator,resumable:this.streamingExtension?.resumable,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:{...r.inlinedTypes,...this.convertResponseHeaders().inlinedTypes},examples:r.examples,headers:this.convertResponseHeaders().headers};default:return}}returnJsonResponse({mediaTypeObject:t,convertedSchema:r}){return{responseBody:kl.json(K0.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:{...r.inlinedTypes,...this.convertResponseHeaders().inlinedTypes},examples:r.examples,headers:this.convertResponseHeaders().headers}}returnBytesResponse({mediaTypeObject:t}){return{responseBody:kl.bytes({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:this.convertResponseHeaders().inlinedTypes,headers:this.convertResponseHeaders().headers}}returnFileDownloadResponse({mediaTypeObject:t}){return{responseBody:kl.fileDownload({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:this.convertResponseHeaders().inlinedTypes,headers:this.convertResponseHeaders().headers}}returnTextResponse({mediaTypeObject:t,contentType:r}){return{responseBody:kl.text({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"}),contentType:gp.parse(r)?.isPlainText()?void 0:r}),streamResponseBody:void 0,inlinedTypes:this.convertResponseHeaders().inlinedTypes,headers:this.convertResponseHeaders().headers}}isBinarySchema(t){let r=t.type;switch(r.type){case"container":case"named":case"unknown":return!1;case"primitive":return r.primitive.v2==null?!1:r.primitive.v2.type==="string"&&r.primitive.v2.validation?.format==="binary";default:return!1}}shouldConvertAsStreaming(){return this.streamingExtension!=null}shouldReturnJsonResponse(t){return t.includes("json")}shouldReturnBytesResponse(){return this.context.settings.useBytesForBinaryResponse&&this.streamingExtension==null}shouldReturnTextResponse(t){return gp.parse(t)?.isText()??!1}convertResponseHeaders(){return this.convertedResponseHeaders??=Mct({context:this.context,breadcrumbs:this.breadcrumbs,headers:this.responseBody.headers}),this.convertedResponseHeaders}}});var MKr,H7l=h(()=>{"use strict";mt();zn();Uo();MKr=class extends Tm.AbstractConverters.AbstractMediaTypeObjectConverter{responseError;statusCode;methodName;isWildcardStatusCode;convertedResponseHeaders;constructor({context:t,breadcrumbs:r,responseError:n,group:i,method:o,methodName:s,statusCode:a,isWildcardStatusCode:c}){super({context:t,breadcrumbs:r,group:i,method:o}),this.responseError=n,this.statusCode=a,this.methodName=s,this.isWildcardStatusCode=c}convert(){if(!this.responseError.content)return this.constructSchemalessErrorOutput();let t=Object.keys(this.responseError.content).filter(n=>n.includes("json"));if(t.length===0)return this.constructSchemalessErrorOutput();let r=this.getErrorNameForStatusCode(this.statusCode,this.isWildcardStatusCode);if(r==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}for(let n of[...t]){let i=this.responseError.content?.[n];if(i==null)continue;let o=this.parseMediaTypeObject({mediaTypeObject:i,schemaId:G6(`${this.methodName}Request${r}`),contentType:n});if(o==null)continue;let s=this.getErrorIdFromErrorName(r);if(o.schema!=null)return this.constructErrorConverterOutput({errorName:r,errorId:s,fernFilepath:o.schema.typeDeclaration.name.fernFilepath,convertedSchema:o,mediaTypeObject:i});if(o.type.type==="named")return this.constructErrorConverterOutput({errorName:r,errorId:s,fernFilepath:o.type.fernFilepath,convertedSchema:o,mediaTypeObject:i})}}constructSchemalessErrorOutput(){let t=this.getErrorNameForStatusCode(this.statusCode,this.isWildcardStatusCode);if(t==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}let r=this.getErrorIdFromErrorName(t),n={error:{name:this.context.casingsGenerator.generateName(r),fernFilepath:{allParts:[],packagePath:[],file:void 0},errorId:r},docs:this.responseError.description},i=this.convertResponseHeaders();return{error:n,errorType:Hr.unknown(),displayName:t,statusCode:this.statusCode,isWildcardStatusCode:this.isWildcardStatusCode,inlinedTypes:i.inlinedTypes,examples:{},headers:i.headers}}constructErrorConverterOutput({errorName:t,errorId:r,fernFilepath:n,convertedSchema:i,mediaTypeObject:o}){return{error:{error:{name:this.context.casingsGenerator.generateName(r),fernFilepath:n,errorId:r},docs:this.responseError.description},errorType:i.type,displayName:t,statusCode:this.statusCode,isWildcardStatusCode:this.isWildcardStatusCode,inlinedTypes:{...i.inlinedTypes,...this.convertResponseHeaders().inlinedTypes},examples:this.convertErrorExamples({mediaTypeObject:o}),headers:this.convertResponseHeaders().headers}}convertErrorExamples({mediaTypeObject:t}){let r=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_error_example`});if(r.length===0)return;let n=new Set,i={};for(let[o,s]of r){let a=this.context.resolveExampleWithValue(s),c=this.context.resolveExampleRecursively({example:s,breadcrumbs:this.breadcrumbs}),l=this.getIdForErrorExample({key:o,example:c,usedExampleNames:n});n.add(l),a!=null&&(i[l]=a)}return Object.keys(i).length>0?i:void 0}getIdForErrorExample({key:t,example:r,usedExampleNames:n}){if(this.context.isExampleWithSummary(r)){let i=r.summary;if(!n.has(i))return i;let o=`${i} (${t})`;return n.has(o)?t:o}return t}getErrorNameForStatusCode(t,r){if(r){if(t===400)return"ClientRequestError";if(t===500)return"ServerError"}return hKr[t]}getErrorIdFromErrorName(t){return this.context.enableUniqueErrorsPerEndpoint?G6(`${this.methodName}Request${t}`):t}convertResponseHeaders(){return this.convertedResponseHeaders??=Mct({context:this.context,breadcrumbs:this.breadcrumbs,headers:this.responseError.headers}),this.convertedResponseHeaders}}});var LKr,K7l=h(()=>{"use strict";lo();zn();sc();W5();Uo();xo();U7l();G7l();q7l();W7l();H7l();JGo();LKr=class e extends Uct{idempotent;subtitle;globalParameterIds;idToAuthScheme;topLevelServers;pathLevelServers;streamingExtension;static AUTHORIZATION_HEADER="Authorization";constructor({context:t,breadcrumbs:r,operation:n,method:i,path:o,pathItemParameters:s,idempotent:a,subtitle:c,globalParameterIds:l,idToAuthScheme:u,topLevelServers:p,pathLevelServers:d,streamingExtension:f}){super({context:t,breadcrumbs:r,operation:n,method:i,path:o,pathItemParameters:s}),this.idempotent=a,this.subtitle=c,this.globalParameterIds=l,this.idToAuthScheme=u,this.topLevelServers=p,this.pathLevelServers=d,this.streamingExtension=f}convert(){let t=this.convertHttpMethod();if(t==null)return;let{group:r,method:n}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),i=this.getGroupDisplayName(r),o=this.getGroupDescription(r),{headers:s,pathParameters:a,queryParameters:c}=this.convertParameters({breadcrumbs:[...this.breadcrumbs,"parameters"]}),l=this.collectQueryParameterAudiences({breadcrumbs:[...this.breadcrumbs,"parameters"]}),u=this.convertRequestBody({breadcrumbs:[...this.breadcrumbs,"requestBody"],group:r,method:n,streamingExtension:this.streamingExtension,queryParameters:c}),p=u?.[0]?.requestBody,d=u?.[0]?.streamRequestBody,f=u?.[0]?.inlinedPropertiesByAudience,m={requestBodies:u?.map(ue=>ue.requestBody)},g=this.convertResponseBody({breadcrumbs:[...this.breadcrumbs,"responses"],group:r,method:n,streamingExtension:this.streamingExtension}),A=g?.response,b=g?.streamResponse,I=g!=null?g.errors:[],C={},x=I.map(ue=>ue.error),S=jy(this.path),P=this.context.perSpecBasePath,D=this.getEndpointBaseUrl(),R=this.getEndpointBaseUrls(),O=this.convertExamples({httpPath:S,httpMethod:t,baseUrl:D});if(Object.keys(O.examples).length===0&&Object.keys(O.streamExamples).length===0){let ue=this.synthesizeEndpointExamplesFromNativeRequestBody({httpPath:S,httpMethod:t,baseUrl:D});if(ue!=null)for(let[Pe,Ie]of Object.entries(ue))O.examples[Pe]=Ie}if(Object.keys(O.examples).length===0&&Object.keys(O.streamExamples).length===0&&u!=null&&u.length>1){let ue=this.synthesizeEndpointExamplesFromPerContentTypeRequestBodies({convertedRequestBodies:u,httpPath:S,httpMethod:t,baseUrl:D});if(ue!=null)for(let[Pe,Ie]of Object.entries(ue))O.examples[Pe]=Ie}let j=new Set(this.operation.security?.flatMap(ue=>Object.keys(ue))??[]),Y=this.authSchemeToHeaders(Array.from(j));Y.length>0&&s.push(...Y);for(let ue of I){let Pe=ue.error,Ie=ue.errorType,je=Pe.error.errorId,_e=ue.examples;C[je]={name:Pe.error,displayName:ue.displayName,discriminantValue:{name:Pe.error.name,wireValue:je},type:Ie,statusCode:ue.statusCode,isWildcardStatusCode:ue.isWildcardStatusCode,docs:Pe.docs,examples:[],v2Examples:{userSpecifiedExamples:_e??{},autogeneratedExamples:{}},headers:ue.headers}}let ee=this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],ce=new PGt({context:this.context,breadcrumbs:this.breadcrumbs,document:this.context.spec}).convert(),he=new PGt({context:this.context,breadcrumbs:this.breadcrumbs,document:this.operation}).convert()??ce,xe={displayName:this.operation.summary,subtitle:this.subtitle,method:t,baseUrl:D,v2BaseUrls:R,path:S,pathParameters:a,queryParameters:c,headers:s.filter((ue,Pe,Ie)=>Pe===Ie.findIndex(je=>cr(je.name)===cr(ue.name))),responseHeaders:g?.responseHeaders,sdkRequest:void 0,errors:x,auth:this.computeEndpointAuth(),security:this.computeEndpointSecurity(),availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),userSpecifiedExamples:[],autogeneratedExamples:[],idempotent:this.idempotent??!1,basePath:P!=null?jy(P):void 0,fullPath:P!=null?jy(`${P}${this.path}`):S,allPathParameters:a,pagination:void 0,transport:void 0,source:HD.openapi(),audiences:ee,retries:void 0,globalParameters:this.globalParameterIds,apiPlayground:he},Te=this.context.namespace!=null?[this.context.namespace]:[],pe=r?.map(ue=>ao(ue));return Te.push(...pe??[]),{audiences:ee,group:r,groupDisplayName:i,groupDescription:o,errors:C,endpoint:{...xe,id:`endpoint_${Te.join("/")}.${n}`,name:this.context.casingsGenerator.generateName(n),requestBody:p,v2RequestBodies:m,response:A,docs:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:O.examples},v2Responses:{responses:g?.v2Responses}},streamEndpoint:b!=null&&b.body!=null?{...xe,id:`endpoint_${Te.join("/")}.${n}_stream`,name:this.context.casingsGenerator.generateName(`${n}_stream`),requestBody:d,v2RequestBodies:void 0,response:b,docs:this.streamingExtension?.type==="streamCondition"?this.streamingExtension.streamDescription??this.operation.description:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:O.streamExamples},v2Responses:{responses:[{statusCode:200,isWildcardStatusCode:void 0,body:b.body,docs:b.docs}]}}:void 0,inlinedTypes:this.inlinedTypes,servers:this.filterOutTopLevelServers(this.operation.servers??this.pathLevelServers??[]),inlinedRequestPropertiesByAudience:f,queryParametersByAudience:l}}collectQueryParameterAudiences({breadcrumbs:t}){let r=this.mergeParameters(this.pathItemParameters,this.operation.parameters??[]);if(r.length===0)return;let n={},i=!1;for(let o of r){let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:t,skipErrorCollector:!0});if(s==null||s.in!=="query")continue;let a=this.context.getAudiences({operation:s,breadcrumbs:t})??[];if(a.length!==0){i=!0;for(let c of a)n[c]==null&&(n[c]=new Set),n[c].add(s.name)}}return i?n:void 0}convertResponseBody({breadcrumbs:t,group:r,method:n,streamingExtension:i}){if(this.operation.responses==null)return;let o,s=!1,a=!1;for(let[c,l]of Object.entries(this.operation.responses)){let u=/^[45]XX$/i.test(c),p,d=!1;if(u)p=parseInt(c.charAt(0))*100,d=!0;else{if(p=parseInt(c),isNaN(p)||p<200||p>=300&&p<400)continue;d=p>=400&&p<600}if(o==null&&(o={response:void 0,v2Responses:void 0,streamResponse:void 0,errors:[],examples:{},responseHeaders:[]}),p>=200&&p<300){let f=this.context.resolveMaybeReference({schemaOrReference:l,breadcrumbs:[...t,c]});if(f==null)continue;let g=new BGt({context:this.context,breadcrumbs:[...t,c],responseBody:f,group:r??[],method:n,statusCode:c,streamingExtension:i}).convert();if(g==null){a=!0,o.response==null&&(o.response={statusCode:p,isWildcardStatusCode:u?!0:void 0,body:void 0,docs:f.description});continue}g!=null&&(this.inlinedTypes={...this.inlinedTypes,...g.inlinedTypes},s||(s=!0,o.response={statusCode:p,isWildcardStatusCode:u?!0:void 0,body:g.responseBody,docs:f.description},o.streamResponse={statusCode:p,isWildcardStatusCode:u?!0:void 0,body:g.streamResponseBody,docs:f.description},g.headers!=null&&(o.responseHeaders=g.headers)),o.v2Responses=[...o.v2Responses??[],{statusCode:p,isWildcardStatusCode:u?!0:void 0,body:g.responseBody,docs:f.description}])}if(d){let f=this.context.resolveMaybeReference({schemaOrReference:l,breadcrumbs:[...t,c]});if(f==null)continue;let g=new MKr({context:this.context,breadcrumbs:[...t,c],responseError:f,group:r??[],method:n,methodName:this.evaluateMethodNameFromOperation(),statusCode:p,isWildcardStatusCode:u?!0:void 0}).convert();g!=null&&(this.inlinedTypes={...this.inlinedTypes,...g.inlinedTypes},o.errors.push(g))}}if(this.streamingExtension!=null){o==null&&(o={response:void 0,v2Responses:void 0,streamResponse:void 0,errors:[],examples:{},responseHeaders:[]});let l=new BGt({context:this.context,breadcrumbs:[...t,"stream"],responseBody:{description:""},group:r??[],method:n,statusCode:"stream",streamingExtension:i}).convert();l!=null&&(this.inlinedTypes={...this.inlinedTypes,...l.inlinedTypes},o.response={statusCode:200,isWildcardStatusCode:void 0,body:l.responseBody,docs:void 0},o.streamResponse={statusCode:200,isWildcardStatusCode:void 0,body:l.streamResponseBody,docs:void 0},o.v2Responses=[{statusCode:200,isWildcardStatusCode:void 0,body:l.responseBody,docs:void 0}])}if(a&&s&&o?.response?.body!=null){let c=o.response.body;if(c.type==="json"&&c.value.type==="response"){let l=c.value.responseBodyType;(l.type!=="container"||l.container.type!=="optional")&&(o.response={...o.response,body:kl.json(K0.response({...c.value,responseBodyType:Hr.container(As.optional(l))}))})}}return o}computeEndpointAuth(){return this.operation.security!=null&&this.operation.security.length===0?!1:this.operation.security!=null&&this.operation.security.length>0?!0:this.context.spec.security!=null&&this.context.spec.security.length>0||this.shouldApplyDefaultAuthOverrides()}computeEndpointSecurity(){return this.operation.security!=null&&this.operation.security.length===0?[]:this.context.authOverrides?.auth!=null&&!this.usesEndpointSecurity()?this.getDefaultSecurityFromAuthOverrides():UGo(this.operation.security??this.context.spec.security)}usesEndpointSecurity(){let t=this.context.authOverrides?.auth;return t!=null&&rnt(t)}shouldApplyDefaultAuthOverrides(){if(!this.context.authOverrides?.auth||this.usesEndpointSecurity())return!1;let t=this.context.spec.security!=null&&this.context.spec.security.length>0,r=this.operation.security!=null&&this.operation.security.length>0;return!(t||r)}getDefaultSecurityFromAuthOverrides(){if(!this.context.authOverrides?.auth)return;let t=this.context.authOverrides.auth;if(typeof t=="string"){let r={};return r[t]=[],[r]}if(typeof t=="object"&&"any"in t){let r=t.any;if(Array.isArray(r))return r.map(n=>{let i=typeof n=="string"?n:n.scheme,o={};return o[i]=[],o})}}authSchemeToHeaders(t){let r=[];for(let n of t){let i=this.idToAuthScheme?.[n];if(i==null)continue;let o={valueType:Ki.STRING,availability:void 0,docs:void 0,env:void 0,v2Examples:void 0,clientDefault:void 0,defaultValue:void 0};switch(i.type){case"bearer":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},...o});break;case"basic":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},...o});break;case"header":r.push({name:i.name,...o});break}}return r}convertExamples({httpPath:t,httpMethod:r,baseUrl:n}){let o=new zKr({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],a=new NKr({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],l=o.some(u=>Array.isArray(u["code-samples"])&&u["code-samples"].length>0)?o:[...o,...a];return l.length===0?{examples:{},streamExamples:{}}:this.streamingExtension?.type==="streamCondition"?this.convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:l}):{examples:this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:l}),streamExamples:{}}}synthesizeEndpointExamplesFromNativeRequestBody({httpPath:t,httpMethod:r,baseUrl:n}){if(this.operation.requestBody==null)return;let i=this.context.resolveMaybeReference({schemaOrReference:this.operation.requestBody,breadcrumbs:[...this.breadcrumbs,"requestBody"]});if(i==null)return;let o=this.extractNativeResponseExample(),s={};for(let[,a]of Object.entries(i.content)){if(a.schema!=null)continue;let c=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:a,breadcrumbs:[...this.breadcrumbs,"requestBody"],defaultExampleName:"Example"});for(let[l,u]of c){let p=this.context.resolveExampleWithValue(u);p!=null&&(s[l]={displayName:void 0,contentType:void 0,request:{docs:void 0,endpoint:{method:r,path:this.buildExamplePath(t,{})},baseUrl:void 0,environment:n,auth:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:p},response:o,codeSamples:void 0})}}return Object.keys(s).length>0?s:void 0}extractNativeResponseExample(){if(this.operation.responses!=null)for(let[t,r]of Object.entries(this.operation.responses)){let n=parseInt(t);if(isNaN(n)||n<200||n>=300)continue;let i=this.context.resolveMaybeReference({schemaOrReference:r,breadcrumbs:[...this.breadcrumbs,"responses",t]});if(i?.content!=null)for(let[,o]of Object.entries(i.content)){let s=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:o,breadcrumbs:[...this.breadcrumbs,"responses",t],defaultExampleName:"Example"});for(let[,a]of s){let c=this.context.resolveExampleWithValue(a);if(c!=null)return{docs:void 0,statusCode:n,body:$t.V2HttpEndpointResponseBody.json(c)}}}}}synthesizeEndpointExamplesFromPerContentTypeRequestBodies({convertedRequestBodies:t,httpPath:r,httpMethod:n,baseUrl:i}){let o={},s=this.extractNativeResponseExamplesByContentType();for(let a of t){let c=a.requestBody,l=c.contentType,u=c.v2Examples;if(u==null)continue;let p=u.userSpecifiedExamples;if(Object.keys(p).length===0)continue;let d=l!=null?s.get(l):void 0;for(let[f,m]of Object.entries(p)){let g=t.length>1&&l!=null?`${f} (${l})`:f;o[g]={displayName:t.length>1?g:void 0,contentType:l??void 0,request:{docs:void 0,endpoint:{method:n,path:this.buildExamplePath(r,{})},baseUrl:void 0,environment:i,auth:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:m},response:d??this.extractNativeResponseExample()??void 0,codeSamples:void 0}}}return Object.keys(o).length>0?o:void 0}extractNativeResponseExamplesByContentType(){let t=new Map;if(this.operation.responses==null)return t;for(let[r,n]of Object.entries(this.operation.responses)){let i=parseInt(r);if(isNaN(i)||i<200||i>=300)continue;let o=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:[...this.breadcrumbs,"responses",r]});if(o?.content!=null)for(let[s,a]of Object.entries(o.content)){if(t.has(s))continue;let c=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:a,breadcrumbs:[...this.breadcrumbs,"responses",r],defaultExampleName:"Example"});for(let[,l]of c){let u=this.context.resolveExampleWithValue(l);if(u!=null){t.set(s,{docs:void 0,statusCode:i,body:$t.V2HttpEndpointResponseBody.json(u)});break}}}}return t}convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:i}){let o=i.filter(l=>!(l.response!=null&&"stream"in l.response)),s=i.filter(l=>l.response!=null&&"stream"in l.response),a=this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:o}),c=this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:s});return{examples:a,streamExamples:c}}convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:i}){return Object.fromEntries(i.map((o,s)=>[this.getExampleName({example:o,exampleIndex:s}),{displayName:void 0,contentType:void 0,request:o.request!=null||o["path-parameters"]!=null||o["query-parameters"]!=null||o.headers!=null?{docs:void 0,endpoint:{method:r,path:this.buildExamplePath(t,o["path-parameters"]??{})},baseUrl:void 0,environment:n,auth:void 0,pathParameters:o["path-parameters"]??{},queryParameters:o["query-parameters"]??{},headers:o.headers??{},requestBody:o.request??void 0}:void 0,response:o.response!=null?{docs:void 0,statusCode:void 0,body:this.getExampleResponseBody({example:o})}:void 0,codeSamples:o["code-samples"]?.map(a=>{let c=("language"in a?a.language:a.sdk)??void 0;return{name:a.name,docs:void 0,language:c,code:a.code}})}]))}getExampleName({example:t,exampleIndex:r}){return t.name??t["code-samples"]?.[0]?.name??`Example_${r}`}getExampleResponseBody({example:t}){if(t.response!=null){if("stream"in t.response)return $t.V2HttpEndpointResponseBody.stream(t.response.stream);if("body"in t.response)return $t.V2HttpEndpointResponseBody.json(t.response.body)}}getEndpointBaseUrl(){let r=new vC.ServerFromOperationNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert();if(r!=null)return this.context.logger.debug(`[getEndpointBaseUrl] Endpoint ${this.method.toUpperCase()} ${this.path} specifies a server with "${un.SERVER_NAME_V2}" extension. Returning server type: ${r}`),r;let n=this.operation.servers?.[0]??this.pathLevelServers?.[0];if(n==null)return;let o=this.topLevelServers?.find(s=>s.url===n.url)??n;return l3.getServerName({server:o,context:this.context})}getEndpointBaseUrls(){if(new vC.ServerFromOperationNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()!=null)return;let n=this.operation.servers??this.pathLevelServers;return n?.map(o=>{let a=this.topLevelServers?.find(c=>c.url===o.url)??o;return l3.getServerName({server:a,context:this.context})})}buildExamplePath(t,r){return t.head+t.parts.map(n=>`${r[n.pathParameter]?.toString()??n.pathParameter}${n.tail}`).join("")}filterOutTopLevelServers(t){return t.filter(r=>!this.topLevelServers?.some(n=>n.url===r.url))}getGroupDisplayName(t){let r=this.operation.tags?.[0],n=t?.[t.length-1];if(r==null||n==null)return;let i=this.context.getDisplayNameForTag(r);if(i.toLowerCase().replaceAll(" ","")===n||this.context.hasExplicitDisplayNameForTag(r)&&ao(r)===ao(n))return i}getGroupDescription(t){let r=this.operation.tags?.[0],n=t?.[t.length-1];if(!(r==null||n==null)&&ao(r)===ao(n))return this.context.getDescriptionForTag(r)}}});var e9o,_Kr,J7l=h(()=>{"use strict";Uo();e9o=Ae(zUt(),1);k7l();F7l();N7l();z7l();Q7l();M7l();L7l();K7l();YGo();_Kr=class extends Ki{pathItem;path;idToAuthScheme;topLevelServers;declaredGlobalParameterIds;constructor({context:t,breadcrumbs:r,pathItem:n,path:i,idToAuthScheme:o,topLevelServers:s,declaredGlobalParameterIds:a}){super({context:t,breadcrumbs:r}),this.pathItem=n,this.path=i,this.idToAuthScheme=o,this.topLevelServers=s,this.declaredGlobalParameterIds=a}convert(){let t=[],r=[],n={};for(let i of R7l){let o=this.pathItem[i];if(o==null)continue;let s=[...this.breadcrumbs,i],a=this.tryParseAsWebhook({operationBreadcrumbs:s,operation:o,method:i,context:this.context});if(a!=null){r.push(a),Object.assign(n,a.inlinedTypes);continue}let l=new RKr({breadcrumbs:s,document:this.context.spec,operation:o,context:this.context}).convert();l==null&&this.operationHasTextEventStreamResponse(o)&&(l={type:"stream",format:"sse",terminator:void 0,resumable:$Go(this.context.spec)??!1});let u=this.tryParseAsHttpEndpoint({operationBreadcrumbs:s,operation:o,method:i,streamingExtension:l});u!=null&&(t.push(u),Object.assign(n,u.inlinedTypes))}return{endpoints:t,webhooks:r,inlinedTypes:n}}tryParseAsWebhook({operation:t,method:r,operationBreadcrumbs:n,context:i}){return new FKr({breadcrumbs:n,operation:t,context:i}).convert()?new Vct({context:this.context,breadcrumbs:n,operation:t,method:e9o.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path,pathItemParameters:this.pathItem.parameters}).convert():void 0}operationHasTextEventStreamResponse(t){if(t.responses==null)return!1;for(let[r,n]of Object.entries(t.responses)){let i=parseInt(r);if(isNaN(i)||i<200||i>=300)continue;let o=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:this.breadcrumbs});if(o?.content==null)continue;let s=Object.keys(o.content);if(s.length===1&&s[0]?.includes("text/event-stream"))return!0}return!1}tryParseAsHttpEndpoint({operation:t,method:r,operationBreadcrumbs:n,streamingExtension:i}){new DKr({breadcrumbs:n,operation:t,document:this.context.spec,context:this.context}).convert()!=null;let c=new BKr({breadcrumbs:n,operation:t,context:this.context}).convert(),u=new kKr({breadcrumbs:n,operation:t,context:this.context}).convert(),d=new PKr({breadcrumbs:n,operation:t,context:this.context}).convert();if(d!=null&&this.declaredGlobalParameterIds!=null){let m=[];for(let g of d)this.declaredGlobalParameterIds.has(g)?m.push(g):this.context.errorCollector.collect({message:`x-fern-global-parameter references undeclared global parameter '${g}'. Declared parameters: ${[...this.declaredGlobalParameterIds].join(", ")}`,path:[...n,"x-fern-global-parameter"]});d=m.length>0?m:void 0}return new LKr({context:this.context,breadcrumbs:n,operation:t,method:e9o.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path,pathItemParameters:this.pathItem.parameters,idempotent:c,subtitle:u,globalParameterIds:d,idToAuthScheme:this.idToAuthScheme,topLevelServers:this.topLevelServers,pathLevelServers:this.pathItem.servers,streamingExtension:i}).convert()}}});var UKr,Y7l=h(()=>{"use strict";zn();Uo();UKr=class extends Ki{securityScheme;schemeId;constructor({context:t,breadcrumbs:r,securityScheme:n,schemeId:i}){super({context:t,breadcrumbs:r}),this.securityScheme=n,this.schemeId=i}getExtension(t){return this.securityScheme[t]}convert(){let t=this.getExtension("x-fern-playground-description");switch(this.securityScheme.type){case"http":{if(this.securityScheme.scheme?.toLowerCase()==="bearer"){let r=this.getExtension("x-fern-bearer"),n=r?.name??"token",i=r?.env,o=r?.placeholder;return kp.bearer({key:this.schemeId,token:this.context.casingsGenerator.generateName(n),tokenEnvVar:i,tokenPlaceholder:o,docs:this.securityScheme.description,playgroundDocs:t})}if(this.securityScheme.scheme?.toLowerCase()==="basic"){let r=this.getExtension("x-fern-basic"),n=r?.username?.name??"username",i=r?.password?.name??"password",o=r?.username?.env,s=r?.password?.env,a=r?.username?.placeholder,c=r?.password?.placeholder;return kp.basic({key:this.schemeId,username:this.context.casingsGenerator.generateName(n),password:this.context.casingsGenerator.generateName(i),usernameEnvVar:o,passwordEnvVar:s,usernameOmit:!1,passwordOmit:!1,usernamePlaceholder:a,passwordPlaceholder:c,docs:this.securityScheme.description,playgroundDocs:t})}break}case"apiKey":{if(this.securityScheme.in==="header"){let r=this.getExtension("x-fern-header"),n=r?.name??"apiKey",i=r?.env,o=r?.prefix,s=r?.placeholder;return kp.header({key:this.schemeId,name:{name:this.context.casingsGenerator.generateName(n),wireValue:this.securityScheme.name},valueType:Ki.OPTIONAL_STRING,prefix:o,headerEnvVar:i,headerPlaceholder:s,docs:this.securityScheme.description,playgroundDocs:t})}break}case"oauth2":return kp.bearer({key:this.schemeId,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,tokenPlaceholder:void 0,docs:this.securityScheme.description,playgroundDocs:t})}}}});function m9m(e){if(e!=null){if(typeof e=="string")return kE.string(e);if(typeof e=="boolean")return kE.boolean(e)}}var X7l,DGt,Z7l=h(()=>{"use strict";mt();lo();zn();sc();W5();Uo();X7l=Ae(zUt(),1);E7l();I7l();v7l();C7l();S7l();T7l();P7l();YGo();J7l();Y7l();DGt=class extends tJ{constructor({breadcrumbs:t,context:r,audiences:n}){super({breadcrumbs:t,context:r,audiences:n})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.context.spec=await this.resolveAllExternalRefs({spec:this.context.spec}),this.context.spec=QUt({document:this.context.spec,options:this.context.settings,logger:this.context.logger}),_Go({spec:this.context.spec,errorCollector:this.context.errorCollector}),this.overrideOpenApiAuthWithGeneratorsAuth(),this.convertSecuritySchemes(),this.convertGlobalHeaders(),this.convertGlobalParameters(),this.convertBasePath(),this.convertSchemas(),this.convertWebhooks();let{endpointLevelServers:t,errors:r}=this.convertPaths();this.addErrorsToIr(r);let{defaultUrl:n}=this.convertServers({endpointLevelServers:t});this.updateEndpointsWithDefaultUrl(n);let i=this.context.spec.info?.title?.trim();return i&&i!=='""'&&(this.ir.apiDisplayName=i),this.finalizeIr()}convertGlobalHeaders(){if(this.context.globalHeaderOverrides){let n=x7l({globalHeaderOverrides:this.context.globalHeaderOverrides,context:this.context});this.addGlobalHeadersToIr(n),this.context.setGlobalHeaders(n);return}let r=new SKr({breadcrumbs:["x-fern-global-headers"],document:this.context.spec,context:this.context}).convert();if(r!=null){let n=w7l({globalHeaders:r,context:this.context});this.addGlobalHeadersToIr(n),this.context.setGlobalHeaders(n)}}convertGlobalParameters(){let r=new wKr({breadcrumbs:["x-fern-global-parameters"],document:this.context.spec,context:this.context}).convert();if(r!=null){let n=O7l({globalParameters:r,context:this.context});if(this.ir.globalParameters=n,this.ir.headers.length>0){let i=new Set(this.ir.headers.map(o=>{let s=o.name;return(typeof s=="string"?s:s.wireValue).toLowerCase()}));for(let o of r){let s=(o.target??o.name).toLowerCase();o.in==="header"&&i.has(s)&&this.context.logger.warn(`Global parameter "${o.name}" (in: header, target: "${o.target??o.name}") overlaps with an x-fern-global-headers entry. The x-fern-global-parameters definition takes precedence.`)}}}}convertBasePath(){let r=new CKr({breadcrumbs:["x-fern-base-path"],document:this.context.spec,context:this.context}).convert();if(r!=null){if(this.context.settings.respectPerSpecBasePath&&r.parameters.length===0){r.pathsIncludeBasePath||(this.context.perSpecBasePath=Xh(r.path));return}this.context.settings.respectPerSpecBasePath&&r.parameters.length>0&&this.context.errorCollector.collect({message:"respect-per-spec-base-path only applies to an x-fern-base-path without path parameters; this base path is used as the API-wide base path instead, which only one spec keeps when multiple specs are merged",path:["x-fern-base-path"]}),this.ir.basePath=jy(r.path);for(let n of r.parameters)n.type!=="string"&&this.context.errorCollector.collect({message:`x-fern-base-path parameter '${n.name}' uses type '${n.type}' which is not yet supported; treating as string`,path:["x-fern-base-path","parameters",n.name]}),this.ir.pathParameters.push({name:this.context.casingsGenerator.generateName(n.name),valueType:Ki.STRING,docs:n.docs,location:$t.PathParameterLocation.Root,variable:void 0,clientDefault:m9m(n.default),v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}},explode:void 0});if(r.pathsIncludeBasePath){let n=jUt({openApi:this.context.spec,basePath:r.path,rootPathParameterNames:new Set(r.parameters.map(i=>i.name))});for(let i of n)this.context.errorCollector.collect({message:i,path:["x-fern-base-path","paths-include-base-path"]})}}}convertSecuritySchemes(){let t=this.convertOpenApiSecuritySchemes();if(this.context.authOverrides){let r=new Map(t.map(n=>[n.key,n.docs]));this.convertAuthOverrides(r,this.context.authOverrides);return}t.length>0&&this.addAuthToIR({requirement:t.length===1?"ALL":"ANY",schemes:t,docs:void 0})}convertAuthOverrides(t,r){let n={...r,"auth-schemes":Object.fromEntries(Object.entries(r["auth-schemes"]??{}).map(([o,s])=>[o,{...s}]))};for(let[o,s]of Object.entries(n["auth-schemes"]))!s.docs&&t.has(o)&&(s.docs=t.get(o));let i=G5t({rawApiFileSchema:n,casingsGenerator:this.context.casingsGenerator});this.addAuthToIR({requirement:i.requirement,schemes:i.schemes,docs:i.docs})}convertOpenApiSecuritySchemes(){let t=[];for(let[r,n]of Object.entries(this.context.spec.components?.securitySchemes??{})){let i=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:["components","securitySchemes",r]});if(i==null)continue;let s=new UKr({context:this.context,breadcrumbs:["components","securitySchemes",r],securityScheme:i,schemeId:r}).convert();s!=null&&t.push(s)}return t}convertServers({endpointLevelServers:t}){let n=new xKr({breadcrumbs:["x-fern-base-url-env"],document:this.context.spec,context:this.context}).convert();if(this.context.environmentOverrides){let s=q5t({rawApiFileSchema:this.context.environmentOverrides,casingsGenerator:this.context.casingsGenerator});return s!=null&&this.addEnvironmentsToIr({environmentConfig:{...s.environmentsConfig,baseUrlEnvVar:s.environmentsConfig.baseUrlEnvVar??n},audiences:s.audiences}),{defaultUrl:this.context.environmentOverrides["default-url"]}}let o=new l3({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t,baseUrlEnvVar:n}).convert();return this.addEnvironmentsToIr({environmentConfig:o?.value}),{defaultUrl:o?.defaultUrl}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{})){let i=new Tm.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:["components","schemas",t],schema:r}).convert();i!=null&&this.addSchemaOutputToIr(t,i)}}convertWebhooks(){for(let[t,r]of Object.entries(this.context.spec.webhooks??{})){if(r==null){this.context.errorCollector.collect({message:"Skipping empty webhook",path:this.breadcrumbs});continue}if(!("post"in r)||r.post==null){this.context.errorCollector.collect({message:"Skipping webhook as it is not a POST method",path:this.breadcrumbs});continue}let n=r.post.operationId??t,i=r.post.operationId!=null?r.post:{...r.post,operationId:n},s=new Vct({context:this.context,breadcrumbs:["webhooks",n],operation:i,method:X7l.OpenAPIV3.HttpMethods.POST,path:n}).convert();s!=null&&(this.addWebhookToIr({webhook:s.webhook,operationId:n,audiences:s.audiences,group:s.group,inlinedPayloadPropertiesByAudience:s.inlinedPayloadPropertiesByAudience}),this.addTypesToIr(s.inlinedTypes))}}convertPaths(){let t=[],r={},n=this.ir.globalParameters!=null?new Set(this.ir.globalParameters.map(i=>i.id)):void 0;for(let[i,o]of Object.entries(this.context.spec.paths??{})){if(o==null)continue;let a=new _Kr({context:this.context,breadcrumbs:["paths",i],topLevelServers:this.context.spec.servers,pathItem:o,path:i,declaredGlobalParameterIds:n}).convert();if(a!=null){for(let c of a.endpoints){if(c.streamEndpoint!=null&&this.addEndpointToIr({endpoint:c.streamEndpoint,audiences:c.audiences,endpointGroup:c.group,endpointGroupDisplayName:c.groupDisplayName,endpointGroupDescription:c.groupDescription,inlinedRequestPropertiesByAudience:c.inlinedRequestPropertiesByAudience,queryParametersByAudience:c.queryParametersByAudience}),this.addEndpointToIr({endpoint:c.endpoint,audiences:c.audiences,endpointGroup:c.group,endpointGroupDisplayName:c.groupDisplayName,endpointGroupDescription:c.groupDescription,inlinedRequestPropertiesByAudience:c.inlinedRequestPropertiesByAudience,queryParametersByAudience:c.queryParametersByAudience}),c.servers)for(let l of c.servers)this.shouldAddServerToCollectedServers({server:l,currentServers:t})&&t.push(l);if(c.errors)for(let[l,u]of Object.entries(c.errors))r[l]=u}for(let c of a.webhooks){let l=this.context.getGroup({groupParts:c.group,namespace:this.context.namespace});this.addWebhookToIr({webhook:c.webhook,operationId:l.join("."),group:l,audiences:c.audiences,inlinedPayloadPropertiesByAudience:c.inlinedPayloadPropertiesByAudience})}this.addTypesToIr(a.inlinedTypes)}}return{endpointLevelServers:t,errors:r}}overrideOpenApiAuthWithGeneratorsAuth(){if(!this.context.authOverrides?.["auth-schemes"])return;let t=this.context.authOverrides.auth;if(t!=null&&rnt(t))return;let r={};for(let n of Object.keys(this.context.authOverrides["auth-schemes"]))r[n]=[];this.context.spec.security=[r],this.removeEndpointSpecificAuth()}removeEndpointSpecificAuth(){if(this.context.spec.paths)for(let t of Object.values(this.context.spec.paths)){if(!t)continue;let r=["get","post","put","patch","delete","options","head","trace"];for(let n of r){let i=t[n];i?.security!=null&&i.security.length>0&&delete i.security}}}}});var VKr,$7l=h(()=>{"use strict";Uo();VKr=class extends Vo{tag;key="x-displayName";constructor({breadcrumbs:t,tag:r,context:n}){super({breadcrumbs:t,context:n}),this.tag=r}convert(){if(typeof this.tag!="object"||this.tag==null)return;let t=this.tag[this.key];if(t!=null){if(typeof t!="string"){this.context.errorCollector.collect({message:"x-displayName extension must be a string",path:this.breadcrumbs});return}if(t.trim().length!==0)return{displayName:t}}}}});var wUe,eHl=h(()=>{"use strict";zn();sc();Uo();$7l();wUe=class extends Yb{perSpecBasePath;globalHeaderNames;tagToDisplayName={};tagsWithExplicitDisplayName=new Set;tagToDescription=new Map;tagDescriptionsIndexed=!1;isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i}){let o=this.getTypeIdFromSchemaReference(t);if(o==null)return{ok:!1};let s=t.$ref.split("/").pop()??o,a=this.resolveReference({reference:t,breadcrumbs:r});if(!a.resolved)return{ok:!1};let c;i==="reference_identifier"?c=n??a.value.title:i==="discriminator_key"?c=a.value.title??n:c=a.value.title??s;let l;if(o.includes("/")){let p=new Tm.SchemaConverters.SchemaConverter({context:this,breadcrumbs:r??[],schema:a.value,id:o}).convert();p!=null&&(l={[o]:p.convertedSchema})}return{ok:!0,reference:Hr.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(s),typeId:o,default:void 0,inline:!1,displayName:c}),inlinedTypes:l}}setGlobalHeaders(t){this.globalHeaderNames=t.map(r=>cr(r.name))}getDisplayNameForTag(t){if(Object.keys(this.tagToDisplayName).length===0)for(let r of this.spec.tags??[]){let i=new VKr({breadcrumbs:["tags",r.name],tag:r,context:this}).convert()?.displayName;i!=null&&this.tagsWithExplicitDisplayName.add(r.name),this.tagToDisplayName[r.name]=i??r.name}return this.tagToDisplayName[t]??t}hasExplicitDisplayNameForTag(t){return this.getDisplayNameForTag(t),this.tagsWithExplicitDisplayName.has(t)}getDescriptionForTag(t){if(!this.tagDescriptionsIndexed){this.tagDescriptionsIndexed=!0;for(let r of this.spec.tags??[])r.description!=null&&r.description.trim().length>0&&this.tagToDescription.set(r.name,r.description)}return this.tagToDescription.get(t)}}});function r9o({ir:e,authOverrides:t}){if(!t["auth-schemes"]||!e.auth)return e;let r=t["auth-schemes"],n=[];for(let i of e.auth.schemes){if(i.type!=="bearer"){n.push(i);continue}let o=r[i.key];if(o==null){n.push(i);continue}let s=Ode(o,{header:()=>{},basic:()=>{},tokenBearer:()=>{},inferredBearer:()=>{},oauth:a=>g9m({ir:e,key:i.key,oauthScheme:a})});n.push(s??i)}return{...e,auth:{...e.auth,schemes:n}}}function g9m({ir:e,key:t,oauthScheme:r}){if(r.type!=="client-credentials")return;let n=r["get-token"];if(n==null)return;let i=tHl({ir:e,endpointRef:n.endpoint});if(i==null)return;let{endpoint:o,serviceId:s,subpackageId:a}=i,c=n["request-properties"],l=n["response-properties"],u=t9o({ir:e,endpoint:o,wireValue:nJ(c?.["client-id"],"client_id")}),p=t9o({ir:e,endpoint:o,wireValue:nJ(c?.["client-secret"],"client_secret")}),d=Gct({ir:e,endpoint:o,wireValue:nJ(l?.["access-token"],"access_token")});if(!(u==null||p==null||d==null))return kp.oauth({key:t,docs:r.docs,playgroundDocs:r["playground-docs"],configuration:qD.clientCredentials({clientIdEnvVar:r["client-id-env"],clientSecretEnvVar:r["client-secret-env"],tokenPrefix:r["token-prefix"],tokenHeader:r["token-header"],scopes:r.scopes,tokenEndpoint:{endpointReference:{endpointId:o.id,serviceId:s,subpackageId:a},requestProperties:{clientId:u,clientSecret:p,scopes:void 0,customProperties:b9m({ir:e,endpoint:o,excludeWireValues:[nJ(c?.["client-id"],"client_id"),nJ(c?.["client-secret"],"client_secret")]})},responseProperties:{accessToken:d,expiresIn:Gct({ir:e,endpoint:o,wireValue:nJ(l?.["expires-in"],"expires_in")}),refreshToken:Gct({ir:e,endpoint:o,wireValue:nJ(l?.["refresh-token"],"refresh_token")})}},refreshEndpoint:r["refresh-token"]!=null?A9m({ir:e,refreshTokenConfig:r["refresh-token"]}):void 0})})}function A9m({ir:e,refreshTokenConfig:t}){let r=tHl({ir:e,endpointRef:t.endpoint});if(r==null)return;let{endpoint:n,serviceId:i,subpackageId:o}=r,s=t["request-properties"],a=t["response-properties"],c=t9o({ir:e,endpoint:n,wireValue:nJ(s?.["refresh-token"],"refresh_token")}),l=Gct({ir:e,endpoint:n,wireValue:nJ(a?.["access-token"],"access_token")});if(!(c==null||l==null))return{endpointReference:{endpointId:n.id,serviceId:i,subpackageId:o},requestProperties:{refreshToken:c},responseProperties:{accessToken:l,expiresIn:Gct({ir:e,endpoint:n,wireValue:nJ(a?.["expires-in"],"expires_in")}),refreshToken:Gct({ir:e,endpoint:n,wireValue:nJ(a?.["refresh-token"],"refresh_token")})}}}function tHl({ir:e,endpointRef:t}){let r=t.trim().split(/\s+/);if(r.length!==2)return;let n=h9m[r[0]?.toUpperCase()??""],i=Xh(r[1]);if(!(n==null||i==null))for(let[o,s]of Object.entries(e.services))for(let a of s.endpoints){if(a.method!==n)continue;if(y9m(a.fullPath)===i){let l=Object.entries(e.subpackages).find(([,u])=>u.service===o)?.[0];return{endpoint:a,serviceId:o,subpackageId:l}}}}function y9m(e){let t=e.head;for(let r of e.parts)t+=`{${r.pathParameter}}${r.tail}`;return Xh(t)}function nJ(e,t){return e==null?t:e.match(/^\$(?:request|response)\.(.+)$/)?.[1]??e}function rHl(e,t){return e.find(r=>cr(r.name)===t)}function n9o(e,t){let r=e.types[t];if(r?.shape.type==="object")return r.shape.properties}function t9o({ir:e,endpoint:t,wireValue:r}){if(t.requestBody==null)return;let n;t.requestBody.type==="inlinedRequestBody"?n=t.requestBody.properties.map(o=>({...o,xml:void 0})):t.requestBody.type==="reference"&&t.requestBody.requestBodyType.type==="named"&&(n=n9o(e,t.requestBody.requestBodyType.typeId));let i=n!=null?rHl(n,r):void 0;if(i!=null)return{propertyPath:void 0,property:YP.body({...i})}}function b9m({ir:e,endpoint:t,excludeWireValues:r}){if(t.requestBody==null)return;let n;if(t.requestBody.type==="inlinedRequestBody"?n=t.requestBody.properties.map(s=>({...s,xml:void 0})):t.requestBody.type==="reference"&&t.requestBody.requestBodyType.type==="named"&&(n=n9o(e,t.requestBody.requestBodyType.typeId)),n==null)return;let i=new Set(r),o=n.filter(s=>!i.has(cr(s.name))).map(s=>({propertyPath:void 0,property:YP.body({...s})}));return o.length>0?o:void 0}function Gct({ir:e,endpoint:t,wireValue:r}){if(t.response?.body?.type!=="json")return;let n=t.response.body.value.responseBodyType;if(n.type!=="named")return;let i=n9o(e,n.typeId),o=i!=null?rHl(i,r):void 0;if(o!=null)return{propertyPath:void 0,property:o}}var h9m,nHl=h(()=>{"use strict";mt();lo();zn();sc();h9m={GET:gm.Get,POST:gm.Post,PUT:gm.Put,PATCH:gm.Patch,DELETE:gm.Delete}});var i9o=h(()=>{"use strict";Z7l();eHl();nHl()});var qct,o9o=h(()=>{"use strict";Uo();qct=class extends Vo{document;key="x-fern-explorer";constructor({breadcrumbs:t,document:r,context:n}){super({breadcrumbs:t,context:n}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-explorer",path:this.breadcrumbs});return}return t}}}});var E9m,I9m,v9m,GKr,iHl=h(()=>{"use strict";mt();Uo();nn();E9m=Xt.object({description:Xt.string().optional(),required:Xt.boolean().optional(),deprecated:Xt.boolean().optional(),allowEmptyValue:Xt.boolean().optional(),style:Xt.string().optional(),explode:Xt.boolean().optional(),allowReserved:Xt.boolean().optional(),schema:Xt.any().optional(),example:Xt.any().optional(),examples:Xt.record(Xt.string(),Xt.any()).optional(),content:Xt.record(Xt.string(),Xt.any()).optional()}),I9m=E9m.extend({name:Xt.string(),in:Xt.string()}),v9m=Xt.array(I9m),GKr=class extends Vo{operation;key="x-fern-parameters";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null)try{return v9m.parse(t)}catch(r){this.context.errorCollector.collect({message:`Failed to parse x-fern-parameters extension: ${rn(r)}`,path:this.breadcrumbs});return}}}});var qKr,oHl=h(()=>{"use strict";zn();sc();Uo();o9o();qKr=class extends Ki{method;pathParameters;queryParameters;headers;topLevelServers;globalApiPlayground;constructor({context:t,breadcrumbs:r,method:n,pathParameters:i=[],queryParameters:o=[],headers:s=[],topLevelServers:a=[],globalApiPlayground:c}){super({context:t,breadcrumbs:r}),this.method=n,this.pathParameters=i,this.queryParameters=o,this.headers=s,this.topLevelServers=a,this.globalApiPlayground=c}convert(){let t={},r="";for(let l of this.pathParameters)r+=`/{${jr(l.name)}}`;let n=jy(r),i=[];for(let[l,u]of this.method.params.entries()){let p;if(this.context.isReferenceObject(u)){let g=this.context.resolveReference({reference:u});if(g.resolved)p=g.value;else continue}else p=u;let d=[this.method.name,"Param",p.name].join("_"),m=new Tm.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"Param",p.name],schemaIdOverride:d,context:this.context,schemaOrReference:p.schema,wrapAsOptional:!p.required}).convert();m!=null&&(i.push({docs:p.description,availability:this.context.getAvailability({node:u,breadcrumbs:[...this.breadcrumbs,"parameters"]}),name:this.context.casingsGenerator.generateNameAndWireValue({name:p.name,wireValue:p.name}),valueType:m.type,defaultValue:p.schema!=null&&typeof p.schema=="object"?p.schema.default:void 0,v2Examples:m.schema?.typeDeclaration.v2Examples,propertyAccess:void 0}),t={...m.inlinedTypes,...t,...m.schema!=null?{[d]:m.schema}:{}})}let o;if(this.method.result!=null){let l=this.context.resolveMaybeReference({schemaOrReference:this.method.result,breadcrumbs:[...this.breadcrumbs,"result"]});if(l!=null){let u=new Tm.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"result"],context:this.context,schemaOrReference:l.schema}),p=[this.method.name,"Result"].join("_"),d=u.convert();d!=null&&(o={docs:l.description,v2Examples:d.schema?.typeDeclaration.v2Examples,responseBodyType:d.type},t={...d.inlinedTypes,...t,...d.schema!=null?{[p]:d.schema}:{}})}}let s=this.getEndpointBaseUrls(),a=this.context.getAudiences({operation:this.method,breadcrumbs:this.breadcrumbs})??[];return{endpoint:{baseUrl:void 0,v2BaseUrls:s,basePath:void 0,auth:!1,security:void 0,method:"POST",id:this.method.name,docs:this.method.description,name:this.context.casingsGenerator.generateName(this.method.name),headers:this.headers,displayName:this.method.name,subtitle:void 0,pathParameters:this.pathParameters,queryParameters:this.queryParameters,allPathParameters:this.pathParameters,path:n,fullPath:n,requestBody:i.length>0?md.inlinedRequestBody({name:this.context.casingsGenerator.generateName([this.method.name,"Request"].join("_")),docs:void 0,properties:i,extends:[],extendedProperties:[],contentType:"application/json",extraProperties:!1,v2Examples:void 0}):void 0,v2RequestBodies:void 0,sdkRequest:void 0,response:o!=null?{body:kl.json(K0.response(o)),statusCode:void 0,isWildcardStatusCode:void 0,docs:o.docs}:void 0,v2Responses:void 0,errors:[],idempotent:!1,pagination:void 0,userSpecifiedExamples:[],autogeneratedExamples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples(r)},transport:void 0,availability:void 0,source:HD.openrpc({paramStructure:this.convertParamStructure()}),audiences:a,retries:void 0,globalParameters:void 0,apiPlayground:this.convertApiPlayground(),responseHeaders:[]},audiences:a,inlinedTypes:t,servers:this.filterOutTopLevelServers(this.method.servers??[])}}convertApiPlayground(){return new qct({breadcrumbs:[...this.breadcrumbs,this.method.name],document:this.method,context:this.context}).convert()??this.globalApiPlayground}convertParamStructure(){let t=this.method.paramStructure;switch(t){case"by-name":return $t.OpenRpcParamStructure.ByName;case"by-position":return $t.OpenRpcParamStructure.ByPosition;case"either":return $t.OpenRpcParamStructure.Either;case void 0:return;default:return}}convertExampleParams(t){return this.method.paramStructure==="by-name"?Object.fromEntries(t.map(r=>[r.name,r.value])):t.map(r=>r.value)}filterOutTopLevelServers(t){return t.filter(r=>!this.topLevelServers.some(n=>n.url===r.url))}getEndpointBaseUrls(){let t=this.method.servers;return t?.map(n=>{if(this.topLevelServers.find(a=>a.name===n.name&&a.url!==n.url)!=null)return n.url;let s=this.topLevelServers.find(a=>a.url===n.url)??n;return l3.getServerName({server:s,context:this.context})})}convertExamples(t){let r={},n={};for(let o of this.pathParameters){let s=Object.values(o.v2Examples?.userSpecifiedExamples??{})[0],a=Object.values(o.v2Examples?.autogeneratedExamples??{})[0],c=s!==void 0?s:a;c!==void 0&&(n[jr(o.name)]=c)}let i=0;if(this.method.examples&&this.method.examples.length>0){for(let o of this.method.examples??[]){let s;if(this.context.isReferenceObject(o)){let u=this.context.resolveReference({reference:o});if(u.resolved)s=u.value;else continue}else s=o;let a;if(s.result)if(this.context.isReferenceObject(s.result)){let u=this.context.resolveReference({reference:s.result});u.resolved&&(a=u.value)}else a=s.result;let c=s.name??`Example ${i+1}`,l=[];if(s.params&&Array.isArray(s.params)){l=[];for(let u of s.params)if(this.context.isReferenceObject(u)){let p=this.context.resolveReference({reference:u});if(p.resolved)l.push(p.value);else continue}else l.push(u)}r[c]={displayName:void 0,contentType:void 0,request:{docs:void 0,endpoint:{method:"POST",path:t},baseUrl:void 0,environment:void 0,auth:void 0,pathParameters:n,queryParameters:{},headers:{},requestBody:this.convertExampleParams(l)},response:{docs:void 0,statusCode:void 0,body:a?.value!==void 0?$t.V2HttpEndpointResponseBody.json({jsonrpc:"2.0",id:s.examplePairedRequest?.id||"1",result:a.value}):void 0},codeSamples:[]}}++i}return r}}});var WKr,sHl=h(()=>{"use strict";Uo();WKr=class extends Tm.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:n}){super({context:t,breadcrumbs:r,parameter:n})}convert(){let t,r={};if(this.parameter.schema!=null){let i=new Tm.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaOrReference:this.parameter.schema,wrapAsOptional:this.parameter.required==null||!this.parameter.required}).convert();i!=null&&(t=i.type,r=i.inlinedTypes??{})}return this.convertToOutput({schema:this.parameter.schema??{type:"string"},typeReference:t,inlinedTypes:r})}}});var RGt,aHl=h(()=>{"use strict";Uo();o9o();iHl();oHl();sHl();RGt=class extends tJ{constructor({context:t,breadcrumbs:r,audiences:n}){super({context:t,breadcrumbs:r,audiences:n})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.convertSchemas();let{endpointLevelServers:t}=this.convertMethods(),{defaultUrl:r}=this.convertServers({endpointLevelServers:t});return this.updateEndpointsWithDefaultUrl(r),this.finalizeIr()}convertServers({endpointLevelServers:t}){let n=new l3({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t}).convert();return this.addEnvironmentsToIr({environmentConfig:n?.value}),{defaultUrl:n?.defaultUrl}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{})){let i=new Tm.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:["components","schemas",t],schema:r}).convert();i!=null&&this.addSchemaOutputToIr(t,i)}}convertMethods(){let t=[],n=new GKr({context:this.context,breadcrumbs:["methods"],operation:this.context.spec}).convert(),i=[],o=[],s=[];if(n&&n.length>0)for(let[l,u]of n.entries()){let d=new WKr({context:this.context,breadcrumbs:[...this.breadcrumbs,`x-fern-parameters[${l}]`],parameter:u}).convert();if(d!=null)switch(d.type){case"path":{i.push(d.parameter);break}case"query":{o.push(d.parameter);break}case"header":{s.push(d.parameter);break}}}let a=this.context.getGroup({groupParts:[],namespace:this.context.namespace}),c=new qct({breadcrumbs:[],document:this.context.spec,context:this.context}).convert();for(let l of this.context.spec.methods??[]){let u=this.context.resolveMaybeReference({schemaOrReference:l,breadcrumbs:["methods"]});if(u==null)continue;let d=new qKr({context:this.context,breadcrumbs:["methods"],method:u,pathParameters:i,queryParameters:o,headers:s,topLevelServers:this.context.spec.servers,globalApiPlayground:c}).convert();if(d!=null&&(this.addEndpointToIr({endpoint:d.endpoint,audiences:d.audiences,endpointGroup:a,serviceName:"service_root"}),this.addTypesToIr(d.inlinedTypes),d.servers))for(let f of d.servers)this.shouldAddServerToCollectedServers({server:f,currentServers:t,specType:"openrpc"})&&t.push(this.maybeDeduplicateServerName(f))}return{endpointLevelServers:t}}maybeDeduplicateServerName(t){return this.context.spec.servers?.find(n=>n.name===t.name&&n.url!==t.url)?{...t,name:t.url}:t}}});var kGt,cHl=h(()=>{"use strict";zn();Uo();kGt=class extends Yb{isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i}){let o=this.getTypeIdFromSchemaReference(t);if(o==null)return{ok:!1};let s=this.resolveReference({reference:t,breadcrumbs:r});if(!s.resolved)return{ok:!1};let a;if(i==="reference_identifier")a=n??s.value.title;else if(i==="discriminator_key")a=s.value.title??n;else{let c=t.$ref.split("/").pop()??o;a=s.value.title??c}return{ok:!0,reference:Hr.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}}});var lHl=h(()=>{"use strict";aHl();cHl()});var uHl,pHl=h(()=>{"use strict";uHl=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i});function C9m(e){return typeof e=="string"&&uHl.test(e)}var s9o,fHl=h(()=>{"use strict";pHl();s9o=C9m});function dHl(e,t=0){return(bB[e[t+0]]+bB[e[t+1]]+bB[e[t+2]]+bB[e[t+3]]+"-"+bB[e[t+4]]+bB[e[t+5]]+"-"+bB[e[t+6]]+bB[e[t+7]]+"-"+bB[e[t+8]]+bB[e[t+9]]+"-"+bB[e[t+10]]+bB[e[t+11]]+bB[e[t+12]]+bB[e[t+13]]+bB[e[t+14]]+bB[e[t+15]]).toLowerCase()}var bB,mHl=h(()=>{"use strict";bB=[];for(let e=0;e<256;++e)bB.push((e+256).toString(16).slice(1))});function a9o(){return crypto.getRandomValues(x9m)}var x9m,hHl=h(()=>{"use strict";x9m=new Uint8Array(16)});function S9m(e,t,r){return!t&&!e&&crypto.randomUUID?crypto.randomUUID():w9m(e,t,r)}function w9m(e,t,r){e=e||{};let n=e.random??e.rng?.()??a9o();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){if(r=r||0,r<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let i=0;i<16;++i)t[r+i]=n[i];return t}return dHl(n)}var Dw,gHl=h(()=>{"use strict";hHl();mHl();Dw=S9m});var TUe=h(()=>{"use strict";gHl();fHl()});async function Wct({absoluteFilePathToOverrides:e,data:t,context:r,allowNullKeys:n}){let i=null;try{let o=(await(0,AHl.readFile)(e,"utf8")).toString();try{i=JSON.parse(o)}catch{i=Er.load(o,{json:!0})}}catch{return r.failAndThrow(`Failed to read overrides from file ${e}`,void 0,{code:T.Code.ParseError})}return QX({data:t,overrides:i,allowNullKeys:n})}var AHl,HKr=h(()=>{"use strict";mt();Bt();AHl=require("fs/promises");Ko()});async function c9o({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let n=(await(0,yHl.readFile)(t)).toString(),i;try{i=JSON.parse(n)}catch{i=Er.load(n)}let o=[];r!=null&&(Array.isArray(r)?o=r:o=[r]);let s=i;for(let a of o)s=await Wct({absoluteFilePathToOverrides:a,context:e,data:s});return s}var yHl,bHl=h(()=>{"use strict";yHl=require("fs/promises");Ko();HKr()});async function l9o({document:e,settings:t}){let r=t?.errorResponses;if(r==null)return{document:e,errorResponses:void 0};let n=typeof r.schema=="string"?await T9m(Zt.of(r.schema)):r.schema;return{document:Bjo({document:e,errorResponses:r,schema:n}),errorResponses:{...r,schema:n}}}async function T9m(e){let t=(await(0,EHl.readFile)(e)).toString(),r=Er.load(t);if(!gr(r))throw new T({message:`Expected ${e} to contain an OpenAPI schema object.`,code:T.Code.ConfigError});return r}var EHl,IHl=h(()=>{"use strict";vc();mt();tr();Bt();EHl=require("fs/promises");Ko()});var CHl=E((FUv,vHl)=>{"use strict";function O9m(){return typeof process=="object"&&typeof process.nextTick=="function"?process.nextTick:typeof setImmediate=="function"?setImmediate:function(t){setTimeout(t,0)}}vHl.exports=O9m()});var wHl=E((NUv,SHl)=>{"use strict";var xHl=CHl();SHl.exports=function(t,r){if(t){r.then(function(n){xHl(function(){t(null,n)})},function(n){xHl(function(){t(n)})});return}else return r}});var p9o=E((jUv,OHl)=>{"use strict";var u9o=class{constructor(t,r){this.cb=t,this.delay=r,this.timers={},this.pausers={}}setDelay(t){t>=0&&(this.delay=t)}pause(t){this.pausers[t]=this.pausers[t]||0,this.pausers[t]++}unpause(t){var r=this.pausers[t]||0;r>0&&r--,this.pausers[t]=r}unpauseAndTime(t){this.unpause(t),this.time(t)}time(t){var r=this,n=this.timers,i=this.timers[t];this.pausers[t]>0||(i&&clearTimeout(i),n[t]=setTimeout(function(){r.cb(t),delete n[t]},r.delay))}},KKr=class extends TypeError{constructor(t,r,n){let i=t.includes(".")?"property":"argument",o=`The "${t}" ${i} ${determiner} ${r}`}};function THl(e,t,r="Object"){if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e))){let n=new KKr(t,r,e);throw Error.captureStackTrace(n,THl),n}}OHl.exports={ERR_INVALID_ARG_TYPE:KKr,assertIsObject:THl,DebounceTimers:u9o}});var DHl=E((zUv,BHl)=>{"use strict";var{assertIsObject:PHl}=p9o();function P9m(e){return PHl(e,"options"),e=Object.assign({},e),e.allowHalfOpen=!0,e.rejectUnauthorized=!1,PHl(e.settings,"options.settings"),e.settings=Object.assign({},e.settings),e.Http1IncomingMessage=e.Http1IncomingMessage||this.http.IncomingMessage,e.Http1ServerResponse=e.Http1ServerResponse||this.http.ServerResponse,e.Http2ServerRequest=e.Http2ServerRequest||(this.http2||{}).Http2ServerRequest,e.Http2ServerResponse=e.Http2ServerResponse||(this.http2||{}).Http2ServerResponse,e}function B9m(e,t){e=P9m.call(this,e);var r=e.ALPNProtocols=[];return this.http2Support&&r.push("h2"),(e.allowHTTP1==!0||!this.http2Support)&&r.push("http/1.1"),t!==void 0&&e.servername===void 0&&(e.servername=t),e}BHl.exports={initializeTLSOptions:B9m}});var ZKr=E((MUv,NHl)=>{"use strict";var{URL:JKr}=require("url"),{EventEmitter:kHl}=require("events"),YKr=require("util")._extend,{DebounceTimers:D9m,assertIsObject:RHl,ERR_INVALID_ARG_TYPE:QUv}=p9o(),{initializeTLSOptions:R9m}=DHl(),FGt=require("http"),f9o=require("https"),{Stream:k9m}=require("stream");function XKr(e,t){let r=t.prototype;Object.keys(r).forEach(n=>{e.indexOf(n)==-1&&n.indexOf("_")!=0&&typeof r[n]=="function"&&e.push(n)})}var _me=[];XKr(_me,FGt.ClientRequest);XKr(_me,FGt.OutgoingMessage);XKr(_me,kHl);XKr(_me,k9m);var F9m=["httpVersionMajor","httpVersionMinor","httpVersion"],N9m=["host","connection"],zSe=Symbol("stubs");function NGt(){this.http2Mimic=!0,this[zSe]=[];for(var e=0;e<_me.length;e++){let l=_me[e];NGt.prototype[l]||(this[l]=function(){return this.genericStubber(l,arguments)}.bind(this))}var t,r,n,i;let o=arguments[0]instanceof jGt;var s,a;if(o){let l=arguments[0];l.method&&(s=l.method),l.protocol&&(a=l.protocol)}if(o?i=arguments[0].args:i=arguments,i[2]!=null?(n=i[0],t=i[1],r=i[2]):i[1]==null?t=i[0]:(t=i[0],r=i[1]),r=r||function(){},typeof t=="string"){if(t=d9o(new JKr(t)),!t.hostname)throw new Error("Unable to determine the domain name")}else n?t=YKr(d9o(new JKr(n)),t):t=YKr({},t);a!=a&&(t.protocol=a),t.protocol=="https:"&&!t.port&&t.port!=0&&(t.port=443),!t.port&&t.port!=0&&(t.port=80),s?t.method=s:t.method||(t.method="GET"),t.method=t.method.toUpperCase(),(t.requestManager||this.getGlobalManager(t)).handleClientRequest(this,t,r)}NGt.prototype={getGlobalManager(e){return e.agent?e.agent.protocol=="https:"?MSe.globalManager:LSe.globalManager:QSe.globalManager},genericStubber(e,t){return this[zSe]?(this[zSe].push([e,t]),!0):this[e](...arguments)},on(e,t){e=="response"&&(t.http2Safe||(e="http1.response",arguments[0]=e)),this._on?this._on(...arguments):this.genericStubber("on",arguments)},once(e,t){e=="response"&&(t.http2Safe||(e="http1.response")),this._once?this._once(...arguments):this.genericStubber("once",arguments)},emitError(e){if(this[zSe])this[zSe].forEach(([t,r])=>{(t==="on"||t==="once")&&r[0]==="error"&&r[1](e)});else return this.emit("error",e)},take(e){for(var t=0;t<_me.length;t++){let n=_me[t];e[n]&&(this[n]=e[n].bind(e))}this._on=e.on.bind(e),this._once=e.once.bind(e),this.proxyProps(e);for(let n=0;n<this[zSe].length;n++){var r=this[zSe][n];e[r[0]](...r[1])}this[zSe]=null},proxyProps(e){function t(){return e[this]}function r(c){e[this]=c}let n=["on","_on","_once","once","http2Mimic"].concat(_me),i=Object.keys(this),o=[].concat(F9m);i.forEach(function(l){n.indexOf(l)==-1&&o.indexOf(l)==-1&&o.push(l)});let s=Object.getOwnPropertyDescriptors(e);for(var a=0;a<o.length;a++){let c=o[a],l=s[c],u;l||(u=!0),l&&(l.writable||l)&&(u=!0),u&&(e[c]=this[c]),Object.defineProperty(this,c,{get:t.bind(c),set:r.bind(c)})}}};var QSe=class e extends kHl{constructor(t){super(),this.httpsAgent=f9o.globalAgent,this.httpAgent=FGt.globalAgent,this.init(t)}log(){}init(t){t=t||{},this.http2Clients={},this.cachedHTTP1Result={},this.setModules(),this.http2Debouncer=new D9m(function(n){this.log("stopping ",n);var i=this.http2Clients[n];i&&this.removeHttp2Client(n,i)}.bind(this),1e3),this.keepH1IdentificationCacheFor=t.keepH1IdentificationCacheFor||3e4,this.http2Debouncer.setDelay(t.keepH2ConnectionFor),t.useHttp?this.enforceProtocol="http:":t.useHttps&&(this.enforceProtocol="https:")}setModules(){this.http=require("http"),this.https=require("https"),this.tls=require("tls"),this.net=require("net"),this.http2Support=!1;try{this.http2=require("http2"),this.http2Support=!0}catch{}}handleClientRequest(t,r,n){let i=this,o=i.getClientKey(r);if(i.hasCachedConnection(o)){let s=i.getHttp2Client(o),a={createConnection(){return s}};process.nextTick(function(){i.makeRequest(t,o,r,n,a)}.bind(i))}else i.holdConnectionToIdentification(o,r,function(a,c){if(a){t.emitError(a);return}i.makeRequest(t,o,r,n,c)}.bind(i))}getClientKey(t){return`${t.protocol||this.enforceProtocol}${t.servername||t.host||t.hostname}:${t.port}`}getHttp2Client(t){return this.http2Clients[t]}setHttp2Client(t,r){let n=this,i=n.http2Clients[t];i&&n.removeHttp2Client(t,i),n.http2Clients[t]=r;function o(){n.removeHttp2Client(t,r)}r.on("close",o),r.on("goaway",o),r.on("error",o),r.on("frameError",o),r.on("timeout",o)}removeHttp2Client(t,r){try{delete this.http2Clients[t],r.closed||r.close()}catch{}r.removeAllListeners("close"),r.removeAllListeners("error"),r.removeAllListeners("frameError"),r.removeAllListeners("timeout")}request(t,r,n){var i=new jGt(arguments);return this.enforceProtocol&&(i.protocol=this.enforceProtocol),new NGt(i)}get(){var t=new jGt(arguments);t.method="GET";var r=this.request(t);return r.end(),r}hasCachedConnection(t){return this.getHttp2Client(t)?!0:this.cachedHTTP1Result[t]+this.keepH1IdentificationCacheFor<Date.now()}makeRequest(t,r,n,i,o){let s=this.getHttp2Client(r);return s?this.makeHttp2Request(r,t,s,Object.assign(o||{},n),i):(n.agent||(n.protocol=="https:"?n.agent=this.httpsAgent:n.agent=this.httpAgent),this.makeHttpRequest(r,t,n,i,o))}holdConnectionToIdentification(t,r,n){let i=`identify-${t}`;if(this._events[i])this.once(i,n);else{this.once(i,function(){});let o=this.identifyConnection(r,function(a,c){if(a)return n(a);var l={createConnection(){return o}};if(c=="h2"&&this.http2Support){var u=this.http2.connect(r,l);this.setHttp2Client(t,u)}else this.cachedHTTP1Result[t]=Date.now();n(null,l),this.emit(i,l)}.bind(this))}}makeHttpRequest(t,r,n,i,o){n instanceof JKr&&(n=d9o(n));let s=YKr({},n);o&&(s.createConnection=o.createConnection);let c=(s.protocol=="https:"?this.https:this.http).request(s,i);r.take(c),r._on("response",function(u){this.emit("http1.response",u)})}makeHttp2Request(t,r,n,i,o){var s=this.http2Debouncer;s.pause(t);var a=YKr({},i.headers||{});i.method&&(a[":method"]=i.method),i.path&&(a[":path"]=i.path),Object.keys(a).forEach(d=>{N9m.indexOf((d+"").toLowerCase())!=-1&&delete a[d]}),i.headers=a;var c=n.request(a);r.emit("socket",i.createConnection());let l,u=0;c.on("data",function(f){u+=f.length,u>=l&&s.unpauseAndTime(t)}),r.take(c);function p(d){l=parseInt(d["content-length"]),l<0&&this.http2Debouncer.unpauseAndTime(t),e.httpCompatibleResponse(c,i,d),r.emit("http1.response",c),o&&o(c)}p.http2Safe=!0,c.once("response",p.bind(this))}static httpCompatibleResponse(t,r,n){t.httpVersion="2.0",t.rawHeaders=n,t.headers=n,t.statusCode=n[":status"],delete n[":status"]}identifyConnection(t,r){var n=this.connect(t,{allowHTTP1:!0},function(){n.removeListener("error",r),n.alpnProtocol=="h2"?r(null,"h2"):(n.end(),r(null,"h1"))});return n.on("error",r),n}connect(t,r,n){typeof r=="function"&&(n=r,r=void 0),RHl(r,"options"),r=Object.assign({},r),typeof t=="string"&&(t=new JKr(t)),RHl(t,"authority",["string","Object","URL"]);var i=t.protocol||r.protocol||(this.enforceProtocol!="detect"?this.enforceProtocol:null)||"http:",o=""+(t.port!==""?t.port:t.protocol==="http:"?80:443),s=t.hostname||t.host||"localhost",a;if(typeof r.createConnection=="function")a=r.createConnection(t,r);else switch(i){case"http:":a=this.net.connect(o,s,n);break;case"https:":a=this.tls.connect(o,s,R9m.call(this,r,s),n);break;default:throw new Error("Not supprted"+i)}return a}};function d9o(e){var t={protocol:e.protocol,hostname:e.hostname,hash:e.hash,search:e.search,pathname:e.pathname,path:`${e.pathname}${e.search}`,href:e.href};return e.port!==""&&(t.port=Number(e.port)),(e.username||e.password)&&(t.auth=`${e.username}:${e.password}`),t}var jGt=class e{constructor(t){if(t[0]instanceof e)return t[0];this.args=t,this.method=null,this.protocol=null}},MSe=class extends QSe{constructor(){super(...arguments),this.Agent=f9o.Agent,this.globalAgent=f9o.globalAgent,this.enforceProtocol="https:"}},j9m=new MSe;MSe.globalManager=j9m;MSe.Manager=MSe;var LSe=class extends QSe{constructor(){super(...arguments),this.Agent=FGt.Agent,this.globalAgent=FGt.globalAgent,this.enforceProtocol="http:"}},z9m=new LSe;LSe.globalManager=z9m;LSe.Manager=LSe;var FHl=new QSe;FHl.enforceProtocol="detect";QSe.globalManager=FHl;NHl.exports={HttpRequest:LSe,HttpsRequest:MSe,HTTP2OutgoingMessage:NGt,ClientRequest:NGt,HttpRequestManager:QSe}});var zHl=E((LUv,jHl)=>{"use strict";var{HttpRequest:Q9m,ClientRequest:M9m}=ZKr(),zGt=Q9m.globalManager,L9m=zGt.request.bind(zGt),_9m=zGt.get.bind(zGt),U9m=Object.assign({},require("http"));jHl.exports=Object.assign(U9m,{ClientRequest:M9m,globalManager:zGt,request:L9m,get:_9m})});var MHl=E((_Uv,QHl)=>{"use strict";var{HttpsRequest:V9m,ClientRequest:G9m}=ZKr(),QGt=V9m.globalManager,q9m=QGt.request.bind(QGt),W9m=QGt.get.bind(QGt),H9m=Object.assign({},require("https"));QHl.exports=Object.assign(H9m,{ClientRequest:G9m,globalManager:QGt,request:q9m,get:W9m})});var _Hl=E((UUv,LHl)=>{"use strict";var{HttpRequestManager:m9o,HTTP2OutgoingMessage:K9m,ClientRequest:J9m}=ZKr(),Y9m=zHl(),X9m=MHl(),MGt=new m9o;m9o.globalManager=MGt;var Z9m=MGt.request.bind(MGt),$9m=MGt.get.bind(MGt);LHl.exports={HTTP2OutgoingMessage:K9m,ClientRequest:J9m,globalManager:m9o.globalManager,request:Z9m,get:$9m,http:Y9m,https:X9m}});var C9o={};ne(C9o,{FetchError:()=>yR,Headers:()=>d8,Request:()=>USe,Response:()=>vre,default:()=>uqm});function yR(e,t,r){Error.call(this,e),this.message=e,this.type=t,r&&(this.code=this.errno=r.code),Error.captureStackTrace(this,this.constructor)}function jT(e){var t=this,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=r.size;let i=n===void 0?0:n;var o=r.timeout;let s=o===void 0?0:o;e==null?e=null:HHl(e)?e=Buffer.from(e.toString()):e instanceof BUe?e=e[PUe]:Buffer.isBuffer(e)||(Object.prototype.toString.call(e)==="[object ArrayBuffer]"?e=Buffer.from(e):ArrayBuffer.isView(e)?e=Buffer.from(e.buffer,e.byteOffset,e.byteLength):e instanceof iJ.default||(e=Buffer.from(String(e)))),this[Vme]={body:e,disturbed:!1,error:null},this.size=i,this.timeout=s,e instanceof iJ.default&&e.on("error",function(a){let c=a.name==="AbortError"?a:new yR(`Invalid response body while trying to fetch ${t.url}: ${a.message}`,"system",a);t[Vme].error=c})}function Hct(){var e=this;if(this[Vme].disturbed)return jT.Promise.reject(new TypeError(`body used already for: ${this.url}`));if(this[Vme].disturbed=!0,this[Vme].error)return jT.Promise.reject(this[Vme].error);if(this.body===null)return jT.Promise.resolve(Buffer.alloc(0));if(Buffer.isBuffer(this.body))return jT.Promise.resolve(this.body);if(!(this.body instanceof iJ.default))return jT.Promise.resolve(Buffer.alloc(0));let t=[],r=0,n=!1;return new jT.Promise(function(i,o){let s;e.timeout&&(s=setTimeout(function(){n=!0,o(new yR(`Response timeout while trying to fetch ${e.url} (over ${e.timeout}ms)`,"body-timeout"))},e.timeout)),e.body.on("error",function(a){a.name==="AbortError"?(n=!0,o(a)):o(new yR(`Invalid response body while trying to fetch ${e.url}: ${a.message}`,"system",a))}),e.body.on("data",function(a){if(!(n||a===null)){if(e.size&&r+a.length>e.size){n=!0,o(new yR(`content size at ${e.url} over limit: ${e.size}`,"max-size"));return}r+=a.length,t.push(a)}}),e.body.on("end",function(){if(!n){clearTimeout(s);try{i(Buffer.concat(t))}catch(a){o(new yR(`Could not create Buffer from response body for ${e.url}: ${a.message}`,"system",a))}}})})}function eqm(e,t){if(typeof y9o!="function")throw new Error("The package `encoding` must be installed to use the textConverted() function");let r=t.get("content-type"),n="utf-8",i,o;return r&&(i=/charset=([^;]*)/i.exec(r)),o=e.slice(0,1024).toString(),!i&&o&&(i=/<meta.+?charset=(['"])(.+?)\1/i.exec(o)),!i&&o&&(i=/<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(o),i&&(i=/charset=(.*)/i.exec(i.pop()))),!i&&o&&(i=/<\?xml.+?encoding=(['"])(.+?)\1/i.exec(o)),i&&(n=i.pop(),(n==="gb2312"||n==="gbk")&&(n="gb18030")),y9o(e,"UTF-8",n).toString()}function HHl(e){return typeof e!="object"||typeof e.append!="function"||typeof e.delete!="function"||typeof e.get!="function"||typeof e.getAll!="function"||typeof e.has!="function"||typeof e.set!="function"?!1:e.constructor.name==="URLSearchParams"||Object.prototype.toString.call(e)==="[object URLSearchParams]"||typeof e.sort=="function"}function KHl(e){let t,r,n=e.body;if(e.bodyUsed)throw new Error("cannot clone body after it is used");return n instanceof iJ.default&&typeof n.getBoundary!="function"&&(t=new UHl,r=new UHl,n.pipe(t),n.pipe(r),e[Vme].body=t,n=r),n}function JHl(e){return e===null?null:typeof e=="string"?"text/plain;charset=UTF-8":HHl(e)?"application/x-www-form-urlencoded;charset=UTF-8":e instanceof BUe?e.type||null:Buffer.isBuffer(e)||Object.prototype.toString.call(e)==="[object ArrayBuffer]"||ArrayBuffer.isView(e)?null:typeof e.getBoundary=="function"?`multipart/form-data;boundary=${e.getBoundary()}`:e instanceof iJ.default?null:"text/plain;charset=UTF-8"}function YHl(e){let t=e.body;return t===null?0:Buffer.isBuffer(t)?t.length:t&&typeof t.getLengthSync=="function"&&(t._lengthRetrievers&&t._lengthRetrievers.length==0||t.hasKnownLength&&t.hasKnownLength())?t.getLengthSync():null}function tqm(e,t){let r=t.body;r===null?e.end():Buffer.isBuffer(r)?(e.write(r),e.end()):r.pipe(e)}function LGt(e){if(e=`${e}`,XHl.test(e))throw new TypeError(`${e} is not a legal HTTP header name`)}function VHl(e){if(e=`${e}`,b9o.test(e))throw new TypeError(`${e} is not a legal HTTP header value`)}function Jct(e,t){t=t.toLowerCase();for(let r in e)if(r.toLowerCase()===t)return r}function E9o(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"key+value";return Object.keys(e[CC]).sort().map(t==="key"?function(n){return n.toLowerCase()}:t==="value"?function(n){return e[CC][n].join(", ")}:function(n){return[n.toLowerCase(),e[CC][n].join(", ")]})}function g9o(e,t){let r=Object.create(v9o);return r[I9o]={target:e,kind:t,index:0},r}function rqm(e){let t=Object.assign({__proto__:null},e[CC]),r=Jct(e[CC],"Host");return r!==void 0&&(t[r]=t[r][0]),t}function nqm(e){let t=new d8;for(let r of Object.keys(e))if(!XHl.test(r))if(Array.isArray(e[r]))for(let n of e[r])b9o.test(n)||(t[CC][r]===void 0?t[CC][r]=[n]:t[CC][r].push(n));else b9o.test(e[r])||(t[CC][r]=[e[r]]);return t}function $Kr(e){return typeof e=="object"&&typeof e[Ume]=="object"}function aqm(e){let t=e&&typeof e=="object"&&Object.getPrototypeOf(e);return!!(t&&t.constructor.name==="AbortSignal")}function cqm(e){let t=e[Ume].parsedURL,r=new d8(e[Ume].headers);if(r.has("Accept")||r.set("Accept","*/*"),!t.protocol||!t.hostname)throw new TypeError("Only absolute URLs are supported");if(!/^https?:$/.test(t.protocol))throw new TypeError("Only HTTP(S) protocols are supported");if(e.signal&&e.body instanceof iJ.default.Readable&&!sqm)throw new Error("Cancellation of streamed requests with AbortSignal is not supported in node < 8");let n=null;if(e.body==null&&/^(POST|PUT)$/i.test(e.method)&&(n="0"),e.body!=null){let i=YHl(e);typeof i=="number"&&(n=String(i))}return n&&r.set("Content-Length",n),r.has("User-Agent")||r.set("User-Agent","node-fetch/1.0 (+https://github.com/bitinn/node-fetch)"),e.compress&&!r.has("Accept-Encoding")&&r.set("Accept-Encoding","gzip,deflate"),!r.has("Connection")&&!e.agent&&r.set("Connection","close"),Object.assign({},t,{method:e.method,headers:rqm(r),agent:e.agent})}function _Gt(e){Error.call(this,e),this.type="aborted",this.message=e,Error.captureStackTrace(this,this.constructor)}function _Se(e,t){if(!_Se.Promise)throw new Error("native promise missing, set fetch.Promise to your favorite alternative");return jT.Promise=_Se.Promise,new _Se.Promise(function(r,n){let i=new USe(e,t),o=cqm(i),s=WHl.default.request,a=i.signal,c=null,l=function(){let g=new _Gt("The user aborted a request.");n(g),i.body&&i.body instanceof iJ.default.Readable&&i.body.destroy(g),!(!c||!c.body)&&c.body.emit("error",g)};if(a&&a.aborted){l();return}let u=function(){l(),f()},p=s(o),d;a&&a.addEventListener("abort",u);function f(){p.abort(),a&&a.removeEventListener("abort",u),clearTimeout(d)}i.timeout&&p.once("socket",function(m){d=setTimeout(function(){n(new yR(`network timeout at: ${i.url}`,"request-timeout")),f()},i.timeout)}),p.on("error",function(m){n(new yR(`request to ${i.url} failed, reason: ${m.message}`,"system",m)),f()}),p.on("response",function(m){clearTimeout(d);let g=nqm(m.headers);if(_Se.isRedirect(m.statusCode)){let x=g.get("Location"),S=x===null?null:lqm(i.url,x);switch(i.redirect){case"error":n(new yR(`redirect mode is set to error: ${i.url}`,"no-redirect")),f();return;case"manual":if(S!==null)try{g.set("Location",S)}catch(D){n(D)}break;case"follow":if(S===null)break;if(i.counter>=i.follow){n(new yR(`maximum redirect reached at: ${i.url}`,"max-redirect")),f();return}let P={headers:new d8(i.headers),follow:i.follow,counter:i.counter+1,agent:i.agent,compress:i.compress,method:i.method,body:i.body,signal:i.signal};if(m.statusCode!==303&&i.body&&YHl(i)===null){n(new yR("Cannot follow redirect with body being a readable stream","unsupported-redirect")),f();return}(m.statusCode===303||(m.statusCode===301||m.statusCode===302)&&i.method==="POST")&&(P.method="GET",P.body=void 0,P.headers.delete("content-length")),r(_Se(new USe(S,P))),f();return}}m.once("end",function(){a&&a.removeEventListener("abort",u)});let A=m.pipe(new GHl),b={url:i.url,status:m.statusCode,statusText:m.statusMessage,headers:g,size:i.size,timeout:i.timeout},I=g.get("Content-Encoding");if(!i.compress||i.method==="HEAD"||I===null||m.statusCode===204||m.statusCode===304){c=new vre(A,b),r(c);return}let C={flush:Kct.default.Z_SYNC_FLUSH,finishFlush:Kct.default.Z_SYNC_FLUSH};if(I=="gzip"||I=="x-gzip"){A=A.pipe(Kct.default.createGunzip(C)),c=new vre(A,b),r(c);return}if(I=="deflate"||I=="x-deflate"){m.pipe(new GHl).once("data",function(S){(S[0]&15)===8?A=A.pipe(Kct.default.createInflate()):A=A.pipe(Kct.default.createInflateRaw()),c=new vre(A,b),r(c)});return}c=new vre(A,b),r(c)}),tqm(p,i)})}var iJ,qHl,eJr,WHl,Kct,PUe,h9o,BUe,y9o,Vme,UHl,XHl,b9o,CC,d8,I9o,v9o,OUe,iqm,vre,Ume,A9o,oqm,sqm,USe,GHl,lqm,uqm,x9o=h(()=>{"use strict";iJ=Ae(require("stream"),1),qHl=Ae(require("http"),1),eJr=Ae(require("url"),1),WHl=Ae(_Hl(),1),Kct=Ae(require("zlib"),1),PUe=Symbol("buffer"),h9o=Symbol("type"),BUe=class e{constructor(){this[h9o]="";let t=arguments[0],r=arguments[1],n=[];if(t){let o=t,s=Number(o.length);for(let a=0;a<s;a++){let c=o[a],l;c instanceof Buffer?l=c:ArrayBuffer.isView(c)?l=Buffer.from(c.buffer,c.byteOffset,c.byteLength):c instanceof ArrayBuffer?l=Buffer.from(c):c instanceof e?l=c[PUe]:l=Buffer.from(typeof c=="string"?c:String(c)),n.push(l)}}this[PUe]=Buffer.concat(n);let i=r&&r.type!==void 0&&String(r.type).toLowerCase();i&&!/[^\u0020-\u007E]/.test(i)&&(this[h9o]=i)}get size(){return this[PUe].length}get type(){return this[h9o]}slice(){let t=this.size,r=arguments[0],n=arguments[1],i,o;r===void 0?i=0:r<0?i=Math.max(t+r,0):i=Math.min(r,t),n===void 0?o=t:n<0?o=Math.max(t+n,0):o=Math.min(n,t);let s=Math.max(o-i,0),c=this[PUe].slice(i,i+s),l=new e([],{type:arguments[2]});return l[PUe]=c,l}};Object.defineProperties(BUe.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});Object.defineProperty(BUe.prototype,Symbol.toStringTag,{value:"Blob",writable:!1,enumerable:!1,configurable:!0});yR.prototype=Object.create(Error.prototype);yR.prototype.constructor=yR;yR.prototype.name="FetchError";try{y9o=require("encoding").convert}catch{}Vme=Symbol("Body internals"),UHl=iJ.default.PassThrough;jT.prototype={get body(){return this[Vme].body},get bodyUsed(){return this[Vme].disturbed},arrayBuffer(){return Hct.call(this).then(function(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)})},blob(){let e=this.headers&&this.headers.get("content-type")||"";return Hct.call(this).then(function(t){return Object.assign(new BUe([],{type:e.toLowerCase()}),{[PUe]:t})})},json(){var e=this;return Hct.call(this).then(function(t){try{return JSON.parse(t.toString())}catch(r){return jT.Promise.reject(new yR(`invalid json response body at ${e.url} reason: ${r.message}`,"invalid-json"))}})},text(){return Hct.call(this).then(function(e){return e.toString()})},buffer(){return Hct.call(this)},textConverted(){var e=this;return Hct.call(this).then(function(t){return eqm(t,e.headers)})}};Object.defineProperties(jT.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0}});jT.mixIn=function(e){for(let t of Object.getOwnPropertyNames(jT.prototype))if(!(t in e)){let r=Object.getOwnPropertyDescriptor(jT.prototype,t);Object.defineProperty(e,t,r)}};jT.Promise=global.Promise;XHl=/[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/,b9o=/[^\t\x20-\x7e\x80-\xff]/;CC=Symbol("map"),d8=class e{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:void 0;if(this[CC]=Object.create(null),t instanceof e){let r=t.raw(),n=Object.keys(r);for(let i of n)for(let o of r[i])this.append(i,o);return}if(t!=null)if(typeof t=="object"){let r=t[Symbol.iterator];if(r!=null){if(typeof r!="function")throw new TypeError("Header pairs must be iterable");let n=[];for(let i of t){if(typeof i!="object"||typeof i[Symbol.iterator]!="function")throw new TypeError("Each header pair must be iterable");n.push(Array.from(i))}for(let i of n){if(i.length!==2)throw new TypeError("Each header pair must be a name/value tuple");this.append(i[0],i[1])}}else for(let n of Object.keys(t)){let i=t[n];this.append(n,i)}}else throw new TypeError("Provided initializer must be an object")}get(t){t=`${t}`,LGt(t);let r=Jct(this[CC],t);return r===void 0?null:this[CC][r].join(", ")}forEach(t){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:void 0,n=E9o(this),i=0;for(;i<n.length;){var o=n[i];let s=o[0],a=o[1];t.call(r,a,s,this),n=E9o(this),i++}}set(t,r){t=`${t}`,r=`${r}`,LGt(t),VHl(r);let n=Jct(this[CC],t);this[CC][n!==void 0?n:t]=[r]}append(t,r){t=`${t}`,r=`${r}`,LGt(t),VHl(r);let n=Jct(this[CC],t);n!==void 0?this[CC][n].push(r):this[CC][t]=[r]}has(t){return t=`${t}`,LGt(t),Jct(this[CC],t)!==void 0}delete(t){t=`${t}`,LGt(t);let r=Jct(this[CC],t);r!==void 0&&delete this[CC][r]}raw(){return this[CC]}keys(){return g9o(this,"key")}values(){return g9o(this,"value")}[Symbol.iterator](){return g9o(this,"key+value")}};d8.prototype.entries=d8.prototype[Symbol.iterator];Object.defineProperty(d8.prototype,Symbol.toStringTag,{value:"Headers",writable:!1,enumerable:!1,configurable:!0});Object.defineProperties(d8.prototype,{get:{enumerable:!0},forEach:{enumerable:!0},set:{enumerable:!0},append:{enumerable:!0},has:{enumerable:!0},delete:{enumerable:!0},keys:{enumerable:!0},values:{enumerable:!0},entries:{enumerable:!0}});I9o=Symbol("internal");v9o=Object.setPrototypeOf({next(){if(!this||Object.getPrototypeOf(this)!==v9o)throw new TypeError("Value of `this` is not a HeadersIterator");var e=this[I9o];let t=e.target,r=e.kind,n=e.index,i=E9o(t,r),o=i.length;return n>=o?{value:void 0,done:!0}:(this[I9o].index=n+1,{value:i[n],done:!1})}},Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));Object.defineProperty(v9o,Symbol.toStringTag,{value:"HeadersIterator",writable:!1,enumerable:!1,configurable:!0});OUe=Symbol("Response internals"),iqm=qHl.default.STATUS_CODES,vre=class e{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};jT.call(this,t,r);let n=r.status||200,i=new d8(r.headers);if(t!=null&&!i.has("Content-Type")){let o=JHl(t);o&&i.append("Content-Type",o)}this[OUe]={url:r.url,status:n,statusText:r.statusText||iqm[n],headers:i}}get url(){return this[OUe].url}get status(){return this[OUe].status}get ok(){return this[OUe].status>=200&&this[OUe].status<300}get statusText(){return this[OUe].statusText}get headers(){return this[OUe].headers}clone(){return new e(KHl(this),{url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok})}};jT.mixIn(vre.prototype);Object.defineProperties(vre.prototype,{url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});Object.defineProperty(vre.prototype,Symbol.toStringTag,{value:"Response",writable:!1,enumerable:!1,configurable:!0});Ume=Symbol("Request internals"),A9o=eJr.default.parse,oqm=eJr.default.format,sqm="destroy"in iJ.default.Readable.prototype;USe=class e{constructor(t){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n;$Kr(t)?n=A9o(t.url):(t&&t.href?n=A9o(t.href):n=A9o(`${t}`),t={});let i=r.method||t.method||"GET";if(i=i.toUpperCase(),(r.body!=null||$Kr(t)&&t.body!==null)&&(i==="GET"||i==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let o=r.body!=null?r.body:$Kr(t)&&t.body!==null?KHl(t):null;jT.call(this,o,{timeout:r.timeout||t.timeout||0,size:r.size||t.size||0});let s=new d8(r.headers||t.headers||{});if(o!=null&&!s.has("Content-Type")){let c=JHl(o);c&&s.append("Content-Type",c)}let a=$Kr(t)?t.signal:null;if("signal"in r&&(a=r.signal),a!=null&&!aqm(a))throw new TypeError("Expected signal to be an instanceof AbortSignal");this[Ume]={method:i,redirect:r.redirect||t.redirect||"follow",headers:s,parsedURL:n,signal:a},this.follow=r.follow!==void 0?r.follow:t.follow!==void 0?t.follow:20,this.compress=r.compress!==void 0?r.compress:t.compress!==void 0?t.compress:!0,this.counter=r.counter||t.counter||0,this.agent=r.agent||t.agent}get method(){return this[Ume].method}get url(){return oqm(this[Ume].parsedURL)}get headers(){return this[Ume].headers}get redirect(){return this[Ume].redirect}get signal(){return this[Ume].signal}clone(){return new e(this)}};jT.mixIn(USe.prototype);Object.defineProperty(USe.prototype,Symbol.toStringTag,{value:"Request",writable:!1,enumerable:!1,configurable:!0});Object.defineProperties(USe.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0}});_Gt.prototype=Object.create(Error.prototype);_Gt.prototype.constructor=_Gt;_Gt.prototype.name="AbortError";GHl=iJ.default.PassThrough,lqm=eJr.default.resolve;_Se.isRedirect=function(e){return e===301||e===302||e===303||e===307||e===308};_Se.Promise=global.Promise;uqm=_Se});var RUe=E(GQ=>{"use strict";var Gme={ANCHOR:"&",COMMENT:"#",TAG:"!",DIRECTIVES_END:"-",DOCUMENT_END:"."},UGt={ALIAS:"ALIAS",BLANK_LINE:"BLANK_LINE",BLOCK_FOLDED:"BLOCK_FOLDED",BLOCK_LITERAL:"BLOCK_LITERAL",COMMENT:"COMMENT",DIRECTIVE:"DIRECTIVE",DOCUMENT:"DOCUMENT",FLOW_MAP:"FLOW_MAP",FLOW_SEQ:"FLOW_SEQ",MAP:"MAP",MAP_KEY:"MAP_KEY",MAP_VALUE:"MAP_VALUE",PLAIN:"PLAIN",QUOTE_DOUBLE:"QUOTE_DOUBLE",QUOTE_SINGLE:"QUOTE_SINGLE",SEQ:"SEQ",SEQ_ITEM:"SEQ_ITEM"},pqm="tag:yaml.org,2002:",fqm={MAP:"tag:yaml.org,2002:map",SEQ:"tag:yaml.org,2002:seq",STR:"tag:yaml.org,2002:str"};function ZHl(e){let t=[0],r=e.indexOf(`
|
|
551
551
|
`);for(;r!==-1;)r+=1,t.push(r),r=e.indexOf(`
|
|
552
552
|
`,r);return t}function $Hl(e){let t,r;return typeof e=="string"?(t=ZHl(e),r=e):(Array.isArray(e)&&(e=e[0]),e&&e.context&&(e.lineStarts||(e.lineStarts=ZHl(e.context.src)),t=e.lineStarts,r=e.context.src)),{lineStarts:t,src:r}}function S9o(e,t){if(typeof e!="number"||e<0)return null;let{lineStarts:r,src:n}=$Hl(t);if(!r||!n||e>n.length)return null;for(let o=0;o<r.length;++o){let s=r[o];if(e<s)return{line:o,col:e-r[o-1]+1};if(e===s)return{line:o+1,col:1}}let i=r.length;return{line:i,col:e-r[i-1]+1}}function dqm(e,t){let{lineStarts:r,src:n}=$Hl(t);if(!r||!(e>=1)||e>r.length)return null;let i=r[e-1],o=r[e];for(;o&&o>i&&n[o-1]===`
|
|
553
553
|
`;)--o;return n.slice(i,o)}function mqm({start:e,end:t},r,n=80){let i=dqm(e.line,r);if(!i)return null;let{col:o}=e;if(i.length>n)if(o<=n-10)i=i.substr(0,n-1)+"\u2026";else{let u=Math.round(n/2);i.length>o+u&&(i=i.substr(0,o+u-1)+"\u2026"),o-=i.length-n,i="\u2026"+i.substr(1-n)}let s=1,a="";t&&(t.line===e.line&&o+(t.col-e.col)<=n+1?s=t.col-e.col:(s=Math.min(i.length+1,n)-o,a="\u2026"));let c=o>1?" ".repeat(o-1):"",l="^".repeat(s);return`${i}
|
|
@@ -3495,7 +3495,7 @@ ${esu.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&YHo(th
|
|
|
3495
3495
|
`).length),this}updateBottomBar(t){return Lqt(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+`
|
|
3496
3496
|
`}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&&Wen(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var qd=Ae(v3(),1),bau=Ae(Aqt(),1);var Stn=Ae(v3(),1),Aau=Ae(Aqt(),1),wtn=function(e,t,r){return typeof e[t]!="function"?(0,Stn.of)(e):(0,Stn.from)((0,Aau.default)(e[t])(r).then(n=>(e[t]=n,e)))};var yau={set:(e,t="",r)=>{let n=e;t.split(".").forEach((i,o,s)=>{i==="__proto__"||i==="constructor"||(o===s.length-1?n[i]=r:(!(i in n)||typeof n[i]!="object")&&(n[i]={}),n=n[i])})},get:(e,t="",r)=>{let n=o=>String.prototype.split.call(t,o).filter(Boolean).reduce((s,a)=>s!=null?s[a]:s,e),i=n(/[,[\]]+?/)||n(/[,.[\]]+?/);return i===void 0||i===e?r:i}},Qut=class extends vVe{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=typeof r=="object"?{...r}:{};let n;return Array.isArray(t)?n=(0,qd.from)(t):(0,qd.isObservable)(t)?n=t:Object.values(t).every(i=>typeof i=="object"&&!Array.isArray(i)&&i!=null)?n=(0,qd.from)(Object.entries(t).map(([i,o])=>({name:i,...o}))):n=(0,qd.from)([t]),this.process=n.pipe((0,qd.concatMap)(this.processQuestion.bind(this)),(0,qd.publish)()),this.process.connect(),this.process.pipe((0,qd.reduce)((i,o)=>(yau.set(i,o.name,o.answer),i),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,qd.defer)(()=>(0,qd.of)(t).pipe((0,qd.concatMap)(this.setDefaultType.bind(this)),(0,qd.concatMap)(this.filterIfRunnable.bind(this)),(0,qd.concatMap)(()=>wtn(t,"message",this.answers)),(0,qd.concatMap)(()=>wtn(t,"default",this.answers)),(0,qd.concatMap)(()=>wtn(t,"choices",this.answers)),(0,qd.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,qd.defer)(()=>(0,qd.from)(this.activePrompt.run().then(n=>({name:t.name,answer:n}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,qd.defer)(()=>(0,qd.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&yau.get(this.answers,t.name)!==void 0)return qd.EMPTY;if(t.when===!1)return qd.EMPTY;if(typeof t.when!="function")return(0,qd.of)(t);let{answers:r}=this;return(0,qd.defer)(()=>(0,qd.from)((0,bau.default)(t.when)(r).then(n=>{if(n)return t})).pipe((0,qd.filter)(n=>n!=null)))}};function Eau(e){let t=function(r,n){let i;try{i=new Qut(t.prompts,e)}catch(s){return Promise.reject(s)}let o=i.run(r,n);return o.ui=i,o};return t.prompts={},t.registerPrompt=function(r,n){return t.prompts[r]=n,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",Uqt),this.registerPrompt("input",AVe),this.registerPrompt("number",Vqt),this.registerPrompt("confirm",Gqt),this.registerPrompt("rawlist",qqt),this.registerPrompt("expand",Wqt),this.registerPrompt("checkbox",Hqt),this.registerPrompt("password",Kqt),this.registerPrompt("editor",rWt)},t.restoreDefaultPrompts(),t}var yJo=Eau();function Mgh(e,t){yJo.registerPrompt(e,t)}function Lgh(){yJo.restoreDefaultPrompts()}var _gh={prompt:yJo,ui:{BottomBar:nWt,Prompt:Qut},createPromptModule:Eau,registerPrompt:Mgh,restoreDefaultPrompts:Lgh,Separator:$Q},bo=_gh;var Ugh=["prod","pre-prod","beta","dev","local"];function Vgh(e){return Ugh.some(t=>t===e)}function gJ(e="prod"){let t=e?.trim();return t!=null&&Vgh(t)?t:"local"}function Ttn(){let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";return e==null||e.trim().length===0?!1:process.env.FERN_DISABLE_TELEMETRY!=="true"}var Mut=require("path");function vau(){let e=Ggh();return async t=>{for(let r of t)r.module=e(r.filename);return t}}function Ggh(e=process.argv[1]?(0,Mut.dirname)(process.argv[1]):process.cwd(),t=Mut.sep==="\\"){let r=t?Iau(e):e;return n=>{if(!n)return;let i=t?Iau(n):n,{dir:o,base:s,ext:a}=Mut.posix.parse(i);(a===".js"||a===".mjs"||a===".cjs")&&(s=s.slice(0,-1*a.length));let c=decodeURIComponent(s);o||(o=".");let l=o.lastIndexOf("/node_modules");if(l>-1)return`${o.slice(l+14).replace(/\//g,".")}:${c}`;if(o.startsWith(r)){let u=o.slice(r.length+1).replace(/\//g,".");return u?`${u}:${c}`:c}return c}}function Iau(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var LT={};ne(LT,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>qtn,DOMExceptionCoercer:()=>NJo,EXCEPTION_STEP_INTERNAL_FIELDS:()=>dWt,ErrorCoercer:()=>lWt,ErrorEventCoercer:()=>jJo,ErrorPropertiesBuilder:()=>cWt,EventCoercer:()=>zJo,ExceptionStepsBuffer:()=>_Jo,ObjectCoercer:()=>pWt,PrimitiveCoercer:()=>fWt,PromiseRejectionEventCoercer:()=>QJo,ReduceableCache:()=>MJo,StringCoercer:()=>uWt,chromeStackLineParser:()=>DJo,createDefaultStackParser:()=>FJo,createStackParser:()=>ucu,geckoStackLineParser:()=>RJo,getInjectedReleaseId:()=>iyh,getUtf8ByteLength:()=>fcu,nodeStackLineParser:()=>icu,opera10StackLineParser:()=>tcu,opera11StackLineParser:()=>rcu,resolveExceptionStepsConfig:()=>LJo,reverseAndStripFrames:()=>lcu,stripReservedExceptionStepFields:()=>tyh,winjsStackLineParser:()=>ecu});var tM=(function(e){return e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.EnablePersonProcessing="enable_person_processing",e.PersonMode="person_mode",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.AiQueue="ai_queue",e.AiCaptureQueue="ai_capture_queue",e.LogsQueue="logs_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.PushRegistered="push_registered",e.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysInProgress="surveys_in_progress",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e.DeviceId="device_id",e})({});function Rwe(e){let t=[];return JSON.stringify(e,function(r,n){if(typeof n=="bigint")return n.toString();if(!(typeof n=="function"||typeof n=="symbol")){if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(n&&typeof n=="object"){for(;t.length>0&&t[t.length-1]!==this;)t.pop();if(t.includes(n))return"[Circular]";t.push(n)}return n}})??"null"}var qgh=Array.isArray,xau=Object.prototype,cuC=xau.hasOwnProperty,Otn=xau.toString,x3=qgh||function(e){return Otn.call(e)==="[object Array]"};var iWt=e=>e===Object(e)&&!x3(e);var mhe=e=>e===void 0,wR=e=>Otn.call(e)=="[object String]",bJo=e=>wR(e)&&e.trim().length===0,EJo=e=>e===null,AJ=e=>mhe(e)||EJo(e),Lut=e=>Otn.call(e)=="[object Number]"&&e===e;var Sau=e=>Otn.call(e)==="[object Boolean]";function Ptn(e){return e===null||typeof e!="object"}function CVe(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function kwe(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Oau(e,Error)}}function wau(e){return CVe(e,"ErrorEvent")}function _ut(e){return"u">typeof Event&&Oau(e,Event)}function Tau(e){return CVe(e,"Object")}function Oau(e,t){try{return e instanceof t}catch{return!1}}var Wgh=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterestbot","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],Btn=new Map,Hgh=256;function Kgh(e,t){let r="";for(let n=0;n<t.length;n++){let i=t[n];r+=i.length+":"+i}return e.length+":"+e+"|"+t.length+":"+r}var Pau=function(e,t=[]){if(!e)return!1;let r=Kgh(e,t),n=Btn.get(r);if(n!==void 0)return n;let i=e.toLowerCase(),o=Wgh.concat(t).some(s=>i.indexOf(s.toLowerCase())!==-1);return Btn.size>=Hgh&&Btn.clear(),Btn.set(r,o),o};function oWt(e,t,r,n,i){return t>r&&(n.warn("min cannot be greater than max."),t=r),Lut(e)?e>r?(n.warn(" cannot be greater than max: "+r+". Using max value instead."),r):e<t?(n.warn(" cannot be less than min: "+t+". Using min value instead."),t):e:(n.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+i),oWt(i??r,t,r,n))}var Jgh=864e5,Ygh=1,Xgh=10;function Bau(e={}){return{refillRate:e.exceptionRateLimiterRefillRate??e.__exceptionRateLimiterRefillRate??Ygh,bucketSize:e.exceptionRateLimiterBucketSize??e.__exceptionRateLimiterBucketSize??Xgh}}var Dtn=class{constructor(t){this._buckets={},this._onBucketRateLimited=t._onBucketRateLimited,this._bucketSize=oWt(t.bucketSize,0,100,t._logger),this._refillRate=oWt(t.refillRate,0,this._bucketSize,t._logger),this._refillInterval=oWt(t.refillInterval,0,Jgh,t._logger)}_applyRefill(t,r){let n=r-t.lastAccess,i=Math.floor(n/this._refillInterval);if(i>0){let o=i*this._refillRate;t.tokens=Math.min(t.tokens+o,this._bucketSize),t.lastAccess=t.lastAccess+i*this._refillInterval}}consumeRateLimit(t){let r=Date.now(),n=String(t),i=this._buckets[n];return i?this._applyRefill(i,r):(i={tokens:this._bucketSize,lastAccess:r},this._buckets[n]=i),i.tokens===0?!0:(i.tokens--,i.tokens===0&&this._onBucketRateLimited?.(t),i.tokens===0)}stop(){this._buckets={}}};var Rtn="0123456789abcdef",ktn=class e{constructor(t){this.bytes=t}static ofInner(t){if(t.length===16)return new e(t);throw new TypeError("not 128-bit length")}static fromFieldsV7(t,r,n,i){if(!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(n)||!Number.isInteger(i)||t<0||r<0||n<0||i<0||t>0xffffffffffff||r>4095||n>1073741823||i>4294967295)throw new RangeError("invalid field value");let o=new Uint8Array(16);return o[0]=t/2**40,o[1]=t/2**32,o[2]=t/2**24,o[3]=t/2**16,o[4]=t/256,o[5]=t,o[6]=112|r>>>8,o[7]=r,o[8]=128|n>>>24,o[9]=n>>>16,o[10]=n>>>8,o[11]=n,o[12]=i>>>24,o[13]=i>>>16,o[14]=i>>>8,o[15]=i,new e(o)}static parse(t){let r;switch(t.length){case 32:r=/^[0-9a-f]{32}$/i.exec(t)?.[0];break;case 36:r=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break;case 38:r=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(t)?.slice(1,6).join("");break;case 45:r=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break;default:break}if(r){let n=new Uint8Array(16);for(let i=0;i<16;i+=4){let o=parseInt(r.substring(2*i,2*i+8),16);n[i+0]=o>>>24,n[i+1]=o>>>16,n[i+2]=o>>>8,n[i+3]=o}return new e(n)}throw new SyntaxError("could not parse UUID string")}toString(){let t="";for(let r=0;r<this.bytes.length;r++)t+=Rtn.charAt(this.bytes[r]>>>4),t+=Rtn.charAt(15&this.bytes[r]),(r===3||r===5||r===7||r===9)&&(t+="-");return t}toHex(){let t="";for(let r=0;r<this.bytes.length;r++)t+=Rtn.charAt(this.bytes[r]>>>4),t+=Rtn.charAt(15&this.bytes[r]);return t}toJSON(){return this.toString()}getVariant(){let t=this.bytes[8]>>>4;if(t<0)throw new Error("unreachable");if(t<=7)return this.bytes.every(r=>r===0)?"NIL":"VAR_0";if(t<=11)return"VAR_10";if(t<=13)return"VAR_110";if(t<=15)return this.bytes.every(r=>r===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new e(this.bytes.slice(0))}equals(t){return this.compareTo(t)===0}compareTo(t){for(let r=0;r<16;r++){let n=this.bytes[r]-t.bytes[r];if(n!==0)return Math.sign(n)}return 0}},IJo=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??Zgh()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(t,r){let n=this.generateOrAbortCore(t,r);return n===void 0&&(this.timestamp=0,n=this.generateOrAbortCore(t,r)),n}generateOrAbortCore(t,r){if(!Number.isInteger(t)||t<1||t>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(r<0||r>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(t>this.timestamp)this.timestamp=t,this.resetCounter();else{if(!(t+r>=this.timestamp))return;this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter())}return ktn.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let t=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return t[6]=64|t[6]>>>4,t[8]=128|t[8]>>>2,ktn.ofInner(t)}},Zgh=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),Dau,Z2=()=>$gh().toString(),$gh=()=>(Dau||(Dau=new IJo)).generate();var Ftn=class{add(t){let r=Z2(),n=++this.nextId;return this.promiseByIds[r]={id:n,promise:t},t.catch(()=>{}).finally(()=>{delete this.promiseByIds[r]}),t}async join(){let t=Object.values(this.promiseByIds).map(n=>n.promise),r=t.length;for(;r>0;)await Promise.all(t),t=Object.values(this.promiseByIds).map(n=>n.promise),r=t.length}getPromises(t=[],r=this.nextId){let n=new Set(t);return Object.values(this.promiseByIds).filter(i=>i.id<=r&&!n.has(i.promise)).map(i=>i.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}};function eAh(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var Rau=(e,t,r)=>{function n(o,...s){t(()=>{let a=r[o];a(e,...s)})}return{debug:(...o)=>{n("debug",...o)},info:(...o)=>{n("log",...o)},warn:(...o)=>{n("warn",...o)},error:(...o)=>{n("error",...o)},critical:(...o)=>{r.error(e,...o)},createLogger:o=>Rau(`${e} ${o}`,t,r)}},tAh=e=>e();function kau(e,t=tAh){return Rau(e,t,eAh())}var Vut="Mobile",jtn="iOS",Uut="Android",Qau="Tablet",CuC=Uut+" "+Qau;var nAh="Apple",xuC=nAh+" Watch",Mau="Safari",ztn="BlackBerry",Lau="Samsung",iAh=Lau+"Browser",oAh=Lau+" Internet",Qtn="Chrome",sAh=Qtn+" OS",aAh=Qtn+" "+jtn,_au="Internet Explorer",cAh=_au+" "+Vut,xJo="Opera",SuC=xJo+" Mini",Uau="Edge",lAh="Microsoft "+Uau,SJo="Firefox",uAh=SJo+" "+jtn,wJo="Nintendo",TJo="PlayStation",Ntn="Xbox",pAh=Uut+" "+Vut,fAh=Vut+" "+Mau,sWt="Windows",dAh=sWt+" Phone";var Vau="Generic",wuC=Vau+" "+Vut.toLowerCase(),TuC=Vau+" "+Qau.toLowerCase(),mAh="Konqueror",hAh="Oculus Browser",Fau="Vivaldi",gAh="Yandex",Nau="Whale",AAh="DuckDuckGo",yAh="Pale Moon",jau="Waterfox",zau="Brave",Gau="Claude",qau="Codex",Wau="ChatGPT",bAh="Google Search App",$b="(\\d+(\\.\\d+)?)",vJo=new RegExp("Version/"+$b),CJo=new RegExp("("+Gau+"|"+qau+"|"+Wau+")\\/"+$b);var OuC=new RegExp(Ntn,"i"),PuC=new RegExp(TJo+" \\w+","i"),BuC=new RegExp(wJo+" \\w+","i"),EAh=new RegExp(ztn+"|PlayBook|BB10","i"),IAh={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000","5.1":"XP","5.2":"XP","6.0":"Vista","6.1":"7","6.2":"8","6.3":"8.1","6.4":"10","10.0":"10"};var DuC={[cAh]:[new RegExp("rv:"+$b)],[lAh]:[new RegExp(Uau+"?\\/"+$b)],[Qtn]:[new RegExp("("+Qtn+"|CrMo)\\/"+$b)],[aAh]:[new RegExp("CriOS\\/"+$b)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+$b)],[Mau]:[vJo],[fAh]:[vJo],[xJo]:[new RegExp("("+xJo+"|OPR)\\/"+$b)],[SJo]:[new RegExp(SJo+"\\/"+$b)],[uAh]:[new RegExp("FxiOS\\/"+$b)],[mAh]:[new RegExp("Konqueror[:/]?"+$b,"i")],[ztn]:[new RegExp(ztn+" "+$b),vJo],[pAh]:[new RegExp("android\\s"+$b,"i")],[oAh]:[new RegExp(iAh+"\\/"+$b)],[hAh]:[new RegExp("OculusBrowser\\/"+$b)],[Fau]:[new RegExp(Fau+"\\/"+$b)],[gAh]:[new RegExp("YaBrowser\\/"+$b)],[Nau]:[new RegExp(Nau+"\\/"+$b)],[zau]:[new RegExp(zau+"\\/"+$b)],[Gau]:[CJo],[qau]:[CJo],[Wau]:[CJo],[AAh]:[new RegExp("(DuckDuckGo|Ddg)\\/"+$b)],[yAh]:[new RegExp("PaleMoon\\/"+$b)],[jau]:[new RegExp(jau+"\\/"+$b)],[bAh]:[new RegExp("GSA\\/"+$b)],[_au]:[new RegExp("(rv:|MSIE )"+$b)],Mozilla:[new RegExp("rv:"+$b)]};var RuC=[[new RegExp(Ntn+"; "+Ntn+" (.*?)[);]","i"),e=>[Ntn,e&&e[1]||""]],[new RegExp(wJo,"i"),[wJo,""]],[new RegExp(TJo,"i"),[TJo,""]],[EAh,[ztn,""]],[new RegExp(sWt,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[dAh,""];if(new RegExp(Vut).test(t)&&!/IEMobile\b/.test(t))return[sWt+" "+Vut,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let n=r[1],i=IAh[n]||"";return/arm/i.test(t)&&(i="RT"),[sWt,i]}return[sWt,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[jtn,t.join(".")]}return[jtn,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=mhe(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+Uut+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Uut+")","i"),e=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[Uut,t.join(".")]}return[Uut,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,e=>{let t=["Mac OS X",""];if(e&&e[1]){let r=[e[1],e[2],e[3]||"0"];t[1]=r.join(".")}return t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[sAh,""]],[/Linux|debian/i,["Linux",""]]];var Mtn="[Circular]",Ltn="[Truncated]",T8="[Unserializable]",Hau="[Function]",NuC=Date.prototype.getTime,juC=Date.prototype.toISOString;function Qre(e){let t="";for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>=55296&&n<=56319){let i=e.charCodeAt(r+1);i>=56320&&i<=57343?(t+=e[r]+e[r+1],r++):t+="\uFFFD"}else t+=n>=56320&&n<=57343?"\uFFFD":e[r]}return t}function hhe(e,t){if(!t)return e;let r=[];try{r=Object.keys(t)}catch{r=[]}for(let n of r){let i;try{i=t[n]}catch{i=T8}Object.defineProperty(e,n,{value:i,enumerable:!0,writable:!0,configurable:!0})}return e}function OJo(e,t=Date.now()){if(typeof e!="string"||!e)return;let r=e.trim(),n=/^\d+\s*,/.test(r)?r.slice(0,r.indexOf(",")).trim():r;if(/^\d+$/.test(n)){let s=1e3*Math.min(Number(n),300);return s>0?s:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(n))return;let i=/^\w{3} \w{3} /.test(n)?n+" GMT":n,o=Date.parse(i)-t;if(!(!Number.isFinite(o)||o<=0))return Math.min(o,3e5)}var xVe=class{record(t){if(t.kind==="too-large")return;if(t.kind!=="retry-later")return void this.reset();if(!t.retryAfterMs)return;let r=this.isOpen(),n=Date.now(),i=Math.min(t.retryAfterMs,3e5);if(!r){this._installedAt=n,this._until=n+i;return}this._until=Math.max(this._until,Math.min(n+i,this._installedAt+3e5))}remainingMs(){let t=Date.now();if(t<this._installedAt-5e3)return this.reset(),0;let r=Math.min(3e5,Math.max(0,this._until-t));return r===0&&this.reset(),r}isOpen(){return this.remainingMs()>0}reset(){this._until=0,this._installedAt=0}constructor(){this._until=0,this._installedAt=0}};var Kau="utf8",vAh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function CAh(e){return typeof e=="string"&&vAh.test(e)}function SVe(e,t){return CAh(e)?e:t()}function Gut(e,t){let r=new Error(t);try{Object.defineProperty(r,"name",{value:e,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function Jau(e){return e?.replace(/\/+$/,"")}async function Yau(e,t){let r=null;for(let n=0;n<t.retryCount+1;n++){n>0&&await new Promise(i=>setTimeout(i,t.retryDelay));try{return await e()}catch(i){if(r=i,!t.retryCheck(i))throw i}}throw r}function PJo(){return new Date().toISOString()}function $2(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}async function Fwe(e,t,r){let n;try{return await Promise.race([e,new Promise((i,o)=>{n=$2(()=>{try{r?.(),i()}catch(s){o(s)}},t)})])}finally{clearTimeout(n)}}var Xau=e=>e&&typeof e.then=="function";function aWt(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var _tn,Zau,Utn;function $au(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);return Utn&&r.length===Zau||(Zau=r.length,Utn=r.reduce((n,i)=>{_tn||(_tn={});let o=_tn[i];if(o)n[o[0]]=o[1];else{let s=e(i);for(let a=s.length-1;a>=0;a--){let l=s[a]?.filename,u=t[i];if(l&&u){n[l]=u,_tn[i]=[l,u];break}}}return n},{})),Utn}var BJo=50,xAh=1e3,SAh=100,wAh=4,cWt=class{constructor(t,r,n=[]){this.coercers=t,this.stackParser=r,this.modifiers=n}buildFromUnknown(t,r={}){let i=r&&r.mechanism||{handled:!0,type:"generic"},s=this.buildCoercingContext(i,r,0).apply(t),a=this.buildParsingContext(r),c=this.parseStacktrace(s,a);return{$exception_list:this.convertToExceptionList(c,i),$exception_level:"error"}}async modifyFrames(t){for(let r of t)r.stacktrace&&r.stacktrace.frames&&x3(r.stacktrace.frames)&&(r.stacktrace.frames=await this.applyModifiers(r.stacktrace.frames));return t}coerceFallback(t){return{type:"Error",value:"Unknown error",stack:t.syntheticException?.stack,synthetic:!0}}parseStacktrace(t,r){let n;t.cause!=null&&(n=this.parseStacktrace(t.cause,r));let i;if(t.stack!=""&&t.stack!=null)try{i=this.applyChunkIds(this.stackParser(t.stack,t.synthetic?r.skipFirstLines:0),r.chunkIdMap)}catch{}return{...t,cause:n,stack:i,errors:t.errors?.map(o=>this.parseStacktrace(o,r))}}applyChunkIds(t,r){return t.map(n=>(n.filename&&r&&(n.chunk_id=r[n.filename]),n))}applyCoercers(t,r){for(let n of this.coercers)if(n.match(t))return n.coerce(t,r);return this.coerceFallback(r)}async applyModifiers(t){let r=t;for(let n of this.modifiers)r=await n(r);return r}convertToExceptionList(t,r){let n=[],i=(o,s,a)=>{let c=n.length,l=s===void 0?{type:typeof r.type=="string"&&r.type.length>0?r.type:"generic",...typeof r.handled=="boolean"?{handled:r.handled}:r.handled===void 0?{handled:!0}:{},synthetic:typeof r.synthetic=="boolean"?r.synthetic:o.synthetic,exception_id:c}:{type:"chained",source:a,synthetic:o.synthetic,exception_id:c,parent_id:s},u={type:o.type,value:o.value,mechanism:l};o.stack&&(u.stacktrace={type:"raw",frames:o.stack}),n.push(u),o.cause&&i(o.cause,c,"cause");for(let p of o.errors??[])i(p,c,"member")};return i(t),n}buildParsingContext(t){return{chunkIdMap:$au(this.stackParser),skipFirstLines:t.skipFirstLines??1}}getAggregateErrors(t){try{if(kwe(t)){let r=Object.getPrototypeOf(t);for(let n=0;r&&n<SAh;n++){let i=Object.getOwnPropertyDescriptor(r,"constructor")?.value;if(typeof i=="function"&&i.name==="AggregateError"){let o=t.errors;return x3(o)?o:void 0}r=Object.getPrototypeOf(r)}}}catch{}}buildCoercingContext(t,r,n=0){let i=0,o=0,s=!1,a=new Set,c=[],l={},u=(f,m,g=0)=>{let A=p(m,g),b=A.apply;if(A.apply=D=>{c.push(f);try{return b(D)}finally{c.pop()}},g>wAh||g>0&&c.indexOf(f)!==-1)return this.coerceFallback(A);let I=typeof f=="object"&&f!==null||typeof f=="function";if(g===0&&i>=BJo||I&&a.has(f))return;I&&a.add(f),g===0&&i++;let C=this.getAggregateErrors(f);s||=!!C;let x;try{if(x=this.applyCoercers(f,A),!x)throw l}catch(D){if(D===l){g===0&&i--;return}if(!s)throw D;x=this.coerceFallback(A)}if(!C||i>=BJo)return x;let S;try{S=C.length}catch{return x}if(!Number.isInteger(S)||S<0||S>4294967295)return x;let P=[];for(let D=0;i<BJo&&o<xAh&&D<S;D++){o++;let R;try{R=A.next(C[D])}catch{i++,R=this.coerceFallback(p(m+1))}R&&P.push(R)}return{...x,errors:P}},p=(f,m=0)=>({...r,syntheticException:f==0?r.syntheticException:void 0,mechanism:f==0?t:{},apply:g=>{let A=u(g,f,m+1);if(!A)throw l;return A},next:g=>u(g,f+1)}),d=p(n);return{...d,apply:f=>u(f,n)??this.coerceFallback(d)}}};var TB="?",TAh="<anonymous>",OAh=/^([a-z][a-z0-9.+-]+):/i,PAh=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function BAh(e){if(!e||e===TAh)return!1;let t=OAh.exec(e);return!t||PAh.includes(t[1].toLowerCase())}function Mre(e,t,r,n,i){let o={platform:e,filename:t,function:r==="<anonymous>"?TB:r,in_app:BAh(t)};return mhe(n)||(o.lineno=n),mhe(i)||(o.colno=i),o}var Vtn=(e,t)=>{let r=e.indexOf("safari-extension")!==-1,n=e.indexOf("safari-web-extension")!==-1;return r||n?[e.indexOf("@")!==-1?e.split("@")[0]:TB,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var DAh=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,RAh=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,kAh=/\((\S*)(?::(\d+))(?::(\d+))\)/,DJo=(e,t)=>{let r=DAh.exec(e);if(r){let[,i,o,s]=r;return Mre(t,i,TB,+o,+s)}let n=RAh.exec(e);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=kAh.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}let[o,s]=Vtn(n[1]||TB,n[2]);return Mre(t,s,o,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var FAh=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,NAh=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,RJo=(e,t)=>{let r=FAh.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let s=NAh.exec(r[3]);s&&(r[1]=r[1]||"eval",r[3]=s[1],r[4]=s[2],r[5]="")}let i=r[3],o=r[1]||TB;return[o,i]=Vtn(o,i),Mre(t,i,o,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var jAh=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,ecu=(e,t)=>{let r=jAh.exec(e);return r?Mre(t,r[2],r[1]||TB,+r[3],r[4]?+r[4]:void 0):void 0};var zAh=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,tcu=(e,t)=>{let r=zAh.exec(e);return r?Mre(t,r[2],r[3]||TB,+r[1]):void 0},QAh=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,rcu=(e,t)=>{let r=QAh.exec(e);return r?Mre(t,r[5],r[3]||r[4]||TB,+r[1],+r[2]):void 0};var MAh=/^\s*[-]{4,}$/,LAh=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,_Ah=/^Promise\.(?:all|any)$/,UAh=/^index \d+$/,VAh="node:internal/promise",icu=(e,t)=>{let r=e.match(LAh);if(r){let n,i,o,s,a;if(r[1]){o=r[1];let u=o.lastIndexOf(".");if(o[u-1]==="."&&u--,u>0){n=o.slice(0,u),i=o.slice(u+1);let p=n.indexOf(".Module");p>0&&(o=o.slice(p+1),n=n.slice(0,p))}s=void 0}i&&(s=n,a=i),i==="<anonymous>"&&(a=void 0,o=void 0),o===void 0&&(a=a||TB,o=s?`${s}.${a}`:a);let c=r[2]?.startsWith("file://")?r[2].slice(7):r[2],l=r[5]==="native";return c?.match(/\/[A-Z]:/)&&(c=c.slice(1)),!c&&r[5]&&!l&&(c=r[5]),_Ah.test(o)&&UAh.test(c||"")&&(c=VAh),{filename:c?decodeURI(c):void 0,module:void 0,function:o,lineno:ncu(r[3]),colno:ncu(r[4]),in_app:GAh(c||"",l),platform:t}}if(e.match(MAh))return{filename:e,platform:t}};function GAh(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 ncu(e){return parseInt(e||"",10)||void 0}var ocu=/\(error: (.*)\)/,scu=50,qAh=10,WAh=1e3;function kJo(e,t){return e.filename===t.filename&&e.function===t.function&&e.module===t.module&&e.lineno===t.lineno&&e.colno===t.colno}function HAh(e){for(let t=1;t<=qAh;t++){let r=e.length-2*t;if(r<0)break;let n=!0;for(let i=0;i<t;i++){let o=e[r+i];if(!kJo(o,e[r+t+i])){n=!1;break}}if(n){for(let i=0;i<t;i++)e[r+i]=e[r+t+i];return e.length=r+t,{start:r,length:t}}}}function KAh(e,t){let r=t.start+t.length,n=ccu(e,t);n&&e.splice(r+n===e.length?r:t.start,n)}function acu(e,t){let r=t.start;for(;r>0&&kJo(e[r-1],e[r-1+t.length]);)r--;return t.start-r}function ccu(e,t){let r=t.start+t.length,n=r;for(;n<e.length&&kJo(e[n],e[n-t.length]);)n++;return n-r}function JAh(e,t){let r=t[0],n=e.length-(r?acu(e,r):0);for(let i of t)n-=ccu(e,i);return n}function YAh(e){let t=e.map(n=>`${n.function}|${n.filename}|${n.lineno}|${n.colno}|${n.module}`),r=0;for(let n=1;n<t.length;n++)XAh(t,n,r)&&(r=n);e.push(...e.splice(0,r))}function XAh(e,t,r){for(let n=0;n<e.length;n++){let i=e[(t+n)%e.length],o=e[(r+n)%e.length];if(i!==o)return i<o}return!1}function lcu(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,scu).map(r=>({...r,filename:r.filename||ZAh(t).filename,function:r.function||TB}))}function ZAh(e){return e[e.length-1]||{}}function FJo(){return ucu("web:javascript",DJo,RJo)}function ucu(e,...t){return(r,n=0)=>{let i=[],o=r.split(`
|
|
3497
3497
|
`),s=Math.min(o.length,n+WAh),a=[];for(let u=n;u<s;u++){let p=o[u];if(p.length>1024)continue;let d=ocu.test(p)?p.replace(ocu,"$1"):p;if(!d.match(/\S*Error: /)){for(let f of t){let m=f(d,e);if(m){i.push(m);let g=HAh(i);if(g){for(let A=a.length-1;A>=0;A--){let b=a[A];if(b.start+b.length<=g.start)break;a.pop()}a.push(g)}break}}if(JAh(i,a)>=scu)break}}let c=[...a].sort((u,p)=>p.start-u.start),l=c[c.length-1];if(l){let u=acu(i,l);i.splice(l.start-u,u);for(let p of c)p.start-=u}for(let u of c)KAh(i,u);return a.some(u=>u.start===0&&i.length===u.length)&&YAh(i),lcu(i)}}var NJo=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let n=wR(t.stack);return{type:this.getType(t),value:this.getValue(t),stack:n?t.stack:void 0,cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return this.isDOMError(t)?"DOMError":"DOMException"}getValue(t){let r=t.name||(this.isDOMError(t)?"DOMError":"DOMException");return t.message?`${r}: ${t.message}`:r}isDOMException(t){return CVe(t,"DOMException")}isDOMError(t){return CVe(t,"DOMError")}};var lWt=class{match(t){return kwe(t)}coerce(t,r){let n=this.getStack(t),i=n===void 0?r.syntheticException?.stack:void 0,o=!!i;return{type:this.getType(t),value:this.getMessage(t,r),stack:n??i,cause:t.cause?r.next(t.cause):void 0,synthetic:o}}getType(t){return t.name||t.constructor.name}getMessage(t,r){let n=t.message;return n.error&&typeof n.error.message=="string"?String(n.error.message):String(n)}getStack(t){try{let r=t.stacktrace;if(typeof r=="string"&&r.length>0)return r;let n=t.stack;return typeof n=="string"&&n.length>0?n:void 0}catch{return}}};var jJo=class{match(t){if(!wau(t))return!1;let r=t;return r.error!=null||this._hasUsableMessage(r)}coerce(t,r){if(t.error!=null)return r.apply(t.error);let n=r.apply(t.message);return{...n,stack:this._buildLocationStack(t)??n.stack,synthetic:!0}}_hasUsableMessage(t){return wR(t.message)&&t.message.length>0}_buildLocationStack(t){let r=t,n=r.lineno??0,i=r.colno??0;if(!(!wR(r.filename)||r.filename.length===0)&&n!==0)return`Error
|
|
3498
|
-
at ${r.filename}:${n}:${i}`}};var $Ah=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,uWt=class{match(t){return typeof t=="string"}coerce(t,r){let[n,i]=this.getInfos(t);return{type:n??"Error",value:i??t,stack:r.syntheticException?.stack,synthetic:!0}}getInfos(t){let r="Error",n=t,i=t.match($Ah);return i&&(r=i[1],n=i[2]),[r,n]}};var pcu=["fatal","error","warning","log","info","debug"];function Gtn(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let n=r.length;n>0;n--){let i=r.slice(0,n).join(", ");if(!(i.length>t))return n===r.length||i.length<=t?i:`${i.slice(0,t)}...`}return""}var pWt=class{match(t){return typeof t=="object"&&t!==null}coerce(t,r){let n=this.getErrorPropertyFromObject(t);return n?r.apply(n):{type:this.getType(t),value:this.getValue(t),stack:this.getStack(t)??r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){if(_ut(t))return t.constructor.name;let r="name"in t?t.name:void 0;return wR(r)&&!bJo(r)?r:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){let i=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(i+=` with message: '${t.message}'`),i}if("message"in t&&typeof t.message=="string")return t.message;let r=this.getObjectClassName(t),n=Gtn(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(t){return wR(t)&&!bJo(t)&&pcu.indexOf(t)>=0}getStack(t){try{return wR(t.stacktrace)&&t.stacktrace.length>0?t.stacktrace:wR(t.stack)&&t.stack.length>0?t.stack:void 0}catch{return}}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(kwe(n))return n}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var zJo=class{match(t){return _ut(t)}coerce(t,r){let n=t.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${Gtn(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var fWt=class{match(t){return Ptn(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var QJo=class{match(t){return CVe(t,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(t)}isCustomEventWrappingRejection(t){if(!_ut(t))return!1;try{let r=t.detail;return r!=null&&typeof r=="object"&&"reason"in r}catch{return!1}}coerce(t,r){let n=this.getUnhandledRejectionReason(t);return Ptn(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(n)}getUnhandledRejectionReason(t){try{if("reason"in t)return t.reason;if("detail"in t&&t.detail!=null&&typeof t.detail=="object"&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var MJo=class{constructor(t){this._maxSize=t,this._cache=new Map}get(t){let r=this._cache.get(t);if(r!==void 0)return this._cache.delete(t),this._cache.set(t,r),r}set(t,r){this._cache.set(t,r)}reduce(){for(;this._cache.size>=this._maxSize;){let t=this._cache.keys().next().value;t&&this._cache.delete(t)}}};var dWt={MESSAGE:"$message",TIMESTAMP:"$timestamp"},eyh=new Set([dWt.MESSAGE,dWt.TIMESTAMP]),qtn={enabled:!0,max_bytes:32768};function LJo(e){return e?{enabled:e.enabled??qtn.enabled,max_bytes:ryh(e.max_bytes,qtn.max_bytes)}:{...qtn}}function tyh(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((n,i)=>eyh.has(i)?(t.push(i),n):(n[i]=e[i],n),{}),droppedKeys:t}}var _Jo=class{constructor(t){this._entries=[],this._totalBytes=0,this._config=LJo(t)}setConfig(t){this._config=LJo(t),this._trimToMaxBytes()}add(t){let r=nyh(t);if(!r)return;let n=fcu(r.json);n>this._config.max_bytes||(this._entries.push({step:r.step,bytes:n}),this._totalBytes+=n,this._trimToMaxBytes())}getAttachable(){return this._entries.map(t=>t.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){let t=this._entries.shift();t&&(this._totalBytes-=t.bytes)}}};function ryh(e,t){if(!Lut(e)||e===1/0||e===-1/0)return t;let r=Math.floor(e);return r<0?t:r}function nyh(e){let t;try{t=Rwe(e)}catch{return}try{let r=JSON.parse(t);if(!iWt(r))return;let n=r,i=n[dWt.MESSAGE],o=n[dWt.TIMESTAMP];return!wR(i)||i.trim().length===0||!wR(o)&&!Lut(o)?void 0:{step:n,json:t}}catch{return}}function fcu(e){if("u">typeof TextEncoder)return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),r=0;for(let n=0;n<t.length;n++)t[n]==="%"?(r+=1,n+=2):r+=1;return r}function iyh(){let e=globalThis._posthogReleaseId;return typeof e=="string"&&e.length>0?e:void 0}var UJo=e=>{if("flags"in e){let t=dcu(e.flags),r=mcu(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([i,o])=>[i,qut(o)])),n=Object.fromEntries(Object.entries(t).map(([i,o])=>[i,oyh(i,o,r[i])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:n}}};function oyh(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 dcu=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,mWt(r)]).filter(([,t])=>t!==void 0)),mcu=e=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter(r=>{let n=t[r];return n.enabled&&n.metadata&&n.metadata.payload!==void 0}).map(r=>{let n=t[r].metadata?.payload;return[r,n?qut(n):void 0]}))},mWt=e=>e===void 0?void 0:e.variant??e.enabled,qut=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var hcu=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","irclid","_kx"],syh=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain",...hcu,"$session_id","$window_id","$lib","$lib_version","$device_id","$is_server","$react_native_version"],hWt=(e,t=[])=>{let r={},n=i=>{e[i]!==void 0&&(r[i]=e[i])};return syh.forEach(n),t.forEach(n),r};var Wtn=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(n=>n!==r)}}emit(t,r){for(let n of this.events[t]||[])n(r);for(let n of this.events["*"]||[])n(t,r)}};function VJo(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var cyh="NativeGzipValidationError",lyh=31,uyh=139,pyh=8,fyh=e=>e.length>=2&&e[0]===lyh&&e[1]===uyh;var gWt,dyh=()=>{if(gWt)return gWt;gWt=[];for(let e=0;e<256;e++){let t=e;for(let r=0;r<8;r++)t=1&t?3988292384^t>>>1:t>>>1;gWt[e]=t>>>0}return gWt},myh=e=>{let t=dyh(),r=4294967295;for(let n=0;n<e.length;n++)r=t[(r^e[n])&255]^r>>>8;return(4294967295^r)>>>0},Htn=e=>{throw Gut(cyh,`Native gzip produced invalid output: ${e}`)},hyh=async(e,t)=>{e.size<18&&Htn("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());(!fyh(r)||r[2]!==pyh)&&Htn("invalid-header");let n=new DataView(await e.slice(e.size-8).arrayBuffer());n.getUint32(0,!0)!==myh(t)&&Htn("invalid-crc");let i=t.length>>>0;n.getUint32(4,!0)!==i&&Htn("invalid-size")};async function AWt(e,t=!0,r){try{let n=new TextEncoder().encode(e),i=new globalThis.CompressionStream("gzip"),o=i.writable.getWriter(),s=o.write(n).then(()=>o.close()).catch(async l=>{try{await o.abort(l)}catch{}throw l}),a=new Response(i.readable).blob(),[c]=await Promise.all([a,s]);return await hyh(c,n),c}catch(n){if(r?.rethrow)throw n;return t&&console.error("Failed to gzip compress data",n),null}}var O8=class extends Error{constructor(t,r,n,i){super("HTTP error while fetching PostHog: status="+t.status+", reqByteLength="+r),this.response=t,this.reqByteLength=r,this.responseBodyDeadline=n,this.abortController=i,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return OJo(this.response.headers?.get("retry-after"))}catch{return}}get bodyReadTimedOut(){return this._bodyReadTimedOut}get text(){if(!this.responseBodyTextPromise)if(Date.now()>=this.responseBodyDeadline){this._bodyReadTimedOut=!0;let t=Gut("AbortError","Response body read timed out");this.cancelResponseBody(t),this.responseBodyTextPromise=Promise.reject(t)}else{let t=new Promise((n,i)=>{this.responseBodyTimer=$2(()=>{this._bodyReadTimedOut=!0;let o=Gut("AbortError","Response body read timed out");i(o),this.cancelResponseBody(o)},this.responseBodyDeadline-Date.now())}),r;try{r=Promise.resolve(this.response.text())}catch(n){r=Promise.reject(n)}this.responseBodyTextPromise=Promise.race([r,t]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then(t=>JSON.parse(t))}cancelResponseBody(t){clearTimeout(this.responseBodyTimer),this.abortController.signal.aborted||this.abortController.abort(t),(async()=>{try{await this.response.body?.cancel()}catch{}})()}},ghe=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};var Ecu=(e,t)=>{for(let r of Object.keys(t))(r.startsWith("$feature/")||r==="$active_feature_flags")&&(e[r]=t[r])};async function gcu(e){if(e instanceof O8){let t="";try{t=await e.text}catch{e.bodyReadTimedOut&&(t="<response body read timed out>")}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 gyh(e){return typeof e=="object"&&(e instanceof O8||Icu(e))}function Icu(e){return e instanceof ghe}function Ayh(e){if(e instanceof O8)return e.status===502||e.status===504;if(!(e instanceof ghe))return!1;let t=e.error;return(t?.code??t?.cause?.code)!=="ECONNREFUSED"}var Acu=10485760;function ycu(e){try{return typeof e!="string"?e instanceof Uint8Array?e.byteLength:e.size:"u">typeof Buffer?Buffer.byteLength(e,Kau):new TextEncoder().encode(e).length}catch{return 0}}function Wut(e){return typeof e=="object"&&e instanceof O8&&e.status===413}function Ktn(e){return e instanceof O8?e.status===408||e.status===429||e.status>=500:Icu(e)}function bcu(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var GJo="default",yWt=class{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new cWt([new lWt,new pWt,new uWt,new fWt],FJo())}getEvaluationRuntime(){}constructor(t,r={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new Ftn,this._events=new Wtn,this._isInitialized=!1;let n=typeof t=="string"?t.trim():"",i=typeof r.host=="string"?r.host.trim():"",o=!n;this._logger=kau("[PostHog]",this.logMsgIfDebug.bind(this)),o&&this._logger.error("You must pass your PostHog project's api key. The client will be disabled."),this.apiKey=n,this.host=Jau(i||"https://us.i.posthog.com"),this.flushAt=r.flushAt?Math.max(r.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,r.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,r.maxQueueSize??1e3),this.flushInterval=r.flushInterval??1e4,this.preloadFeatureFlags=r.preloadFeatureFlags??!0,this.defaultOptIn=r.defaultOptIn??!0,this.disableSurveys=r.disableSurveys??!1,this._retryOptions={retryCount:r.fetchRetryCount??3,retryDelay:r.fetchRetryDelay??3e3,retryCheck:Ktn},this.requestTimeout=r.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=r.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=r.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=r.disableGeoip??!0,this.disabled=(r.disabled??!1)||o,this.historicalMigration=r?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=r?.evaluationContexts??r?.evaluationEnvironments,r?.evaluationEnvironments&&!r?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!VJo()||(r?.disableCompression??!1)}logMsgIfDebug(t){this.isDebug&&t()}wrap(t){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return t();this._initPromise.then(()=>t())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(tM.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(tM.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(tM.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(n,i)=>this._logger.info(n,i));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(t){let r=t.properties||{},n={...r,...this.getCommonEventProperties()};return Ecu(n,r),t.event==="$feature_flag_called"&&n.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled()&&(n=hWt(n)),{distinct_id:t.distinct_id,event:t.event,properties:n}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(t){return this.promiseQueue.add(t)}identifyStateless(t,r,n){this.wrap(()=>{let i={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",i,n)})}async identifyStatelessImmediate(t,r,n){let i={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};await this.sendImmediate("identify",i,n)}captureStateless(t,r,n,i){this.wrap(()=>{let o=this.buildPayload({distinct_id:t,event:r,properties:n});this.enqueue("capture",o,i)})}async captureStatelessImmediate(t,r,n,i){let o=this.buildPayload({distinct_id:t,event:r,properties:n});await this.sendImmediate("capture",o,i)}aliasStateless(t,r,n,i){this.wrap(()=>{let o=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:t}});this.enqueue("alias",o,i)})}async aliasStatelessImmediate(t,r,n,i){let o=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:t}});await this.sendImmediate("alias",o,i)}groupIdentifyStateless(t,r,n,i,o,s){this.wrap(()=>{let a=this.buildPayload({distinct_id:o||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{},...s||{}}});this.enqueue("capture",a,i)})}async groupIdentifyStatelessImmediate(t,r,n,i,o,s){let a=this.buildPayload({distinct_id:o||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{},...s||{}}});await this.sendImmediate("capture",a,i)}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`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(r,n,{type:"required",consume:i=>i.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).catch(i=>{this._logger.error("Remote config could not be loaded",i),this._events.emit("error",i)})}async getFlags(t,r={},n={},i={},o={},s=!1){await this._initPromise;let a=s?"&config=true":"",c=`${this.host}/flags/?v=2${a}`,l={token:this.apiKey,distinct_id:t,groups:r,person_properties:n,group_properties:i,...o};n.$device_id&&(l.$device_id=n.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(l.evaluation_contexts=this.evaluationContexts);let u=this.getEvaluationRuntime();u&&(l.evaluation_runtime=u);let p={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(l)};return this._logger.info("Flags URL",c),this.fetchWithRetry(c,p,{type:"required",consume:d=>d.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:Ayh},this.featureFlagsRequestTimeoutMs).then(d=>({success:!0,response:UJo(d)})).catch(d=>(this._events.emit("error",d),{success:!1,error:this.categorizeRequestError(d)}))}categorizeRequestError(t){if(t instanceof O8)return{type:"api_error",statusCode:t.status};if(t instanceof ghe){let r=t.error;return r instanceof Error&&(r.name==="AbortError"||r.name==="TimeoutError")?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(t,r,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagDetailStateless(t,r,n,i,o,s);if(a===void 0)return{response:void 0,requestId:void 0};let c=mWt(a.response);return c===void 0&&(c=!1),{response:c,requestId:a.requestId}}async getFeatureFlagDetailStateless(t,r,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(r,n,i,o,s,[t]);return a===void 0?void 0:{response:a.flags[t],requestId:a.requestId,evaluatedAt:a.evaluatedAt}}async getFeatureFlagPayloadStateless(t,r,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagPayloadsStateless(r,n,i,o,s,[t]);if(!a)return;let c=a[t];return c===void 0?null:c}async getFeatureFlagPayloadsStateless(t,r={},n={},i={},o,s){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,o,s)).payloads}async getFeatureFlagsStateless(t,r={},n={},i={},o,s){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,o,s)}async getFeatureFlagsAndPayloadsStateless(t,r={},n={},i={},o,s){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(t,r,n,i,o,s);return a?{flags:a.featureFlags,payloads:a.featureFlagPayloads,requestId:a.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(t,r={},n={},i={},o,s){await this._initPromise;let a={geoip_disable:o??this.disableGeoip};s&&(a.flag_keys_to_evaluate=s);let c=await this.getFlags(t,r,n,i,a);if(!c.success)return;let l=c.response;return l.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"),l.quotaLimited?.includes("feature_flags")?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:l?.requestId,quotaLimited:l.quotaLimited}):l}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let t=`${this.host}/api/surveys/?token=${this.apiKey}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},i=(await this.fetchWithRetry(t,r,{type:"required",consume:o=>{if(o.status!==200||!o.json){let s=`Surveys API could not be loaded: ${o.status}`,a=new Error(s);return this._logger.error(a),this._events.emit("error",new Error(s)),Promise.resolve(void 0)}return o.json()}}).catch(o=>{this._logger.error("Surveys API could not be loaded",o),this._events.emit("error",o)}))?.surveys;return i&&this._logger.info("Surveys fetched from API: ",JSON.stringify(i)),i??[]}get props(){return this._props||(this._props=this.getPersistedProperty(tM.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(tM.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(tM.Props,this.props)})}processBeforeEnqueue(t){return t}async flushStorage(){}getQueueRouteKey(t){return GJo}persistedQueueKeyForRoute(t){return tM.Queue}getActiveQueueRoutes(){return[GJo]}getRouteQueue(t){return this.getPersistedProperty(this.persistedQueueKeyForRoute(t))||[]}enqueue(t,r,n,i){this.wrap(()=>{if(this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let o=this.prepareMessage(r,n);if(o=this.processBeforeEnqueue(o),o===null)return;o=this.normalizeMessage(o);let s=this.persistedQueueKeyForRoute(i??this.getQueueRouteKey(o)),a=this.getPersistedProperty(s)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),a.push({message:o}),this.setPersistedProperty(s,a),this._events.emit(t,o),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=$2(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,n,i){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let o=this.prepareMessage(r,n);if(o=this.processBeforeEnqueue(o),o!==null){o=this.normalizeMessage(o);try{await this.sendBatch([o],void 0,i??this.getQueueRouteKey(o))}catch(s){this._events.emit("error",s)}}}normalizeMessage(t){let{type:r,library:n,library_version:i,...o}=t,s=bcu(o.properties)?o.properties:void 0;return n!==void 0&&s?.$lib===void 0&&(s={...s||{},$lib:n}),i!==void 0&&s?.$lib_version===void 0&&(s={...s||{},$lib_version:i}),s&&(o.properties=s),o.uuid=SVe(o.uuid,Z2),o}normalizeTimestampForWire(t){let r=t instanceof Date?t:typeof t=="string"?new Date(t):null;if(!r||Number.isNaN(r.getTime()))return t;let n=r.toISOString(),i=typeof t=="string"?t.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return i&&i.length>3?n.replace(/\.\d{3}Z$/,`.${i}Z`):n}prepareMessage(t,r){let n={...t,timestamp:r?.timestamp?r?.timestamp:PJo(),uuid:SVe(r?.uuid,Z2)};return(r?.disableGeoip??this.disableGeoip)&&(bcu(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.pendingFlushPromise||this.flushAutomatic().catch(async t=>{await gcu(t)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(t,r=[]){let n=r.filter(o=>!!o),i=0;for(;;){let o=this.promiseQueue.getPromises([...n,...this.flushPromises],t);if(o.length===0)return;i>0&&this._logger.debug(`flush() re-checking ${o.length} pending promise(s) before flushing`),await Promise.all(o.map(s=>s.catch(()=>{}))),i++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(t){if(this.disabled)return Promise.resolve();if(!t&&this.pendingFlushPromise)return this.pendingFlushPromise;let r=this.flushPromise,n=this.promiseQueue.maxId,i=Promise.resolve().then(()=>{if(t)return this.waitForPendingPromises(n,[r,i])}).then(()=>aWt([r])).then(()=>(this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=i,this.flushPromise=i,this.flushPromises.add(i),this.addPendingPromise(i),aWt([i]).then(()=>{this.flushPromises.delete(i),this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this.flushPromise===i&&(this.flushPromise=null)}),i}getCustomHeaders(){let t=this.getCustomUserAgent(),r={};return t&&t!==""&&(r["User-Agent"]=t),r}compressPayload(t){return AWt(t,this.isDebug)}getBatchEndpointPath(t){return"/batch/"}async sendBatch(t,r,n=GJo){let i={api_key:this.apiKey,batch:t.map(l=>{if(!l)return l;let u=this.normalizeTimestampForWire(l.timestamp);return u===l.timestamp?l:{...l,timestamp:u}}),sent_at:PJo()};this.historicalMigration&&(i.historical_migration=!0);let o=Rwe(i),s=`${this.host}${this.getBatchEndpointPath(n)}`,a=this.disableCompression?null:await this.compressPayload(o),c={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...a!==null&&{"Content-Encoding":"gzip"}},body:a||o};await this.fetchWithRetry(s,c,{type:"successful-write"},r)}async _flush(){this.clearFlushTimer(),await this._initPromise;let t=this.getActiveQueueRoutes();if(!t.some(i=>this.getRouteQueue(i).length>0))return;let r=[],n;for(let i of t)try{await this._flushRoute(i,r)}catch(o){n===void 0&&(n=o)}if(n!==void 0)throw n;this._events.emit("flush",r)}async _flushRoute(t,r){let n=this.persistedQueueKeyForRoute(t),i=this.getPersistedProperty(n)||[];if(!i.length)return;let o=i.length,s=0;for(;i.length>0&&s<o;){let a=i.slice(0,this.maxBatchSize),c=a.map(p=>p.message===void 0?p.message:this.normalizeMessage(p.message)),l=async()=>{let p=this.getPersistedProperty(n)||[],d=[...a],f=p.filter(m=>{let g=m.message?.uuid,A=d.findIndex(b=>b===m||typeof g=="string"&&g.length>0&&b.message?.uuid===g);return A===-1?!0:(d.splice(A,1),!1)});this.setPersistedProperty(n,f),i=f,this._dequeuedMessagesCount+=a.length,await this.flushStorage()},u={retryCheck:p=>Wut(p)?!1:Ktn(p)};try{await this.sendBatch(c,u,t)}catch(p){if(Wut(p)&&c.length>1){this.maxBatchSize=Math.max(1,Math.floor(c.length/2)),this._logger.warn(`Received 413 when sending batch of size ${c.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw p instanceof ghe||await l(),this._events.emit("error",p),p}await l(),r.push(...c),s+=c.length}}async _sendOtlpBatch({path:t,auth:r,payload:n}){if(this.disabled)return{kind:"fatal",error:new Error("The client is disabled")};let i;try{i=JSON.stringify(n)}catch(u){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${t} batch; reporting it as too large`,u)),{kind:"too-large",measuredLocally:!0}}let o=ycu(i);if(o>Acu)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${t} batch of ${o} bytes: the endpoint accepts at most ${Acu}`)),{kind:"too-large",measuredLocally:!0};let s=r==="bearer"?`${this.host}/i/v1/${t}`:`${this.host}/i/v1/${t}?token=${encodeURIComponent(this.apiKey)}`,a=this.disableCompression?null:await this.compressPayload(i),c=a||i,l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...r==="bearer"&&{Authorization:`Bearer ${this.apiKey}`},...a!==null&&{"Content-Encoding":"gzip"}},body:c};try{return await this.fetchWithRetry(s,l,{type:"successful-write"},{retryCheck:u=>Wut(u)||u instanceof O8&&u.retryAfterMs!==void 0?!1:Ktn(u)}),{kind:"ok"}}catch(u){if(Wut(u))return{kind:"too-large"};if(Ktn(u)){let p=u instanceof O8?u.retryAfterMs:void 0;return{kind:"retry-later",error:u,...p!==void 0&&{retryAfterMs:p}}}return{kind:"fatal",error:u}}}async _sendLogsBatch(t){return this._sendOtlpBatch({path:"logs",auth:"query-token",payload:t})}async _sendMetricsBatch(t){return this._sendOtlpBatch({path:"metrics",auth:"query-token",payload:t})}async _sendTracesBatch(t){return this._sendOtlpBatch({path:"traces",auth:"bearer",payload:t})}async fetchWithRetry(t,r,n,i,o){let s=r.body?r.body:"",a=ycu(s),c={...this._retryOptions,...i},l=0;return await Yau(async()=>{l++;let u=new AbortController,p=o??this.requestTimeout,d=Date.now()+p,f,m=new Promise((C,x)=>{f=$2(()=>{let S=Gut("AbortError",`Request timed out after ${p}ms`);x(S),u.abort(S)},p)}),g,A=!1,b,I=()=>b??=(async()=>{try{await g?.body?.cancel()}catch{}})();try{let C;try{C=this.fetch(t,{signal:u.signal,...r})}catch(P){throw new ghe(P)}C.then(P=>{u.signal.aborted&&!A&&Promise.resolve(P.body?.cancel()).catch(()=>{})}).catch(()=>{});try{g=await Promise.race([C,m]),A=!0}catch(P){throw new ghe(P)}let x=r.mode==="no-cors",S=n.type==="successful-write"?300:400;if(!x&&(g.status<200||g.status>=S))throw new O8(g,a,d,u);if(n.type==="successful-write"){try{await Promise.race([I(),m])}catch{}return}try{return await Promise.race([n.consume(g),m])}catch(P){throw u.signal.aborted?new ghe(P):P}}finally{clearTimeout(f),u.signal.aborted&&g&&I()}},{...c,retryCheck:u=>{let p=c.retryCheck(u);return p&&l<=c.retryCount&&u instanceof O8&&u.cancelResponseBody(),p}})}async _shutdown(t=3e4){await this._initPromise;let r=!1;return this.clearFlushTimer(),this.disabled?void 0:Fwe((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(s=>this.getRouteQueue(s).length>0);){let o=this._dequeuedMessagesCount;if(await this.flush(),r)break;if(this._dequeuedMessagesCount===o){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(i){if(!gyh(i))throw i;await gcu(i)}})(),t,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:t}),r=!0})}async shutdown(t=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(t).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}};var vyh=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi;var UfC=new RegExp(vyh.source,"i"),vcu=/[a-z][a-z0-9+.-]{0,63}:\/\//i,VfC=new RegExp(`^${vcu.source}`,"i"),GfC=new RegExp(vcu.source,"gi");var Cyh=["is_not","is_set"],xyh=1152921504606847e3,Gl=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,e.prototype)}};function qJo(e){if(typeof e=="boolean")return!0;if(typeof e=="string"){let t=e.toLowerCase();return t==="true"||t==="false"}if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!qJo(t in e?e[t]:null))return!1;return!0}function WJo(e){if(typeof e=="boolean")return e;if(typeof e=="string")return e.toLowerCase()==="true";if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!WJo(t in e?e[t]:null))return!1;return!0}function bWt(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(t+1>=e.length||n<56320||n>57343)throw new Gl("Cannot stringify an unpaired surrogate like the flags service");t++}else if(r>=56320&&r<=57343)throw new Gl("Cannot stringify an unpaired surrogate like the flags service")}}function Ytn(e,t=new Set){if(!(e===null||typeof e=="boolean")){if(typeof e=="string")return void bWt(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new Gl(`Cannot represent non-finite number ${e} like the flags service`);return}if(Array.isArray(e)){if(t.has(e))throw new Gl("Cannot represent a circular array during local evaluation");t.add(e);try{for(let r=0;r<e.length;r++)r in e&&Ytn(e[r],t)}finally{t.delete(e)}return}if(typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Gl("Cannot represent a non-JSON object like the flags service");if(t.has(e))throw new Gl("Cannot represent a circular object during local evaluation");t.add(e);try{for(let n of Object.keys(e))bWt(n),Ytn(e[n],t)}finally{t.delete(e)}return}throw new Gl(`Cannot represent ${typeof e} like the flags service`)}}function Syh(e,t){let r=0,n=0;for(;r<e.length&&n<t.length;){let i=e.charCodeAt(r),o=t.charCodeAt(n),s=i>=55296&&i<=56319,a=o>=55296&&o<=56319,c=s?e.charCodeAt(r+1):0,l=a?t.charCodeAt(n+1):0,u=s?(i-55296)*1024+c-56320+65536:i,p=a?(o-55296)*1024+l-56320+65536:o;if(u!==p)return u-p;r+=s?2:1,n+=a?2:1}return e.length-t.length}function HJo(e,t=new Set){if(e===null)return"null";if(typeof e=="string")return bWt(e),JSON.stringify(e);if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"){if(!Number.isFinite(e))throw new Gl(`Cannot stringify non-finite number ${e} like the flags service`);if(Number.isInteger(e))throw new Gl(`Cannot distinguish integer ${e} from an integral JSON float during local evaluation`);return String(e)}if(Array.isArray(e)){if(t.has(e))throw new Gl("Cannot stringify a circular array during local evaluation");t.add(e);try{let r=[];for(let n=0;n<e.length;n++)r.push(n in e?HJo(e[n],t):"null");return`[${r.join(",")}]`}finally{t.delete(e)}}if(typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Gl("Cannot stringify a non-JSON object like the flags service");if(t.has(e))throw new Gl("Cannot stringify a circular object during local evaluation");t.add(e);try{let n=Object.keys(e);return n.forEach(bWt),`{${n.sort(Syh).map(i=>`${JSON.stringify(i)}:${HJo(e[i],t)}`).join(",")}}`}finally{t.delete(e)}}throw new Gl(`Cannot stringify ${typeof e} like the flags service`)}function Jtn(e){return typeof e=="string"?(bWt(e),e):HJo(e)}function Ccu(e){try{return new RegExp(e),!0}catch{return!1}}function P8(e){return String(e).replace(/[A-Z]/g,t=>t.toLowerCase())}function Scu(e,t,r){if(!/^\d+$/.test(e)||r==="strict"&&e.length>1&&e[0]==="0")throw new Gl(`Invalid semver: ${t}`);return parseInt(e,10)}function Fw(e,t="strict"){let n=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!n||n.startsWith("."))throw new Gl(`Invalid semver: ${e}`);let i=n.split("."),o=s=>s===void 0||s===""?0:Scu(s,e,t);return[o(i[0]),o(i[1]),o(i[2])]}function B8(e,t){for(let r=0;r<3;r++){if(e[r]<t[r])return-1;if(e[r]>t[r])return 1}return 0}function wyh(e,t){let r=Fw(e,t);return{lower:[r[0],r[1],r[2]],upper:[r[0],r[1]+1,0]}}function Tyh(e,t){let[r,n,i]=Fw(e,t),o=[r,n,i],s;return s=r>0?[r+1,0,0]:n>0?[0,n+1,0]:[0,0,i+1],{lower:o,upper:s}}function Oyh(e,t){let n=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!n)throw new Gl(`Invalid wildcard semver: ${e}`);let i=n.split("."),o=c=>{if(t==="legacy-permissive"){let l=parseInt(c,10);if(!isNaN(l))return l}else try{return Scu(c,e,t)}catch{}throw new Gl(`Invalid wildcard semver: ${e}`)},s=o(i[0]);if(i.length===1)return{lower:[s,0,0],upper:[s+1,0,0]};let a=o(i[1]);return{lower:[s,a,0],upper:[s,a+1,0]}}function xcu(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 Gl(`${e} is in an invalid date format`)}throw new Gl(`The date provided ${e} must be a string, number, or date object`)}function KJo(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),n=new Date(new Date().toISOString());if(!r||!r.groups)return null;let i=parseInt(r.groups.number);if(i>=1e4)return null;let o=r.groups.interval;if(o==="h")n.setUTCHours(n.getUTCHours()-i);else if(o==="d")n.setUTCDate(n.getUTCDate()-i);else if(o==="w")n.setUTCDate(n.getUTCDate()-7*i);else if(o==="m")n.setUTCMonth(n.getUTCMonth()-i);else{if(o!=="y")return null;n.setUTCFullYear(n.getUTCFullYear()-i)}return n}function JJo(e,t,r={}){let n=e.key,i=e.value,o=e.operator||"exact",s=r.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(t,n)){if(o==="is_not_set")return!1;if(o==="is_set")return!0}else throw new Gl(`Property ${n} not found in propertyValues`);let c=t[n];if(c===void 0)return r.warnFunction?.(`Property ${n} cannot have a value of undefined with the ${o} operator`),o==="is_not";if(c===null&&!Cyh.includes(o)&&o!=="exact"&&o!=="is_not")return r.warnFunction?.(`Property ${n} cannot have a value of null with the ${o} operator`),!1;let l=(p,d)=>{if(r.propertyMatchingVersion!==2&&qJo(p)||Array.isArray(p)&&p.length===0)return Ytn(d),WJo(p)===WJo(d);if(r.propertyMatchingVersion===2&&typeof d=="number"&&qJo(p))return Ytn(d),!1;if(Array.isArray(p)){let f=Jtn(d).toLowerCase();return p.some(m=>Jtn(m).toLowerCase()===f)}return Jtn(p).toLowerCase()===Jtn(d).toLowerCase()},u=(p,d,f)=>{if(f==="gt")return p>d;if(f==="gte")return p>=d;if(f==="lt")return p<d;if(f==="lte")return p<=d;throw new Error(`Invalid operator: ${f}`)};switch(o){case"exact":return l(i,c);case"is_not":return!l(i,c);case"is_set":return!0;case"icontains":return P8(c).includes(P8(i));case"not_icontains":return!P8(c).includes(P8(i));case"starts_with":return P8(c).startsWith(P8(i));case"not_starts_with":return!P8(c).startsWith(P8(i));case"ends_with":return P8(c).endsWith(P8(i));case"not_ends_with":return!P8(c).endsWith(P8(i));case"regex":return Ccu(String(i))&&String(c).match(String(i))!==null;case"not_regex":return Ccu(String(i))&&String(c).match(String(i))===null;case"gt":case"gte":case"lt":case"lte":{let p=typeof i=="number"?i:parseFloat(String(i)),d=typeof c=="number"?c:c!=null?parseFloat(String(c)):NaN;return Number.isFinite(p)&&Number.isFinite(d)?u(d,p,o):u(String(c),String(i),o)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new Gl("Date operations cannot be performed on boolean values");let p=KJo(String(i));p==null&&(p=xcu(i));let d=xcu(c);return o==="is_date_before"?d<p:d>p}case"semver_eq":return B8(Fw(String(c),s),Fw(String(i),s))===0;case"semver_neq":return B8(Fw(String(c),s),Fw(String(i),s))!==0;case"semver_gt":return B8(Fw(String(c),s),Fw(String(i),s))>0;case"semver_gte":return B8(Fw(String(c),s),Fw(String(i),s))>=0;case"semver_lt":return B8(Fw(String(c),s),Fw(String(i),s))<0;case"semver_lte":return B8(Fw(String(c),s),Fw(String(i),s))<=0;case"semver_tilde":{let p=Fw(String(c),s),{lower:d,upper:f}=wyh(String(i),s);return B8(p,d)>=0&&B8(p,f)<0}case"semver_caret":{let p=Fw(String(c),s),{lower:d,upper:f}=Tyh(String(i),s);return B8(p,d)>=0&&B8(p,f)<0}case"semver_wildcard":{let p=Fw(String(c),s),{lower:d,upper:f}=Oyh(String(i),s);return B8(p,d)>=0&&B8(p,f)<0}default:throw new Gl(`Unknown operator: ${o}`)}}async function wcu(e){let t=globalThis.crypto?.subtle;if(!t)throw new Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}async function EWt(e,t,r="",n="."){let i=await wcu(`${e}${n}${t}${r}`);return parseInt(i.slice(0,15),16)/xyh}async function YJo(e,t){if(e==null||e.id==null||e.exclusion_percentage==null)return;let r=Number(e.exclusion_percentage);if(!Number.isFinite(r))return;let n=Math.min(Math.max(r,0),100);if(!(n!==100&&await EWt("holdout",t,"","-")>n/100))return`holdout-${e.id}`}function Xtn(e){let t=[],r=0;for(let n of e){let i=r+n.rollout_percentage/100;t.push({valueMin:r,valueMax:i,key:n.key}),r=i}return t}async function XJo(e,t,r){let n=await EWt(e,t,"variant");return Xtn(r).find(i=>n>=i.valueMin&&n<i.valueMax)?.key}function ZJo(e,t){if(t===!1||t==null||!e)return null;let r=typeof t=="boolean"?t.toString():t,n=e[r]||null;return n==null?null:qut(n)}var Tcu=9223372036854776e3,Pyh="9223372036854775808",Byh=Object.prototype.propertyIsEnumerable;function Dyh(){return{ancestors:new WeakSet,remainingNodes:1e4}}function Lre(e,t){try{return Ocu(e,t,Dyh(),0)}catch{return[]}}function Ryh(e,t){let r=e.toString(),n=BigInt(Pyh);return e>=n||e<-n?(t?.debug(`Attribute ${r} is outside the int64 range; encoding it as a string`),{stringValue:r}):{intValue:r}}function tYo(e,t,r,n){if(r.remainingNodes<=0)return{stringValue:Ltn};if(r.remainingNodes--,Sau(e))return{boolValue:e};if(typeof e=="bigint")return Ryh(e,t);if(typeof e=="number"){if(!Number.isFinite(e))return{stringValue:String(e)};if(Number.isInteger(e)){if(Number.isSafeInteger(e))return{intValue:String(e)};if("u"<typeof BigInt)return{stringValue:String(e)};let i=BigInt(e).toString();return e>=Tcu||e<-Tcu?(t?.debug(`Attribute ${i} is outside the int64 range; encoding it as a string`),{stringValue:i}):{intValue:i}}return{doubleValue:e}}if(typeof e=="string")return{stringValue:Qre(e)};if(typeof e=="function")return{stringValue:Hau};if(typeof e=="symbol")return{stringValue:String(e)};if(typeof e=="object"&&e!==null){if(r.ancestors.has(e))return{stringValue:Mtn};if(n>=20)return{stringValue:Ltn};if(e instanceof Date){let i=e.getTime(),o=Number.isFinite(i)?e.toISOString():String(e);return{stringValue:typeof o=="string"?Qre(o):String(o)}}r.ancestors.add(e);try{try{let i=e.toJSON;if(typeof i=="function")return tYo(i.call(e),t,r,n+1)}catch{}return x3(e)?{arrayValue:{values:kyh(e,t,r,n+1)}}:{kvlistValue:{values:Ocu(e,t,r,n+1)}}}finally{r.ancestors.delete(e)}}return{stringValue:Qre(String(e))}}function kyh(e,t,r,n){let i=[],o=Math.min(e.length,1e3),s=0;for(;s<o&&r.remainingNodes>0;s++)try{let a=s in e?e[s]:void 0;if(AJ(a))continue;i.push(tYo(a,t,r,n))}catch{i.push({stringValue:T8})}return e.length>s&&i.push({stringValue:Ltn}),i}function Ocu(e,t,r,n){let i=[];for(let o in e)if(Byh.call(e,o)){if(!o){t?.debug("Dropping an attribute with an empty key");continue}if(i.length>=1e3||r.remainingNodes<=0){t?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let s=e[o];if(EJo(s)||mhe(s))continue;i.push({key:Qre(o),value:tYo(s,t,r,n)})}catch{i.push({key:Qre(o),value:{stringValue:T8}})}}return i}function vWt(e,t,r){return{...hhe({},e.resourceAttributes),"service.name":e.serviceName||"unknown_service",...e.environment&&{"deployment.environment":e.environment},...e.serviceVersion&&{"service.version":e.serviceVersion},"telemetry.sdk.name":t,"telemetry.sdk.version":r}}var Fyh=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function CWt(e,t){let r=hhe({},e),n={};for(let i of Fyh)Object.prototype.hasOwnProperty.call(r,i)&&(n[i]=r[i],delete r[i]);return[...Lre(r,t),...Lre(n,t)]}var Pcu={darwin:"macOS",win32:"Windows",cygwin:"Windows",linux:"Linux",android:"Android",freebsd:"FreeBSD",openbsd:"OpenBSD",netbsd:"NetBSD",sunos:"SunOS",aix:"AIX",haiku:"Haiku","Mac OS X":"macOS"};function Nyh(e){if(e)return Object.prototype.hasOwnProperty.call(Pcu,e)?Pcu[e]:e}function rYo(e,t){let r=Nyh(e);return{...r?{"os.name":r}:{},...t?{"os.version":t}:{}}}var jyh={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},sdC=jyh.info;var wVe=class{constructor(t){this._onFire=t,this._firesAt=0}get pending(){return!!this._timer}arm(t){this.clear(),this._firesAt=Date.now()+t,this._timer=$2(()=>{this._timer=void 0,this._onFire()},t)}armNoEarlierThan(t){this._timer&&Date.now()+t<=this._firesAt||this.arm(t)}clear(){this._timer&&(clearTimeout(this._timer),this._timer=void 0)}};function xWt(){return 1-.25+Math.random()*.25*2}var D8=1;function SWt(e,t,r,n){let i=Math.min(Math.max(0,t-1),6),o=e*2**i,s=n===void 0?o:Math.min(o,Math.max(n,e));return Math.round(s*r)}var wWt=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function nYo(e){return String(e)+"000000"}function iYo(e,t,r,n){let i="";return n&&(i=Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${JSON.stringify(n[s])}`).join(",")),`${e}\0${t}\0${r??""}\0${i}`}function Bcu(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}function oYo(e,t,r){return vWt(e,t,r)}function sYo(e,t,r,n){return{resourceMetrics:[{resource:{attributes:CWt(t)},scopeMetrics:[{scope:{name:r,version:n},metrics:e}]}]}}function $tn(e){let t=e?.resourceAttributes;return{serviceName:t?.["service.name"]??e?.serviceName,serviceVersion:t?.["service.version"]??e?.serviceVersion,environment:t?.["deployment.environment"]??e?.environment,resourceAttributes:t,beforeSend:e?.beforeSend,flushIntervalMs:e?.flushIntervalMs??1e4,maxSeriesPerFlush:e?.maxSeriesPerFlush??1e3}}var Dcu=1,TWt=class{constructor(t,r,n){this._instance=t,this._config=r,this._logger=n,this._series=new Map,this._flushTimer=new wVe(()=>this.flush().catch(i=>{this._logger.error("Metrics flush failed:",i)})),this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._retryAfter=new xVe,this._consecutiveFlushFailures=0,this._flushJitter=D8,this._generation=0}count(t,r=1,n){this._capture({name:t,type:"count",value:r,unit:n?.unit,attributes:n?.attributes})}gauge(t,r,n){this._capture({name:t,type:"gauge",value:r,unit:n?.unit,attributes:n?.attributes})}histogram(t,r,n){this._capture({name:t,type:"histogram",value:r,unit:n?.unit,attributes:n?.attributes})}flush(){let t=this._flushPromise,n=(async()=>{t&&await t.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===n&&(this._flushPromise=null)});return this._flushPromise=n,n}drainWindow(){if(this._series.size===0)return null;let t=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(t)}reset(){this._generation++,this._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=D8,this._flushTimer.clear(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(t){if(this._instance.isDisabled||this._instance.optedOut)return;let r=this._runBeforeSend(t);if(r===null)return;if(!r.name||typeof r.name!="string")return void this._logger.warn("Dropping metric with empty name");if(typeof r.value!="number"||!Number.isFinite(r.value))return void this._logger.warn(`Dropping metric '${r.name}': value must be a finite number`);if(r.type==="count"&&r.value<0)return void this._logger.warn(`Dropping count '${r.name}': counters are monotonic, value must be >= 0`);let n,i;try{n=r.attributes?{...r.attributes}:void 0,i=iYo(r.type,r.name,r.unit,n)}catch(a){this._logger.warn(`Dropping metric '${r.name}': attributes could not be serialized`,a);return}let o=this._series.get(i);if(!o){if(!this._admitNewSeries())return;o={name:r.name,type:r.type,unit:r.unit,attributes:n,windowStartMs:Date.now()},this._series.set(i,o)}let s=this._typeByName.get(r.name);s===void 0?this._typeByName.set(r.name,r.type):s!==r.type&&!this._typeCollisionWarned.has(r.name)&&(this._typeCollisionWarned.add(r.name),this._logger.warn(`Metric name '${r.name}' is already used as a ${s}; recording it as a ${r.type} too will blend both series in charts. Use a distinct name.`)),this._fold(o,r.value),this._armFlushTimer()}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush?!0:(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}_fold(t,r){switch(t.type){case"count":t.total=(t.total??0)+r;break;case"gauge":t.last=r;break;case"histogram":{t.hist||(t.hist={count:0,sum:0,min:r,max:r,bucketCounts:new Array(wWt.length+1).fill(0)});let n=t.hist;n.count+=1,n.sum+=r,n.min=Math.min(n.min,r),n.max=Math.max(n.max,r),n.bucketCounts[Bcu(r,wWt)]+=1;break}}}_runBeforeSend(t){let r=this._config.beforeSend;if(!r)return t;let n=x3(r)?r:[r],i=t;for(let o of n)try{let s=o(i);if(!s)return this._logger.info("Metric was rejected in beforeSend function"),null;i=s}catch(s){return this._logger.error("Error in beforeSend function for metric:",s),null}return i}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(SWt(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}async _doFlush(){if(this._flushTimer.clear(),this._series.size===0)return;let t=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let r=this._generation,n=await this._instance._sendMetricsBatch(this._buildPayload(t));if(r===this._generation)switch(this._retryAfter.record(n),n.kind==="retry-later"?(this._consecutiveFlushFailures++,this._flushJitter=xWt()):(this._consecutiveFlushFailures=0,this._flushJitter=D8),this._flushTimer.pending&&this._flushTimer.arm(this._nextFlushDelay()),n.kind){case"ok":return;case"retry-later":this._mergeWindowBack(t),this._flushTimer.armNoEarlierThan(this._nextFlushDelay());return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",n.error);return}}_buildPayload(t){return sYo(this._buildMetrics(t),oYo(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(t){let r=nYo(Date.now()),n=new Map;for(let i of t.values()){let o=iYo(i.type,i.name,i.unit,void 0),s=n.get(o);s||(s={name:i.name,...i.unit&&{unit:i.unit}},i.type==="count"?s.sum={aggregationTemporality:Dcu,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?s.gauge={dataPoints:[]}:s.histogram={aggregationTemporality:Dcu,dataPoints:[]},n.set(o,s));let a=Lre(i.attributes??{},this._logger),c=nYo(i.windowStartMs);if(i.type==="count"){let l={attributes:a,startTimeUnixNano:c,timeUnixNano:r,asDouble:i.total??0};s.sum.dataPoints.push(l)}else if(i.type==="gauge"){let l={attributes:a,timeUnixNano:r,asDouble:i.last??0};s.gauge.dataPoints.push(l)}else if(i.hist){let l={attributes:a,startTimeUnixNano:c,timeUnixNano:r,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:wWt};s.histogram.dataPoints.push(l)}}return Array.from(n.values())}_mergeWindowBack(t){for(let[r,n]of t){let i=this._series.get(r);if(!i){this._admitNewSeries()&&this._series.set(r,n);continue}switch(i.windowStartMs=Math.min(i.windowStartMs,n.windowStartMs),i.type){case"count":i.total=(i.total??0)+(n.total??0);break;case"gauge":break;case"histogram":if(n.hist)if(i.hist){i.hist.count+=n.hist.count,i.hist.sum+=n.hist.sum,i.hist.min=Math.min(i.hist.min,n.hist.min),i.hist.max=Math.max(i.hist.max,n.hist.max);for(let o=0;o<i.hist.bucketCounts.length;o++)i.hist.bucketCounts[o]+=n.hist.bucketCounts[o]}else i.hist=n.hist;break}}}};var Lyh="0".repeat(32),_yh="0".repeat(16),Uyh=/^[0-9a-f]+$/;function Vyh(e){let t=new Uint8Array(e),r=globalThis.crypto;if(r&&typeof r.getRandomValues=="function")try{return r.getRandomValues(t),t}catch{}for(let n=0;n<e;n++)t[n]=Math.floor(256*Math.random());return t}function Gyh(e){let t="";for(let r=0;r<e.length;r++)t+=e[r].toString(16).padStart(2,"0");return t}function Rcu(e){let t=Gyh(Vyh(e));return/[^0]/.test(t)?t:t.slice(0,-1)+"1"}function kcu(){return Rcu(16)}function Fcu(){return Rcu(8)}function Ncu(e,t,r){return typeof e=="string"&&e.length===t&&e!==r&&Uyh.test(e)}function jcu(e){return Ncu(e,32,Lyh)}function zcu(e){return Ncu(e,16,_yh)}var qyh=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function Qcu(e){let t=Mcu(e);return t&&{traceId:t.traceId,spanId:t.spanId,flags:Wyh(t.flags)}}function Wyh(e){return 1&parseInt(e,16)?trn:Hyh}function Mcu(e){if(typeof e!="string")return;let t=qyh.exec(e.trim());if(!t)return;let[,r,n,i,o,s]=t;if(r!=="ff"&&!(r==="00"&&s)&&!(!jcu(n)||!zcu(i)))return{version:r,traceId:n,spanId:i,flags:o}}function Lcu(e){return Mcu(e)&&e.trim()}function ern(e){return Array.isArray(e)&&e.length===1?e[0]:e}var trn="01",Hyh="00";function _cu(e,t,r=trn){return`00-${e}-${t}-${r}`}var Kyh=32,aYo=512;function rrn(e){if(typeof e!="string")return;let t=e.trim();if(!t||/[^\x20-\x7e\t]/.test(t))return;let r=t.split(",");if(!(r.length>Kyh)){for(let n of r)if(n.trim()&&!n.includes("="))return;return t.length<=aYo?t:Yyh(r)}}var Jyh=128;function Yyh(e){let t=[...e],r=()=>t.reduce((n,i)=>n+i.length,0)+t.length-1;for(let n=t.length-1;n>=0&&r()>aYo;n--)t[n].length>Jyh&&t.splice(n,1);for(;t.length&&r()>aYo;)t.pop();return t.length?t.join(","):void 0}var Ucu="unknown";function TVe(e,t,r,n){return typeof e=="string"&&e.trim()?e.length>r?e.slice(0,r):e:(n?.debug(`${t} must be a non-empty string; using "${Ucu}"`),Ucu)}function Hut(e){if(e==null)return;let t=e;if(e instanceof Date)try{t=e.getTime()}catch{return}if(!(typeof t!="number"||!Number.isFinite(t))&&!(t<0||t>9223372036854))return t}function Vcu(e,t,r){let n=Hut(e);return n===void 0?(e!==void 0&&r?.debug("Span startTime is out of range or not a valid time; using the current time"),t):(t-n>864e5?r?.debug("Span startTime is more than 24 hours in the past; the server will clamp it to receive time and keep the original in $originalTimestamp"):n>t&&r?.debug("Span startTime is in the future; the span may export with a zero duration"),n)}function nrn(e,t){return e<t?t:e}function OWt(e,t,r,n){let i=Hut(e);return i===void 0?(e!==void 0&&n?.debug(`Span ${r} is out of range or not a valid time; using the derived time`),t):i}function orn(){let e=globalThis.performance;return typeof e?.now=="function"?e.now():void 0}var Kut=class{constructor(t,r,n){this._onEnd=r,this._logger=n,this._events=[],this._ended=!1,this._userAttributeCount=0,this._userEventCount=0,this._droppedAttributes=0,this._droppedEvents=0,this._traceId=t.traceId,this._spanId=t.spanId,this._parentSpanId=t.parentSpanId,this._traceState=t.traceState,this._traceFlags=t.traceFlags??trn,this._parentIsRemote=t.parentIsRemote??!1,this._name=t.name,this._kind=t.kind,this._autoKeys=new Set(t.autoAttributeKeys),this._maxAttributes=t.maxAttributes,this._maxEvents=t.maxEvents,this._maxAttributesPerEvent=t.maxAttributesPerEvent,this._maxAttributeValueLength=t.maxAttributeValueLength,this._attributes=Object.create(null);for(let i of Object.keys(t.attributes))this._writeAttribute(i,t.attributes[i]);this._startMono=t.backdated?void 0:orn(),this._startTime=t.clockAnchor&&this._startMono!==void 0?t.clockAnchor.wall+(this._startMono-t.clockAnchor.mono):t.startTime,this._startMono!==void 0&&(this._clockAnchor=t.clockAnchor??{wall:this._startTime,mono:this._startMono})}_now(){if(this._startMono!==void 0){let t=orn();if(t!==void 0)return this._startTime+Math.max(0,t-this._startMono)}return Date.now()}_mutable(t){return this._ended?(this._logger?.debug(`Ignoring ${t} on a span that has already ended`),!1):!0}_writeAttribute(t,r){if(AJ(r)){t in this._attributes&&!this._autoKeys.has(t)&&this._userAttributeCount--,delete this._attributes[t];return}if(!this._autoKeys.has(t)&&!(t in this._attributes)){if(this._userAttributeCount>=this._maxAttributes)return void this._droppedAttributes++;this._userAttributeCount++}this._attributes[t]=arn(r,this._maxAttributeValueLength)}setAttribute(t,r){return this._mutable("setAttribute")&&this._writeAttribute(t,r),this}setAttributes(t){if(this._mutable("setAttributes")){let r=hhe({},t);for(let n of Object.keys(r))this._writeAttribute(n,r[n])}return this}addEvent(t,r,n){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let i=r&&Hcu(r,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:TVe(t,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:OWt(n,this._now(),"event timestamp",this._logger),...i&&{attributes:i.attributes,...i.dropped&&{droppedAttributesCount:i.dropped}}})}return this}setStatus(t,r){if(this._mutable("setStatus")){if(t!=="ok"&&t!=="error")return this._logger?.debug(`Ignoring unknown span status "${String(t)}"; expected "ok" or "error"`),this;this._status={code:t,...r&&{message:cYo(r,this._maxAttributeValueLength)}}}return this}get statusIsExplicitlyOk(){return this._status?.code==="ok"}recordException(t){if(!this._mutable("recordException"))return this;let{type:r,message:n,stack:i}=lYo(t);return this.addEvent(Xyh,{"exception.type":r,"exception.message":n,...i&&{"exception.stacktrace":i}}),this.setStatus("error",n)}updateName(t){return this._mutable("updateName")&&(this._name=TVe(t,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return _cu(this._traceId,this._spanId,this._traceFlags)}tracestate(){return this._traceState??null}childContext(){return{traceId:this._traceId,parentSpanId:this._spanId,traceState:this._traceState,traceFlags:this._traceFlags,clockAnchor:this._clockAnchor}}end(t){if(this._ended)return void this._logger?.debug("Ignoring end() on a span that has already ended");this._ended=!0;let r=this._now(),n=OWt(t,r,"end time",this._logger);this._onEnd({traceId:this._traceId,spanId:this._spanId,...this._parentSpanId&&{parentSpanId:this._parentSpanId},...this._traceState&&{traceState:this._traceState},traceFlags:this._traceFlags,parentIsRemote:this._parentIsRemote,name:this._name,kind:this._kind,...this._status&&{status:this._status},attributes:{...this._attributes},events:this._events,startTime:this._startTime,endTime:nrn(n,this._startTime),...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}},Xyh="exception",Zyh=4294967295;function $yh(e){try{return typeof e=="string"?e:String(e)}catch{return T8}}function OVe(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?0:Math.min(Math.floor(e),Zyh)}function ebh(e,t){if(!t.length)return Object.keys(e);let r=t.filter(i=>Object.prototype.propertyIsEnumerable.call(e,i)),n=new Set(r);return[...r,...Object.keys(e).filter(i=>!n.has(i))]}function qcu(e,t,r,n,i,o,s=[]){let a=0,c=0,l={};for(let f of ebh(e.attributes,s)){let m=e.attributes[f];if(!AJ(m)){if(!t.has(f)){if(a>=r){c++;continue}a++}Object.defineProperty(l,f,{value:arn(m,o),enumerable:!0,writable:!0,configurable:!0})}}e.attributes=l,c&&(e.droppedAttributesCount=OVe(e.droppedAttributesCount)+c);let u=0,p=0,d=[];for(let f of e.events){if(u>=n){p++;continue}if(u++,f.attributes){let m=Hcu(f.attributes,i,o);f.attributes=m.attributes,m.dropped&&(f.droppedAttributesCount=OVe(f.droppedAttributesCount)+m.dropped)}d.push(f)}e.events=d,p&&(e.droppedEventsCount=OVe(e.droppedEventsCount)+p),e.status?.message&&(e.status={...e.status,message:cYo($yh(e.status.message),o)})}var srn=class{setAttribute(){return this}setAttributes(){return this}addEvent(){return this}setStatus(){return this}recordException(){return this}updateName(){return this}traceparent(){return null}tracestate(){return null}end(){}},Wcu=new srn,PWt=class extends srn{constructor(t,r){super(),this._traceparent=t,this._tracestate=r}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}};function tbh(e){try{let t=e.stack;return typeof t=="string"&&t?{stack:t}:{}}catch{return{}}}function Nwe(e,t){let r=ern(e?.parent)??t,n=typeof r=="string"||r==null?r:Gcu(r,"traceparent"),i=Lcu(n);if(!i)return Wcu;let o=typeof r=="string"||r==null?e?.tracestate:Gcu(r,"tracestate");return new PWt(i,rrn(o))}function Gcu(e,t){try{let r=e[t];return typeof r=="function"?r.call(e):void 0}catch{return}}function cYo(e,t){return e.length>t?e.slice(0,t):e}function arn(e,t){return irn(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}function irn(e,t,r,n){if(e===null||typeof e!="object")return AJ(e)||r.remainingNodes<=0?e:(r.remainingNodes--,typeof e=="string"?cYo(e,t):e);if(r.ancestors.has(e))return Mtn;if(r.remainingNodes<=0||n>=20)return e;r.remainingNodes--,r.ancestors.add(e);try{if(e instanceof Date)return e;let i=rbh(e);if(i.selfDescribed)return AJ(i.value)?String(i.value):irn(i.value,t,r,n+1);if(x3(e)){let a=Math.min(e.length,1e3),c=[];for(let l=0;l<a;l++)try{c.push(irn(e[l],t,r,n+1))}catch{c.push(T8)}return e.length>a&&(c.length=e.length),c}let o={},s=0;for(let a of Object.keys(e)){if(s>=1e3)break;let c;try{c=irn(e[a],t,r,n+1)}catch{c=T8}a&&!AJ(c)&&s++,Object.defineProperty(o,a,{value:c,enumerable:!0,writable:!0,configurable:!0})}return o}catch{return e}finally{r.ancestors.delete(e)}}function rbh(e){try{let t=e.toJSON;if(typeof t=="function")return{selfDescribed:!0,value:t.call(e)}}catch{}return{selfDescribed:!1}}function Hcu(e,t,r){let n;try{n=Object.keys(e)}catch{return{attributes:{},dropped:0}}let i={},o=0,s=0;for(let a of n){if(o>=t){s++;continue}let c;try{c=arn(e[a],r)}catch{c=T8}AJ(c)||(o++,Object.defineProperty(i,a,{value:c,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:i,dropped:s}}function Kcu(e,t){for(let r of Object.keys(e))e[r]=arn(e[r],t);return e}function BWt(e,t,r){return t===Wcu?r(t):e.with(t,()=>r(t))}function lYo(e){try{let t=tbh(e);if(kwe(e))return{type:e.name||"Error",message:e.message||"",...t};if(typeof e=="string")return{type:"string",message:e};if(e&&typeof e=="object"){let r=e;if(typeof r.message=="string")return{type:typeof r.name=="string"?r.name:"Object",message:r.message,...t}}return{type:typeof e,message:String(e)}}catch{return{type:typeof e,message:""}}}var uYo={internal:1,server:2,client:3,producer:4,consumer:5},nbh={ok:1,error:2},ibh=1,obh=256,sbh=512;function abh(e){let t=parseInt(e.traceFlags,16);return(Number.isFinite(t)?255&t:ibh)|obh|(e.parentIsRemote?sbh:0)}function crn(e){if(typeof e=="string")return Qre(e);try{return Qre(String(e))}catch{return T8}}function cbh(e){return e&&Object.prototype.hasOwnProperty.call(uYo,e)?uYo[e]:uYo.internal}function pYo(e){let t=Math.floor(e),r=Math.round((e-t)*1e6);return r>=1e6&&(t+=1,r=0),String(t)+String(r).padStart(6,"0")}function lbh(e,t){let r={name:crn(e.name),timeUnixNano:pYo(e.timestamp)};if(e.attributes){let i=Lre(e.attributes,t);i.length&&(r.attributes=i)}let n=OVe(e.droppedAttributesCount);return n&&(r.droppedAttributesCount=n),r}function Jcu(e,t){let r={traceId:e.traceId,spanId:e.spanId,name:crn(e.name),kind:cbh(e.kind),startTimeUnixNano:pYo(e.startTime),endTimeUnixNano:pYo(e.endTime),flags:abh(e)};e.parentSpanId&&(r.parentSpanId=e.parentSpanId),e.traceState&&(r.traceState=crn(e.traceState));let n=Lre(e.attributes,t);n.length&&(r.attributes=n),e.events.length&&(r.events=e.events.map(s=>lbh(s,t)));let i=OVe(e.droppedAttributesCount);i&&(r.droppedAttributesCount=i);let o=OVe(e.droppedEventsCount);return o&&(r.droppedEventsCount=o),e.status&&(r.status={code:nbh[e.status.code],...e.status.message&&{message:crn(e.status.message)}}),r}function Ycu(e,t,r){return vWt(e,t,r)}function Xcu(e,t,r,n,i){return{resourceSpans:[{resource:{attributes:CWt(t,i)},scopeSpans:[{scope:{name:r,version:n},spans:e}]}]}}var Zcu=8;function lrn(){return orn()??Date.now()}function fYo(e){try{return e instanceof Kut}catch{return!1}}function $cu(e,t){let r=Qcu(e);if(r)return{traceId:r.traceId,parentSpanId:r.spanId,traceState:rrn(t),traceFlags:r.flags,isRemote:!0}}function ubh(e){try{return typeof e.traceparent=="function"}catch{return!1}}function pbh(e){return!!e.attributes&&typeof e.attributes=="object"&&!Array.isArray(e.attributes)&&Array.isArray(e.events)&&e.name!==void 0&&e.kind!==void 0&&e.startTime!==void 0&&e.endTime!==void 0}function urn(e,t,r){e[t]!==r&&(e[t]=r)}function fbh(e,t){try{let r=Object.getOwnPropertyDescriptors(e);for(let n of["traceId","spanId","parentSpanId","traceState"])r[n]={value:t[n],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(e),r)}catch{return e}}var DWt=class{constructor(t,r,n,i,o,s){this._instance=t,this._config=r,this._logger=n,this._getContext=i,this._contextManager=o,this._onSpanQueued=s,this._queue=[],this._flushTimer=new wVe(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=D8,this._retryAfter=new xVe,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=r.maxExportBatchSize}startSpan(t,r){if(this._instance.isDisabled||this._instance.optedOut)return Nwe(r,this._contextManager.active());let n=ern(r?.parent);if(n&&typeof n!="string"&&!fYo(n)){if(ubh(n))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),Nwe(r,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let i=this._resolveParent(n,r);if(this._liveSpans.size>=this._config.maxLiveSpans&&this._evictAgedSpans(),this._liveSpans.size>=this._config.maxLiveSpans)return this._recordDrop(1,`the live-span limit (${this._config.maxLiveSpans}) was reached \u2014 spans are being started and never ended`),Nwe(r,this._contextManager.active());let o=Date.now(),s=Vcu(r?.startTime,o,this._logger),a=Fcu();this._liveSpans.set(a,lrn());let c=this._autoContextAttributes();return new Kut({traceId:i?.traceId??kcu(),spanId:a,parentSpanId:i?.parentSpanId,traceState:i?.traceState,traceFlags:i?.traceFlags,parentIsRemote:i?.isRemote,name:TVe(t,"Span name",this._config.maxAttributeValueLength,this._logger),kind:r?.kind??"internal",attributes:hhe({...c},r?.attributes),autoAttributeKeys:Object.keys(c),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:s,backdated:s!==o,clockAnchor:Hut(r?.startTime)===void 0?i?.clockAnchor:void 0},(l,u)=>this._onSpanEnd(l,u),this._logger)}withSpan(t,r,n){let i=typeof r=="function"?void 0:r,o=typeof r=="function"?r:n,s=this.startSpan(t,i);try{let a=BWt(this._contextManager,s,o);return Xau(a)?a.then(c=>(s.end(),c),c=>{throw this._recordCallbackError(s,c),s.end(),c}):(s.end(),a)}catch(a){throw this._recordCallbackError(s,a),s.end(),a}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;)if(!this._queue.length||!await(this._flushPromise??this._startFlush()))return}_startFlush(){this._flushTimer.clear();let t=this._generation,r=Promise.resolve().then(()=>t===this._generation?this._flushInner():0).finally(()=>{this._flushPromise===r&&(this._flushPromise=null),this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=r,r}reset(){this._flushTimer.clear(),this._queue.length&&this._logger.critical(`Discarding ${this._queue.length} span(s) that were still queued when tracing was shut down. Raise the shutdown timeout or flush earlier if they matter.`),this._queue=[],this._liveSpans.clear(),this._flushPromise=null,this._generation++,this._maxExportBatchSize=this._config.maxExportBatchSize,this._droppedSinceWarning=0,this._dropReasons.clear(),this._lastDropWarningAt=0,this._consecutiveFlushFailures=0,this._flushJitter=D8,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(t,r){if(typeof t=="string"){let i=$cu(t,r?.tracestate);return i||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),i}if(fYo(t))return t.childContext();let n=this._contextManager.active();if(fYo(n))return n.childContext();if(n instanceof PWt)return $cu(n.traceparent(),n.tracestate()??void 0)}_autoContextAttributes(){let t;try{t=this._getContext()}catch(n){return this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes",n),{}}let r={};return t.distinctId&&(r.posthogDistinctId=t.distinctId),t.sessionId&&(r.sessionId=t.sessionId),t.currentUrl&&(r["url.full"]=t.currentUrl),t.screenName&&(r["screen.name"]=t.screenName),t.appState&&(r["app.state"]=t.appState),r}_recordCallbackError(t,r){if(!(t instanceof Kut))return;let{type:n,message:i,stack:o}=lYo(r);t.addEvent("exception",{"exception.type":n,"exception.message":i,...o&&{"exception.stacktrace":o}}),t.statusIsExplicitlyOk||t.setStatus("error",i)}_evictAgedSpans(){let t=lrn()-this._config.maxSpanAgeMs,r=0;for(let[n,i]of this._liveSpans){if(i>t)break;this._liveSpans.delete(n),r++}r&&this._recordDrop(r,`they were still live after ${this._config.maxSpanAgeMs}ms`)}_onSpanEnd(t,r){if(!this._liveSpans.delete(t.spanId))return;if(this._instance.isDisabled||this._instance.optedOut)return void this._recordDrop(1,"the user has opted out");let n=this._runBeforeSpanSend(t,r);if(n){if(this._reportLimitDrops(n),this._queue.length>=this._config.maxQueueSize)return void this._recordDrop(1,`the queue is full (${this._config.maxQueueSize}) \u2014 raise the flush frequency or reduce span volume`);this._queue.push(n);try{this._onSpanQueued?.()}catch(i){this._logger.debug("Span queue notification failed",i)}!(this._queue.length>=this._maxExportBatchSize)||this._consecutiveFlushFailures||this._retryAfter.isOpen()?this._armFlushTimerIfQueued():this._flushInBackground()}}_reportLimitDrops(t){let r=t.droppedAttributesCount??0,n=t.droppedEventsCount??0,i=0;for(let o of t.events)i+=o.droppedAttributesCount??0;(r||n||i)&&this._logger.debug(`Span limits discarded data from "${t.name}": ${r} attributes, ${n} events, ${i} event attributes`)}_runBeforeSpanSend(t,r){if(!this._config.beforeSpanSend.length)return t;let n={traceId:t.traceId,spanId:t.spanId,parentSpanId:t.parentSpanId,traceState:t.traceState},i={startTime:t.startTime,endTime:t.endTime},o={attributes:t.droppedAttributesCount,events:t.droppedEventsCount},s=Object.keys(t.attributes),a={traceFlags:t.traceFlags,parentIsRemote:t.parentIsRemote},c=t.status&&{...t.status},l=t,u=t;try{for(let f of this._config.beforeSpanSend){let m=f(l);if(!m)return this._recordDrop(1,"beforeSpanSend dropped it"),null;l=this._keepSpanIdentity(m,n)}if(u={traceId:n.traceId,spanId:n.spanId,parentSpanId:n.parentSpanId,traceState:n.traceState,name:l.name,kind:l.kind,status:l.status,attributes:l.attributes,events:l.events,startTime:l.startTime,endTime:l.endTime,traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote,droppedAttributesCount:o.attributes,droppedEventsCount:o.events},!pbh(u))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;u.name=TVe(u.name,"Span name",this._config.maxAttributeValueLength,this._logger),u.status&&u.status.code!=="ok"&&u.status.code!=="error"&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),u.status=c),u.startTime=Hut(u.startTime)??i.startTime,u.endTime=nrn(Hut(u.endTime)??i.endTime,u.startTime);let d=[];for(let f of u.events)try{d.push({...f,name:TVe(f.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:OWt(f.timestamp,u.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return u.events=d,qcu(u,r,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,s),u}catch(p){return this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed",p),this._recordDrop(1,"beforeSpanSend failed"),null}}_keepSpanIdentity(t,r){(t.traceId!==r.traceId||t.spanId!==r.spanId||t.parentSpanId!==r.parentSpanId)&&this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");try{urn(t,"traceId",r.traceId),urn(t,"spanId",r.spanId),urn(t,"parentSpanId",r.parentSpanId),urn(t,"traceState",r.traceState)}catch{return fbh(t,r)}return t}_recordDrop(t,r){this._droppedSinceWarning+=t,this._dropReasons.add(r),Date.now()-this._lastDropWarningAt>=this._config.flushIntervalMs&&this._warnAboutDrops()}_warnAboutDrops(){this._droppedSinceWarning&&(this._lastDropWarningAt=Date.now(),this._logger.warn(`Dropping ${this._droppedSinceWarning} span(s): ${[...this._dropReasons].join("; ")}`),this._droppedSinceWarning=0,this._dropReasons.clear())}_encodeBatch(t){let r=[];for(let n of t)try{r.push(Jcu(n,this._logger))}catch(i){this._logger.debug("Failed to encode a span; dropping it",i),this._recordDrop(1,"its attributes could not be encoded")}return r}_discardQueueIfConsentWithdrawn(){if(!this._instance.isDisabled&&!this._instance.optedOut)return 0;let t=this._queue.length;return this._queue=[],this._resetHeadBatchBudget(),this._recordDrop(t,"the user has opted out"),this._warnAboutDrops(),t}async _flushInner(){if(!this._queue.length)return 0;let t=this._discardQueueIfConsentWithdrawn();if(t)return t;let r=Kcu(Ycu(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._config.maxAttributeValueLength),n=this._instance.getLibraryId(),i=this._instance.getLibraryVersion(),o=this._queue.length,s=0,a=1/0,c=this._generation;try{for(;o>0&&this._queue.length>0;){let l=this._discardQueueIfConsentWithdrawn();if(l)return s+l;let u=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,p=Math.max(1,Math.min(u,a,o,this._queue.length)),d=this._queue.slice(0,p),f=this._encodeBatch(d);if(!f.length){this._queue.splice(0,p),o-=p,s+=p,this._resetHeadBatchBudget();continue}let m=lrn()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),g=await this._instance._sendTracesBatch(Xcu(f,r,n,i,this._logger));if(c!==this._generation)break;if(this._retryAfter.record(g),g.kind==="ok"){this._consecutiveFlushFailures=0,this._flushJitter=D8,this._resetHeadBatchBudget(),this._queue.splice(0,p),o-=p,s+=p,this._maxExportBatchSize<this._config.maxExportBatchSize&&this._maxExportBatchSize++;continue}if(g.kind==="too-large"){if(p===1){this._queue.splice(0,1),o-=1,s+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=D8,this._resetHeadBatchBudget();continue}let A=Math.max(1,Math.floor(p/2));g.measuredLocally?a=A:this._maxExportBatchSize=A,this._resetHeadBatchBudget(),this._logger.debug(`Batch too large; retrying the same spans in batches of ${A}`);continue}if(g.kind==="retry-later"){if(this._consecutiveFlushFailures++,this._flushJitter=xWt(),this._headBatchSize=p,m&&(this._headBatchFailures++,this._headBatchChargeableAt=lrn()+this._nextFlushDelay()),this._headBatchFailures<Zcu)return this._logger.debug("Span export failed; retrying on the next flush",g.error),s;if(this._queue.splice(0,p),o-=p,s+=p,this._consecutiveFlushFailures=0,this._flushJitter=D8,this._resetHeadBatchBudget(),this._recordDrop(p,`the ingestion endpoint failed ${Zcu} times in a row`),this._retryAfter.isOpen())return s;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",g.error),this._queue.splice(0,p),o-=p,s+=p,this._consecutiveFlushFailures=0,this._flushJitter=D8,this._resetHeadBatchBudget(),this._recordDrop(p,"the ingestion endpoint rejected the batch")}return s}finally{this._warnAboutDrops()}}_flushInBackground(){this._backgroundFlush||(this._backgroundFlush=this.flush().catch(t=>{this._logger.debug("Background span flush failed",t)}).finally(()=>{this._backgroundFlush=void 0,this._armFlushTimerIfQueuedNoEarlierThan()}))}_armFlushTimerIfQueued(){this._flushTimer.pending||!this._queue.length||this._flushTimer.arm(this._nextFlushDelay())}_armFlushTimerIfQueuedNoEarlierThan(){this._queue.length&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(SWt(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}};var RWt=class{active(){return this._active}with(t,r){let n=this._active;this._active=t;try{return r()}finally{this._active=n}}};var dbh=5e3,mbh=512,hbh=2048,gbh=128,Abh=128,ybh=128,bbh=8192,Ebh=1e4,Ibh=36e5;function jwe(e,t){return typeof e=="number"&&Number.isInteger(e)&&e>=1?e:t}var elu=["service.name","service.version","deployment.environment"];function vbh(e){if(!(!e||typeof e!="object"||Array.isArray(e)))try{if(elu.every(r=>!(r in e)||typeof e[r]=="string"))return e;let t={...e};for(let r of elu)r in t&&typeof t[r]!="string"&&delete t[r];return t}catch{return}}function Cbh(e,t){if(!e)return[];let r=[e].flat().filter(i=>!!i),n=r.filter(i=>typeof i=="function");return n.length!==r.length&&t?.critical(`beforeSpanSend: ignoring ${r.length-n.length} of ${r.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`),n}function dYo(e,t,r){let n=hhe({...t},vbh(e?.resourceAttributes)),i=jwe(e?.maxExportBatchSize,mbh);return{serviceName:n?.["service.name"]??e?.serviceName,serviceVersion:n?.["service.version"]??e?.serviceVersion,environment:n?.["deployment.environment"]??e?.environment,resourceAttributes:n,beforeSpanSend:Cbh(e?.beforeSpanSend,r),maxAttributesPerSpan:jwe(e?.maxAttributesPerSpan,gbh),maxEventsPerSpan:jwe(e?.maxEventsPerSpan,Abh),maxAttributesPerEvent:ybh,maxAttributeValueLength:jwe(e?.maxAttributeValueLength,bbh),flushIntervalMs:jwe(e?.flushIntervalMs,dbh),maxExportBatchSize:i,maxQueueSize:Math.max(jwe(e?.maxQueueSize,hbh),i),maxLiveSpans:jwe(e?.maxLiveSpans,Ebh),maxSpanAgeMs:jwe(e?.maxSpanAgeMs,Ibh)}}var mYo=require("fs"),nlu=require("fs/promises"),gYo=require("path"),ilu=require("readline"),prn=new LT.ReduceableCache(25),kWt=new LT.ReduceableCache(20),AYo=7,xbh=1e3,Sbh=1e4,hYo=10485760;async function olu(e,t=nlu.open,r){let n={},i;try{i=process.cwd()}catch{}for(let a=e.length-1;a>=0;a--){let c=e[a],l=c?.filename;if(!c||typeof l!="string"||typeof c.lineno!="number"||Bbh(l)||Dbh(c)||!(0,gYo.isAbsolute)(l)&&i===void 0)continue;n[l]||(n[l]=[]),n[l].push(c.lineno)}let o=Object.keys(n);if(o.length==0)return e;let s=[];for(let a of o){let c=slu(a,i);if(c===void 0||kWt.get(c))continue;let l=n[a];if(!l)continue;l.sort((d,f)=>d-f);let u=kbh(l);if(u.every(d=>Rbh(c,d)))continue;let p=Fbh(prn,c,{});s.push(Tbh(a,u,p,c,t,r))}return await Promise.all(s).catch(()=>{}),e&&e.length>0&&Obh(e,prn,i),prn.reduce(),e}async function wbh(e,t,r){let n,i=!1;try{n=await t(e,mYo.constants.O_RDONLY|mYo.constants.O_NONBLOCK);let o=await n.stat();return o.isFile()?o.size>hYo?void r?.debug(`Skipping source context for oversized file ${e}: ${o.size} bytes exceeds ${hYo}`):(i=!0,n):void 0}catch{return}finally{n&&!i&&await n.close().catch(()=>{})}}async function Tbh(e,t,r,n,i,o){let s=await wbh(e,i,o);if(s===void 0)return void kWt.set(n,1);let a=s;return new Promise(c=>{let l=!1;function u(C){l||(l=!0,C?.destroy(),a.close().then(c,c))}let p;try{p=a.createReadStream({autoClose:!1,start:0,end:hYo-1})}catch{kWt.set(n,1),u();return}let d;try{d=(0,ilu.createInterface)({input:p})}catch{kWt.set(n,1),u(p);return}let f=0,m=0,g=t[m];if(g===void 0)return void u(p);let A=g[0],b=g[1];function I(){kWt.set(n,1),d.close(),d.removeAllListeners(),u(p)}p.on("error",I),d.on("error",I),d.on("close",()=>u(p)),d.on("line",C=>{if(f++,!(f<A)&&(r[f]=Nbh(C,0),f>=b)){if(m===t.length-1){d.close(),d.removeAllListeners();return}m++;let x=t[m];if(x===void 0){d.close(),d.removeAllListeners();return}A=x[0],b=x[1]}})})}function Obh(e,t,r){for(let n of e)if(n.filename&&n.context_line===void 0&&typeof n.lineno=="number"){let i=slu(n.filename,r),o=i===void 0?void 0:t.get(i);if(o===void 0)continue;Pbh(n.lineno,n,o)}}function Pbh(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=alu(e);i<e;i++){let o=r[i];if(o===void 0)return void tlu(t);t.pre_context.push(o)}if(r[e]===void 0)return void tlu(t);t.context_line=r[e];let n=clu(e);t.post_context=[];for(let i=e+1;i<=n;i++){let o=r[i];if(o===void 0)break;t.post_context.push(o)}}function tlu(e){delete e.pre_context,delete e.context_line,delete e.post_context}function Bbh(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function Dbh(e){return e.lineno!==void 0&&e.lineno>Sbh||e.colno!==void 0&&e.colno>xbh}function slu(e,t){return(0,gYo.isAbsolute)(e)?JSON.stringify([null,e]):t===void 0?void 0:JSON.stringify([t,e])}function Rbh(e,t){let r=prn.get(e);if(r===void 0)return!1;for(let n=t[0];n<=t[1];n++)if(r[n]===void 0)return!1;return!0}function kbh(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=rlu(r),i=[];for(;;){if(t===e.length-1){i.push(n);break}let o=e[t+1];if(typeof o!="number")break;o<=n[1]?n[1]=o+AYo:(i.push(n),n=rlu(o)),t++}return i}function rlu(e){return[alu(e),clu(e)]}function alu(e){return Math.max(1,e-AYo)}function clu(e){return e+AYo}function Fbh(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function Nbh(e,t){let r=e,n=r.length;if(n<=150)return r;t>n&&(t=n);let i=Math.max(t-60,0);i<5&&(i=0);let o=Math.min(i+140,n);return o>n-5&&(o=n),o===n&&(i=Math.max(o-140,0)),r=r.slice(i,o),i>0&&(r=`...${r}`),o<n&&(r+="..."),r}var Jut=require("path");function llu(e=process.cwd()){let t=Jut.sep==="\\",r=i=>t?i.replace(/\\/g,"/"):i,n=r(e);return async i=>{for(let o of i)!o.filename||o.filename.startsWith("node:")||o.filename.startsWith("data:")||(0,Jut.isAbsolute)(o.filename)&&(o.filename=r((0,Jut.relative)(n,r(o.filename))));return i}}var ulu="5.55.0";var Ahe={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var zwe=class e{constructor(t){this._host=t.host,this._distinctId=t.distinctId,this._groups=t.groups,this._disableGeoip=t.disableGeoip,this._flags=t.flags,this._requestId=t.requestId,this._evaluatedAt=t.evaluatedAt,this._flagDefinitionsLoadedAt=t.flagDefinitionsLoadedAt,this._errorsWhileComputing=t.errorsWhileComputing??!1,this._quotaLimited=t.quotaLimited??!1,this._accessed=t.accessed??new Set,this._isSlice=t.isSlice??!1}isEnabled(t,r={}){let n=this._flags[t];return this._recordAccess(t),n?.enabled??r.defaultValue??!1}getFlag(t){let r=this._flags[t];if(this._recordAccess(t),!!r)return r.enabled?r.variant??!0:!1}getFlagPayload(t){return this._flags[t]?.payload}onlyAccessed(){let t={};for(let r of this._accessed){let n=this._flags[r];n&&(t[r]=n)}return this._cloneWith(t)}only(t){let r={},n=[];for(let i of t){let o=this._flags[i];o?r[i]=o:n.push(i)}return n.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${n.join(", ")}`),this._cloneWith(r)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let t={},r=[];for(let[n,i]of Object.entries(this._flags)){let o=i.enabled===!1?!1:i.variant??!0;t[`$feature/${n}`]=o,i.enabled&&r.push(n)}return r.length>0&&(r.sort(),t.$active_feature_flags=r),t}_cloneWith(t){return new e({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:t,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(t){if(this._accessed.add(t),this._distinctId===""||this._isSlice&&!(t in this._flags))return;let r=this._flags[t],n=r===void 0?void 0:r.enabled===!1?!1:r.variant??!0,i={$feature_flag:t,$feature_flag_response:n,$feature_flag_id:r?.id,$feature_flag_version:r?.version,$feature_flag_reason:r?.reason,locally_evaluated:r?.locallyEvaluated??!1,[`$feature/${t}`]:n,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:r?.locallyEvaluated?Date.now():this._evaluatedAt};r?.hasExperiment!==void 0&&(i.$feature_flag_has_experiment=r.hasExperiment),r?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0&&(i.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let o=[];this._errorsWhileComputing&&o.push(Ahe.ERRORS_WHILE_COMPUTING),this._quotaLimited&&o.push(Ahe.QUOTA_LIMITED),r===void 0&&o.push(Ahe.FLAG_MISSING),o.length>0&&(i.$feature_flag_error=o.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:t,response:n,groups:this._groups,disableGeoip:this._disableGeoip,properties:i})}};var jbh=6e4;function plu(e){return e==="client"||e==="server"?e:"all"}function zbh(e,t){return e===t||e==="all"||t==="all"}var Yut=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}};function Qbh(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}var _re=class e extends Error{constructor(t){super(t),Qbh(this,e)}},frn=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:n,timeout:i,host:o,customHeaders:s,...a}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollerStopped=!1,this.filteredOutFlagKeys=new Set,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=i,this.projectApiKey=n,this.host=o,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=s,this.onLoad=a.onLoad,this.onMinimalFlagCalledEvents=a.onMinimalFlagCalledEvents,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.evaluationContexts=a.evaluationContexts,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}withEvaluationSnapshot(t){return t.definitions?t:{...t,evaluationCache:{},definitions:{featureFlagsByKey:this.featureFlagsByKey,groupTypeMapping:this.groupTypeMapping,cohorts:this.cohorts,filteredOutFlagKeys:this.filteredOutFlagKeys,propertyMatchingVersion:this.propertyMatchingVersion}}}createEvaluationContext(t,r={},n={},i={},o={}){return{distinctId:t,groups:r,personProperties:n,groupProperties:i,evaluationCache:o}}async getFeatureFlag(t,r,n={},i={},o={}){await this.loadFeatureFlags();let s,a;if(!this.loadedSuccessfullyOnce)return s;if(a=this.featureFlagsByKey[t],a!==void 0){let c=this.createEvaluationContext(r,n,i,o);try{s=(await this.computeFlagAndPayloadLocally(a,c)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${s}`))}catch(l){l instanceof _re||l instanceof Gl?this.logMsgIfDebug(()=>console.debug(`${l.name} when computing flag locally: ${t}: ${l.message}`)):l instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${l}`))}}return s}async getAllFlagsAndPayloads(t,r){await this.loadFeatureFlags();let n={},i={},o=this.featureFlags.length==0,s=r?r.map(c=>this.featureFlagsByKey[c]).filter(Boolean):this.featureFlags,a=this.withEvaluationSnapshot({...t,definitions:void 0});return await Promise.all(s.map(async c=>{try{let{value:l,payload:u}=await this.computeFlagAndPayloadLocally(c,a,{skipLoadCheck:!0});n[c.key]=l,u&&(i[c.key]=u)}catch(l){l instanceof _re||l instanceof Gl?this.logMsgIfDebug(()=>console.debug(`${l.name} when computing flag locally: ${c.key}: ${l.message}`)):l instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${c.key}: ${l}`)),o=!0}})),{response:n,payloads:i,fallbackToFlags:o}}async computeFlagAndPayloadLocally(t,r,n={}){let{matchValue:i,skipLoadCheck:o=!1}=n;if(this.loadedSuccessfullyOnce&&(r=this.withEvaluationSnapshot(r)),o||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};r=this.withEvaluationSnapshot(r),t=r.definitions.featureFlagsByKey[t.key]??t;let s;s=i!==void 0?i:await this.computeFlagValueLocally(t,r);let a=ZJo(t.filters?.payloads,s);return{value:s,payload:a}}async computeFlagValueLocally(t,r){let{distinctId:n,groups:i,personProperties:o,groupProperties:s}=r;if(!t.active)return!1;if(t.ensure_experience_continuity)throw new Gl("Flag has experience continuity enabled");let c=(t.filters||{}).aggregation_group_type_index;if(c!=null){let l=r.definitions.groupTypeMapping[String(c)];if(!l)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new Gl("Flag has unknown group type index");if(!(l in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;t.bucketing_identifier==="device_id"&&(o?.$device_id===void 0||o?.$device_id===null||o?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${t.key}`));let u=s[l];return await this.matchFeatureFlagProperties(t,i[l],u,r)}{let l=this.getBucketingValueForFlag(t,n,o);if(l===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${t.key} without $device_id, falling back to server evaluation`)),new Gl(`Can't compute feature flag: ${t.key} without $device_id`);return await this.matchFeatureFlagProperties(t,l,o,r)}}getBucketingValueForFlag(t,r,n){if(t.filters?.aggregation_group_type_index!=null)return r;if(t.bucketing_identifier==="device_id"){let i=n?.$device_id;return i==null||i===""?void 0:i}return r}async evaluateFlagDependency(t,r,n){let{evaluationCache:i}=n,o=t.key;if(!n.definitions.featureFlagsByKey)throw new Gl("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new Gl(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let s=t.dependency_chain;if(!Array.isArray(s))throw new Gl(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new Gl(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let c of s){if(!(c in i)){let u=n.definitions.featureFlagsByKey[c];if(u)if(u.active)try{let p=await this.computeFlagValueLocally(u,n);i[c]=p}catch(p){throw new Gl(`Error evaluating flag dependency '${c}' for flag '${o}': ${p}`)}else i[c]=!1;else if(n.definitions.filteredOutFlagKeys.has(c))i[c]=!1;else throw new Gl(`Missing flag dependency '${c}' for flag '${o}'`)}if(i[c]==null)throw new Gl(`Dependency '${c}' could not be evaluated`)}let a=i[o];return this.flagEvaluatesToExpectedValue(t.value,a)}flagEvaluatesToExpectedValue(t,r){return typeof t=="boolean"?t===r||typeof r=="string"&&r!==""&&t===!0:typeof t=="string"?r===t:!1}async matchFeatureFlagProperties(t,r,n,i){i=this.withEvaluationSnapshot(i);let o=t.filters||{},s=await YJo(o.holdout,r);if(s!==void 0)return s;let a=o.groups||[],c=o.aggregation_group_type_index,l=o.early_exit??!1,{groups:u,groupProperties:p}=i,d=!1,f;for(let m of a)try{let g=m.aggregation_group_type_index!==void 0?m.aggregation_group_type_index:c,A=n,b=r;if(g!==c&&g!=null){let C=i.definitions.groupTypeMapping[String(g)];if(!C||!(C in u)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${t.key}': group type index ${g} not available`));continue}if(!(C in p)){d=!0;continue}A=p[C],b=u[C]}let I=await this.isConditionMatch(t,b,m,A,i);if(I==="match"){let C=m.variant,x=o.multivariate?.variants||[];f=C&&x.some(S=>S.key===C)?C:await this.getMatchingVariant(t,b)||!0;break}if(l&&I==="out_of_rollout_bound"){if(d)break;return!1}}catch(g){if(g instanceof _re)throw g;if(g instanceof Gl)d=!0;else throw g}if(f!==void 0)return f;if(d)throw new Gl("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,n,i,o){o=this.withEvaluationSnapshot(o);let s=o.definitions,a=n.rollout_percentage,c=l=>{this.logMsgIfDebug(()=>console.warn(l))};if((n.properties||[]).length>0){for(let l of n.properties){let u=l.type,p=!1;if(u==="cohort"){let d=await dlu(l,i,s.cohorts,this.debugMode,f=>this.evaluateFlagDependency(f,i,o),s.propertyMatchingVersion);p=l.operator==="not_in"?!d:d}else p=u==="flag"?await this.evaluateFlagDependency(l,i,o):flu(l,i,c,s.propertyMatchingVersion);if(!p)return"no_match"}if(a==null)return"match"}return a!=null&&await EWt(t.key,r)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(t,r){return XJo(t.key,r,t.filters?.multivariate?.variants||[])}variantLookupTable(t){return Xtn(t.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(t){if(!this.evaluationContexts||this.evaluationContexts.length===0)return t;let r=new Set(this.evaluationContexts);return t.filter(n=>{let i=n.evaluation_contexts??n.evaluation_tags;return!i||i.length===0?!0:i.some(o=>r.has(o))})}getEvaluationRuntimeForFlag(t){let r=this.featureFlagsByKey[t];return r?plu(r.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(t){return this.featureFlags.filter(r=>zbh(plu(r.evaluation_runtime),t)).map(r=>r.key)}updateFlagState(t){let r=this.filterFlagsByEvaluationContexts(t.flags);this.featureFlags=r,this.featureFlagsByKey=r.reduce((i,o)=>(i[o.key]=o,i),{});let n=new Set(r.map(i=>i.key));this.filteredOutFlagKeys=new Set(t.flags.filter(i=>!n.has(i.key)).map(i=>i.key)),this.groupTypeMapping=t.group_type_mapping??t.groupTypeMapping??{},this.cohorts=t.cohorts,this.propertyMatchingVersion=t.property_matching_version??t.propertyMatchingVersion,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.((t.minimal_flag_called_events??t.minimalFlagCalledEvents)===!0)}warnAboutExperienceContinuityFlags(t){if(this.strictLocalEvaluation)return;let r=t.filter(n=>n.ensure_experience_continuity);r.length>0&&console.warn(`[PostHog] You are using local evaluation but ${r.length} flag(s) have experience continuity enabled: ${r.map(n=>n.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(t){if(!this.cacheProvider)return!1;try{let r=await this.cacheProvider.getFlagDefinitions();return r?(this.updateFlagState(r),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${t} (${r.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags),!0):!1}catch(r){return this.onError?.(new Error(`Failed to load from cache: ${r}`)),!1}}async loadFeatureFlags(t=!1){if(!(this.loadedSuccessfullyOnce&&!t))return!t&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(r=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${r}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){let t=this.pollingInterval??3e4;return this.shouldBeginExponentialBackoff?Math.min(jbh,t*2**this.backOffCount):t}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0);try{let t=!0;if(this.cacheProvider)try{t=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(n){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${n}`))}if(!t&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let r=await this._requestFeatureFlagDefinitions();if(!r)return;switch(r.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=r.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new Yut(`Your project key or secret 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.filteredOutFlagKeys=new Set,this.groupTypeMapping={},this.cohorts={},this.propertyMatchingVersion=void 0,this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new Yut(`Your secret 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 secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new Yut(`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 n=await r.json()??{};if(!("flags"in n))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(n)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let i=n.group_type_mapping||{},o=n.minimal_flag_called_events===!0,s={flags:n.flags??[],group_type_mapping:i,cohorts:n.cohorts||{},minimal_flag_called_events:o,property_matching_version:n.property_matching_version,propertyMatchingVersion:n.property_matching_version,groupTypeMapping:i,minimalFlagCalledEvents:o};if(this.updateFlagState(s),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(s)}catch(a){this.onError?.(new Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags);break}default:return}}catch(t){t instanceof Yut&&this.onError?.(t)}finally{!this.pollerStopped&&this.pollingInterval!==null&&(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}getPersonalApiKeyRequestOptions(t="GET",r){let n={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(n["If-None-Match"]=r),{method:t,headers:n}}async _requestFeatureFlagDefinitions(){let t=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let o=new AbortController;n=$2(()=>{o.abort()},this.timeout),r.signal=o.signal}let i=()=>clearTimeout(n);try{let o=this.fetch,s=await o(t,r);return s.status!==200?(i(),s):{status:s.status,headers:s.headers,body:s.body,text:async()=>{try{return await s.text()}finally{i()}},json:async()=>{try{return await s.json()}finally{i()}}}}catch(o){throw i(),o}}async stopPoller(t=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await Fwe(r,t,()=>{throw new Error(`Cache shutdown timeout after ${t}ms`)})}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};function flu(e,t,r,n){return JJo(e,t,{warnFunction:r,propertyMatchingVersion:n})}function Mbh(e,t){if(!(e in t))throw new _re(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function dlu(e,t,r,n=!1,i,o){let s=String(e.value);Mbh(s,r);let a=r[s];return mlu(a,t,r,n,i,o)}async function mlu(e,t,r,n=!1,i,o){if(!e)return!0;let s=e.type,a=e.values;if(!a||a.length===0)return!0;let c=!1;if("values"in a[0]){for(let l of a)try{let u=await mlu(l,t,r,n,i,o);if(s==="AND"){if(!u)return!1}else if(u)return!0}catch(u){if(u instanceof _re)throw u;if(u instanceof Gl)n&&console.debug(`Failed to compute property ${l} locally: ${u}`),c=!0;else throw u}if(c)throw new Gl("Can't match cohort without a given cohort property value");return s==="AND"}for(let l of a)try{let u;if(l.type==="cohort")u=await dlu(l,t,r,n,i,o);else if(l.type==="flag"){if(!i)throw new Gl(`Flag dependency '${l.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);u=await i(l)}else u=flu(l,t,void 0,o);let p=l.negation||!1;if(s==="AND"){if(!u&&!p||u&&p)return!1}else if(u&&!p||!u&&p)return!0}catch(u){if(u instanceof _re)throw u;if(u instanceof Gl)n&&console.debug(`Failed to compute property ${l} locally: ${u}`),c=!0;else throw u}if(c)throw new Gl("can't match cohort without a given cohort property value");return s==="AND"}var Lbh=["--unhandled-rejections","--unhandled_rejections"],_bh=new Set(["throw","strict","warn","warn-with-error-code","none"]),Ubh=[...globalThis.process?.execArgv??[]],Vbh=globalThis.process?.env?.NODE_OPTIONS;function Gbh(e){let t=[],r="",n=!1;for(let i=0;i<e.length;i++){let o=e[i];o==="\\"&&n&&i+1<e.length?r+=e[++i]:o!==" "||n?o==='"'?n=!n:r+=o:r&&(t.push(r),r="")}return r&&t.push(r),t}function hlu(e){let t;for(let r=0;r<e.length;r++){let n=e[r],i=Lbh.find(s=>n===s||n.startsWith(`${s}=`));if(!i)continue;let o=n===i?e[++r]:n.slice(i.length+1);_bh.has(o)&&(t=o)}return t}function qbh(e=Ubh,t=Vbh){return hlu(e)??hlu(Gbh(t??""))??"throw"}var glu=qbh();function Alu(e,t,r){e(t,{mechanism:{type:r==="unhandledRejection"?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function Wbh(e,t){let r=!1;return Object.assign((n,i)=>{let o=global.process.listeners("uncaughtException").filter(s=>s.name!=="domainUncaughtExceptionClear"&&s._posthogErrorHandler!==!0).length;Alu(e,n,i),!r&&o===0&&(r=!0,t(n))},{_posthogErrorHandler:!0})}function ylu(e,t,r=glu){let n=globalThis.process;if(n){if(r==="strict")return void n.on("uncaughtExceptionMonitor",(i,o)=>Alu(e,i,o));n.on("uncaughtException",Wbh(e,t))}}function blu(e,t=glu){let r=globalThis.process;!r||t==="throw"||t==="strict"||t==="warn-with-error-code"||r.on("unhandledRejection",n=>{e(n,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var Hbh=2e3,yYo=class e{constructor(t,r,n){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new Dtn({...Bau(r),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return iWt(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}static async buildEventMessage(t,r,n,i,o){let s={...o},a=t.buildFromUnknown(r,n);a.$exception_list=await t.modifyFrames(a.$exception_list);let c=LT.getInjectedReleaseId();return c&&(s.$release_id=c),{event:"$exception",distinctId:i,properties:{...a,...s},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(ylu(this.onException.bind(this),this.onFatalError.bind(this)),blu(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let n=await e.buildEventMessage(this.client.getErrorPropertiesBuilder(),t,r),o=n.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(o)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:o}):this.client._capturePreparedEvent(n,!1)}})())}async onFatalError(t){console.error(t),await this.client.shutdown(Hbh),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}},PVe=yYo;var drn=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};function Kbh(e){return e==="v0"||e==="v1"}function Elu(){let e="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return Kbh(e)?e:"v0"}var Jbh="$ai_",FWt="analytics";function Ilu(e){return typeof e.event=="string"&&e.event.startsWith(Jbh)}var Xut=class e extends Error{constructor({requestId:t,drops:r,retryExhausted:n,cause:i}){super(e.buildMessage(t,r,n,i)),this.name="CaptureV1Error",this.requestId=t,this.drops=r,this.retryExhausted=n,this.cause=i}static buildMessage(t,r,n,i){let o=`Capture V1 batch ${t} did not fully deliver: ${r.length} dropped, ${n.length} undelivered`;return i instanceof Error&&(o+=` (${i.message})`),o}};function bYo(e){if(typeof e=="boolean")return e;if(typeof e=="number")return e!==0;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}}function Ybh(e){return typeof e=="string"?e:void 0}var Xbh=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:bYo},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:bYo},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:bYo},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:Ybh}],Zbh=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function $bh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function eEh(e){if(typeof e=="string"){let r=new Date(e);if(Number.isNaN(r.getTime()))return new Date().toISOString();let n=r.toISOString(),i=e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return i&&i.length>3?n.replace(/\.\d{3}Z$/,`.${i}Z`):n}if(e instanceof Date)return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString();let t=e==null?new Date:new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}function vlu(e,t,r){r!==void 0&&!(t in e)&&(e[t]=r)}function tEh(e){let r={...$bh(e.properties)?e.properties:{}},n={};for(let{property:o,optionKey:s,coerce:a}of Xbh)if(o in r){let c=a(r[o]);c!==void 0&&(n[s]=c),delete r[o]}let i={};for(let{property:o,field:s}of Zbh)if(o in r){let a=r[o];typeof a=="string"&&(i[s]=a),delete r[o]}return delete r.$lib,delete r.$lib_version,vlu(r,"$set",e.$set),vlu(r,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:eEh(e.timestamp),...i,options:n,properties:r}}function Clu(e,{createdAt:t,historicalMigration:r}){let n={created_at:t,batch:e.map(tEh)};return r&&(n.historical_migration=!0),n}var rEh="/i/v1/analytics/events",nEh=3e4,iEh=new Set([408,500,502,503,504]),mrn=class{constructor(t,r){this.config=t,this.maxBackoffMs=t.maxBackoffMs??nEh,this.fetchFn=r.fetch,this.onError=r.onError,this.now=r.now??Date.now,this.sleep=r.sleep??(n=>new Promise(i=>$2(i,n))),this.generateRequestId=r.generateRequestId??Z2,this.compress=r.compress??AWt}async sendV1Batch(t){if(t.length===0)return;let r=this.generateRequestId(),n=new Date(this.now()).toISOString(),{batch:i}=Clu(t,{createdAt:n,historicalMigration:this.config.historicalMigration}),o=`${this.config.host}${rEh}`,s=[],a=i,c=Math.max(1,this.config.maxAttempts);for(let l=1;l<=c;l++){let u=l===c,p=Rwe({created_at:n,...this.config.historicalMigration?{historical_migration:!0}:{},batch:a}),d,f;try{d=await this.sendOnce(o,p,l,r);let{response:m,signal:g}=d,{status:A}=m;if(A<200||A>=300)if(!u&&iEh.has(A)){let b=this.parseRetryAfter(m);await d.waitFor(d.cancelBody()).catch(()=>{}),f=this.backoffDelay(l,b)}else{let b=await this.buildHttpError(m,A,d.waitFor);return this.surfaceBatchFailure(r,s,a,b)}else{let b;try{b=await d.waitFor(this.parseResponse(m))}catch(x){if(g.aborted)throw x;return this.surfaceBatchFailure(r,s,a,new Error(`Capture V1 returned an unparseable ${A} response body`))}let I=this.classify(a,b,s);if(I.length===0)return this.surfacePartialDrops(r,s);if(u)return void this.onError(new Xut({requestId:r,drops:s,retryExhausted:I.map(x=>x.uuid)}));a=I;let C=this.parseRetryAfter(m);f=this.backoffDelay(l,C)}}catch(m){if(d&&!d.signal.aborted)throw m;if(u)return this.surfaceBatchFailure(r,s,a,m);f=this.backoffDelay(l)}finally{d?.cleanup()}f!==void 0&&await this.sleep(f)}}async sendOnce(t,r,n,i){let o=this.buildHeaders(n,i),s=r;if(this.config.compressionEnabled){let p=await this.compress(r,this.config.isDebug);p!==null&&(s=p,o["Content-Encoding"]="gzip")}let a=new AbortController,c="waiting for response headers",l,u=new Promise((p,d)=>{l=$2(()=>{let f=new Error(`Capture V1 request timed out ${c} after ${this.config.requestTimeoutMs}ms`);f.name="AbortError",d(f),a.abort(f)},this.config.requestTimeoutMs)});try{let p=this.fetchFn(t,{method:"POST",headers:o,body:s,signal:a.signal}),d=!1;p.then(b=>{a.signal.aborted&&!d&&this.cancelBody(b)}).catch(()=>{});let f=await Promise.race([p,u]);d=!0,c="while reading the response body";let m=!1,g,A=()=>g??=this.cancelBody(f);return{response:f,signal:a.signal,waitFor:b=>Promise.race([b,u]),cancelBody:A,cleanup:()=>{m||(m=!0,clearTimeout(l),a.signal.aborted&&A())}}}catch(p){throw clearTimeout(l),p}}buildHeaders(t,r){let n=`${this.config.libraryId}/${this.config.libraryVersion}`,i={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":n,"PostHog-Attempt":String(t),"PostHog-Request-Id":r,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(i["User-Agent"]=this.config.userAgent),i}classify(t,r,n){let i=r.results??{},o=[];for(let s of t){let a=i[s.uuid];a&&(a.result==="drop"?n.push({uuid:s.uuid,details:a.details??void 0}):a.result==="retry"&&o.push(s))}return o}backoffDelay(t,r){let n=Math.min(this.config.initialRetryDelayMs*2**(t-1),this.maxBackoffMs);return r===void 0?n:Math.max(n,Math.min(r,this.maxBackoffMs))}parseRetryAfter(t){let r=t.headers?.get("Retry-After");if(!r)return;let n=r.trim();if(/^\d+$/.test(n)){let s=parseInt(n,10);return Number.isFinite(s)&&s>0?1e3*s:void 0}let i=Date.parse(n);if(Number.isNaN(i))return;let o=i-this.now();return o>0?o:void 0}async parseResponse(t){let r=await t.text(),n=JSON.parse(r);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("unexpected response shape");let i=n.results;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw new Error("unexpected results shape");return{results:i??{}}}async buildHttpError(t,r,n){let i="";try{i=(await n(t.text())).slice(0,512)}catch{}let o=i?`: ${i}`:"";return new Error(`Capture V1 request failed with HTTP ${r}${o}`)}surfaceBatchFailure(t,r,n,i){this.onError(new Xut({requestId:t,drops:r,retryExhausted:n.map(o=>o.uuid),cause:i}))}surfacePartialDrops(t,r){r.length>0&&this.onError(new Xut({requestId:t,drops:r,retryExhausted:[]}))}async cancelBody(t){try{await t.body?.cancel()}catch{}}};var BVe="ai-capture",hrn="/i/v0/ai/batch/";var sEh=new TextEncoder;function IYo(e){return sEh.encode(Rwe(e)).length}function xlu(e,t=8388608,r=5242880){let n=[],i=[],o=[],s=0;for(let a of e){if(a===void 0)continue;let c=IYo(a);if(c>t){i.push({event:typeof a.event=="string"?a.event:"unknown",bytes:c});continue}o.length>0&&s+c>r&&(n.push(o),o=[],s=0),o.push(a),s+=c}return o.length>0&&n.push(o),{batches:n,dropped:i}}var aEh=100,Slu=3e4,cEh=5e4,lEh=50,uEh=500,pEh="https://us.i.posthog.com",wlu=new Set;function Arn(e,t){wlu.has(e)||(wlu.add(e),console.warn(`[PostHog] ${t}`))}function fEh(e){return typeof e=="string"?e.trim():""}function dEh(e){return(typeof e=="string"?e.trim():"")||void 0}function mEh(e){return(typeof e=="string"?e.trim():"")||pEh}function hEh(e){return(Array.isArray(e)?e:[e]).filter(r=>typeof r=="string"&&r.trim().length>0)}function gEh(e){if(!e)return{};let t={};for(let[n,i]of Object.entries(e))t[`$feature/${n}`]=i;let r=Object.keys(e).filter(n=>e[n]!==!1).sort();return r.length>0&&(t.$active_feature_flags=r),t}var yrn=class extends yWt{constructor(t,r={}){let n=fEh(t),i={...r,maxQueueSize:r.maxQueueSize??1e4,flushInterval:r.flushInterval??5e3,host:mEh(r.host),personalApiKey:dEh(r.secretKey??r.personalApiKey)};if(super(n,i),this._memoryStorage=new drn,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=i,this.captureMode=Elu(),this.enableFullAiCapture=i.enableFullAiCapture===!0,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof i.featureFlagsPollingInterval=="number"?Math.max(i.featureFlagsPollingInterval,aEh):i.featureFlagsPollingInterval===null?null:Slu,typeof i.waitUntilDebounceMs=="number"&&(this.options.waitUntilDebounceMs=Math.max(i.waitUntilDebounceMs,0)),typeof i.waitUntilMaxWaitMs=="number"&&(this.options.waitUntilMaxWaitMs=Math.max(i.waitUntilMaxWaitMs,0)),!this.disabled&&i.personalApiKey){if(i.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.');i.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new frn({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:i.personalApiKey,projectApiKey:n,timeout:i.requestTimeout??1e4,host:this.host,fetch:i.fetch,onError:s=>{this._events.emit("error",s)},onLoad:s=>{this._events.emit("localEvaluationFlagsLoaded",s)},onMinimalFlagCalledEvents:s=>{this._minimalFlagCalledEvents=s},customHeaders:this.getCustomHeaders(),cacheProvider:i.flagDefinitionCacheProvider,strictLocalEvaluation:i.strictLocalEvaluation,evaluationContexts:i.evaluationContexts??i.evaluationEnvironments}))}this.errorTracking=new PVe(this,i,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=i.maxCacheSize||cEh}enqueue(t,r,n,i){super.enqueue(t,r,n,i),this.scheduleDebouncedFlush()}_flushEventsAndSpans(t=!1){let r=this.flushWithPendingPromises();return!this._traces||t&&this._traces.throttled?r:aWt([r,this._traces.flush().catch(()=>{})]).then(([n])=>{if(n.status==="rejected")throw n.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this._flushKeepingRuntimeAlive(!1)}_flushKeepingRuntimeAlive(t){let r=this._flushEventsAndSpans(t),n=this.options.waitUntil;if(n&&!this._waitUntilCycle)try{n(r.catch(()=>{}))}catch{}return r}scheduleDebouncedFlush(){let t=this.options.waitUntil;if(!t||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let s,a=new Promise(c=>{s=c});try{t(a)}catch{return}this._waitUntilCycle={resolve:s,startedAt:Date.now(),timer:void 0}}let r=Date.now()-this._waitUntilCycle.startedAt,n=this.options.waitUntilMaxWaitMs??uEh,i=r>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),i)return void this.resolveWaitUntilFlush();let o=this.options.waitUntilDebounceMs??lEh;this._waitUntilCycle.timer=$2(()=>{this.resolveWaitUntilFlush()},o)}_consumeWaitUntilCycle(){let t=this._waitUntilCycle;return t&&(clearTimeout(t.timer),this._waitUntilCycle=void 0),t?.resolve}async resolveWaitUntilFlush(){let t=this._consumeWaitUntilCycle();try{await this._flushEventsAndSpans()}catch{}finally{t?.()}}getPersistedProperty(t){return this._memoryStorage.getProperty(t)}setPersistedProperty(t,r){return this._memoryStorage.setProperty(t,r)}fetch(t,r){return this.options.fetch?this.options.fetch(t,r):fetch(t,r)}getQueueRouteKey(t){return this.captureMode==="v1"&&Ilu(t)?"ai":FWt}persistedQueueKeyForRoute(t){return t===BVe?tM.AiCaptureQueue:t==="ai"?tM.AiQueue:tM.Queue}getActiveQueueRoutes(){let t=this.captureMode==="v1"?[FWt,"ai"]:[FWt];return this._aiCaptureRouteActive&&t.push(BVe),t}getBatchEndpointPath(t){return t===BVe?hrn:super.getBatchEndpointPath(t)}async sendBatch(t,r,n=FWt){if(n===BVe)return this.sendAiCaptureBatch(t,r);if(this.captureMode!=="v1"||n==="ai")return super.sendBatch(t,r,n);let i=t.filter(o=>o!==void 0);await this.getV1Sender().sendV1Batch(i)}async sendAiCaptureBatch(t,r){let{batches:n,dropped:i}=xlu(t);for(let{event:o,bytes:s}of i){let a=`Event ${o} (${s} bytes) exceeds the ${8388608/1048576}MiB limit for ${hrn}, dropping.`;this._logger.error(a),this._events.emit("error",new Error(a))}for(let o of n)await this.sendAiSubBatch(o,r)}async sendAiSubBatch(t,r){try{await super.sendBatch(t,r,BVe)}catch(n){if(!Wut(n))throw n;if(t.length===1){let[o]=t,a=`Event ${typeof o.event=="string"?o.event:"unknown"} (${IYo(o)} bytes) was rejected with 413 by ${hrn} on its own, dropping.`;this._logger.error(a),this._events.emit("error",new Error(a));return}let i=Math.ceil(t.length/2);await this.sendAiSubBatch(t.slice(0,i),r),await this.sendAiSubBatch(t.slice(i),r)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new mrn({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3e3,isDebug:this.isDebug},{fetch:(t,r)=>this.fetch(t,r),onError:t=>this._events.emit("error",t),compress:t=>this.compressPayload(t)})),this._v1Sender}getLibraryVersion(){return ulu}get metrics(){return this._metrics||(this._metrics=new TWt(this,$tn(this.options.metrics),this._logger)),this._metrics}initializeSpanContextManager(){return new RWt}hostResourceAttributes(){return{}}get _spanContextManager(){return this._spanContext||(this._spanContext=this.initializeSpanContextManager()),this._spanContext}get _tracesPipeline(){if(this.options.traces)return this._traces||(this._traces=new DWt(this,dYo(this.options.traces,this.hostResourceAttributes(),this._logger),this._logger,()=>this._tracingContext(),this._spanContextManager,()=>this.scheduleDebouncedFlush())),this._traces}_tracingContext(){let t=this.context?.get();return{distinctId:t?.distinctId,sessionId:t?.sessionId}}startSpan(t,r){return this._tracesPipeline?.startSpan(t,r)??Nwe(r,this._spanContextManager.active())}withSpan(t,r,n){let i=typeof r=="function"?void 0:r,o=typeof r=="function"?r:n,s=this._tracesPipeline;return s?i?s.withSpan(t,i,o):s.withSpan(t,o):BWt(this._spanContextManager,Nwe(i,this._spanContextManager.active()),o)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getEvaluationRuntime(){return"server"}getCommonEventProperties(){let t=super.getCommonEventProperties();return(this.options.isServer??!0)&&(t.$is_server=!0),t}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}_warnIfInvalidCapture(t,r,n){typeof t=="string"&&this._logger.warn(r),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn(n)}_sendPreparedEvent(t,r,n,i,o){return this.addPendingPromise(this._prepareEventMessage(r,i).then(({distinctId:s,event:a,properties:c,options:l})=>{let u={timestamp:l.timestamp,disableGeoip:l.disableGeoip,uuid:l.uuid},p={distinctId:s,event:a,properties:{...c,...this.getCommonEventProperties()}};return n?this.sendImmediate(t,p,u,o):this.enqueue(t,p,u,o)}).catch(s=>{s&&console.error(s)}))}_capturePreparedEvent(t,r){return this._sendPreparedEvent("capture",t,r)}capture(t){this._warnIfInvalidCapture(t,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(t,!1)}async captureImmediate(t){return this._warnIfInvalidCapture(t,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(t,!0)}captureAi(t){if(this.disabled)return;let r=SVe(t.uuid,Z2);return this._sendPreparedAiEvent({...t,uuid:r},!1),r}async captureAiImmediate(t){if(this.disabled)return;let r=SVe(t.uuid,Z2);return await this._sendPreparedAiEvent({...t,uuid:r},!0),r}_sendPreparedAiEvent(t,r){return typeof t?.event=="string"&&!t.event.startsWith("$ai_")&&this._logger.debug(`captureAi called with non-AI event ${t.event}; routing it to the AI endpoint anyway.`),this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",t,r,void 0,BVe)}identify({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,u={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};this._sendPreparedEvent("identify",{distinctId:t,event:"$identify",properties:u,disableGeoip:n},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,u={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};await this._sendPreparedEvent("identify",{distinctId:t,event:"$identify",properties:u,disableGeoip:n},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:t,properties:r={},propertiesOnce:n={}}){if(Object.keys(r).length===0&&Object.keys(n).length===0)return;let i={};Object.keys(r).length>0&&(i.$set=r),Object.keys(n).length>0&&(i.$set_once=n),this.capture({distinctId:t,event:"$set",properties:i})}unsetPersonProperties({distinctId:t,properties:r}){let n=hEh(r);n.length!==0&&this.capture({distinctId:t,event:"$set",properties:{$unset:n}})}alias(t){this._sendPreparedEvent("alias",{distinctId:t.distinctId,event:"$create_alias",properties:{distinct_id:t.distinctId,alias:t.alias},disableGeoip:t.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(t){await this._sendPreparedEvent("alias",{distinctId:t.distinctId,event:"$create_alias",properties:{distinct_id:t.distinctId,alias:t.alias},disableGeoip:t.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}getFeatureFlagEvaluationRuntime(t){return this.featureFlagsPoller?.getEvaluationRuntimeForFlag(t)}getFeatureFlagKeysByEvaluationRuntime(t){return this.featureFlagsPoller?.getFlagKeysByEvaluationRuntime(t)??[]}async waitForLocalEvaluationReady(t=Slu){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let n=setTimeout(()=>{i(),r(!1)},t),i=this._events.on("localEvaluationFlagsLoaded",o=>{clearTimeout(n),i(),r(o>0)})})}_resolveDistinctId(t,r){return typeof t=="string"?{distinctId:t,options:r}:{distinctId:this.context?.get()?.distinctId,options:t}}async _getFeatureFlagResult(t,r,n={},i){if(this.disabled)return void this._logger.warn("The client is disabled");let o=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let D=this._flagOverrides[t];if(D===void 0)return;let R=this._payloadOverrides?.[t];return{key:t,enabled:D!==!1,variant:typeof D=="string"?D:void 0,payload:R}}let{groups:s,disableGeoip:a}=n,{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=n,p=this.addLocalPersonAndGroupProperties(r,s,l,u);l=p.allPersonProperties,u=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,s,this.personPropertiesForLocalEvaluation(r,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let f,m=!1,g,A,b,I,C,x,S;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let D=this.featureFlagsPoller?.featureFlagsByKey[t];if(D)try{let R=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(D,d,{matchValue:i});if(R){m=!0;let O=R.value;I=D.id,x="Evaluated locally",S=D.has_experiment,f={key:t,enabled:O!==!1,variant:typeof O=="string"?O:void 0,payload:R.payload??void 0,reason:x,reasonCode:D.active===!1?"flag_disabled":void 0}}}catch(R){if(R instanceof _re||R instanceof Gl)this._logger?.info(`${R.name} when computing flag locally: ${t}: ${R.message}`);else throw R}}if(!m&&!c){let D=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,l,u,a,[t]);if(D===void 0)b=Ahe.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=D.minimalFlagCalledEvents===!0,g=D.requestId,A=D.evaluatedAt;let R=[];D.errorsWhileComputingFlags&&R.push(Ahe.ERRORS_WHILE_COMPUTING),D.quotaLimited?.includes("feature_flags")&&R.push(Ahe.QUOTA_LIMITED);let O=D.flags[t];if(O===void 0)R.push(Ahe.FLAG_MISSING);else{I=O.metadata?.id,C=O.metadata?.version,x=O.reason?.description??O.reason?.code,S=O.metadata?.has_experiment;let j;if(O.metadata?.payload!==void 0)try{j=JSON.parse(O.metadata.payload)}catch{j=O.metadata.payload}f={key:t,enabled:O.enabled,variant:O.variant??void 0,payload:j,reason:x,reasonCode:O.reason?.code}}R.length>0&&(b=R.join(","))}}if(o){let D=f===void 0?void 0:f.enabled===!1?!1:f.variant??!0,R={$feature_flag:t,$feature_flag_response:D,$feature_flag_id:I,$feature_flag_version:C,$feature_flag_reason:x,locally_evaluated:m,[`$feature/${t}`]:D,$feature_flag_request_id:g,$feature_flag_evaluated_at:m?Date.now():A};if(S!==void 0&&(R.$feature_flag_has_experiment=S),m&&this.featureFlagsPoller){let O=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();O!==void 0&&(R.$feature_flag_definitions_loaded_at=O)}b&&(R.$feature_flag_error=b),this._captureFlagCalledEventIfNeeded({distinctId:r,key:t,response:D,groups:s,disableGeoip:a,properties:R})}return f!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(f={...f,payload:this._payloadOverrides[t]}),f}async getFeatureFlag(t,r,n){Arn("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(i!==void 0)return i.enabled===!1?!1:i.variant??!0}async getFeatureFlagPayload(t,r,n,i){if(Arn("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request."),this._payloadOverrides!==void 0&&t in this._payloadOverrides)return this._payloadOverrides[t];let o=await this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:!1},n);if(o!==void 0)return o.payload??null}async getFeatureFlagResult(t,r,n){let{distinctId:i,options:o}=this._resolveDistinctId(r,n);return i?this._getFeatureFlagResult(t,i,{...o,sendFeatureFlagEvents:o?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()")}async getRemoteConfigPayload(t){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let r=await this._requestRemoteConfigPayload(t);if(!r)return;let n=await r.json();if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}async isFeatureEnabled(t,r,n){Arn("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});return i===void 0?void 0:i.enabled===!1?!1:!!(i.variant??!0)||!1}async getAllFlags(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);return n?(await this.getAllFlagsAndPayloads(n,i)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);if(!n)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:o,disableGeoip:s,flagKeys:a}=i||{},{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,l,u);l=p.allPersonProperties,u=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),m={},g={},A=!0;if(f&&(m=f.response,g=f.payloads,A=f.fallbackToFlags),A&&!c){let b=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,l,u,s,a);m={...m,...b.flags||{}},g={...g,...b.payloads||{}}}return this._flagOverrides!==void 0&&(m={...m,...this._flagOverrides}),this._payloadOverrides!==void 0&&(g={...g,...this._payloadOverrides}),{featureFlags:m,featureFlagPayloads:g}}async evaluateFlags(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);if(!n)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new zwe({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new zwe({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,flags:{}});let{groups:o,disableGeoip:s}=i||{},a=i?.flagKeys??void 0;if(a?.length===0)return new zwe({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:{}});let{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,l,u);l=p.allPersonProperties,u=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=a?new Set(a):void 0,m={},g,A,b=!1,I=!1,C=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),x=new Set;if(C)for(let[D,R]of Object.entries(C.response)){let O=this.featureFlagsPoller?.featureFlagsByKey[D];m[D]={key:D,enabled:R!==!1,variant:typeof R=="string"?R:void 0,payload:C.payloads[D],id:O?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:O?.has_experiment},x.add(D)}let S=f!==void 0&&Array.from(f).some(D=>this.featureFlagsPoller?.featureFlagsByKey[D]===void 0);if((C?C.fallbackToFlags||S:!0)&&!c){let D=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,l,u,s,a);if(D){this._minimalFlagCalledEvents=D.minimalFlagCalledEvents===!0,g=D.requestId,A=D.evaluatedAt,b=!!D.errorsWhileComputingFlags,I=Array.isArray(D.quotaLimited)&&D.quotaLimited.includes("feature_flags");for(let[R,O]of Object.entries(D.flags)){if(x.has(R))continue;let j;if(O.metadata?.payload!==void 0)try{j=JSON.parse(O.metadata.payload)}catch{j=O.metadata.payload}m[R]={key:R,enabled:O.enabled,variant:O.variant,payload:j,id:O.metadata?.id,version:O.metadata?.version,reason:O.reason?.description??O.reason?.code,locallyEvaluated:!1,hasExperiment:O.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[D,R]of Object.entries(this._flagOverrides)){if(R===void 0){delete m[D];continue}let O=m[D];m[D]={key:D,enabled:R!==!1,variant:typeof R=="string"?R:void 0,payload:O?.payload,id:O?.id,version:O?.version,reason:O?.reason,locallyEvaluated:O?.locallyEvaluated??!1,hasExperiment:O?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[D,R]of Object.entries(this._payloadOverrides)){let O=m[D];O&&(m[D]={...O,payload:R})}if(f!==void 0)for(let D of Object.keys(m))f.has(D)||delete m[D];return new zwe({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:m,requestId:g,evaluatedAt:A,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:b,quotaLimited:I})}_shouldSendMinimalFlagCalledEvent(t,r){return t==="$feature_flag_called"&&this._minimalFlagCalledEvents&&r.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(t){let{distinctId:r,key:n,response:i,groups:o,disableGeoip:s,properties:a}=t,c=o&&Object.keys(o).length>0?`_${JSON.stringify(Object.entries(o).sort(([u],[p])=>u<p?-1:u>p?1:0))}`:"",l=`${n}_${i}${c}`;r in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[r].has(l)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),this.distinctIdHasSentFlagCalls[r]instanceof Set?this.distinctIdHasSentFlagCalls[r].add(l):this.distinctIdHasSentFlagCalls[r]=new Set([l]),this.capture({distinctId:r,event:"$feature_flag_called",properties:a,groups:o,disableGeoip:s}))}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:t=>this._captureFlagCalledEventIfNeeded(t),logWarning:t=>{this.options.featureFlagsLogWarnings!==!1&&console.warn(`[PostHog] ${t}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){this._sendPreparedEvent("capture",{distinctId:i||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{}},disableGeoip:o},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){await this._sendPreparedEvent("capture",{distinctId:i||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{}},disableGeoip:o},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(t){let r=n=>Object.fromEntries(n.map(i=>[i,!0]));if(t===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(t)){this._flagOverrides=r(t);return}if(this._isFeatureFlagOverrideOptions(t)){"flags"in t&&(t.flags===!1?this._flagOverrides=void 0:Array.isArray(t.flags)?this._flagOverrides=r(t.flags):t.flags!==void 0&&(this._flagOverrides={...t.flags})),"payloads"in t&&(t.payloads===!1?this._payloadOverrides=void 0:t.payloads!==void 0&&(this._payloadOverrides={...t.payloads}));return}this._flagOverrides={...t}}_isFeatureFlagOverrideOptions(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let r=t;if("flags"in r){let n=r.flags;if(n===!1||Array.isArray(n)||typeof n=="object"&&n!==null)return!0}if("payloads"in r){let n=r.payloads;if(n===!1||typeof n=="object"&&n!==null)return!0}return!1}withContext(t,r,n){return this.context?this.context.run(t,r,n):r()}getContext(){return this.context?.get()}enterContext(t,r){this.context?.enter(t,r)}async _shutdown(t){let r=Date.now()+(t??3e4),n=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown(),this._metrics&&(await Fwe(this._metrics.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._metrics.reset()),this._traces&&(await Fwe(this._traces.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._traces.reset());try{return await super._shutdown(Math.max(0,r-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},n?.()}}async _requestRemoteConfigPayload(t){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config?token=${encodeURIComponent(this.apiKey)}`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let o=new AbortController;i=$2(()=>{o.abort()},this.options.requestTimeout),n.signal=o.signal}try{return await this.fetch(r,n)}catch(o){this._events.emit("error",o);return}finally{i&&clearTimeout(i)}}extractPropertiesFromEvent(t,r){if(!t)return{personProperties:{},groupProperties:{}};let n={},i={};for(let[o,s]of Object.entries(t))if(Tau(s)&&r&&o in r){let a={};for(let[c,l]of Object.entries(s))a[String(c)]=String(l);i[String(o)]=a}else n[String(o)]=String(s);return{personProperties:n,groupProperties:i}}async getFeatureFlagsForEvent(t,r,n,i){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let o=i?.personProperties||{},s=i?.groupProperties||{},a=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let l={};for(let[u,p]of Object.entries(r||{}))l[u]=String(p);return await this.getAllFlags(t,{groups:l,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let l={};for(let[u,p]of Object.entries(r||{}))l[u]=String(p);return await this.getAllFlags(t,{groups:l,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(t,r,o,s,n)).flags}addLocalPersonAndGroupProperties(t,r,n,i){let o={...n||{}},s={};if(r)for(let a of Object.keys(r))s[a]={$group_key:r[a],...i?.[a]||{}};return{allPersonProperties:o,allGroupProperties:s}}personPropertiesForLocalEvaluation(t,r){return{distinct_id:t,...r||{}}}createFeatureFlagEvaluationContext(t,r,n,i){return{distinctId:t,groups:r||{},personProperties:n||{},groupProperties:i||{},evaluationCache:{}}}captureException(t,r,n,i,o){if(!PVe.isPreviouslyCapturedError(t)){let s=new Error("PostHog syntheticException");this.addPendingPromise(PVe.buildEventMessage(this.getErrorPropertiesBuilder(),t,{syntheticException:s},r,n).then(a=>this._capturePreparedEvent({...a,uuid:i,flags:o},!1)))}}async captureExceptionImmediate(t,r,n,i){if(!PVe.isPreviouslyCapturedError(t)){let o=new Error("PostHog syntheticException");return this.addPendingPromise(PVe.buildEventMessage(this.getErrorPropertiesBuilder(),t,{syntheticException:o},r,n).then(s=>this.captureImmediate({...s,flags:i})))}}async prepareEventMessage(t){return this._prepareEventMessage(t)}async _prepareEventMessage(t,r={}){let{distinctId:n,event:i,properties:o,groups:s,flags:a,sendFeatureFlags:c,timestamp:l,disableGeoip:u,uuid:p}=t,d=this.context?.get(),f=r.includeContextProperties??!0,m=n||d?.distinctId,g=f?{...this.props,...d?.properties||{},...o||{}}:{...o||{}};m||(m=Z2(),g.$process_person_profile=!1),f&&d?.sessionId&&!g.$session_id&&(g.$session_id=d.sessionId);let A=this._shouldSendMinimalFlagCalledEvent(i,g)?hWt(g):g,b=this._runBeforeSend({distinctId:m,event:i,properties:A,groups:s,flags:a,sendFeatureFlags:c,timestamp:l,disableGeoip:u,uuid:p});if(!b)return Promise.reject(null);let I=await Promise.resolve().then(async()=>{if(a)return c&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),a._getEventProperties();if(c){Arn("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead \u2014 it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");let C=typeof c=="object"?c:void 0,x=await this.getFeatureFlagsForEvent(b.distinctId,s,u,C);return gEh(x)}return{}}).catch(()=>({})).then(C=>{let x=b.groups||s;return{...C,...b.properties||{},...x!==void 0&&Object.keys(x).length>0?{$groups:x}:{}}});return b.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof I.$raw_user_agent=="string"&&Pau(I.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(b.event="$bot_pageview",I.$browser_type="bot"),{distinctId:b.distinctId,event:b.event,properties:I,options:{timestamp:b.timestamp,disableGeoip:b.disableGeoip,uuid:b.uuid}}}_runBeforeSend(t){let r=this.options.before_send;if(!r)return t;let n=Array.isArray(r)?r:[r],i=t;for(let o of n)try{if(i=o(i),!i)return this._logger.info(`Event '${t.event}' was rejected in beforeSend function`),null;if(!i.properties||Object.keys(i.properties).length===0){let s=`Event '${i.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(s)}}catch(s){return this._logger.error(`Error in before_send function for event '${t.event}':`,s),null}return i}};var Tlu=require("async_hooks"),brn=class{constructor(){this.storage=new Tlu.AsyncLocalStorage}get(){return this.storage.getStore()}run(t,r,n){return this.storage.run(this.resolve(t,n),r)}enter(t,r){this.storage.enterWith(this.resolve(t,r))}resolve(t,r){if(r?.fresh===!0)return t;let n=this.get()||{};return{distinctId:t.distinctId??n.distinctId,sessionId:t.sessionId??n.sessionId,properties:{...n.properties||{},...t.properties||{}}}}};var Olu=require("async_hooks"),Ern=class{active(){return this._storage.getStore()}with(t,r){return this._storage.run(t,r)}constructor(){this._storage=new Olu.AsyncLocalStorage}};var Plu=require("zlib"),Blu=require("util"),AEh=(0,Blu.promisify)(Plu.gzip);async function Dlu(e,t=!0){try{let r=await AEh(e);return new Uint8Array(r)}catch(r){return t&&console.error("Failed to gzip compress data",r),null}}var Irn=require("os");function Rlu(){let e,t;try{e=(0,Irn.platform)(),t=(0,Irn.release)()}catch{}return rYo(e,t)}var klu="posthog-node";function yEh(e,{organization:t,projectId:r,prefix:n,severityAllowList:i=["error"],sendExceptionsToPostHog:o=!0}={}){return s=>{if(!(i==="*"||i.includes(s.level)))return s;s.tags||(s.tags={});let c=s.tags[vYo.POSTHOG_ID_TAG];if(c===void 0)return s;let l=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${c}`,l).toString();s.tags["PostHog Person URL"]=u;let p=s.exception?.values||[],d=p.map(g=>({...g,stacktrace:g.stacktrace?{...g.stacktrace,type:"raw",frames:(g.stacktrace.frames||[]).map(A=>({...A,platform:"node:javascript"}))}:void 0})),f={$exception_message:p[0]?.value||s.message,$exception_type:p[0]?.type,$exception_level:s.level,$exception_list:d,$sentry_event_id:s.event_id,$sentry_exception:s.exception,$sentry_exception_message:p[0]?.value||s.message,$sentry_exception_type:p[0]?.type,$sentry_tags:s.tags},m=LT.getInjectedReleaseId();return m&&(f.$release_id=m),t&&r&&(f.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+s.event_id),o&&e.capture({event:"$exception",distinctId:c,properties:f}),s}}var vYo=class{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(t,r,n,i,o){this.name=klu,this.name=klu,this.setupOnce=function(s,a){let c=a()?.getClient()?.getDsn()?.projectId;s(yEh(t,{organization:r,projectId:c,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o??!0}))}}};var Ure=class extends yrn{getLibraryId(){return"posthog-node"}compressPayload(t){return Dlu(t,this.isDebug)}initializeContext(){return new brn}initializeSpanContextManager(){return new Ern}hostResourceAttributes(){return Rlu()}createErrorPropertiesBuilder(){return new LT.ErrorPropertiesBuilder([new LT.EventCoercer,new LT.ErrorCoercer,new LT.ObjectCoercer,new LT.StringCoercer,new LT.PrimitiveCoercer],LT.createStackParser("node:javascript",LT.nodeStackLineParser),[vau(),t=>olu(t,void 0,this._logger),llu()])}};function Flu(e){return e==null||!e.enabled?!1:e.variant==null||e.variant==="true"}var vrn=class{isEnabled(){return Promise.resolve(!1)}getCachedValue(){}flush(){return Promise.resolve()}},bEh="feature_flag_evaluated",EEh=3e3,IEh=3e3,Crn=class{evaluator;environment;sendFeatureFlagEvents;pending=new Map;resolved=new Map;constructor({environment:t,sendFeatureFlagEvents:r,posthogApiKey:n,evaluator:i}){this.environment=t,this.sendFeatureFlagEvents=r,this.evaluator=i??new Ure(n??"",{featureFlagsRequestTimeoutMs:EEh,isServer:!1})}isEnabled(t,r){let n=Nlu(t,r),i=this.pending.get(n);if(i!=null)return i;let o=this.evaluateAndRemember(t,r,n);return this.pending.set(n,o),o}async evaluateAndRemember(t,r,n){let i=await this.evaluate(t,r);return this.resolved.set(n,i),i}getCachedValue(t,r){return this.resolved.get(Nlu(t,r))}async flush(){if(!this.sendFeatureFlagEvents)return;let t;try{await Promise.race([this.flushAfterPendingEvaluations(),new Promise(r=>{t=setTimeout(r,IEh),t.unref()})])}catch{}finally{clearTimeout(t)}}async flushAfterPendingEvaluations(){await Promise.allSettled(this.pending.values()),await this.evaluator.flush()}async evaluate(t,r){let{org:n}=r,i=CEh(r,this.environment),o;try{o=await this.evaluator.getFeatureFlagResult(t,CYo(n),{personProperties:i,groups:{organization:n},groupProperties:{organization:i},sendFeatureFlagEvents:!1})}catch{return!1}return this.sendFeatureFlagEvents&&this.captureFlagUsage({flag:t,org:n,result:o,properties:i}),Flu(o)}captureFlagUsage({flag:t,org:r,result:n,properties:i}){let o=vEh(n),s={...i,...n?.reason!=null?{$feature_flag_reason:n.reason}:{},version:"5.226.1"};this.tryCapture({distinctId:CYo(r),event:"$feature_flag_called",groups:{organization:r},properties:{...s,$feature_flag:t,$feature_flag_response:o,[`$feature/${t}`]:o}}),this.tryCapture({distinctId:CYo(r),event:bEh,groups:{organization:r},properties:{...s,flag:t,response:o,enabled:Flu(n)}})}tryCapture(t){try{this.evaluator.capture(t)}catch{}}};function vEh(e){if(e!=null)return e.enabled?e.variant??!0:!1}function CYo(e){return`org:${e}`}function CEh({org:e,generator:t,language:r},n){return{org:e,environment:n,...t!=null?{generator:t}:{},...r!=null?{language:r}:{}}}function Nlu(e,{org:t,generator:r,language:n}){return JSON.stringify([e,t,r??null,n??null])}var xrn;function Srn(){return xrn==null&&(xrn=xEh()),xrn}async function xYo(){await xrn?.flush()}function xEh(){let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";return e==null||e.trim().length===0?new vrn:new Crn({posthogApiKey:e,environment:gJ(),sendFeatureFlagEvents:Ttn()})}var wrn=class{posthog;constructor({posthogApiKey:t}){this.posthog=new Ure(t,{isServer:!1})}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"5.226.1",usingAccessToken:!0,cliReleaseEnvironment:gJ(),...Rfe()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:{...t.properties,cliReleaseEnvironment:gJ()}})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}};var NWt=class{async sendEvent(){}async sendAutomationEvent(){}async identify(){}async flush(){}};sf();tr();var Zut=require("fs/promises"),jlu=require("os"),zlu=require("path");TUe();var SEh="id",wEh=".fern",jWt=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new Ure(r,{isServer:!1}),this.userId=t==null?void 0:JJi(t),this.token=t}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){let r=await this.getUserEmail();this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"5.226.1",...t,...t.properties,usingAccessToken:!1,cliReleaseEnvironment:gJ(),agent:Dpr(),...r!=null?{userEmail:r}:{},...Rfe()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:{...t.properties,cliReleaseEnvironment:gJ()}})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}userEmail;async getUserEmail(){if(this.userEmail!==null){if(this.userEmail!=null)return this.userEmail;if(this.token==null){this.userEmail=null;return}try{let t=await Dl({token:this.token.value}).user.getMyself();if(t.ok&&t.body.email!=null)return this.userEmail=t.body.email,this.userEmail}catch{}this.userEmail=null}}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Dw(),r=Re(Zt.of((0,jlu.homedir)()),be.of(wEh),be.of(SEh));try{await Ut(r)?this.persistedDistinctId=(await(0,Zut.readFile)(r)).toString():(await(0,Zut.mkdir)((0,zlu.dirname)(r),{recursive:!0}),await(0,Zut.writeFile)(r,t),this.persistedDistinctId=t)}catch{this.persistedDistinctId=t}}return this.persistedDistinctId}};var SYo;async function zWt(){return SYo==null&&(SYo=await TEh()),SYo}async function TEh(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";if(e==null||!Ttn())return new NWt;let t=await uZe();return t!=null?new jWt({token:t,posthogApiKey:e}):await jz()!=null?new wrn({posthogApiKey:e}):new jWt({token:void 0,posthogApiKey:e})}catch{return new NWt}}tn();mt();Bt();_Q();var QWt=Ae(require("process"),1);yKe();var Llu=Ae(s$i(),1),_lu=Ae(Mlu(),1);function _T(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=w7(e),e.length===0))return 0;e=e.replace((0,_lu.default)()," ");let r=t.ambiguousIsNarrow?1:2,n=0;for(let i of e){let o=i.codePointAt(0);if(o<=31||o>=127&&o<=159||o>=768&&o<=879)continue;switch(Llu.default.eastAsianWidth(i)){case"F":case"W":n+=2;break;case"A":n+=r;break;default:n+=1}}return n}tn();function Trn(e){let t=0;for(let r of e.split(`
|
|
3498
|
+
at ${r.filename}:${n}:${i}`}};var $Ah=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,uWt=class{match(t){return typeof t=="string"}coerce(t,r){let[n,i]=this.getInfos(t);return{type:n??"Error",value:i??t,stack:r.syntheticException?.stack,synthetic:!0}}getInfos(t){let r="Error",n=t,i=t.match($Ah);return i&&(r=i[1],n=i[2]),[r,n]}};var pcu=["fatal","error","warning","log","info","debug"];function Gtn(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let n=r.length;n>0;n--){let i=r.slice(0,n).join(", ");if(!(i.length>t))return n===r.length||i.length<=t?i:`${i.slice(0,t)}...`}return""}var pWt=class{match(t){return typeof t=="object"&&t!==null}coerce(t,r){let n=this.getErrorPropertyFromObject(t);return n?r.apply(n):{type:this.getType(t),value:this.getValue(t),stack:this.getStack(t)??r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){if(_ut(t))return t.constructor.name;let r="name"in t?t.name:void 0;return wR(r)&&!bJo(r)?r:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){let i=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(i+=` with message: '${t.message}'`),i}if("message"in t&&typeof t.message=="string")return t.message;let r=this.getObjectClassName(t),n=Gtn(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(t){return wR(t)&&!bJo(t)&&pcu.indexOf(t)>=0}getStack(t){try{return wR(t.stacktrace)&&t.stacktrace.length>0?t.stacktrace:wR(t.stack)&&t.stack.length>0?t.stack:void 0}catch{return}}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(kwe(n))return n}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var zJo=class{match(t){return _ut(t)}coerce(t,r){let n=t.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${Gtn(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var fWt=class{match(t){return Ptn(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var QJo=class{match(t){return CVe(t,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(t)}isCustomEventWrappingRejection(t){if(!_ut(t))return!1;try{let r=t.detail;return r!=null&&typeof r=="object"&&"reason"in r}catch{return!1}}coerce(t,r){let n=this.getUnhandledRejectionReason(t);return Ptn(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(n)}getUnhandledRejectionReason(t){try{if("reason"in t)return t.reason;if("detail"in t&&t.detail!=null&&typeof t.detail=="object"&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var MJo=class{constructor(t){this._maxSize=t,this._cache=new Map}get(t){let r=this._cache.get(t);if(r!==void 0)return this._cache.delete(t),this._cache.set(t,r),r}set(t,r){this._cache.set(t,r)}reduce(){for(;this._cache.size>=this._maxSize;){let t=this._cache.keys().next().value;t&&this._cache.delete(t)}}};var dWt={MESSAGE:"$message",TIMESTAMP:"$timestamp"},eyh=new Set([dWt.MESSAGE,dWt.TIMESTAMP]),qtn={enabled:!0,max_bytes:32768};function LJo(e){return e?{enabled:e.enabled??qtn.enabled,max_bytes:ryh(e.max_bytes,qtn.max_bytes)}:{...qtn}}function tyh(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((n,i)=>eyh.has(i)?(t.push(i),n):(n[i]=e[i],n),{}),droppedKeys:t}}var _Jo=class{constructor(t){this._entries=[],this._totalBytes=0,this._config=LJo(t)}setConfig(t){this._config=LJo(t),this._trimToMaxBytes()}add(t){let r=nyh(t);if(!r)return;let n=fcu(r.json);n>this._config.max_bytes||(this._entries.push({step:r.step,bytes:n}),this._totalBytes+=n,this._trimToMaxBytes())}getAttachable(){return this._entries.map(t=>t.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){let t=this._entries.shift();t&&(this._totalBytes-=t.bytes)}}};function ryh(e,t){if(!Lut(e)||e===1/0||e===-1/0)return t;let r=Math.floor(e);return r<0?t:r}function nyh(e){let t;try{t=Rwe(e)}catch{return}try{let r=JSON.parse(t);if(!iWt(r))return;let n=r,i=n[dWt.MESSAGE],o=n[dWt.TIMESTAMP];return!wR(i)||i.trim().length===0||!wR(o)&&!Lut(o)?void 0:{step:n,json:t}}catch{return}}function fcu(e){if("u">typeof TextEncoder)return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),r=0;for(let n=0;n<t.length;n++)t[n]==="%"?(r+=1,n+=2):r+=1;return r}function iyh(){let e=globalThis._posthogReleaseId;return typeof e=="string"&&e.length>0?e:void 0}var UJo=e=>{if("flags"in e){let t=dcu(e.flags),r=mcu(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([i,o])=>[i,qut(o)])),n=Object.fromEntries(Object.entries(t).map(([i,o])=>[i,oyh(i,o,r[i])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:n}}};function oyh(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 dcu=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,mWt(r)]).filter(([,t])=>t!==void 0)),mcu=e=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter(r=>{let n=t[r];return n.enabled&&n.metadata&&n.metadata.payload!==void 0}).map(r=>{let n=t[r].metadata?.payload;return[r,n?qut(n):void 0]}))},mWt=e=>e===void 0?void 0:e.variant??e.enabled,qut=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var hcu=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","irclid","_kx"],syh=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain",...hcu,"$session_id","$window_id","$lib","$lib_version","$device_id","$is_server","$react_native_version"],hWt=(e,t=[])=>{let r={},n=i=>{e[i]!==void 0&&(r[i]=e[i])};return syh.forEach(n),t.forEach(n),r};var Wtn=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(n=>n!==r)}}emit(t,r){for(let n of this.events[t]||[])n(r);for(let n of this.events["*"]||[])n(t,r)}};function VJo(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var cyh="NativeGzipValidationError",lyh=31,uyh=139,pyh=8,fyh=e=>e.length>=2&&e[0]===lyh&&e[1]===uyh;var gWt,dyh=()=>{if(gWt)return gWt;gWt=[];for(let e=0;e<256;e++){let t=e;for(let r=0;r<8;r++)t=1&t?3988292384^t>>>1:t>>>1;gWt[e]=t>>>0}return gWt},myh=e=>{let t=dyh(),r=4294967295;for(let n=0;n<e.length;n++)r=t[(r^e[n])&255]^r>>>8;return(4294967295^r)>>>0},Htn=e=>{throw Gut(cyh,`Native gzip produced invalid output: ${e}`)},hyh=async(e,t)=>{e.size<18&&Htn("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());(!fyh(r)||r[2]!==pyh)&&Htn("invalid-header");let n=new DataView(await e.slice(e.size-8).arrayBuffer());n.getUint32(0,!0)!==myh(t)&&Htn("invalid-crc");let i=t.length>>>0;n.getUint32(4,!0)!==i&&Htn("invalid-size")};async function AWt(e,t=!0,r){try{let n=new TextEncoder().encode(e),i=new globalThis.CompressionStream("gzip"),o=i.writable.getWriter(),s=o.write(n).then(()=>o.close()).catch(async l=>{try{await o.abort(l)}catch{}throw l}),a=new Response(i.readable).blob(),[c]=await Promise.all([a,s]);return await hyh(c,n),c}catch(n){if(r?.rethrow)throw n;return t&&console.error("Failed to gzip compress data",n),null}}var O8=class extends Error{constructor(t,r,n,i){super("HTTP error while fetching PostHog: status="+t.status+", reqByteLength="+r),this.response=t,this.reqByteLength=r,this.responseBodyDeadline=n,this.abortController=i,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return OJo(this.response.headers?.get("retry-after"))}catch{return}}get bodyReadTimedOut(){return this._bodyReadTimedOut}get text(){if(!this.responseBodyTextPromise)if(Date.now()>=this.responseBodyDeadline){this._bodyReadTimedOut=!0;let t=Gut("AbortError","Response body read timed out");this.cancelResponseBody(t),this.responseBodyTextPromise=Promise.reject(t)}else{let t=new Promise((n,i)=>{this.responseBodyTimer=$2(()=>{this._bodyReadTimedOut=!0;let o=Gut("AbortError","Response body read timed out");i(o),this.cancelResponseBody(o)},this.responseBodyDeadline-Date.now())}),r;try{r=Promise.resolve(this.response.text())}catch(n){r=Promise.reject(n)}this.responseBodyTextPromise=Promise.race([r,t]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then(t=>JSON.parse(t))}cancelResponseBody(t){clearTimeout(this.responseBodyTimer),this.abortController.signal.aborted||this.abortController.abort(t),(async()=>{try{await this.response.body?.cancel()}catch{}})()}},ghe=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};var Ecu=(e,t)=>{for(let r of Object.keys(t))(r.startsWith("$feature/")||r==="$active_feature_flags")&&(e[r]=t[r])};async function gcu(e){if(e instanceof O8){let t="";try{t=await e.text}catch{e.bodyReadTimedOut&&(t="<response body read timed out>")}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 gyh(e){return typeof e=="object"&&(e instanceof O8||Icu(e))}function Icu(e){return e instanceof ghe}function Ayh(e){if(e instanceof O8)return e.status===502||e.status===504;if(!(e instanceof ghe))return!1;let t=e.error;return(t?.code??t?.cause?.code)!=="ECONNREFUSED"}var Acu=10485760;function ycu(e){try{return typeof e!="string"?e instanceof Uint8Array?e.byteLength:e.size:"u">typeof Buffer?Buffer.byteLength(e,Kau):new TextEncoder().encode(e).length}catch{return 0}}function Wut(e){return typeof e=="object"&&e instanceof O8&&e.status===413}function Ktn(e){return e instanceof O8?e.status===408||e.status===429||e.status>=500:Icu(e)}function bcu(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var GJo="default",yWt=class{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new cWt([new lWt,new pWt,new uWt,new fWt],FJo())}getEvaluationRuntime(){}constructor(t,r={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new Ftn,this._events=new Wtn,this._isInitialized=!1;let n=typeof t=="string"?t.trim():"",i=typeof r.host=="string"?r.host.trim():"",o=!n;this._logger=kau("[PostHog]",this.logMsgIfDebug.bind(this)),o&&this._logger.error("You must pass your PostHog project's api key. The client will be disabled."),this.apiKey=n,this.host=Jau(i||"https://us.i.posthog.com"),this.flushAt=r.flushAt?Math.max(r.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,r.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,r.maxQueueSize??1e3),this.flushInterval=r.flushInterval??1e4,this.preloadFeatureFlags=r.preloadFeatureFlags??!0,this.defaultOptIn=r.defaultOptIn??!0,this.disableSurveys=r.disableSurveys??!1,this._retryOptions={retryCount:r.fetchRetryCount??3,retryDelay:r.fetchRetryDelay??3e3,retryCheck:Ktn},this.requestTimeout=r.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=r.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=r.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=r.disableGeoip??!0,this.disabled=(r.disabled??!1)||o,this.historicalMigration=r?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=r?.evaluationContexts??r?.evaluationEnvironments,r?.evaluationEnvironments&&!r?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!VJo()||(r?.disableCompression??!1)}logMsgIfDebug(t){this.isDebug&&t()}wrap(t){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return t();this._initPromise.then(()=>t())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(tM.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(tM.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(tM.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(n,i)=>this._logger.info(n,i));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(t){let r=t.properties||{},n={...r,...this.getCommonEventProperties()};return Ecu(n,r),t.event==="$feature_flag_called"&&n.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled()&&(n=hWt(n)),{distinct_id:t.distinct_id,event:t.event,properties:n}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(t){return this.promiseQueue.add(t)}identifyStateless(t,r,n){this.wrap(()=>{let i={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",i,n)})}async identifyStatelessImmediate(t,r,n){let i={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};await this.sendImmediate("identify",i,n)}captureStateless(t,r,n,i){this.wrap(()=>{let o=this.buildPayload({distinct_id:t,event:r,properties:n});this.enqueue("capture",o,i)})}async captureStatelessImmediate(t,r,n,i){let o=this.buildPayload({distinct_id:t,event:r,properties:n});await this.sendImmediate("capture",o,i)}aliasStateless(t,r,n,i){this.wrap(()=>{let o=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:t}});this.enqueue("alias",o,i)})}async aliasStatelessImmediate(t,r,n,i){let o=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:t}});await this.sendImmediate("alias",o,i)}groupIdentifyStateless(t,r,n,i,o,s){this.wrap(()=>{let a=this.buildPayload({distinct_id:o||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{},...s||{}}});this.enqueue("capture",a,i)})}async groupIdentifyStatelessImmediate(t,r,n,i,o,s){let a=this.buildPayload({distinct_id:o||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{},...s||{}}});await this.sendImmediate("capture",a,i)}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`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(r,n,{type:"required",consume:i=>i.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).catch(i=>{this._logger.error("Remote config could not be loaded",i),this._events.emit("error",i)})}async getFlags(t,r={},n={},i={},o={},s=!1){await this._initPromise;let a=s?"&config=true":"",c=`${this.host}/flags/?v=2${a}`,l={token:this.apiKey,distinct_id:t,groups:r,person_properties:n,group_properties:i,...o};n.$device_id&&(l.$device_id=n.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(l.evaluation_contexts=this.evaluationContexts);let u=this.getEvaluationRuntime();u&&(l.evaluation_runtime=u);let p={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(l)};return this._logger.info("Flags URL",c),this.fetchWithRetry(c,p,{type:"required",consume:d=>d.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:Ayh},this.featureFlagsRequestTimeoutMs).then(d=>({success:!0,response:UJo(d)})).catch(d=>(this._events.emit("error",d),{success:!1,error:this.categorizeRequestError(d)}))}categorizeRequestError(t){if(t instanceof O8)return{type:"api_error",statusCode:t.status};if(t instanceof ghe){let r=t.error;return r instanceof Error&&(r.name==="AbortError"||r.name==="TimeoutError")?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(t,r,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagDetailStateless(t,r,n,i,o,s);if(a===void 0)return{response:void 0,requestId:void 0};let c=mWt(a.response);return c===void 0&&(c=!1),{response:c,requestId:a.requestId}}async getFeatureFlagDetailStateless(t,r,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(r,n,i,o,s,[t]);return a===void 0?void 0:{response:a.flags[t],requestId:a.requestId,evaluatedAt:a.evaluatedAt}}async getFeatureFlagPayloadStateless(t,r,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagPayloadsStateless(r,n,i,o,s,[t]);if(!a)return;let c=a[t];return c===void 0?null:c}async getFeatureFlagPayloadsStateless(t,r={},n={},i={},o,s){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,o,s)).payloads}async getFeatureFlagsStateless(t,r={},n={},i={},o,s){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,o,s)}async getFeatureFlagsAndPayloadsStateless(t,r={},n={},i={},o,s){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(t,r,n,i,o,s);return a?{flags:a.featureFlags,payloads:a.featureFlagPayloads,requestId:a.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(t,r={},n={},i={},o,s){await this._initPromise;let a={geoip_disable:o??this.disableGeoip};s&&(a.flag_keys_to_evaluate=s);let c=await this.getFlags(t,r,n,i,a);if(!c.success)return;let l=c.response;return l.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"),l.quotaLimited?.includes("feature_flags")?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:l?.requestId,quotaLimited:l.quotaLimited}):l}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let t=`${this.host}/api/surveys/?token=${this.apiKey}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},i=(await this.fetchWithRetry(t,r,{type:"required",consume:o=>{if(o.status!==200||!o.json){let s=`Surveys API could not be loaded: ${o.status}`,a=new Error(s);return this._logger.error(a),this._events.emit("error",new Error(s)),Promise.resolve(void 0)}return o.json()}}).catch(o=>{this._logger.error("Surveys API could not be loaded",o),this._events.emit("error",o)}))?.surveys;return i&&this._logger.info("Surveys fetched from API: ",JSON.stringify(i)),i??[]}get props(){return this._props||(this._props=this.getPersistedProperty(tM.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(tM.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(tM.Props,this.props)})}processBeforeEnqueue(t){return t}async flushStorage(){}getQueueRouteKey(t){return GJo}persistedQueueKeyForRoute(t){return tM.Queue}getActiveQueueRoutes(){return[GJo]}getRouteQueue(t){return this.getPersistedProperty(this.persistedQueueKeyForRoute(t))||[]}enqueue(t,r,n,i){this.wrap(()=>{if(this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let o=this.prepareMessage(r,n);if(o=this.processBeforeEnqueue(o),o===null)return;o=this.normalizeMessage(o);let s=this.persistedQueueKeyForRoute(i??this.getQueueRouteKey(o)),a=this.getPersistedProperty(s)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),a.push({message:o}),this.setPersistedProperty(s,a),this._events.emit(t,o),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=$2(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,n,i){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let o=this.prepareMessage(r,n);if(o=this.processBeforeEnqueue(o),o!==null){o=this.normalizeMessage(o);try{await this.sendBatch([o],void 0,i??this.getQueueRouteKey(o))}catch(s){this._events.emit("error",s)}}}normalizeMessage(t){let{type:r,library:n,library_version:i,...o}=t,s=bcu(o.properties)?o.properties:void 0;return n!==void 0&&s?.$lib===void 0&&(s={...s||{},$lib:n}),i!==void 0&&s?.$lib_version===void 0&&(s={...s||{},$lib_version:i}),s&&(o.properties=s),o.uuid=SVe(o.uuid,Z2),o}normalizeTimestampForWire(t){let r=t instanceof Date?t:typeof t=="string"?new Date(t):null;if(!r||Number.isNaN(r.getTime()))return t;let n=r.toISOString(),i=typeof t=="string"?t.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return i&&i.length>3?n.replace(/\.\d{3}Z$/,`.${i}Z`):n}prepareMessage(t,r){let n={...t,timestamp:r?.timestamp?r?.timestamp:PJo(),uuid:SVe(r?.uuid,Z2)};return(r?.disableGeoip??this.disableGeoip)&&(bcu(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.pendingFlushPromise||this.flushAutomatic().catch(async t=>{await gcu(t)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(t,r=[]){let n=r.filter(o=>!!o),i=0;for(;;){let o=this.promiseQueue.getPromises([...n,...this.flushPromises],t);if(o.length===0)return;i>0&&this._logger.debug(`flush() re-checking ${o.length} pending promise(s) before flushing`),await Promise.all(o.map(s=>s.catch(()=>{}))),i++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(t){if(this.disabled)return Promise.resolve();if(!t&&this.pendingFlushPromise)return this.pendingFlushPromise;let r=this.flushPromise,n=this.promiseQueue.maxId,i=Promise.resolve().then(()=>{if(t)return this.waitForPendingPromises(n,[r,i])}).then(()=>aWt([r])).then(()=>(this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=i,this.flushPromise=i,this.flushPromises.add(i),this.addPendingPromise(i),aWt([i]).then(()=>{this.flushPromises.delete(i),this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this.flushPromise===i&&(this.flushPromise=null)}),i}getCustomHeaders(){let t=this.getCustomUserAgent(),r={};return t&&t!==""&&(r["User-Agent"]=t),r}compressPayload(t){return AWt(t,this.isDebug)}getBatchEndpointPath(t){return"/batch/"}async sendBatch(t,r,n=GJo){let i={api_key:this.apiKey,batch:t.map(l=>{if(!l)return l;let u=this.normalizeTimestampForWire(l.timestamp);return u===l.timestamp?l:{...l,timestamp:u}}),sent_at:PJo()};this.historicalMigration&&(i.historical_migration=!0);let o=Rwe(i),s=`${this.host}${this.getBatchEndpointPath(n)}`,a=this.disableCompression?null:await this.compressPayload(o),c={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...a!==null&&{"Content-Encoding":"gzip"}},body:a||o};await this.fetchWithRetry(s,c,{type:"successful-write"},r)}async _flush(){this.clearFlushTimer(),await this._initPromise;let t=this.getActiveQueueRoutes();if(!t.some(i=>this.getRouteQueue(i).length>0))return;let r=[],n;for(let i of t)try{await this._flushRoute(i,r)}catch(o){n===void 0&&(n=o)}if(n!==void 0)throw n;this._events.emit("flush",r)}async _flushRoute(t,r){let n=this.persistedQueueKeyForRoute(t),i=this.getPersistedProperty(n)||[];if(!i.length)return;let o=i.length,s=0;for(;i.length>0&&s<o;){let a=i.slice(0,this.maxBatchSize),c=a.map(p=>p.message===void 0?p.message:this.normalizeMessage(p.message)),l=async()=>{let p=this.getPersistedProperty(n)||[],d=[...a],f=p.filter(m=>{let g=m.message?.uuid,A=d.findIndex(b=>b===m||typeof g=="string"&&g.length>0&&b.message?.uuid===g);return A===-1?!0:(d.splice(A,1),!1)});this.setPersistedProperty(n,f),i=f,this._dequeuedMessagesCount+=a.length,await this.flushStorage()},u={retryCheck:p=>Wut(p)?!1:Ktn(p)};try{await this.sendBatch(c,u,t)}catch(p){if(Wut(p)&&c.length>1){this.maxBatchSize=Math.max(1,Math.floor(c.length/2)),this._logger.warn(`Received 413 when sending batch of size ${c.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw p instanceof ghe||await l(),this._events.emit("error",p),p}await l(),r.push(...c),s+=c.length}}async _sendOtlpBatch({path:t,auth:r,payload:n}){if(this.disabled)return{kind:"fatal",error:new Error("The client is disabled")};let i;try{i=JSON.stringify(n)}catch(u){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${t} batch; reporting it as too large`,u)),{kind:"too-large",measuredLocally:!0}}let o=ycu(i);if(o>Acu)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${t} batch of ${o} bytes: the endpoint accepts at most ${Acu}`)),{kind:"too-large",measuredLocally:!0};let s=r==="bearer"?`${this.host}/i/v1/${t}`:`${this.host}/i/v1/${t}?token=${encodeURIComponent(this.apiKey)}`,a=this.disableCompression?null:await this.compressPayload(i),c=a||i,l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...r==="bearer"&&{Authorization:`Bearer ${this.apiKey}`},...a!==null&&{"Content-Encoding":"gzip"}},body:c};try{return await this.fetchWithRetry(s,l,{type:"successful-write"},{retryCheck:u=>Wut(u)||u instanceof O8&&u.retryAfterMs!==void 0?!1:Ktn(u)}),{kind:"ok"}}catch(u){if(Wut(u))return{kind:"too-large"};if(Ktn(u)){let p=u instanceof O8?u.retryAfterMs:void 0;return{kind:"retry-later",error:u,...p!==void 0&&{retryAfterMs:p}}}return{kind:"fatal",error:u}}}async _sendLogsBatch(t){return this._sendOtlpBatch({path:"logs",auth:"query-token",payload:t})}async _sendMetricsBatch(t){return this._sendOtlpBatch({path:"metrics",auth:"query-token",payload:t})}async _sendTracesBatch(t){return this._sendOtlpBatch({path:"traces",auth:"bearer",payload:t})}async fetchWithRetry(t,r,n,i,o){let s=r.body?r.body:"",a=ycu(s),c={...this._retryOptions,...i},l=0;return await Yau(async()=>{l++;let u=new AbortController,p=o??this.requestTimeout,d=Date.now()+p,f,m=new Promise((C,x)=>{f=$2(()=>{let S=Gut("AbortError",`Request timed out after ${p}ms`);x(S),u.abort(S)},p)}),g,A=!1,b,I=()=>b??=(async()=>{try{await g?.body?.cancel()}catch{}})();try{let C;try{C=this.fetch(t,{signal:u.signal,...r})}catch(P){throw new ghe(P)}C.then(P=>{u.signal.aborted&&!A&&Promise.resolve(P.body?.cancel()).catch(()=>{})}).catch(()=>{});try{g=await Promise.race([C,m]),A=!0}catch(P){throw new ghe(P)}let x=r.mode==="no-cors",S=n.type==="successful-write"?300:400;if(!x&&(g.status<200||g.status>=S))throw new O8(g,a,d,u);if(n.type==="successful-write"){try{await Promise.race([I(),m])}catch{}return}try{return await Promise.race([n.consume(g),m])}catch(P){throw u.signal.aborted?new ghe(P):P}}finally{clearTimeout(f),u.signal.aborted&&g&&I()}},{...c,retryCheck:u=>{let p=c.retryCheck(u);return p&&l<=c.retryCount&&u instanceof O8&&u.cancelResponseBody(),p}})}async _shutdown(t=3e4){await this._initPromise;let r=!1;return this.clearFlushTimer(),this.disabled?void 0:Fwe((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(s=>this.getRouteQueue(s).length>0);){let o=this._dequeuedMessagesCount;if(await this.flush(),r)break;if(this._dequeuedMessagesCount===o){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(i){if(!gyh(i))throw i;await gcu(i)}})(),t,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:t}),r=!0})}async shutdown(t=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(t).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}};var vyh=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi;var UfC=new RegExp(vyh.source,"i"),vcu=/[a-z][a-z0-9+.-]{0,63}:\/\//i,VfC=new RegExp(`^${vcu.source}`,"i"),GfC=new RegExp(vcu.source,"gi");var Cyh=["is_not","is_set"],xyh=1152921504606847e3,Gl=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,e.prototype)}};function qJo(e){if(typeof e=="boolean")return!0;if(typeof e=="string"){let t=e.toLowerCase();return t==="true"||t==="false"}if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!qJo(t in e?e[t]:null))return!1;return!0}function WJo(e){if(typeof e=="boolean")return e;if(typeof e=="string")return e.toLowerCase()==="true";if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!WJo(t in e?e[t]:null))return!1;return!0}function bWt(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(t+1>=e.length||n<56320||n>57343)throw new Gl("Cannot stringify an unpaired surrogate like the flags service");t++}else if(r>=56320&&r<=57343)throw new Gl("Cannot stringify an unpaired surrogate like the flags service")}}function Ytn(e,t=new Set){if(!(e===null||typeof e=="boolean")){if(typeof e=="string")return void bWt(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new Gl(`Cannot represent non-finite number ${e} like the flags service`);return}if(Array.isArray(e)){if(t.has(e))throw new Gl("Cannot represent a circular array during local evaluation");t.add(e);try{for(let r=0;r<e.length;r++)r in e&&Ytn(e[r],t)}finally{t.delete(e)}return}if(typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Gl("Cannot represent a non-JSON object like the flags service");if(t.has(e))throw new Gl("Cannot represent a circular object during local evaluation");t.add(e);try{for(let n of Object.keys(e))bWt(n),Ytn(e[n],t)}finally{t.delete(e)}return}throw new Gl(`Cannot represent ${typeof e} like the flags service`)}}function Syh(e,t){let r=0,n=0;for(;r<e.length&&n<t.length;){let i=e.charCodeAt(r),o=t.charCodeAt(n),s=i>=55296&&i<=56319,a=o>=55296&&o<=56319,c=s?e.charCodeAt(r+1):0,l=a?t.charCodeAt(n+1):0,u=s?(i-55296)*1024+c-56320+65536:i,p=a?(o-55296)*1024+l-56320+65536:o;if(u!==p)return u-p;r+=s?2:1,n+=a?2:1}return e.length-t.length}function HJo(e,t=new Set){if(e===null)return"null";if(typeof e=="string")return bWt(e),JSON.stringify(e);if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"){if(!Number.isFinite(e))throw new Gl(`Cannot stringify non-finite number ${e} like the flags service`);if(Number.isInteger(e))throw new Gl(`Cannot distinguish integer ${e} from an integral JSON float during local evaluation`);return String(e)}if(Array.isArray(e)){if(t.has(e))throw new Gl("Cannot stringify a circular array during local evaluation");t.add(e);try{let r=[];for(let n=0;n<e.length;n++)r.push(n in e?HJo(e[n],t):"null");return`[${r.join(",")}]`}finally{t.delete(e)}}if(typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Gl("Cannot stringify a non-JSON object like the flags service");if(t.has(e))throw new Gl("Cannot stringify a circular object during local evaluation");t.add(e);try{let n=Object.keys(e);return n.forEach(bWt),`{${n.sort(Syh).map(i=>`${JSON.stringify(i)}:${HJo(e[i],t)}`).join(",")}}`}finally{t.delete(e)}}throw new Gl(`Cannot stringify ${typeof e} like the flags service`)}function Jtn(e){return typeof e=="string"?(bWt(e),e):HJo(e)}function Ccu(e){try{return new RegExp(e),!0}catch{return!1}}function P8(e){return String(e).replace(/[A-Z]/g,t=>t.toLowerCase())}function Scu(e,t,r){if(!/^\d+$/.test(e)||r==="strict"&&e.length>1&&e[0]==="0")throw new Gl(`Invalid semver: ${t}`);return parseInt(e,10)}function Fw(e,t="strict"){let n=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!n||n.startsWith("."))throw new Gl(`Invalid semver: ${e}`);let i=n.split("."),o=s=>s===void 0||s===""?0:Scu(s,e,t);return[o(i[0]),o(i[1]),o(i[2])]}function B8(e,t){for(let r=0;r<3;r++){if(e[r]<t[r])return-1;if(e[r]>t[r])return 1}return 0}function wyh(e,t){let r=Fw(e,t);return{lower:[r[0],r[1],r[2]],upper:[r[0],r[1]+1,0]}}function Tyh(e,t){let[r,n,i]=Fw(e,t),o=[r,n,i],s;return s=r>0?[r+1,0,0]:n>0?[0,n+1,0]:[0,0,i+1],{lower:o,upper:s}}function Oyh(e,t){let n=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!n)throw new Gl(`Invalid wildcard semver: ${e}`);let i=n.split("."),o=c=>{if(t==="legacy-permissive"){let l=parseInt(c,10);if(!isNaN(l))return l}else try{return Scu(c,e,t)}catch{}throw new Gl(`Invalid wildcard semver: ${e}`)},s=o(i[0]);if(i.length===1)return{lower:[s,0,0],upper:[s+1,0,0]};let a=o(i[1]);return{lower:[s,a,0],upper:[s,a+1,0]}}function xcu(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 Gl(`${e} is in an invalid date format`)}throw new Gl(`The date provided ${e} must be a string, number, or date object`)}function KJo(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),n=new Date(new Date().toISOString());if(!r||!r.groups)return null;let i=parseInt(r.groups.number);if(i>=1e4)return null;let o=r.groups.interval;if(o==="h")n.setUTCHours(n.getUTCHours()-i);else if(o==="d")n.setUTCDate(n.getUTCDate()-i);else if(o==="w")n.setUTCDate(n.getUTCDate()-7*i);else if(o==="m")n.setUTCMonth(n.getUTCMonth()-i);else{if(o!=="y")return null;n.setUTCFullYear(n.getUTCFullYear()-i)}return n}function JJo(e,t,r={}){let n=e.key,i=e.value,o=e.operator||"exact",s=r.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(t,n)){if(o==="is_not_set")return!1;if(o==="is_set")return!0}else throw new Gl(`Property ${n} not found in propertyValues`);let c=t[n];if(c===void 0)return r.warnFunction?.(`Property ${n} cannot have a value of undefined with the ${o} operator`),o==="is_not";if(c===null&&!Cyh.includes(o)&&o!=="exact"&&o!=="is_not")return r.warnFunction?.(`Property ${n} cannot have a value of null with the ${o} operator`),!1;let l=(p,d)=>{if(r.propertyMatchingVersion!==2&&qJo(p)||Array.isArray(p)&&p.length===0)return Ytn(d),WJo(p)===WJo(d);if(r.propertyMatchingVersion===2&&typeof d=="number"&&qJo(p))return Ytn(d),!1;if(Array.isArray(p)){let f=Jtn(d).toLowerCase();return p.some(m=>Jtn(m).toLowerCase()===f)}return Jtn(p).toLowerCase()===Jtn(d).toLowerCase()},u=(p,d,f)=>{if(f==="gt")return p>d;if(f==="gte")return p>=d;if(f==="lt")return p<d;if(f==="lte")return p<=d;throw new Error(`Invalid operator: ${f}`)};switch(o){case"exact":return l(i,c);case"is_not":return!l(i,c);case"is_set":return!0;case"icontains":return P8(c).includes(P8(i));case"not_icontains":return!P8(c).includes(P8(i));case"starts_with":return P8(c).startsWith(P8(i));case"not_starts_with":return!P8(c).startsWith(P8(i));case"ends_with":return P8(c).endsWith(P8(i));case"not_ends_with":return!P8(c).endsWith(P8(i));case"regex":return Ccu(String(i))&&String(c).match(String(i))!==null;case"not_regex":return Ccu(String(i))&&String(c).match(String(i))===null;case"gt":case"gte":case"lt":case"lte":{let p=typeof i=="number"?i:parseFloat(String(i)),d=typeof c=="number"?c:c!=null?parseFloat(String(c)):NaN;return Number.isFinite(p)&&Number.isFinite(d)?u(d,p,o):u(String(c),String(i),o)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new Gl("Date operations cannot be performed on boolean values");let p=KJo(String(i));p==null&&(p=xcu(i));let d=xcu(c);return o==="is_date_before"?d<p:d>p}case"semver_eq":return B8(Fw(String(c),s),Fw(String(i),s))===0;case"semver_neq":return B8(Fw(String(c),s),Fw(String(i),s))!==0;case"semver_gt":return B8(Fw(String(c),s),Fw(String(i),s))>0;case"semver_gte":return B8(Fw(String(c),s),Fw(String(i),s))>=0;case"semver_lt":return B8(Fw(String(c),s),Fw(String(i),s))<0;case"semver_lte":return B8(Fw(String(c),s),Fw(String(i),s))<=0;case"semver_tilde":{let p=Fw(String(c),s),{lower:d,upper:f}=wyh(String(i),s);return B8(p,d)>=0&&B8(p,f)<0}case"semver_caret":{let p=Fw(String(c),s),{lower:d,upper:f}=Tyh(String(i),s);return B8(p,d)>=0&&B8(p,f)<0}case"semver_wildcard":{let p=Fw(String(c),s),{lower:d,upper:f}=Oyh(String(i),s);return B8(p,d)>=0&&B8(p,f)<0}default:throw new Gl(`Unknown operator: ${o}`)}}async function wcu(e){let t=globalThis.crypto?.subtle;if(!t)throw new Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}async function EWt(e,t,r="",n="."){let i=await wcu(`${e}${n}${t}${r}`);return parseInt(i.slice(0,15),16)/xyh}async function YJo(e,t){if(e==null||e.id==null||e.exclusion_percentage==null)return;let r=Number(e.exclusion_percentage);if(!Number.isFinite(r))return;let n=Math.min(Math.max(r,0),100);if(!(n!==100&&await EWt("holdout",t,"","-")>n/100))return`holdout-${e.id}`}function Xtn(e){let t=[],r=0;for(let n of e){let i=r+n.rollout_percentage/100;t.push({valueMin:r,valueMax:i,key:n.key}),r=i}return t}async function XJo(e,t,r){let n=await EWt(e,t,"variant");return Xtn(r).find(i=>n>=i.valueMin&&n<i.valueMax)?.key}function ZJo(e,t){if(t===!1||t==null||!e)return null;let r=typeof t=="boolean"?t.toString():t,n=e[r]||null;return n==null?null:qut(n)}var Tcu=9223372036854776e3,Pyh="9223372036854775808",Byh=Object.prototype.propertyIsEnumerable;function Dyh(){return{ancestors:new WeakSet,remainingNodes:1e4}}function Lre(e,t){try{return Ocu(e,t,Dyh(),0)}catch{return[]}}function Ryh(e,t){let r=e.toString(),n=BigInt(Pyh);return e>=n||e<-n?(t?.debug(`Attribute ${r} is outside the int64 range; encoding it as a string`),{stringValue:r}):{intValue:r}}function tYo(e,t,r,n){if(r.remainingNodes<=0)return{stringValue:Ltn};if(r.remainingNodes--,Sau(e))return{boolValue:e};if(typeof e=="bigint")return Ryh(e,t);if(typeof e=="number"){if(!Number.isFinite(e))return{stringValue:String(e)};if(Number.isInteger(e)){if(Number.isSafeInteger(e))return{intValue:String(e)};if("u"<typeof BigInt)return{stringValue:String(e)};let i=BigInt(e).toString();return e>=Tcu||e<-Tcu?(t?.debug(`Attribute ${i} is outside the int64 range; encoding it as a string`),{stringValue:i}):{intValue:i}}return{doubleValue:e}}if(typeof e=="string")return{stringValue:Qre(e)};if(typeof e=="function")return{stringValue:Hau};if(typeof e=="symbol")return{stringValue:String(e)};if(typeof e=="object"&&e!==null){if(r.ancestors.has(e))return{stringValue:Mtn};if(n>=20)return{stringValue:Ltn};if(e instanceof Date){let i=e.getTime(),o=Number.isFinite(i)?e.toISOString():String(e);return{stringValue:typeof o=="string"?Qre(o):String(o)}}r.ancestors.add(e);try{try{let i=e.toJSON;if(typeof i=="function")return tYo(i.call(e),t,r,n+1)}catch{}return x3(e)?{arrayValue:{values:kyh(e,t,r,n+1)}}:{kvlistValue:{values:Ocu(e,t,r,n+1)}}}finally{r.ancestors.delete(e)}}return{stringValue:Qre(String(e))}}function kyh(e,t,r,n){let i=[],o=Math.min(e.length,1e3),s=0;for(;s<o&&r.remainingNodes>0;s++)try{let a=s in e?e[s]:void 0;if(AJ(a))continue;i.push(tYo(a,t,r,n))}catch{i.push({stringValue:T8})}return e.length>s&&i.push({stringValue:Ltn}),i}function Ocu(e,t,r,n){let i=[];for(let o in e)if(Byh.call(e,o)){if(!o){t?.debug("Dropping an attribute with an empty key");continue}if(i.length>=1e3||r.remainingNodes<=0){t?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let s=e[o];if(EJo(s)||mhe(s))continue;i.push({key:Qre(o),value:tYo(s,t,r,n)})}catch{i.push({key:Qre(o),value:{stringValue:T8}})}}return i}function vWt(e,t,r){return{...hhe({},e.resourceAttributes),"service.name":e.serviceName||"unknown_service",...e.environment&&{"deployment.environment":e.environment},...e.serviceVersion&&{"service.version":e.serviceVersion},"telemetry.sdk.name":t,"telemetry.sdk.version":r}}var Fyh=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function CWt(e,t){let r=hhe({},e),n={};for(let i of Fyh)Object.prototype.hasOwnProperty.call(r,i)&&(n[i]=r[i],delete r[i]);return[...Lre(r,t),...Lre(n,t)]}var Pcu={darwin:"macOS",win32:"Windows",cygwin:"Windows",linux:"Linux",android:"Android",freebsd:"FreeBSD",openbsd:"OpenBSD",netbsd:"NetBSD",sunos:"SunOS",aix:"AIX",haiku:"Haiku","Mac OS X":"macOS"};function Nyh(e){if(e)return Object.prototype.hasOwnProperty.call(Pcu,e)?Pcu[e]:e}function rYo(e,t){let r=Nyh(e);return{...r?{"os.name":r}:{},...t?{"os.version":t}:{}}}var jyh={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},sdC=jyh.info;var wVe=class{constructor(t){this._onFire=t,this._firesAt=0}get pending(){return!!this._timer}arm(t){this.clear(),this._firesAt=Date.now()+t,this._timer=$2(()=>{this._timer=void 0,this._onFire()},t)}armNoEarlierThan(t){this._timer&&Date.now()+t<=this._firesAt||this.arm(t)}clear(){this._timer&&(clearTimeout(this._timer),this._timer=void 0)}};function xWt(){return 1-.25+Math.random()*.25*2}var D8=1;function SWt(e,t,r,n){let i=Math.min(Math.max(0,t-1),6),o=e*2**i,s=n===void 0?o:Math.min(o,Math.max(n,e));return Math.round(s*r)}var wWt=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function nYo(e){return String(e)+"000000"}function iYo(e,t,r,n){let i="";return n&&(i=Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${JSON.stringify(n[s])}`).join(",")),`${e}\0${t}\0${r??""}\0${i}`}function Bcu(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}function oYo(e,t,r){return vWt(e,t,r)}function sYo(e,t,r,n){return{resourceMetrics:[{resource:{attributes:CWt(t)},scopeMetrics:[{scope:{name:r,version:n},metrics:e}]}]}}function $tn(e){let t=e?.resourceAttributes;return{serviceName:t?.["service.name"]??e?.serviceName,serviceVersion:t?.["service.version"]??e?.serviceVersion,environment:t?.["deployment.environment"]??e?.environment,resourceAttributes:t,beforeSend:e?.beforeSend,flushIntervalMs:e?.flushIntervalMs??1e4,maxSeriesPerFlush:e?.maxSeriesPerFlush??1e3}}var Dcu=1,TWt=class{constructor(t,r,n){this._instance=t,this._config=r,this._logger=n,this._series=new Map,this._flushTimer=new wVe(()=>this.flush().catch(i=>{this._logger.error("Metrics flush failed:",i)})),this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._retryAfter=new xVe,this._consecutiveFlushFailures=0,this._flushJitter=D8,this._generation=0}count(t,r=1,n){this._capture({name:t,type:"count",value:r,unit:n?.unit,attributes:n?.attributes})}gauge(t,r,n){this._capture({name:t,type:"gauge",value:r,unit:n?.unit,attributes:n?.attributes})}histogram(t,r,n){this._capture({name:t,type:"histogram",value:r,unit:n?.unit,attributes:n?.attributes})}flush(){let t=this._flushPromise,n=(async()=>{t&&await t.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===n&&(this._flushPromise=null)});return this._flushPromise=n,n}drainWindow(){if(this._series.size===0)return null;let t=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(t)}reset(){this._generation++,this._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=D8,this._flushTimer.clear(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(t){if(this._instance.isDisabled||this._instance.optedOut)return;let r=this._runBeforeSend(t);if(r===null)return;if(!r.name||typeof r.name!="string")return void this._logger.warn("Dropping metric with empty name");if(typeof r.value!="number"||!Number.isFinite(r.value))return void this._logger.warn(`Dropping metric '${r.name}': value must be a finite number`);if(r.type==="count"&&r.value<0)return void this._logger.warn(`Dropping count '${r.name}': counters are monotonic, value must be >= 0`);let n,i;try{n=r.attributes?{...r.attributes}:void 0,i=iYo(r.type,r.name,r.unit,n)}catch(a){this._logger.warn(`Dropping metric '${r.name}': attributes could not be serialized`,a);return}let o=this._series.get(i);if(!o){if(!this._admitNewSeries())return;o={name:r.name,type:r.type,unit:r.unit,attributes:n,windowStartMs:Date.now()},this._series.set(i,o)}let s=this._typeByName.get(r.name);s===void 0?this._typeByName.set(r.name,r.type):s!==r.type&&!this._typeCollisionWarned.has(r.name)&&(this._typeCollisionWarned.add(r.name),this._logger.warn(`Metric name '${r.name}' is already used as a ${s}; recording it as a ${r.type} too will blend both series in charts. Use a distinct name.`)),this._fold(o,r.value),this._armFlushTimer()}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush?!0:(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}_fold(t,r){switch(t.type){case"count":t.total=(t.total??0)+r;break;case"gauge":t.last=r;break;case"histogram":{t.hist||(t.hist={count:0,sum:0,min:r,max:r,bucketCounts:new Array(wWt.length+1).fill(0)});let n=t.hist;n.count+=1,n.sum+=r,n.min=Math.min(n.min,r),n.max=Math.max(n.max,r),n.bucketCounts[Bcu(r,wWt)]+=1;break}}}_runBeforeSend(t){let r=this._config.beforeSend;if(!r)return t;let n=x3(r)?r:[r],i=t;for(let o of n)try{let s=o(i);if(!s)return this._logger.info("Metric was rejected in beforeSend function"),null;i=s}catch(s){return this._logger.error("Error in beforeSend function for metric:",s),null}return i}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(SWt(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}async _doFlush(){if(this._flushTimer.clear(),this._series.size===0)return;let t=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let r=this._generation,n=await this._instance._sendMetricsBatch(this._buildPayload(t));if(r===this._generation)switch(this._retryAfter.record(n),n.kind==="retry-later"?(this._consecutiveFlushFailures++,this._flushJitter=xWt()):(this._consecutiveFlushFailures=0,this._flushJitter=D8),this._flushTimer.pending&&this._flushTimer.arm(this._nextFlushDelay()),n.kind){case"ok":return;case"retry-later":this._mergeWindowBack(t),this._flushTimer.armNoEarlierThan(this._nextFlushDelay());return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",n.error);return}}_buildPayload(t){return sYo(this._buildMetrics(t),oYo(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(t){let r=nYo(Date.now()),n=new Map;for(let i of t.values()){let o=iYo(i.type,i.name,i.unit,void 0),s=n.get(o);s||(s={name:i.name,...i.unit&&{unit:i.unit}},i.type==="count"?s.sum={aggregationTemporality:Dcu,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?s.gauge={dataPoints:[]}:s.histogram={aggregationTemporality:Dcu,dataPoints:[]},n.set(o,s));let a=Lre(i.attributes??{},this._logger),c=nYo(i.windowStartMs);if(i.type==="count"){let l={attributes:a,startTimeUnixNano:c,timeUnixNano:r,asDouble:i.total??0};s.sum.dataPoints.push(l)}else if(i.type==="gauge"){let l={attributes:a,timeUnixNano:r,asDouble:i.last??0};s.gauge.dataPoints.push(l)}else if(i.hist){let l={attributes:a,startTimeUnixNano:c,timeUnixNano:r,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:wWt};s.histogram.dataPoints.push(l)}}return Array.from(n.values())}_mergeWindowBack(t){for(let[r,n]of t){let i=this._series.get(r);if(!i){this._admitNewSeries()&&this._series.set(r,n);continue}switch(i.windowStartMs=Math.min(i.windowStartMs,n.windowStartMs),i.type){case"count":i.total=(i.total??0)+(n.total??0);break;case"gauge":break;case"histogram":if(n.hist)if(i.hist){i.hist.count+=n.hist.count,i.hist.sum+=n.hist.sum,i.hist.min=Math.min(i.hist.min,n.hist.min),i.hist.max=Math.max(i.hist.max,n.hist.max);for(let o=0;o<i.hist.bucketCounts.length;o++)i.hist.bucketCounts[o]+=n.hist.bucketCounts[o]}else i.hist=n.hist;break}}}};var Lyh="0".repeat(32),_yh="0".repeat(16),Uyh=/^[0-9a-f]+$/;function Vyh(e){let t=new Uint8Array(e),r=globalThis.crypto;if(r&&typeof r.getRandomValues=="function")try{return r.getRandomValues(t),t}catch{}for(let n=0;n<e;n++)t[n]=Math.floor(256*Math.random());return t}function Gyh(e){let t="";for(let r=0;r<e.length;r++)t+=e[r].toString(16).padStart(2,"0");return t}function Rcu(e){let t=Gyh(Vyh(e));return/[^0]/.test(t)?t:t.slice(0,-1)+"1"}function kcu(){return Rcu(16)}function Fcu(){return Rcu(8)}function Ncu(e,t,r){return typeof e=="string"&&e.length===t&&e!==r&&Uyh.test(e)}function jcu(e){return Ncu(e,32,Lyh)}function zcu(e){return Ncu(e,16,_yh)}var qyh=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function Qcu(e){let t=Mcu(e);return t&&{traceId:t.traceId,spanId:t.spanId,flags:Wyh(t.flags)}}function Wyh(e){return 1&parseInt(e,16)?trn:Hyh}function Mcu(e){if(typeof e!="string")return;let t=qyh.exec(e.trim());if(!t)return;let[,r,n,i,o,s]=t;if(r!=="ff"&&!(r==="00"&&s)&&!(!jcu(n)||!zcu(i)))return{version:r,traceId:n,spanId:i,flags:o}}function Lcu(e){return Mcu(e)&&e.trim()}function ern(e){return Array.isArray(e)&&e.length===1?e[0]:e}var trn="01",Hyh="00";function _cu(e,t,r=trn){return`00-${e}-${t}-${r}`}var Kyh=32,aYo=512;function rrn(e){if(typeof e!="string")return;let t=e.trim();if(!t||/[^\x20-\x7e\t]/.test(t))return;let r=t.split(",");if(!(r.length>Kyh)){for(let n of r)if(n.trim()&&!n.includes("="))return;return t.length<=aYo?t:Yyh(r)}}var Jyh=128;function Yyh(e){let t=[...e],r=()=>t.reduce((n,i)=>n+i.length,0)+t.length-1;for(let n=t.length-1;n>=0&&r()>aYo;n--)t[n].length>Jyh&&t.splice(n,1);for(;t.length&&r()>aYo;)t.pop();return t.length?t.join(","):void 0}var Ucu="unknown";function TVe(e,t,r,n){return typeof e=="string"&&e.trim()?e.length>r?e.slice(0,r):e:(n?.debug(`${t} must be a non-empty string; using "${Ucu}"`),Ucu)}function Hut(e){if(e==null)return;let t=e;if(e instanceof Date)try{t=e.getTime()}catch{return}if(!(typeof t!="number"||!Number.isFinite(t))&&!(t<0||t>9223372036854))return t}function Vcu(e,t,r){let n=Hut(e);return n===void 0?(e!==void 0&&r?.debug("Span startTime is out of range or not a valid time; using the current time"),t):(t-n>864e5?r?.debug("Span startTime is more than 24 hours in the past; the server will clamp it to receive time and keep the original in $originalTimestamp"):n>t&&r?.debug("Span startTime is in the future; the span may export with a zero duration"),n)}function nrn(e,t){return e<t?t:e}function OWt(e,t,r,n){let i=Hut(e);return i===void 0?(e!==void 0&&n?.debug(`Span ${r} is out of range or not a valid time; using the derived time`),t):i}function orn(){let e=globalThis.performance;return typeof e?.now=="function"?e.now():void 0}var Kut=class{constructor(t,r,n){this._onEnd=r,this._logger=n,this._events=[],this._ended=!1,this._userAttributeCount=0,this._userEventCount=0,this._droppedAttributes=0,this._droppedEvents=0,this._traceId=t.traceId,this._spanId=t.spanId,this._parentSpanId=t.parentSpanId,this._traceState=t.traceState,this._traceFlags=t.traceFlags??trn,this._parentIsRemote=t.parentIsRemote??!1,this._name=t.name,this._kind=t.kind,this._autoKeys=new Set(t.autoAttributeKeys),this._maxAttributes=t.maxAttributes,this._maxEvents=t.maxEvents,this._maxAttributesPerEvent=t.maxAttributesPerEvent,this._maxAttributeValueLength=t.maxAttributeValueLength,this._attributes=Object.create(null);for(let i of Object.keys(t.attributes))this._writeAttribute(i,t.attributes[i]);this._startMono=t.backdated?void 0:orn(),this._startTime=t.clockAnchor&&this._startMono!==void 0?t.clockAnchor.wall+(this._startMono-t.clockAnchor.mono):t.startTime,this._startMono!==void 0&&(this._clockAnchor=t.clockAnchor??{wall:this._startTime,mono:this._startMono})}_now(){if(this._startMono!==void 0){let t=orn();if(t!==void 0)return this._startTime+Math.max(0,t-this._startMono)}return Date.now()}_mutable(t){return this._ended?(this._logger?.debug(`Ignoring ${t} on a span that has already ended`),!1):!0}_writeAttribute(t,r){if(AJ(r)){t in this._attributes&&!this._autoKeys.has(t)&&this._userAttributeCount--,delete this._attributes[t];return}if(!this._autoKeys.has(t)&&!(t in this._attributes)){if(this._userAttributeCount>=this._maxAttributes)return void this._droppedAttributes++;this._userAttributeCount++}this._attributes[t]=arn(r,this._maxAttributeValueLength)}setAttribute(t,r){return this._mutable("setAttribute")&&this._writeAttribute(t,r),this}setAttributes(t){if(this._mutable("setAttributes")){let r=hhe({},t);for(let n of Object.keys(r))this._writeAttribute(n,r[n])}return this}addEvent(t,r,n){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let i=r&&Hcu(r,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:TVe(t,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:OWt(n,this._now(),"event timestamp",this._logger),...i&&{attributes:i.attributes,...i.dropped&&{droppedAttributesCount:i.dropped}}})}return this}setStatus(t,r){if(this._mutable("setStatus")){if(t!=="ok"&&t!=="error")return this._logger?.debug(`Ignoring unknown span status "${String(t)}"; expected "ok" or "error"`),this;this._status={code:t,...r&&{message:cYo(r,this._maxAttributeValueLength)}}}return this}get statusIsExplicitlyOk(){return this._status?.code==="ok"}recordException(t){if(!this._mutable("recordException"))return this;let{type:r,message:n,stack:i}=lYo(t);return this.addEvent(Xyh,{"exception.type":r,"exception.message":n,...i&&{"exception.stacktrace":i}}),this.setStatus("error",n)}updateName(t){return this._mutable("updateName")&&(this._name=TVe(t,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return _cu(this._traceId,this._spanId,this._traceFlags)}tracestate(){return this._traceState??null}childContext(){return{traceId:this._traceId,parentSpanId:this._spanId,traceState:this._traceState,traceFlags:this._traceFlags,clockAnchor:this._clockAnchor}}end(t){if(this._ended)return void this._logger?.debug("Ignoring end() on a span that has already ended");this._ended=!0;let r=this._now(),n=OWt(t,r,"end time",this._logger);this._onEnd({traceId:this._traceId,spanId:this._spanId,...this._parentSpanId&&{parentSpanId:this._parentSpanId},...this._traceState&&{traceState:this._traceState},traceFlags:this._traceFlags,parentIsRemote:this._parentIsRemote,name:this._name,kind:this._kind,...this._status&&{status:this._status},attributes:{...this._attributes},events:this._events,startTime:this._startTime,endTime:nrn(n,this._startTime),...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}},Xyh="exception",Zyh=4294967295;function $yh(e){try{return typeof e=="string"?e:String(e)}catch{return T8}}function OVe(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?0:Math.min(Math.floor(e),Zyh)}function ebh(e,t){if(!t.length)return Object.keys(e);let r=t.filter(i=>Object.prototype.propertyIsEnumerable.call(e,i)),n=new Set(r);return[...r,...Object.keys(e).filter(i=>!n.has(i))]}function qcu(e,t,r,n,i,o,s=[]){let a=0,c=0,l={};for(let f of ebh(e.attributes,s)){let m=e.attributes[f];if(!AJ(m)){if(!t.has(f)){if(a>=r){c++;continue}a++}Object.defineProperty(l,f,{value:arn(m,o),enumerable:!0,writable:!0,configurable:!0})}}e.attributes=l,c&&(e.droppedAttributesCount=OVe(e.droppedAttributesCount)+c);let u=0,p=0,d=[];for(let f of e.events){if(u>=n){p++;continue}if(u++,f.attributes){let m=Hcu(f.attributes,i,o);f.attributes=m.attributes,m.dropped&&(f.droppedAttributesCount=OVe(f.droppedAttributesCount)+m.dropped)}d.push(f)}e.events=d,p&&(e.droppedEventsCount=OVe(e.droppedEventsCount)+p),e.status?.message&&(e.status={...e.status,message:cYo($yh(e.status.message),o)})}var srn=class{setAttribute(){return this}setAttributes(){return this}addEvent(){return this}setStatus(){return this}recordException(){return this}updateName(){return this}traceparent(){return null}tracestate(){return null}end(){}},Wcu=new srn,PWt=class extends srn{constructor(t,r){super(),this._traceparent=t,this._tracestate=r}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}};function tbh(e){try{let t=e.stack;return typeof t=="string"&&t?{stack:t}:{}}catch{return{}}}function Nwe(e,t){let r=ern(e?.parent)??t,n=typeof r=="string"||r==null?r:Gcu(r,"traceparent"),i=Lcu(n);if(!i)return Wcu;let o=typeof r=="string"||r==null?e?.tracestate:Gcu(r,"tracestate");return new PWt(i,rrn(o))}function Gcu(e,t){try{let r=e[t];return typeof r=="function"?r.call(e):void 0}catch{return}}function cYo(e,t){return e.length>t?e.slice(0,t):e}function arn(e,t){return irn(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}function irn(e,t,r,n){if(e===null||typeof e!="object")return AJ(e)||r.remainingNodes<=0?e:(r.remainingNodes--,typeof e=="string"?cYo(e,t):e);if(r.ancestors.has(e))return Mtn;if(r.remainingNodes<=0||n>=20)return e;r.remainingNodes--,r.ancestors.add(e);try{if(e instanceof Date)return e;let i=rbh(e);if(i.selfDescribed)return AJ(i.value)?String(i.value):irn(i.value,t,r,n+1);if(x3(e)){let a=Math.min(e.length,1e3),c=[];for(let l=0;l<a;l++)try{c.push(irn(e[l],t,r,n+1))}catch{c.push(T8)}return e.length>a&&(c.length=e.length),c}let o={},s=0;for(let a of Object.keys(e)){if(s>=1e3)break;let c;try{c=irn(e[a],t,r,n+1)}catch{c=T8}a&&!AJ(c)&&s++,Object.defineProperty(o,a,{value:c,enumerable:!0,writable:!0,configurable:!0})}return o}catch{return e}finally{r.ancestors.delete(e)}}function rbh(e){try{let t=e.toJSON;if(typeof t=="function")return{selfDescribed:!0,value:t.call(e)}}catch{}return{selfDescribed:!1}}function Hcu(e,t,r){let n;try{n=Object.keys(e)}catch{return{attributes:{},dropped:0}}let i={},o=0,s=0;for(let a of n){if(o>=t){s++;continue}let c;try{c=arn(e[a],r)}catch{c=T8}AJ(c)||(o++,Object.defineProperty(i,a,{value:c,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:i,dropped:s}}function Kcu(e,t){for(let r of Object.keys(e))e[r]=arn(e[r],t);return e}function BWt(e,t,r){return t===Wcu?r(t):e.with(t,()=>r(t))}function lYo(e){try{let t=tbh(e);if(kwe(e))return{type:e.name||"Error",message:e.message||"",...t};if(typeof e=="string")return{type:"string",message:e};if(e&&typeof e=="object"){let r=e;if(typeof r.message=="string")return{type:typeof r.name=="string"?r.name:"Object",message:r.message,...t}}return{type:typeof e,message:String(e)}}catch{return{type:typeof e,message:""}}}var uYo={internal:1,server:2,client:3,producer:4,consumer:5},nbh={ok:1,error:2},ibh=1,obh=256,sbh=512;function abh(e){let t=parseInt(e.traceFlags,16);return(Number.isFinite(t)?255&t:ibh)|obh|(e.parentIsRemote?sbh:0)}function crn(e){if(typeof e=="string")return Qre(e);try{return Qre(String(e))}catch{return T8}}function cbh(e){return e&&Object.prototype.hasOwnProperty.call(uYo,e)?uYo[e]:uYo.internal}function pYo(e){let t=Math.floor(e),r=Math.round((e-t)*1e6);return r>=1e6&&(t+=1,r=0),String(t)+String(r).padStart(6,"0")}function lbh(e,t){let r={name:crn(e.name),timeUnixNano:pYo(e.timestamp)};if(e.attributes){let i=Lre(e.attributes,t);i.length&&(r.attributes=i)}let n=OVe(e.droppedAttributesCount);return n&&(r.droppedAttributesCount=n),r}function Jcu(e,t){let r={traceId:e.traceId,spanId:e.spanId,name:crn(e.name),kind:cbh(e.kind),startTimeUnixNano:pYo(e.startTime),endTimeUnixNano:pYo(e.endTime),flags:abh(e)};e.parentSpanId&&(r.parentSpanId=e.parentSpanId),e.traceState&&(r.traceState=crn(e.traceState));let n=Lre(e.attributes,t);n.length&&(r.attributes=n),e.events.length&&(r.events=e.events.map(s=>lbh(s,t)));let i=OVe(e.droppedAttributesCount);i&&(r.droppedAttributesCount=i);let o=OVe(e.droppedEventsCount);return o&&(r.droppedEventsCount=o),e.status&&(r.status={code:nbh[e.status.code],...e.status.message&&{message:crn(e.status.message)}}),r}function Ycu(e,t,r){return vWt(e,t,r)}function Xcu(e,t,r,n,i){return{resourceSpans:[{resource:{attributes:CWt(t,i)},scopeSpans:[{scope:{name:r,version:n},spans:e}]}]}}var Zcu=8;function lrn(){return orn()??Date.now()}function fYo(e){try{return e instanceof Kut}catch{return!1}}function $cu(e,t){let r=Qcu(e);if(r)return{traceId:r.traceId,parentSpanId:r.spanId,traceState:rrn(t),traceFlags:r.flags,isRemote:!0}}function ubh(e){try{return typeof e.traceparent=="function"}catch{return!1}}function pbh(e){return!!e.attributes&&typeof e.attributes=="object"&&!Array.isArray(e.attributes)&&Array.isArray(e.events)&&e.name!==void 0&&e.kind!==void 0&&e.startTime!==void 0&&e.endTime!==void 0}function urn(e,t,r){e[t]!==r&&(e[t]=r)}function fbh(e,t){try{let r=Object.getOwnPropertyDescriptors(e);for(let n of["traceId","spanId","parentSpanId","traceState"])r[n]={value:t[n],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(e),r)}catch{return e}}var DWt=class{constructor(t,r,n,i,o,s){this._instance=t,this._config=r,this._logger=n,this._getContext=i,this._contextManager=o,this._onSpanQueued=s,this._queue=[],this._flushTimer=new wVe(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=D8,this._retryAfter=new xVe,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=r.maxExportBatchSize}startSpan(t,r){if(this._instance.isDisabled||this._instance.optedOut)return Nwe(r,this._contextManager.active());let n=ern(r?.parent);if(n&&typeof n!="string"&&!fYo(n)){if(ubh(n))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),Nwe(r,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let i=this._resolveParent(n,r);if(this._liveSpans.size>=this._config.maxLiveSpans&&this._evictAgedSpans(),this._liveSpans.size>=this._config.maxLiveSpans)return this._recordDrop(1,`the live-span limit (${this._config.maxLiveSpans}) was reached \u2014 spans are being started and never ended`),Nwe(r,this._contextManager.active());let o=Date.now(),s=Vcu(r?.startTime,o,this._logger),a=Fcu();this._liveSpans.set(a,lrn());let c=this._autoContextAttributes();return new Kut({traceId:i?.traceId??kcu(),spanId:a,parentSpanId:i?.parentSpanId,traceState:i?.traceState,traceFlags:i?.traceFlags,parentIsRemote:i?.isRemote,name:TVe(t,"Span name",this._config.maxAttributeValueLength,this._logger),kind:r?.kind??"internal",attributes:hhe({...c},r?.attributes),autoAttributeKeys:Object.keys(c),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:s,backdated:s!==o,clockAnchor:Hut(r?.startTime)===void 0?i?.clockAnchor:void 0},(l,u)=>this._onSpanEnd(l,u),this._logger)}withSpan(t,r,n){let i=typeof r=="function"?void 0:r,o=typeof r=="function"?r:n,s=this.startSpan(t,i);try{let a=BWt(this._contextManager,s,o);return Xau(a)?a.then(c=>(s.end(),c),c=>{throw this._recordCallbackError(s,c),s.end(),c}):(s.end(),a)}catch(a){throw this._recordCallbackError(s,a),s.end(),a}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;)if(!this._queue.length||!await(this._flushPromise??this._startFlush()))return}_startFlush(){this._flushTimer.clear();let t=this._generation,r=Promise.resolve().then(()=>t===this._generation?this._flushInner():0).finally(()=>{this._flushPromise===r&&(this._flushPromise=null),this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=r,r}reset(){this._flushTimer.clear(),this._queue.length&&this._logger.critical(`Discarding ${this._queue.length} span(s) that were still queued when tracing was shut down. Raise the shutdown timeout or flush earlier if they matter.`),this._queue=[],this._liveSpans.clear(),this._flushPromise=null,this._generation++,this._maxExportBatchSize=this._config.maxExportBatchSize,this._droppedSinceWarning=0,this._dropReasons.clear(),this._lastDropWarningAt=0,this._consecutiveFlushFailures=0,this._flushJitter=D8,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(t,r){if(typeof t=="string"){let i=$cu(t,r?.tracestate);return i||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),i}if(fYo(t))return t.childContext();let n=this._contextManager.active();if(fYo(n))return n.childContext();if(n instanceof PWt)return $cu(n.traceparent(),n.tracestate()??void 0)}_autoContextAttributes(){let t;try{t=this._getContext()}catch(n){return this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes",n),{}}let r={};return t.distinctId&&(r.posthogDistinctId=t.distinctId),t.sessionId&&(r.sessionId=t.sessionId),t.currentUrl&&(r["url.full"]=t.currentUrl),t.screenName&&(r["screen.name"]=t.screenName),t.appState&&(r["app.state"]=t.appState),r}_recordCallbackError(t,r){if(!(t instanceof Kut))return;let{type:n,message:i,stack:o}=lYo(r);t.addEvent("exception",{"exception.type":n,"exception.message":i,...o&&{"exception.stacktrace":o}}),t.statusIsExplicitlyOk||t.setStatus("error",i)}_evictAgedSpans(){let t=lrn()-this._config.maxSpanAgeMs,r=0;for(let[n,i]of this._liveSpans){if(i>t)break;this._liveSpans.delete(n),r++}r&&this._recordDrop(r,`they were still live after ${this._config.maxSpanAgeMs}ms`)}_onSpanEnd(t,r){if(!this._liveSpans.delete(t.spanId))return;if(this._instance.isDisabled||this._instance.optedOut)return void this._recordDrop(1,"the user has opted out");let n=this._runBeforeSpanSend(t,r);if(n){if(this._reportLimitDrops(n),this._queue.length>=this._config.maxQueueSize)return void this._recordDrop(1,`the queue is full (${this._config.maxQueueSize}) \u2014 raise the flush frequency or reduce span volume`);this._queue.push(n);try{this._onSpanQueued?.()}catch(i){this._logger.debug("Span queue notification failed",i)}!(this._queue.length>=this._maxExportBatchSize)||this._consecutiveFlushFailures||this._retryAfter.isOpen()?this._armFlushTimerIfQueued():this._flushInBackground()}}_reportLimitDrops(t){let r=t.droppedAttributesCount??0,n=t.droppedEventsCount??0,i=0;for(let o of t.events)i+=o.droppedAttributesCount??0;(r||n||i)&&this._logger.debug(`Span limits discarded data from "${t.name}": ${r} attributes, ${n} events, ${i} event attributes`)}_runBeforeSpanSend(t,r){if(!this._config.beforeSpanSend.length)return t;let n={traceId:t.traceId,spanId:t.spanId,parentSpanId:t.parentSpanId,traceState:t.traceState},i={startTime:t.startTime,endTime:t.endTime},o={attributes:t.droppedAttributesCount,events:t.droppedEventsCount},s=Object.keys(t.attributes),a={traceFlags:t.traceFlags,parentIsRemote:t.parentIsRemote},c=t.status&&{...t.status},l=t,u=t;try{for(let f of this._config.beforeSpanSend){let m=f(l);if(!m)return this._recordDrop(1,"beforeSpanSend dropped it"),null;l=this._keepSpanIdentity(m,n)}if(u={traceId:n.traceId,spanId:n.spanId,parentSpanId:n.parentSpanId,traceState:n.traceState,name:l.name,kind:l.kind,status:l.status,attributes:l.attributes,events:l.events,startTime:l.startTime,endTime:l.endTime,traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote,droppedAttributesCount:o.attributes,droppedEventsCount:o.events},!pbh(u))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;u.name=TVe(u.name,"Span name",this._config.maxAttributeValueLength,this._logger),u.status&&u.status.code!=="ok"&&u.status.code!=="error"&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),u.status=c),u.startTime=Hut(u.startTime)??i.startTime,u.endTime=nrn(Hut(u.endTime)??i.endTime,u.startTime);let d=[];for(let f of u.events)try{d.push({...f,name:TVe(f.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:OWt(f.timestamp,u.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return u.events=d,qcu(u,r,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,s),u}catch(p){return this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed",p),this._recordDrop(1,"beforeSpanSend failed"),null}}_keepSpanIdentity(t,r){(t.traceId!==r.traceId||t.spanId!==r.spanId||t.parentSpanId!==r.parentSpanId)&&this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");try{urn(t,"traceId",r.traceId),urn(t,"spanId",r.spanId),urn(t,"parentSpanId",r.parentSpanId),urn(t,"traceState",r.traceState)}catch{return fbh(t,r)}return t}_recordDrop(t,r){this._droppedSinceWarning+=t,this._dropReasons.add(r),Date.now()-this._lastDropWarningAt>=this._config.flushIntervalMs&&this._warnAboutDrops()}_warnAboutDrops(){this._droppedSinceWarning&&(this._lastDropWarningAt=Date.now(),this._logger.warn(`Dropping ${this._droppedSinceWarning} span(s): ${[...this._dropReasons].join("; ")}`),this._droppedSinceWarning=0,this._dropReasons.clear())}_encodeBatch(t){let r=[];for(let n of t)try{r.push(Jcu(n,this._logger))}catch(i){this._logger.debug("Failed to encode a span; dropping it",i),this._recordDrop(1,"its attributes could not be encoded")}return r}_discardQueueIfConsentWithdrawn(){if(!this._instance.isDisabled&&!this._instance.optedOut)return 0;let t=this._queue.length;return this._queue=[],this._resetHeadBatchBudget(),this._recordDrop(t,"the user has opted out"),this._warnAboutDrops(),t}async _flushInner(){if(!this._queue.length)return 0;let t=this._discardQueueIfConsentWithdrawn();if(t)return t;let r=Kcu(Ycu(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._config.maxAttributeValueLength),n=this._instance.getLibraryId(),i=this._instance.getLibraryVersion(),o=this._queue.length,s=0,a=1/0,c=this._generation;try{for(;o>0&&this._queue.length>0;){let l=this._discardQueueIfConsentWithdrawn();if(l)return s+l;let u=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,p=Math.max(1,Math.min(u,a,o,this._queue.length)),d=this._queue.slice(0,p),f=this._encodeBatch(d);if(!f.length){this._queue.splice(0,p),o-=p,s+=p,this._resetHeadBatchBudget();continue}let m=lrn()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),g=await this._instance._sendTracesBatch(Xcu(f,r,n,i,this._logger));if(c!==this._generation)break;if(this._retryAfter.record(g),g.kind==="ok"){this._consecutiveFlushFailures=0,this._flushJitter=D8,this._resetHeadBatchBudget(),this._queue.splice(0,p),o-=p,s+=p,this._maxExportBatchSize<this._config.maxExportBatchSize&&this._maxExportBatchSize++;continue}if(g.kind==="too-large"){if(p===1){this._queue.splice(0,1),o-=1,s+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=D8,this._resetHeadBatchBudget();continue}let A=Math.max(1,Math.floor(p/2));g.measuredLocally?a=A:this._maxExportBatchSize=A,this._resetHeadBatchBudget(),this._logger.debug(`Batch too large; retrying the same spans in batches of ${A}`);continue}if(g.kind==="retry-later"){if(this._consecutiveFlushFailures++,this._flushJitter=xWt(),this._headBatchSize=p,m&&(this._headBatchFailures++,this._headBatchChargeableAt=lrn()+this._nextFlushDelay()),this._headBatchFailures<Zcu)return this._logger.debug("Span export failed; retrying on the next flush",g.error),s;if(this._queue.splice(0,p),o-=p,s+=p,this._consecutiveFlushFailures=0,this._flushJitter=D8,this._resetHeadBatchBudget(),this._recordDrop(p,`the ingestion endpoint failed ${Zcu} times in a row`),this._retryAfter.isOpen())return s;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",g.error),this._queue.splice(0,p),o-=p,s+=p,this._consecutiveFlushFailures=0,this._flushJitter=D8,this._resetHeadBatchBudget(),this._recordDrop(p,"the ingestion endpoint rejected the batch")}return s}finally{this._warnAboutDrops()}}_flushInBackground(){this._backgroundFlush||(this._backgroundFlush=this.flush().catch(t=>{this._logger.debug("Background span flush failed",t)}).finally(()=>{this._backgroundFlush=void 0,this._armFlushTimerIfQueuedNoEarlierThan()}))}_armFlushTimerIfQueued(){this._flushTimer.pending||!this._queue.length||this._flushTimer.arm(this._nextFlushDelay())}_armFlushTimerIfQueuedNoEarlierThan(){this._queue.length&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(SWt(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}};var RWt=class{active(){return this._active}with(t,r){let n=this._active;this._active=t;try{return r()}finally{this._active=n}}};var dbh=5e3,mbh=512,hbh=2048,gbh=128,Abh=128,ybh=128,bbh=8192,Ebh=1e4,Ibh=36e5;function jwe(e,t){return typeof e=="number"&&Number.isInteger(e)&&e>=1?e:t}var elu=["service.name","service.version","deployment.environment"];function vbh(e){if(!(!e||typeof e!="object"||Array.isArray(e)))try{if(elu.every(r=>!(r in e)||typeof e[r]=="string"))return e;let t={...e};for(let r of elu)r in t&&typeof t[r]!="string"&&delete t[r];return t}catch{return}}function Cbh(e,t){if(!e)return[];let r=[e].flat().filter(i=>!!i),n=r.filter(i=>typeof i=="function");return n.length!==r.length&&t?.critical(`beforeSpanSend: ignoring ${r.length-n.length} of ${r.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`),n}function dYo(e,t,r){let n=hhe({...t},vbh(e?.resourceAttributes)),i=jwe(e?.maxExportBatchSize,mbh);return{serviceName:n?.["service.name"]??e?.serviceName,serviceVersion:n?.["service.version"]??e?.serviceVersion,environment:n?.["deployment.environment"]??e?.environment,resourceAttributes:n,beforeSpanSend:Cbh(e?.beforeSpanSend,r),maxAttributesPerSpan:jwe(e?.maxAttributesPerSpan,gbh),maxEventsPerSpan:jwe(e?.maxEventsPerSpan,Abh),maxAttributesPerEvent:ybh,maxAttributeValueLength:jwe(e?.maxAttributeValueLength,bbh),flushIntervalMs:jwe(e?.flushIntervalMs,dbh),maxExportBatchSize:i,maxQueueSize:Math.max(jwe(e?.maxQueueSize,hbh),i),maxLiveSpans:jwe(e?.maxLiveSpans,Ebh),maxSpanAgeMs:jwe(e?.maxSpanAgeMs,Ibh)}}var mYo=require("fs"),nlu=require("fs/promises"),gYo=require("path"),ilu=require("readline"),prn=new LT.ReduceableCache(25),kWt=new LT.ReduceableCache(20),AYo=7,xbh=1e3,Sbh=1e4,hYo=10485760;async function olu(e,t=nlu.open,r){let n={},i;try{i=process.cwd()}catch{}for(let a=e.length-1;a>=0;a--){let c=e[a],l=c?.filename;if(!c||typeof l!="string"||typeof c.lineno!="number"||Bbh(l)||Dbh(c)||!(0,gYo.isAbsolute)(l)&&i===void 0)continue;n[l]||(n[l]=[]),n[l].push(c.lineno)}let o=Object.keys(n);if(o.length==0)return e;let s=[];for(let a of o){let c=slu(a,i);if(c===void 0||kWt.get(c))continue;let l=n[a];if(!l)continue;l.sort((d,f)=>d-f);let u=kbh(l);if(u.every(d=>Rbh(c,d)))continue;let p=Fbh(prn,c,{});s.push(Tbh(a,u,p,c,t,r))}return await Promise.all(s).catch(()=>{}),e&&e.length>0&&Obh(e,prn,i),prn.reduce(),e}async function wbh(e,t,r){let n,i=!1;try{n=await t(e,mYo.constants.O_RDONLY|mYo.constants.O_NONBLOCK);let o=await n.stat();return o.isFile()?o.size>hYo?void r?.debug(`Skipping source context for oversized file ${e}: ${o.size} bytes exceeds ${hYo}`):(i=!0,n):void 0}catch{return}finally{n&&!i&&await n.close().catch(()=>{})}}async function Tbh(e,t,r,n,i,o){let s=await wbh(e,i,o);if(s===void 0)return void kWt.set(n,1);let a=s;return new Promise(c=>{let l=!1;function u(C){l||(l=!0,C?.destroy(),a.close().then(c,c))}let p;try{p=a.createReadStream({autoClose:!1,start:0,end:hYo-1})}catch{kWt.set(n,1),u();return}let d;try{d=(0,ilu.createInterface)({input:p})}catch{kWt.set(n,1),u(p);return}let f=0,m=0,g=t[m];if(g===void 0)return void u(p);let A=g[0],b=g[1];function I(){kWt.set(n,1),d.close(),d.removeAllListeners(),u(p)}p.on("error",I),d.on("error",I),d.on("close",()=>u(p)),d.on("line",C=>{if(f++,!(f<A)&&(r[f]=Nbh(C,0),f>=b)){if(m===t.length-1){d.close(),d.removeAllListeners();return}m++;let x=t[m];if(x===void 0){d.close(),d.removeAllListeners();return}A=x[0],b=x[1]}})})}function Obh(e,t,r){for(let n of e)if(n.filename&&n.context_line===void 0&&typeof n.lineno=="number"){let i=slu(n.filename,r),o=i===void 0?void 0:t.get(i);if(o===void 0)continue;Pbh(n.lineno,n,o)}}function Pbh(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=alu(e);i<e;i++){let o=r[i];if(o===void 0)return void tlu(t);t.pre_context.push(o)}if(r[e]===void 0)return void tlu(t);t.context_line=r[e];let n=clu(e);t.post_context=[];for(let i=e+1;i<=n;i++){let o=r[i];if(o===void 0)break;t.post_context.push(o)}}function tlu(e){delete e.pre_context,delete e.context_line,delete e.post_context}function Bbh(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function Dbh(e){return e.lineno!==void 0&&e.lineno>Sbh||e.colno!==void 0&&e.colno>xbh}function slu(e,t){return(0,gYo.isAbsolute)(e)?JSON.stringify([null,e]):t===void 0?void 0:JSON.stringify([t,e])}function Rbh(e,t){let r=prn.get(e);if(r===void 0)return!1;for(let n=t[0];n<=t[1];n++)if(r[n]===void 0)return!1;return!0}function kbh(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=rlu(r),i=[];for(;;){if(t===e.length-1){i.push(n);break}let o=e[t+1];if(typeof o!="number")break;o<=n[1]?n[1]=o+AYo:(i.push(n),n=rlu(o)),t++}return i}function rlu(e){return[alu(e),clu(e)]}function alu(e){return Math.max(1,e-AYo)}function clu(e){return e+AYo}function Fbh(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function Nbh(e,t){let r=e,n=r.length;if(n<=150)return r;t>n&&(t=n);let i=Math.max(t-60,0);i<5&&(i=0);let o=Math.min(i+140,n);return o>n-5&&(o=n),o===n&&(i=Math.max(o-140,0)),r=r.slice(i,o),i>0&&(r=`...${r}`),o<n&&(r+="..."),r}var Jut=require("path");function llu(e=process.cwd()){let t=Jut.sep==="\\",r=i=>t?i.replace(/\\/g,"/"):i,n=r(e);return async i=>{for(let o of i)!o.filename||o.filename.startsWith("node:")||o.filename.startsWith("data:")||(0,Jut.isAbsolute)(o.filename)&&(o.filename=r((0,Jut.relative)(n,r(o.filename))));return i}}var ulu="5.55.0";var Ahe={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var zwe=class e{constructor(t){this._host=t.host,this._distinctId=t.distinctId,this._groups=t.groups,this._disableGeoip=t.disableGeoip,this._flags=t.flags,this._requestId=t.requestId,this._evaluatedAt=t.evaluatedAt,this._flagDefinitionsLoadedAt=t.flagDefinitionsLoadedAt,this._errorsWhileComputing=t.errorsWhileComputing??!1,this._quotaLimited=t.quotaLimited??!1,this._accessed=t.accessed??new Set,this._isSlice=t.isSlice??!1}isEnabled(t,r={}){let n=this._flags[t];return this._recordAccess(t),n?.enabled??r.defaultValue??!1}getFlag(t){let r=this._flags[t];if(this._recordAccess(t),!!r)return r.enabled?r.variant??!0:!1}getFlagPayload(t){return this._flags[t]?.payload}onlyAccessed(){let t={};for(let r of this._accessed){let n=this._flags[r];n&&(t[r]=n)}return this._cloneWith(t)}only(t){let r={},n=[];for(let i of t){let o=this._flags[i];o?r[i]=o:n.push(i)}return n.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${n.join(", ")}`),this._cloneWith(r)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let t={},r=[];for(let[n,i]of Object.entries(this._flags)){let o=i.enabled===!1?!1:i.variant??!0;t[`$feature/${n}`]=o,i.enabled&&r.push(n)}return r.length>0&&(r.sort(),t.$active_feature_flags=r),t}_cloneWith(t){return new e({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:t,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(t){if(this._accessed.add(t),this._distinctId===""||this._isSlice&&!(t in this._flags))return;let r=this._flags[t],n=r===void 0?void 0:r.enabled===!1?!1:r.variant??!0,i={$feature_flag:t,$feature_flag_response:n,$feature_flag_id:r?.id,$feature_flag_version:r?.version,$feature_flag_reason:r?.reason,locally_evaluated:r?.locallyEvaluated??!1,[`$feature/${t}`]:n,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:r?.locallyEvaluated?Date.now():this._evaluatedAt};r?.hasExperiment!==void 0&&(i.$feature_flag_has_experiment=r.hasExperiment),r?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0&&(i.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let o=[];this._errorsWhileComputing&&o.push(Ahe.ERRORS_WHILE_COMPUTING),this._quotaLimited&&o.push(Ahe.QUOTA_LIMITED),r===void 0&&o.push(Ahe.FLAG_MISSING),o.length>0&&(i.$feature_flag_error=o.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:t,response:n,groups:this._groups,disableGeoip:this._disableGeoip,properties:i})}};var jbh=6e4;function plu(e){return e==="client"||e==="server"?e:"all"}function zbh(e,t){return e===t||e==="all"||t==="all"}var Yut=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}};function Qbh(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}var _re=class e extends Error{constructor(t){super(t),Qbh(this,e)}},frn=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:n,timeout:i,host:o,customHeaders:s,...a}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollerStopped=!1,this.filteredOutFlagKeys=new Set,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=i,this.projectApiKey=n,this.host=o,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=s,this.onLoad=a.onLoad,this.onMinimalFlagCalledEvents=a.onMinimalFlagCalledEvents,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.evaluationContexts=a.evaluationContexts,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}withEvaluationSnapshot(t){return t.definitions?t:{...t,evaluationCache:{},definitions:{featureFlagsByKey:this.featureFlagsByKey,groupTypeMapping:this.groupTypeMapping,cohorts:this.cohorts,filteredOutFlagKeys:this.filteredOutFlagKeys,propertyMatchingVersion:this.propertyMatchingVersion}}}createEvaluationContext(t,r={},n={},i={},o={}){return{distinctId:t,groups:r,personProperties:n,groupProperties:i,evaluationCache:o}}async getFeatureFlag(t,r,n={},i={},o={}){await this.loadFeatureFlags();let s,a;if(!this.loadedSuccessfullyOnce)return s;if(a=this.featureFlagsByKey[t],a!==void 0){let c=this.createEvaluationContext(r,n,i,o);try{s=(await this.computeFlagAndPayloadLocally(a,c)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${s}`))}catch(l){l instanceof _re||l instanceof Gl?this.logMsgIfDebug(()=>console.debug(`${l.name} when computing flag locally: ${t}: ${l.message}`)):l instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${l}`))}}return s}async getAllFlagsAndPayloads(t,r){await this.loadFeatureFlags();let n={},i={},o=this.featureFlags.length==0,s=r?r.map(c=>this.featureFlagsByKey[c]).filter(Boolean):this.featureFlags,a=this.withEvaluationSnapshot({...t,definitions:void 0});return await Promise.all(s.map(async c=>{try{let{value:l,payload:u}=await this.computeFlagAndPayloadLocally(c,a,{skipLoadCheck:!0});n[c.key]=l,u&&(i[c.key]=u)}catch(l){l instanceof _re||l instanceof Gl?this.logMsgIfDebug(()=>console.debug(`${l.name} when computing flag locally: ${c.key}: ${l.message}`)):l instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${c.key}: ${l}`)),o=!0}})),{response:n,payloads:i,fallbackToFlags:o}}async computeFlagAndPayloadLocally(t,r,n={}){let{matchValue:i,skipLoadCheck:o=!1}=n;if(this.loadedSuccessfullyOnce&&(r=this.withEvaluationSnapshot(r)),o||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};r=this.withEvaluationSnapshot(r),t=r.definitions.featureFlagsByKey[t.key]??t;let s;s=i!==void 0?i:await this.computeFlagValueLocally(t,r);let a=ZJo(t.filters?.payloads,s);return{value:s,payload:a}}async computeFlagValueLocally(t,r){let{distinctId:n,groups:i,personProperties:o,groupProperties:s}=r;if(!t.active)return!1;if(t.ensure_experience_continuity)throw new Gl("Flag has experience continuity enabled");let c=(t.filters||{}).aggregation_group_type_index;if(c!=null){let l=r.definitions.groupTypeMapping[String(c)];if(!l)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new Gl("Flag has unknown group type index");if(!(l in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;t.bucketing_identifier==="device_id"&&(o?.$device_id===void 0||o?.$device_id===null||o?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${t.key}`));let u=s[l];return await this.matchFeatureFlagProperties(t,i[l],u,r)}{let l=this.getBucketingValueForFlag(t,n,o);if(l===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${t.key} without $device_id, falling back to server evaluation`)),new Gl(`Can't compute feature flag: ${t.key} without $device_id`);return await this.matchFeatureFlagProperties(t,l,o,r)}}getBucketingValueForFlag(t,r,n){if(t.filters?.aggregation_group_type_index!=null)return r;if(t.bucketing_identifier==="device_id"){let i=n?.$device_id;return i==null||i===""?void 0:i}return r}async evaluateFlagDependency(t,r,n){let{evaluationCache:i}=n,o=t.key;if(!n.definitions.featureFlagsByKey)throw new Gl("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new Gl(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let s=t.dependency_chain;if(!Array.isArray(s))throw new Gl(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new Gl(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let c of s){if(!(c in i)){let u=n.definitions.featureFlagsByKey[c];if(u)if(u.active)try{let p=await this.computeFlagValueLocally(u,n);i[c]=p}catch(p){throw new Gl(`Error evaluating flag dependency '${c}' for flag '${o}': ${p}`)}else i[c]=!1;else if(n.definitions.filteredOutFlagKeys.has(c))i[c]=!1;else throw new Gl(`Missing flag dependency '${c}' for flag '${o}'`)}if(i[c]==null)throw new Gl(`Dependency '${c}' could not be evaluated`)}let a=i[o];return this.flagEvaluatesToExpectedValue(t.value,a)}flagEvaluatesToExpectedValue(t,r){return typeof t=="boolean"?t===r||typeof r=="string"&&r!==""&&t===!0:typeof t=="string"?r===t:!1}async matchFeatureFlagProperties(t,r,n,i){i=this.withEvaluationSnapshot(i);let o=t.filters||{},s=await YJo(o.holdout,r);if(s!==void 0)return s;let a=o.groups||[],c=o.aggregation_group_type_index,l=o.early_exit??!1,{groups:u,groupProperties:p}=i,d=!1,f;for(let m of a)try{let g=m.aggregation_group_type_index!==void 0?m.aggregation_group_type_index:c,A=n,b=r;if(g!==c&&g!=null){let C=i.definitions.groupTypeMapping[String(g)];if(!C||!(C in u)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${t.key}': group type index ${g} not available`));continue}if(!(C in p)){d=!0;continue}A=p[C],b=u[C]}let I=await this.isConditionMatch(t,b,m,A,i);if(I==="match"){let C=m.variant,x=o.multivariate?.variants||[];f=C&&x.some(S=>S.key===C)?C:await this.getMatchingVariant(t,b)||!0;break}if(l&&I==="out_of_rollout_bound"){if(d)break;return!1}}catch(g){if(g instanceof _re)throw g;if(g instanceof Gl)d=!0;else throw g}if(f!==void 0)return f;if(d)throw new Gl("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,n,i,o){o=this.withEvaluationSnapshot(o);let s=o.definitions,a=n.rollout_percentage,c=l=>{this.logMsgIfDebug(()=>console.warn(l))};if((n.properties||[]).length>0){for(let l of n.properties){let u=l.type,p=!1;if(u==="cohort"){let d=await dlu(l,i,s.cohorts,this.debugMode,f=>this.evaluateFlagDependency(f,i,o),s.propertyMatchingVersion);p=l.operator==="not_in"?!d:d}else p=u==="flag"?await this.evaluateFlagDependency(l,i,o):flu(l,i,c,s.propertyMatchingVersion);if(!p)return"no_match"}if(a==null)return"match"}return a!=null&&await EWt(t.key,r)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(t,r){return XJo(t.key,r,t.filters?.multivariate?.variants||[])}variantLookupTable(t){return Xtn(t.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(t){if(!this.evaluationContexts||this.evaluationContexts.length===0)return t;let r=new Set(this.evaluationContexts);return t.filter(n=>{let i=n.evaluation_contexts??n.evaluation_tags;return!i||i.length===0?!0:i.some(o=>r.has(o))})}getEvaluationRuntimeForFlag(t){let r=this.featureFlagsByKey[t];return r?plu(r.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(t){return this.featureFlags.filter(r=>zbh(plu(r.evaluation_runtime),t)).map(r=>r.key)}updateFlagState(t){let r=this.filterFlagsByEvaluationContexts(t.flags);this.featureFlags=r,this.featureFlagsByKey=r.reduce((i,o)=>(i[o.key]=o,i),{});let n=new Set(r.map(i=>i.key));this.filteredOutFlagKeys=new Set(t.flags.filter(i=>!n.has(i.key)).map(i=>i.key)),this.groupTypeMapping=t.group_type_mapping??t.groupTypeMapping??{},this.cohorts=t.cohorts,this.propertyMatchingVersion=t.property_matching_version??t.propertyMatchingVersion,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.((t.minimal_flag_called_events??t.minimalFlagCalledEvents)===!0)}warnAboutExperienceContinuityFlags(t){if(this.strictLocalEvaluation)return;let r=t.filter(n=>n.ensure_experience_continuity);r.length>0&&console.warn(`[PostHog] You are using local evaluation but ${r.length} flag(s) have experience continuity enabled: ${r.map(n=>n.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(t){if(!this.cacheProvider)return!1;try{let r=await this.cacheProvider.getFlagDefinitions();return r?(this.updateFlagState(r),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${t} (${r.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags),!0):!1}catch(r){return this.onError?.(new Error(`Failed to load from cache: ${r}`)),!1}}async loadFeatureFlags(t=!1){if(!(this.loadedSuccessfullyOnce&&!t))return!t&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(r=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${r}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){let t=this.pollingInterval??3e4;return this.shouldBeginExponentialBackoff?Math.min(jbh,t*2**this.backOffCount):t}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0);try{let t=!0;if(this.cacheProvider)try{t=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(n){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${n}`))}if(!t&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let r=await this._requestFeatureFlagDefinitions();if(!r)return;switch(r.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=r.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new Yut(`Your project key or secret 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.filteredOutFlagKeys=new Set,this.groupTypeMapping={},this.cohorts={},this.propertyMatchingVersion=void 0,this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new Yut(`Your secret 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 secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new Yut(`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 n=await r.json()??{};if(!("flags"in n))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(n)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let i=n.group_type_mapping||{},o=n.minimal_flag_called_events===!0,s={flags:n.flags??[],group_type_mapping:i,cohorts:n.cohorts||{},minimal_flag_called_events:o,property_matching_version:n.property_matching_version,propertyMatchingVersion:n.property_matching_version,groupTypeMapping:i,minimalFlagCalledEvents:o};if(this.updateFlagState(s),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(s)}catch(a){this.onError?.(new Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags);break}default:return}}catch(t){t instanceof Yut&&this.onError?.(t)}finally{!this.pollerStopped&&this.pollingInterval!==null&&(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}getPersonalApiKeyRequestOptions(t="GET",r){let n={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(n["If-None-Match"]=r),{method:t,headers:n}}async _requestFeatureFlagDefinitions(){let t=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let o=new AbortController;n=$2(()=>{o.abort()},this.timeout),r.signal=o.signal}let i=()=>clearTimeout(n);try{let o=this.fetch,s=await o(t,r);return s.status!==200?(i(),s):{status:s.status,headers:s.headers,body:s.body,text:async()=>{try{return await s.text()}finally{i()}},json:async()=>{try{return await s.json()}finally{i()}}}}catch(o){throw i(),o}}async stopPoller(t=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await Fwe(r,t,()=>{throw new Error(`Cache shutdown timeout after ${t}ms`)})}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};function flu(e,t,r,n){return JJo(e,t,{warnFunction:r,propertyMatchingVersion:n})}function Mbh(e,t){if(!(e in t))throw new _re(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function dlu(e,t,r,n=!1,i,o){let s=String(e.value);Mbh(s,r);let a=r[s];return mlu(a,t,r,n,i,o)}async function mlu(e,t,r,n=!1,i,o){if(!e)return!0;let s=e.type,a=e.values;if(!a||a.length===0)return!0;let c=!1;if("values"in a[0]){for(let l of a)try{let u=await mlu(l,t,r,n,i,o);if(s==="AND"){if(!u)return!1}else if(u)return!0}catch(u){if(u instanceof _re)throw u;if(u instanceof Gl)n&&console.debug(`Failed to compute property ${l} locally: ${u}`),c=!0;else throw u}if(c)throw new Gl("Can't match cohort without a given cohort property value");return s==="AND"}for(let l of a)try{let u;if(l.type==="cohort")u=await dlu(l,t,r,n,i,o);else if(l.type==="flag"){if(!i)throw new Gl(`Flag dependency '${l.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);u=await i(l)}else u=flu(l,t,void 0,o);let p=l.negation||!1;if(s==="AND"){if(!u&&!p||u&&p)return!1}else if(u&&!p||!u&&p)return!0}catch(u){if(u instanceof _re)throw u;if(u instanceof Gl)n&&console.debug(`Failed to compute property ${l} locally: ${u}`),c=!0;else throw u}if(c)throw new Gl("can't match cohort without a given cohort property value");return s==="AND"}var Lbh=["--unhandled-rejections","--unhandled_rejections"],_bh=new Set(["throw","strict","warn","warn-with-error-code","none"]),Ubh=[...globalThis.process?.execArgv??[]],Vbh=globalThis.process?.env?.NODE_OPTIONS;function Gbh(e){let t=[],r="",n=!1;for(let i=0;i<e.length;i++){let o=e[i];o==="\\"&&n&&i+1<e.length?r+=e[++i]:o!==" "||n?o==='"'?n=!n:r+=o:r&&(t.push(r),r="")}return r&&t.push(r),t}function hlu(e){let t;for(let r=0;r<e.length;r++){let n=e[r],i=Lbh.find(s=>n===s||n.startsWith(`${s}=`));if(!i)continue;let o=n===i?e[++r]:n.slice(i.length+1);_bh.has(o)&&(t=o)}return t}function qbh(e=Ubh,t=Vbh){return hlu(e)??hlu(Gbh(t??""))??"throw"}var glu=qbh();function Alu(e,t,r){e(t,{mechanism:{type:r==="unhandledRejection"?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function Wbh(e,t){let r=!1;return Object.assign((n,i)=>{let o=global.process.listeners("uncaughtException").filter(s=>s.name!=="domainUncaughtExceptionClear"&&s._posthogErrorHandler!==!0).length;Alu(e,n,i),!r&&o===0&&(r=!0,t(n))},{_posthogErrorHandler:!0})}function ylu(e,t,r=glu){let n=globalThis.process;if(n){if(r==="strict")return void n.on("uncaughtExceptionMonitor",(i,o)=>Alu(e,i,o));n.on("uncaughtException",Wbh(e,t))}}function blu(e,t=glu){let r=globalThis.process;!r||t==="throw"||t==="strict"||t==="warn-with-error-code"||r.on("unhandledRejection",n=>{e(n,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var Hbh=2e3,yYo=class e{constructor(t,r,n){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new Dtn({...Bau(r),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return iWt(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}static async buildEventMessage(t,r,n,i,o){let s={...o},a=t.buildFromUnknown(r,n);a.$exception_list=await t.modifyFrames(a.$exception_list);let c=LT.getInjectedReleaseId();return c&&(s.$release_id=c),{event:"$exception",distinctId:i,properties:{...a,...s},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(ylu(this.onException.bind(this),this.onFatalError.bind(this)),blu(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let n=await e.buildEventMessage(this.client.getErrorPropertiesBuilder(),t,r),o=n.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(o)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:o}):this.client._capturePreparedEvent(n,!1)}})())}async onFatalError(t){console.error(t),await this.client.shutdown(Hbh),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}},PVe=yYo;var drn=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};function Kbh(e){return e==="v0"||e==="v1"}function Elu(){let e="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return Kbh(e)?e:"v0"}var Jbh="$ai_",FWt="analytics";function Ilu(e){return typeof e.event=="string"&&e.event.startsWith(Jbh)}var Xut=class e extends Error{constructor({requestId:t,drops:r,retryExhausted:n,cause:i}){super(e.buildMessage(t,r,n,i)),this.name="CaptureV1Error",this.requestId=t,this.drops=r,this.retryExhausted=n,this.cause=i}static buildMessage(t,r,n,i){let o=`Capture V1 batch ${t} did not fully deliver: ${r.length} dropped, ${n.length} undelivered`;return i instanceof Error&&(o+=` (${i.message})`),o}};function bYo(e){if(typeof e=="boolean")return e;if(typeof e=="number")return e!==0;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}}function Ybh(e){return typeof e=="string"?e:void 0}var Xbh=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:bYo},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:bYo},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:bYo},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:Ybh}],Zbh=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function $bh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function eEh(e){if(typeof e=="string"){let r=new Date(e);if(Number.isNaN(r.getTime()))return new Date().toISOString();let n=r.toISOString(),i=e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return i&&i.length>3?n.replace(/\.\d{3}Z$/,`.${i}Z`):n}if(e instanceof Date)return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString();let t=e==null?new Date:new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}function vlu(e,t,r){r!==void 0&&!(t in e)&&(e[t]=r)}function tEh(e){let r={...$bh(e.properties)?e.properties:{}},n={};for(let{property:o,optionKey:s,coerce:a}of Xbh)if(o in r){let c=a(r[o]);c!==void 0&&(n[s]=c),delete r[o]}let i={};for(let{property:o,field:s}of Zbh)if(o in r){let a=r[o];typeof a=="string"&&(i[s]=a),delete r[o]}return delete r.$lib,delete r.$lib_version,vlu(r,"$set",e.$set),vlu(r,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:eEh(e.timestamp),...i,options:n,properties:r}}function Clu(e,{createdAt:t,historicalMigration:r}){let n={created_at:t,batch:e.map(tEh)};return r&&(n.historical_migration=!0),n}var rEh="/i/v1/analytics/events",nEh=3e4,iEh=new Set([408,500,502,503,504]),mrn=class{constructor(t,r){this.config=t,this.maxBackoffMs=t.maxBackoffMs??nEh,this.fetchFn=r.fetch,this.onError=r.onError,this.now=r.now??Date.now,this.sleep=r.sleep??(n=>new Promise(i=>$2(i,n))),this.generateRequestId=r.generateRequestId??Z2,this.compress=r.compress??AWt}async sendV1Batch(t){if(t.length===0)return;let r=this.generateRequestId(),n=new Date(this.now()).toISOString(),{batch:i}=Clu(t,{createdAt:n,historicalMigration:this.config.historicalMigration}),o=`${this.config.host}${rEh}`,s=[],a=i,c=Math.max(1,this.config.maxAttempts);for(let l=1;l<=c;l++){let u=l===c,p=Rwe({created_at:n,...this.config.historicalMigration?{historical_migration:!0}:{},batch:a}),d,f;try{d=await this.sendOnce(o,p,l,r);let{response:m,signal:g}=d,{status:A}=m;if(A<200||A>=300)if(!u&&iEh.has(A)){let b=this.parseRetryAfter(m);await d.waitFor(d.cancelBody()).catch(()=>{}),f=this.backoffDelay(l,b)}else{let b=await this.buildHttpError(m,A,d.waitFor);return this.surfaceBatchFailure(r,s,a,b)}else{let b;try{b=await d.waitFor(this.parseResponse(m))}catch(x){if(g.aborted)throw x;return this.surfaceBatchFailure(r,s,a,new Error(`Capture V1 returned an unparseable ${A} response body`))}let I=this.classify(a,b,s);if(I.length===0)return this.surfacePartialDrops(r,s);if(u)return void this.onError(new Xut({requestId:r,drops:s,retryExhausted:I.map(x=>x.uuid)}));a=I;let C=this.parseRetryAfter(m);f=this.backoffDelay(l,C)}}catch(m){if(d&&!d.signal.aborted)throw m;if(u)return this.surfaceBatchFailure(r,s,a,m);f=this.backoffDelay(l)}finally{d?.cleanup()}f!==void 0&&await this.sleep(f)}}async sendOnce(t,r,n,i){let o=this.buildHeaders(n,i),s=r;if(this.config.compressionEnabled){let p=await this.compress(r,this.config.isDebug);p!==null&&(s=p,o["Content-Encoding"]="gzip")}let a=new AbortController,c="waiting for response headers",l,u=new Promise((p,d)=>{l=$2(()=>{let f=new Error(`Capture V1 request timed out ${c} after ${this.config.requestTimeoutMs}ms`);f.name="AbortError",d(f),a.abort(f)},this.config.requestTimeoutMs)});try{let p=this.fetchFn(t,{method:"POST",headers:o,body:s,signal:a.signal}),d=!1;p.then(b=>{a.signal.aborted&&!d&&this.cancelBody(b)}).catch(()=>{});let f=await Promise.race([p,u]);d=!0,c="while reading the response body";let m=!1,g,A=()=>g??=this.cancelBody(f);return{response:f,signal:a.signal,waitFor:b=>Promise.race([b,u]),cancelBody:A,cleanup:()=>{m||(m=!0,clearTimeout(l),a.signal.aborted&&A())}}}catch(p){throw clearTimeout(l),p}}buildHeaders(t,r){let n=`${this.config.libraryId}/${this.config.libraryVersion}`,i={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":n,"PostHog-Attempt":String(t),"PostHog-Request-Id":r,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(i["User-Agent"]=this.config.userAgent),i}classify(t,r,n){let i=r.results??{},o=[];for(let s of t){let a=i[s.uuid];a&&(a.result==="drop"?n.push({uuid:s.uuid,details:a.details??void 0}):a.result==="retry"&&o.push(s))}return o}backoffDelay(t,r){let n=Math.min(this.config.initialRetryDelayMs*2**(t-1),this.maxBackoffMs);return r===void 0?n:Math.max(n,Math.min(r,this.maxBackoffMs))}parseRetryAfter(t){let r=t.headers?.get("Retry-After");if(!r)return;let n=r.trim();if(/^\d+$/.test(n)){let s=parseInt(n,10);return Number.isFinite(s)&&s>0?1e3*s:void 0}let i=Date.parse(n);if(Number.isNaN(i))return;let o=i-this.now();return o>0?o:void 0}async parseResponse(t){let r=await t.text(),n=JSON.parse(r);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("unexpected response shape");let i=n.results;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw new Error("unexpected results shape");return{results:i??{}}}async buildHttpError(t,r,n){let i="";try{i=(await n(t.text())).slice(0,512)}catch{}let o=i?`: ${i}`:"";return new Error(`Capture V1 request failed with HTTP ${r}${o}`)}surfaceBatchFailure(t,r,n,i){this.onError(new Xut({requestId:t,drops:r,retryExhausted:n.map(o=>o.uuid),cause:i}))}surfacePartialDrops(t,r){r.length>0&&this.onError(new Xut({requestId:t,drops:r,retryExhausted:[]}))}async cancelBody(t){try{await t.body?.cancel()}catch{}}};var BVe="ai-capture",hrn="/i/v0/ai/batch/";var sEh=new TextEncoder;function IYo(e){return sEh.encode(Rwe(e)).length}function xlu(e,t=8388608,r=5242880){let n=[],i=[],o=[],s=0;for(let a of e){if(a===void 0)continue;let c=IYo(a);if(c>t){i.push({event:typeof a.event=="string"?a.event:"unknown",bytes:c});continue}o.length>0&&s+c>r&&(n.push(o),o=[],s=0),o.push(a),s+=c}return o.length>0&&n.push(o),{batches:n,dropped:i}}var aEh=100,Slu=3e4,cEh=5e4,lEh=50,uEh=500,pEh="https://us.i.posthog.com",wlu=new Set;function Arn(e,t){wlu.has(e)||(wlu.add(e),console.warn(`[PostHog] ${t}`))}function fEh(e){return typeof e=="string"?e.trim():""}function dEh(e){return(typeof e=="string"?e.trim():"")||void 0}function mEh(e){return(typeof e=="string"?e.trim():"")||pEh}function hEh(e){return(Array.isArray(e)?e:[e]).filter(r=>typeof r=="string"&&r.trim().length>0)}function gEh(e){if(!e)return{};let t={};for(let[n,i]of Object.entries(e))t[`$feature/${n}`]=i;let r=Object.keys(e).filter(n=>e[n]!==!1).sort();return r.length>0&&(t.$active_feature_flags=r),t}var yrn=class extends yWt{constructor(t,r={}){let n=fEh(t),i={...r,maxQueueSize:r.maxQueueSize??1e4,flushInterval:r.flushInterval??5e3,host:mEh(r.host),personalApiKey:dEh(r.secretKey??r.personalApiKey)};if(super(n,i),this._memoryStorage=new drn,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=i,this.captureMode=Elu(),this.enableFullAiCapture=i.enableFullAiCapture===!0,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof i.featureFlagsPollingInterval=="number"?Math.max(i.featureFlagsPollingInterval,aEh):i.featureFlagsPollingInterval===null?null:Slu,typeof i.waitUntilDebounceMs=="number"&&(this.options.waitUntilDebounceMs=Math.max(i.waitUntilDebounceMs,0)),typeof i.waitUntilMaxWaitMs=="number"&&(this.options.waitUntilMaxWaitMs=Math.max(i.waitUntilMaxWaitMs,0)),!this.disabled&&i.personalApiKey){if(i.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.');i.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new frn({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:i.personalApiKey,projectApiKey:n,timeout:i.requestTimeout??1e4,host:this.host,fetch:i.fetch,onError:s=>{this._events.emit("error",s)},onLoad:s=>{this._events.emit("localEvaluationFlagsLoaded",s)},onMinimalFlagCalledEvents:s=>{this._minimalFlagCalledEvents=s},customHeaders:this.getCustomHeaders(),cacheProvider:i.flagDefinitionCacheProvider,strictLocalEvaluation:i.strictLocalEvaluation,evaluationContexts:i.evaluationContexts??i.evaluationEnvironments}))}this.errorTracking=new PVe(this,i,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=i.maxCacheSize||cEh}enqueue(t,r,n,i){super.enqueue(t,r,n,i),this.scheduleDebouncedFlush()}_flushEventsAndSpans(t=!1){let r=this.flushWithPendingPromises();return!this._traces||t&&this._traces.throttled?r:aWt([r,this._traces.flush().catch(()=>{})]).then(([n])=>{if(n.status==="rejected")throw n.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this._flushKeepingRuntimeAlive(!1)}_flushKeepingRuntimeAlive(t){let r=this._flushEventsAndSpans(t),n=this.options.waitUntil;if(n&&!this._waitUntilCycle)try{n(r.catch(()=>{}))}catch{}return r}scheduleDebouncedFlush(){let t=this.options.waitUntil;if(!t||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let s,a=new Promise(c=>{s=c});try{t(a)}catch{return}this._waitUntilCycle={resolve:s,startedAt:Date.now(),timer:void 0}}let r=Date.now()-this._waitUntilCycle.startedAt,n=this.options.waitUntilMaxWaitMs??uEh,i=r>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),i)return void this.resolveWaitUntilFlush();let o=this.options.waitUntilDebounceMs??lEh;this._waitUntilCycle.timer=$2(()=>{this.resolveWaitUntilFlush()},o)}_consumeWaitUntilCycle(){let t=this._waitUntilCycle;return t&&(clearTimeout(t.timer),this._waitUntilCycle=void 0),t?.resolve}async resolveWaitUntilFlush(){let t=this._consumeWaitUntilCycle();try{await this._flushEventsAndSpans()}catch{}finally{t?.()}}getPersistedProperty(t){return this._memoryStorage.getProperty(t)}setPersistedProperty(t,r){return this._memoryStorage.setProperty(t,r)}fetch(t,r){return this.options.fetch?this.options.fetch(t,r):fetch(t,r)}getQueueRouteKey(t){return this.captureMode==="v1"&&Ilu(t)?"ai":FWt}persistedQueueKeyForRoute(t){return t===BVe?tM.AiCaptureQueue:t==="ai"?tM.AiQueue:tM.Queue}getActiveQueueRoutes(){let t=this.captureMode==="v1"?[FWt,"ai"]:[FWt];return this._aiCaptureRouteActive&&t.push(BVe),t}getBatchEndpointPath(t){return t===BVe?hrn:super.getBatchEndpointPath(t)}async sendBatch(t,r,n=FWt){if(n===BVe)return this.sendAiCaptureBatch(t,r);if(this.captureMode!=="v1"||n==="ai")return super.sendBatch(t,r,n);let i=t.filter(o=>o!==void 0);await this.getV1Sender().sendV1Batch(i)}async sendAiCaptureBatch(t,r){let{batches:n,dropped:i}=xlu(t);for(let{event:o,bytes:s}of i){let a=`Event ${o} (${s} bytes) exceeds the ${8388608/1048576}MiB limit for ${hrn}, dropping.`;this._logger.error(a),this._events.emit("error",new Error(a))}for(let o of n)await this.sendAiSubBatch(o,r)}async sendAiSubBatch(t,r){try{await super.sendBatch(t,r,BVe)}catch(n){if(!Wut(n))throw n;if(t.length===1){let[o]=t,a=`Event ${typeof o.event=="string"?o.event:"unknown"} (${IYo(o)} bytes) was rejected with 413 by ${hrn} on its own, dropping.`;this._logger.error(a),this._events.emit("error",new Error(a));return}let i=Math.ceil(t.length/2);await this.sendAiSubBatch(t.slice(0,i),r),await this.sendAiSubBatch(t.slice(i),r)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new mrn({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3e3,isDebug:this.isDebug},{fetch:(t,r)=>this.fetch(t,r),onError:t=>this._events.emit("error",t),compress:t=>this.compressPayload(t)})),this._v1Sender}getLibraryVersion(){return ulu}get metrics(){return this._metrics||(this._metrics=new TWt(this,$tn(this.options.metrics),this._logger)),this._metrics}initializeSpanContextManager(){return new RWt}hostResourceAttributes(){return{}}get _spanContextManager(){return this._spanContext||(this._spanContext=this.initializeSpanContextManager()),this._spanContext}get _tracesPipeline(){if(this.options.traces)return this._traces||(this._traces=new DWt(this,dYo(this.options.traces,this.hostResourceAttributes(),this._logger),this._logger,()=>this._tracingContext(),this._spanContextManager,()=>this.scheduleDebouncedFlush())),this._traces}_tracingContext(){let t=this.context?.get();return{distinctId:t?.distinctId,sessionId:t?.sessionId}}startSpan(t,r){return this._tracesPipeline?.startSpan(t,r)??Nwe(r,this._spanContextManager.active())}withSpan(t,r,n){let i=typeof r=="function"?void 0:r,o=typeof r=="function"?r:n,s=this._tracesPipeline;return s?i?s.withSpan(t,i,o):s.withSpan(t,o):BWt(this._spanContextManager,Nwe(i,this._spanContextManager.active()),o)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getEvaluationRuntime(){return"server"}getCommonEventProperties(){let t=super.getCommonEventProperties();return(this.options.isServer??!0)&&(t.$is_server=!0),t}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}_warnIfInvalidCapture(t,r,n){typeof t=="string"&&this._logger.warn(r),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn(n)}_sendPreparedEvent(t,r,n,i,o){return this.addPendingPromise(this._prepareEventMessage(r,i).then(({distinctId:s,event:a,properties:c,options:l})=>{let u={timestamp:l.timestamp,disableGeoip:l.disableGeoip,uuid:l.uuid},p={distinctId:s,event:a,properties:{...c,...this.getCommonEventProperties()}};return n?this.sendImmediate(t,p,u,o):this.enqueue(t,p,u,o)}).catch(s=>{s&&console.error(s)}))}_capturePreparedEvent(t,r){return this._sendPreparedEvent("capture",t,r)}capture(t){this._warnIfInvalidCapture(t,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(t,!1)}async captureImmediate(t){return this._warnIfInvalidCapture(t,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(t,!0)}captureAi(t){if(this.disabled)return;let r=SVe(t.uuid,Z2);return this._sendPreparedAiEvent({...t,uuid:r},!1),r}async captureAiImmediate(t){if(this.disabled)return;let r=SVe(t.uuid,Z2);return await this._sendPreparedAiEvent({...t,uuid:r},!0),r}_sendPreparedAiEvent(t,r){return typeof t?.event=="string"&&!t.event.startsWith("$ai_")&&this._logger.debug(`captureAi called with non-AI event ${t.event}; routing it to the AI endpoint anyway.`),this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",t,r,void 0,BVe)}identify({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,u={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};this._sendPreparedEvent("identify",{distinctId:t,event:"$identify",properties:u,disableGeoip:n},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,u={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};await this._sendPreparedEvent("identify",{distinctId:t,event:"$identify",properties:u,disableGeoip:n},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:t,properties:r={},propertiesOnce:n={}}){if(Object.keys(r).length===0&&Object.keys(n).length===0)return;let i={};Object.keys(r).length>0&&(i.$set=r),Object.keys(n).length>0&&(i.$set_once=n),this.capture({distinctId:t,event:"$set",properties:i})}unsetPersonProperties({distinctId:t,properties:r}){let n=hEh(r);n.length!==0&&this.capture({distinctId:t,event:"$set",properties:{$unset:n}})}alias(t){this._sendPreparedEvent("alias",{distinctId:t.distinctId,event:"$create_alias",properties:{distinct_id:t.distinctId,alias:t.alias},disableGeoip:t.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(t){await this._sendPreparedEvent("alias",{distinctId:t.distinctId,event:"$create_alias",properties:{distinct_id:t.distinctId,alias:t.alias},disableGeoip:t.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}getFeatureFlagEvaluationRuntime(t){return this.featureFlagsPoller?.getEvaluationRuntimeForFlag(t)}getFeatureFlagKeysByEvaluationRuntime(t){return this.featureFlagsPoller?.getFlagKeysByEvaluationRuntime(t)??[]}async waitForLocalEvaluationReady(t=Slu){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let n=setTimeout(()=>{i(),r(!1)},t),i=this._events.on("localEvaluationFlagsLoaded",o=>{clearTimeout(n),i(),r(o>0)})})}_resolveDistinctId(t,r){return typeof t=="string"?{distinctId:t,options:r}:{distinctId:this.context?.get()?.distinctId,options:t}}async _getFeatureFlagResult(t,r,n={},i){if(this.disabled)return void this._logger.warn("The client is disabled");let o=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let D=this._flagOverrides[t];if(D===void 0)return;let R=this._payloadOverrides?.[t];return{key:t,enabled:D!==!1,variant:typeof D=="string"?D:void 0,payload:R}}let{groups:s,disableGeoip:a}=n,{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=n,p=this.addLocalPersonAndGroupProperties(r,s,l,u);l=p.allPersonProperties,u=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,s,this.personPropertiesForLocalEvaluation(r,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let f,m=!1,g,A,b,I,C,x,S;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let D=this.featureFlagsPoller?.featureFlagsByKey[t];if(D)try{let R=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(D,d,{matchValue:i});if(R){m=!0;let O=R.value;I=D.id,x="Evaluated locally",S=D.has_experiment,f={key:t,enabled:O!==!1,variant:typeof O=="string"?O:void 0,payload:R.payload??void 0,reason:x,reasonCode:D.active===!1?"flag_disabled":void 0}}}catch(R){if(R instanceof _re||R instanceof Gl)this._logger?.info(`${R.name} when computing flag locally: ${t}: ${R.message}`);else throw R}}if(!m&&!c){let D=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,l,u,a,[t]);if(D===void 0)b=Ahe.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=D.minimalFlagCalledEvents===!0,g=D.requestId,A=D.evaluatedAt;let R=[];D.errorsWhileComputingFlags&&R.push(Ahe.ERRORS_WHILE_COMPUTING),D.quotaLimited?.includes("feature_flags")&&R.push(Ahe.QUOTA_LIMITED);let O=D.flags[t];if(O===void 0)R.push(Ahe.FLAG_MISSING);else{I=O.metadata?.id,C=O.metadata?.version,x=O.reason?.description??O.reason?.code,S=O.metadata?.has_experiment;let j;if(O.metadata?.payload!==void 0)try{j=JSON.parse(O.metadata.payload)}catch{j=O.metadata.payload}f={key:t,enabled:O.enabled,variant:O.variant??void 0,payload:j,reason:x,reasonCode:O.reason?.code}}R.length>0&&(b=R.join(","))}}if(o){let D=f===void 0?void 0:f.enabled===!1?!1:f.variant??!0,R={$feature_flag:t,$feature_flag_response:D,$feature_flag_id:I,$feature_flag_version:C,$feature_flag_reason:x,locally_evaluated:m,[`$feature/${t}`]:D,$feature_flag_request_id:g,$feature_flag_evaluated_at:m?Date.now():A};if(S!==void 0&&(R.$feature_flag_has_experiment=S),m&&this.featureFlagsPoller){let O=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();O!==void 0&&(R.$feature_flag_definitions_loaded_at=O)}b&&(R.$feature_flag_error=b),this._captureFlagCalledEventIfNeeded({distinctId:r,key:t,response:D,groups:s,disableGeoip:a,properties:R})}return f!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(f={...f,payload:this._payloadOverrides[t]}),f}async getFeatureFlag(t,r,n){Arn("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(i!==void 0)return i.enabled===!1?!1:i.variant??!0}async getFeatureFlagPayload(t,r,n,i){if(Arn("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request."),this._payloadOverrides!==void 0&&t in this._payloadOverrides)return this._payloadOverrides[t];let o=await this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:!1},n);if(o!==void 0)return o.payload??null}async getFeatureFlagResult(t,r,n){let{distinctId:i,options:o}=this._resolveDistinctId(r,n);return i?this._getFeatureFlagResult(t,i,{...o,sendFeatureFlagEvents:o?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()")}async getRemoteConfigPayload(t){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let r=await this._requestRemoteConfigPayload(t);if(!r)return;let n=await r.json();if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}async isFeatureEnabled(t,r,n){Arn("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});return i===void 0?void 0:i.enabled===!1?!1:!!(i.variant??!0)||!1}async getAllFlags(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);return n?(await this.getAllFlagsAndPayloads(n,i)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);if(!n)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:o,disableGeoip:s,flagKeys:a}=i||{},{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,l,u);l=p.allPersonProperties,u=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),m={},g={},A=!0;if(f&&(m=f.response,g=f.payloads,A=f.fallbackToFlags),A&&!c){let b=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,l,u,s,a);m={...m,...b.flags||{}},g={...g,...b.payloads||{}}}return this._flagOverrides!==void 0&&(m={...m,...this._flagOverrides}),this._payloadOverrides!==void 0&&(g={...g,...this._payloadOverrides}),{featureFlags:m,featureFlagPayloads:g}}async evaluateFlags(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);if(!n)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new zwe({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new zwe({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,flags:{}});let{groups:o,disableGeoip:s}=i||{},a=i?.flagKeys??void 0;if(a?.length===0)return new zwe({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:{}});let{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,l,u);l=p.allPersonProperties,u=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=a?new Set(a):void 0,m={},g,A,b=!1,I=!1,C=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),x=new Set;if(C)for(let[D,R]of Object.entries(C.response)){let O=this.featureFlagsPoller?.featureFlagsByKey[D];m[D]={key:D,enabled:R!==!1,variant:typeof R=="string"?R:void 0,payload:C.payloads[D],id:O?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:O?.has_experiment},x.add(D)}let S=f!==void 0&&Array.from(f).some(D=>this.featureFlagsPoller?.featureFlagsByKey[D]===void 0);if((C?C.fallbackToFlags||S:!0)&&!c){let D=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,l,u,s,a);if(D){this._minimalFlagCalledEvents=D.minimalFlagCalledEvents===!0,g=D.requestId,A=D.evaluatedAt,b=!!D.errorsWhileComputingFlags,I=Array.isArray(D.quotaLimited)&&D.quotaLimited.includes("feature_flags");for(let[R,O]of Object.entries(D.flags)){if(x.has(R))continue;let j;if(O.metadata?.payload!==void 0)try{j=JSON.parse(O.metadata.payload)}catch{j=O.metadata.payload}m[R]={key:R,enabled:O.enabled,variant:O.variant,payload:j,id:O.metadata?.id,version:O.metadata?.version,reason:O.reason?.description??O.reason?.code,locallyEvaluated:!1,hasExperiment:O.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[D,R]of Object.entries(this._flagOverrides)){if(R===void 0){delete m[D];continue}let O=m[D];m[D]={key:D,enabled:R!==!1,variant:typeof R=="string"?R:void 0,payload:O?.payload,id:O?.id,version:O?.version,reason:O?.reason,locallyEvaluated:O?.locallyEvaluated??!1,hasExperiment:O?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[D,R]of Object.entries(this._payloadOverrides)){let O=m[D];O&&(m[D]={...O,payload:R})}if(f!==void 0)for(let D of Object.keys(m))f.has(D)||delete m[D];return new zwe({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:m,requestId:g,evaluatedAt:A,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:b,quotaLimited:I})}_shouldSendMinimalFlagCalledEvent(t,r){return t==="$feature_flag_called"&&this._minimalFlagCalledEvents&&r.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(t){let{distinctId:r,key:n,response:i,groups:o,disableGeoip:s,properties:a}=t,c=o&&Object.keys(o).length>0?`_${JSON.stringify(Object.entries(o).sort(([u],[p])=>u<p?-1:u>p?1:0))}`:"",l=`${n}_${i}${c}`;r in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[r].has(l)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),this.distinctIdHasSentFlagCalls[r]instanceof Set?this.distinctIdHasSentFlagCalls[r].add(l):this.distinctIdHasSentFlagCalls[r]=new Set([l]),this.capture({distinctId:r,event:"$feature_flag_called",properties:a,groups:o,disableGeoip:s}))}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:t=>this._captureFlagCalledEventIfNeeded(t),logWarning:t=>{this.options.featureFlagsLogWarnings!==!1&&console.warn(`[PostHog] ${t}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){this._sendPreparedEvent("capture",{distinctId:i||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{}},disableGeoip:o},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){await this._sendPreparedEvent("capture",{distinctId:i||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{}},disableGeoip:o},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(t){let r=n=>Object.fromEntries(n.map(i=>[i,!0]));if(t===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(t)){this._flagOverrides=r(t);return}if(this._isFeatureFlagOverrideOptions(t)){"flags"in t&&(t.flags===!1?this._flagOverrides=void 0:Array.isArray(t.flags)?this._flagOverrides=r(t.flags):t.flags!==void 0&&(this._flagOverrides={...t.flags})),"payloads"in t&&(t.payloads===!1?this._payloadOverrides=void 0:t.payloads!==void 0&&(this._payloadOverrides={...t.payloads}));return}this._flagOverrides={...t}}_isFeatureFlagOverrideOptions(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let r=t;if("flags"in r){let n=r.flags;if(n===!1||Array.isArray(n)||typeof n=="object"&&n!==null)return!0}if("payloads"in r){let n=r.payloads;if(n===!1||typeof n=="object"&&n!==null)return!0}return!1}withContext(t,r,n){return this.context?this.context.run(t,r,n):r()}getContext(){return this.context?.get()}enterContext(t,r){this.context?.enter(t,r)}async _shutdown(t){let r=Date.now()+(t??3e4),n=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown(),this._metrics&&(await Fwe(this._metrics.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._metrics.reset()),this._traces&&(await Fwe(this._traces.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._traces.reset());try{return await super._shutdown(Math.max(0,r-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},n?.()}}async _requestRemoteConfigPayload(t){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config?token=${encodeURIComponent(this.apiKey)}`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let o=new AbortController;i=$2(()=>{o.abort()},this.options.requestTimeout),n.signal=o.signal}try{return await this.fetch(r,n)}catch(o){this._events.emit("error",o);return}finally{i&&clearTimeout(i)}}extractPropertiesFromEvent(t,r){if(!t)return{personProperties:{},groupProperties:{}};let n={},i={};for(let[o,s]of Object.entries(t))if(Tau(s)&&r&&o in r){let a={};for(let[c,l]of Object.entries(s))a[String(c)]=String(l);i[String(o)]=a}else n[String(o)]=String(s);return{personProperties:n,groupProperties:i}}async getFeatureFlagsForEvent(t,r,n,i){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let o=i?.personProperties||{},s=i?.groupProperties||{},a=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let l={};for(let[u,p]of Object.entries(r||{}))l[u]=String(p);return await this.getAllFlags(t,{groups:l,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let l={};for(let[u,p]of Object.entries(r||{}))l[u]=String(p);return await this.getAllFlags(t,{groups:l,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(t,r,o,s,n)).flags}addLocalPersonAndGroupProperties(t,r,n,i){let o={...n||{}},s={};if(r)for(let a of Object.keys(r))s[a]={$group_key:r[a],...i?.[a]||{}};return{allPersonProperties:o,allGroupProperties:s}}personPropertiesForLocalEvaluation(t,r){return{distinct_id:t,...r||{}}}createFeatureFlagEvaluationContext(t,r,n,i){return{distinctId:t,groups:r||{},personProperties:n||{},groupProperties:i||{},evaluationCache:{}}}captureException(t,r,n,i,o){if(!PVe.isPreviouslyCapturedError(t)){let s=new Error("PostHog syntheticException");this.addPendingPromise(PVe.buildEventMessage(this.getErrorPropertiesBuilder(),t,{syntheticException:s},r,n).then(a=>this._capturePreparedEvent({...a,uuid:i,flags:o},!1)))}}async captureExceptionImmediate(t,r,n,i){if(!PVe.isPreviouslyCapturedError(t)){let o=new Error("PostHog syntheticException");return this.addPendingPromise(PVe.buildEventMessage(this.getErrorPropertiesBuilder(),t,{syntheticException:o},r,n).then(s=>this.captureImmediate({...s,flags:i})))}}async prepareEventMessage(t){return this._prepareEventMessage(t)}async _prepareEventMessage(t,r={}){let{distinctId:n,event:i,properties:o,groups:s,flags:a,sendFeatureFlags:c,timestamp:l,disableGeoip:u,uuid:p}=t,d=this.context?.get(),f=r.includeContextProperties??!0,m=n||d?.distinctId,g=f?{...this.props,...d?.properties||{},...o||{}}:{...o||{}};m||(m=Z2(),g.$process_person_profile=!1),f&&d?.sessionId&&!g.$session_id&&(g.$session_id=d.sessionId);let A=this._shouldSendMinimalFlagCalledEvent(i,g)?hWt(g):g,b=this._runBeforeSend({distinctId:m,event:i,properties:A,groups:s,flags:a,sendFeatureFlags:c,timestamp:l,disableGeoip:u,uuid:p});if(!b)return Promise.reject(null);let I=await Promise.resolve().then(async()=>{if(a)return c&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),a._getEventProperties();if(c){Arn("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead \u2014 it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");let C=typeof c=="object"?c:void 0,x=await this.getFeatureFlagsForEvent(b.distinctId,s,u,C);return gEh(x)}return{}}).catch(()=>({})).then(C=>{let x=b.groups||s;return{...C,...b.properties||{},...x!==void 0&&Object.keys(x).length>0?{$groups:x}:{}}});return b.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof I.$raw_user_agent=="string"&&Pau(I.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(b.event="$bot_pageview",I.$browser_type="bot"),{distinctId:b.distinctId,event:b.event,properties:I,options:{timestamp:b.timestamp,disableGeoip:b.disableGeoip,uuid:b.uuid}}}_runBeforeSend(t){let r=this.options.before_send;if(!r)return t;let n=Array.isArray(r)?r:[r],i=t;for(let o of n)try{if(i=o(i),!i)return this._logger.info(`Event '${t.event}' was rejected in beforeSend function`),null;if(!i.properties||Object.keys(i.properties).length===0){let s=`Event '${i.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(s)}}catch(s){return this._logger.error(`Error in before_send function for event '${t.event}':`,s),null}return i}};var Tlu=require("async_hooks"),brn=class{constructor(){this.storage=new Tlu.AsyncLocalStorage}get(){return this.storage.getStore()}run(t,r,n){return this.storage.run(this.resolve(t,n),r)}enter(t,r){this.storage.enterWith(this.resolve(t,r))}resolve(t,r){if(r?.fresh===!0)return t;let n=this.get()||{};return{distinctId:t.distinctId??n.distinctId,sessionId:t.sessionId??n.sessionId,properties:{...n.properties||{},...t.properties||{}}}}};var Olu=require("async_hooks"),Ern=class{active(){return this._storage.getStore()}with(t,r){return this._storage.run(t,r)}constructor(){this._storage=new Olu.AsyncLocalStorage}};var Plu=require("zlib"),Blu=require("util"),AEh=(0,Blu.promisify)(Plu.gzip);async function Dlu(e,t=!0){try{let r=await AEh(e);return new Uint8Array(r)}catch(r){return t&&console.error("Failed to gzip compress data",r),null}}var Irn=require("os");function Rlu(){let e,t;try{e=(0,Irn.platform)(),t=(0,Irn.release)()}catch{}return rYo(e,t)}var klu="posthog-node";function yEh(e,{organization:t,projectId:r,prefix:n,severityAllowList:i=["error"],sendExceptionsToPostHog:o=!0}={}){return s=>{if(!(i==="*"||i.includes(s.level)))return s;s.tags||(s.tags={});let c=s.tags[vYo.POSTHOG_ID_TAG];if(c===void 0)return s;let l=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${c}`,l).toString();s.tags["PostHog Person URL"]=u;let p=s.exception?.values||[],d=p.map(g=>({...g,stacktrace:g.stacktrace?{...g.stacktrace,type:"raw",frames:(g.stacktrace.frames||[]).map(A=>({...A,platform:"node:javascript"}))}:void 0})),f={$exception_message:p[0]?.value||s.message,$exception_type:p[0]?.type,$exception_level:s.level,$exception_list:d,$sentry_event_id:s.event_id,$sentry_exception:s.exception,$sentry_exception_message:p[0]?.value||s.message,$sentry_exception_type:p[0]?.type,$sentry_tags:s.tags},m=LT.getInjectedReleaseId();return m&&(f.$release_id=m),t&&r&&(f.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+s.event_id),o&&e.capture({event:"$exception",distinctId:c,properties:f}),s}}var vYo=class{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(t,r,n,i,o){this.name=klu,this.name=klu,this.setupOnce=function(s,a){let c=a()?.getClient()?.getDsn()?.projectId;s(yEh(t,{organization:r,projectId:c,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o??!0}))}}};var Ure=class extends yrn{getLibraryId(){return"posthog-node"}compressPayload(t){return Dlu(t,this.isDebug)}initializeContext(){return new brn}initializeSpanContextManager(){return new Ern}hostResourceAttributes(){return Rlu()}createErrorPropertiesBuilder(){return new LT.ErrorPropertiesBuilder([new LT.EventCoercer,new LT.ErrorCoercer,new LT.ObjectCoercer,new LT.StringCoercer,new LT.PrimitiveCoercer],LT.createStackParser("node:javascript",LT.nodeStackLineParser),[vau(),t=>olu(t,void 0,this._logger),llu()])}};function Flu(e){return e==null||!e.enabled?!1:e.variant==null||e.variant==="true"}var vrn=class{isEnabled(){return Promise.resolve(!1)}getCachedValue(){}flush(){return Promise.resolve()}},bEh="feature_flag_evaluated",EEh=3e3,IEh=3e3,Crn=class{evaluator;environment;sendFeatureFlagEvents;pending=new Map;resolved=new Map;constructor({environment:t,sendFeatureFlagEvents:r,posthogApiKey:n,evaluator:i}){this.environment=t,this.sendFeatureFlagEvents=r,this.evaluator=i??new Ure(n??"",{featureFlagsRequestTimeoutMs:EEh,isServer:!1})}isEnabled(t,r){let n=Nlu(t,r),i=this.pending.get(n);if(i!=null)return i;let o=this.evaluateAndRemember(t,r,n);return this.pending.set(n,o),o}async evaluateAndRemember(t,r,n){let i=await this.evaluate(t,r);return this.resolved.set(n,i),i}getCachedValue(t,r){return this.resolved.get(Nlu(t,r))}async flush(){if(!this.sendFeatureFlagEvents)return;let t;try{await Promise.race([this.flushAfterPendingEvaluations(),new Promise(r=>{t=setTimeout(r,IEh),t.unref()})])}catch{}finally{clearTimeout(t)}}async flushAfterPendingEvaluations(){await Promise.allSettled(this.pending.values()),await this.evaluator.flush()}async evaluate(t,r){let{org:n}=r,i=CEh(r,this.environment),o;try{o=await this.evaluator.getFeatureFlagResult(t,CYo(n),{personProperties:i,groups:{organization:n},groupProperties:{organization:i},sendFeatureFlagEvents:!1})}catch{return!1}return this.sendFeatureFlagEvents&&this.captureFlagUsage({flag:t,org:n,result:o,properties:i}),Flu(o)}captureFlagUsage({flag:t,org:r,result:n,properties:i}){let o=vEh(n),s={...i,...n?.reason!=null?{$feature_flag_reason:n.reason}:{},version:"5.226.2"};this.tryCapture({distinctId:CYo(r),event:"$feature_flag_called",groups:{organization:r},properties:{...s,$feature_flag:t,$feature_flag_response:o,[`$feature/${t}`]:o}}),this.tryCapture({distinctId:CYo(r),event:bEh,groups:{organization:r},properties:{...s,flag:t,response:o,enabled:Flu(n)}})}tryCapture(t){try{this.evaluator.capture(t)}catch{}}};function vEh(e){if(e!=null)return e.enabled?e.variant??!0:!1}function CYo(e){return`org:${e}`}function CEh({org:e,generator:t,language:r},n){return{org:e,environment:n,...t!=null?{generator:t}:{},...r!=null?{language:r}:{}}}function Nlu(e,{org:t,generator:r,language:n}){return JSON.stringify([e,t,r??null,n??null])}var xrn;function Srn(){return xrn==null&&(xrn=xEh()),xrn}async function xYo(){await xrn?.flush()}function xEh(){let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";return e==null||e.trim().length===0?new vrn:new Crn({posthogApiKey:e,environment:gJ(),sendFeatureFlagEvents:Ttn()})}var wrn=class{posthog;constructor({posthogApiKey:t}){this.posthog=new Ure(t,{isServer:!1})}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"5.226.2",usingAccessToken:!0,cliReleaseEnvironment:gJ(),...Rfe()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:{...t.properties,cliReleaseEnvironment:gJ()}})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}};var NWt=class{async sendEvent(){}async sendAutomationEvent(){}async identify(){}async flush(){}};sf();tr();var Zut=require("fs/promises"),jlu=require("os"),zlu=require("path");TUe();var SEh="id",wEh=".fern",jWt=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new Ure(r,{isServer:!1}),this.userId=t==null?void 0:JJi(t),this.token=t}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){let r=await this.getUserEmail();this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"5.226.2",...t,...t.properties,usingAccessToken:!1,cliReleaseEnvironment:gJ(),agent:Dpr(),...r!=null?{userEmail:r}:{},...Rfe()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:{...t.properties,cliReleaseEnvironment:gJ()}})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}userEmail;async getUserEmail(){if(this.userEmail!==null){if(this.userEmail!=null)return this.userEmail;if(this.token==null){this.userEmail=null;return}try{let t=await Dl({token:this.token.value}).user.getMyself();if(t.ok&&t.body.email!=null)return this.userEmail=t.body.email,this.userEmail}catch{}this.userEmail=null}}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Dw(),r=Re(Zt.of((0,jlu.homedir)()),be.of(wEh),be.of(SEh));try{await Ut(r)?this.persistedDistinctId=(await(0,Zut.readFile)(r)).toString():(await(0,Zut.mkdir)((0,zlu.dirname)(r),{recursive:!0}),await(0,Zut.writeFile)(r,t),this.persistedDistinctId=t)}catch{this.persistedDistinctId=t}}return this.persistedDistinctId}};var SYo;async function zWt(){return SYo==null&&(SYo=await TEh()),SYo}async function TEh(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";if(e==null||!Ttn())return new NWt;let t=await uZe();return t!=null?new jWt({token:t,posthogApiKey:e}):await jz()!=null?new wrn({posthogApiKey:e}):new jWt({token:void 0,posthogApiKey:e})}catch{return new NWt}}tn();mt();Bt();_Q();var QWt=Ae(require("process"),1);yKe();var Llu=Ae(s$i(),1),_lu=Ae(Mlu(),1);function _T(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=w7(e),e.length===0))return 0;e=e.replace((0,_lu.default)()," ");let r=t.ambiguousIsNarrow?1:2,n=0;for(let i of e){let o=i.codePointAt(0);if(o<=31||o>=127&&o<=159||o>=768&&o<=879)continue;switch(Llu.default.eastAsianWidth(i)){case"F":case"W":n+=2;break;case"A":n+=r;break;default:n+=1}}return n}tn();function Trn(e){let t=0;for(let r of e.split(`
|
|
3499
3499
|
`))t=Math.max(t,_T(r));return t}var auu=Ae(TYo(),1);var PEh=/[\p{Lu}]/u,BEh=/[\p{Ll}]/u,Glu=/^[\p{Lu}](?![\p{Lu}])/gu,Hlu=/([\p{Alpha}\p{N}_]|$)/u,OYo=/[_.\- ]+/,DEh=new RegExp("^"+OYo.source),qlu=new RegExp(OYo.source+Hlu.source,"gu"),Wlu=new RegExp("\\d+"+Hlu.source,"gu"),REh=(e,t,r,n)=>{let i=!1,o=!1,s=!1,a=!1;for(let c=0;c<e.length;c++){let l=e[c];a=c>2?e[c-3]==="-":!0,i&&PEh.test(l)?(e=e.slice(0,c)+"-"+e.slice(c),i=!1,s=o,o=!0,c++):o&&s&&BEh.test(l)&&(!a||n)?(e=e.slice(0,c-1)+"-"+e.slice(c-1),s=o,o=!1,i=!0):(i=t(l)===l&&r(l)!==l,s=o,o=r(l)===l&&t(l)!==l)}return e},kEh=(e,t)=>(Glu.lastIndex=0,e.replace(Glu,r=>t(r))),FEh=(e,t)=>(qlu.lastIndex=0,Wlu.lastIndex=0,e.replace(qlu,(r,n)=>t(n)).replace(Wlu,r=>t(r)));function PYo(e,t){if(!(typeof e=="string"||Array.isArray(e)))throw new TypeError("Expected the input to be `string | string[]`");if(t={pascalCase:!1,preserveConsecutiveUppercase:!1,...t},Array.isArray(e)?e=e.map(o=>o.trim()).filter(o=>o.length).join("-"):e=e.trim(),e.length===0)return"";let r=t.locale===!1?o=>o.toLowerCase():o=>o.toLocaleLowerCase(t.locale),n=t.locale===!1?o=>o.toUpperCase():o=>o.toLocaleUpperCase(t.locale);return e.length===1?OYo.test(e)?"":t.pascalCase?n(e):r(e):(e!==r(e)&&(e=REh(e,r,n,t.preserveConsecutiveUppercase)),e=e.replace(DEh,""),e=t.preserveConsecutiveUppercase?kEh(e,r):r(e),t.pascalCase&&(e=n(e.charAt(0))+e.slice(1)),FEh(e,n))}var kYo=Ae(Jlu(),1);yKe();var Ylu=(e=0)=>t=>`\x1B[${t+e}m`,Xlu=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,Zlu=(e=0)=>(t,r,n)=>`\x1B[${38+e};2;${t};${r};${n}m`,e0={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},XgC=Object.keys(e0.modifier),QEh=Object.keys(e0.color),MEh=Object.keys(e0.bgColor),ZgC=[...QEh,...MEh];function LEh(){let e=new Map;for(let[t,r]of Object.entries(e0)){for(let[n,i]of Object.entries(r))e0[n]={open:`\x1B[${i[0]}m`,close:`\x1B[${i[1]}m`},r[n]=e0[n],e.set(i[0],i[1]);Object.defineProperty(e0,t,{value:r,enumerable:!1})}return Object.defineProperty(e0,"codes",{value:e,enumerable:!1}),e0.color.close="\x1B[39m",e0.bgColor.close="\x1B[49m",e0.color.ansi=Ylu(),e0.color.ansi256=Xlu(),e0.color.ansi16m=Zlu(),e0.bgColor.ansi=Ylu(10),e0.bgColor.ansi256=Xlu(10),e0.bgColor.ansi16m=Zlu(10),Object.defineProperties(e0,{rgbToAnsi256:{value(t,r,n){return t===r&&r===n?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(r/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(t){let r=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!r)return[0,0,0];let[n]=r;n.length===3&&(n=[...n].map(o=>o+o).join(""));let i=Number.parseInt(n,16);return[i>>16&255,i>>8&255,i&255]},enumerable:!1},hexToAnsi256:{value:t=>e0.rgbToAnsi256(...e0.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let r,n,i;if(t>=232)r=((t-232)*10+8)/255,n=r,i=r;else{t-=16;let a=t%36;r=Math.floor(t/36)/5,n=Math.floor(a/6)/5,i=a%6/5}let o=Math.max(r,n,i)*2;if(o===0)return 30;let s=30+(Math.round(i)<<2|Math.round(n)<<1|Math.round(r));return o===2&&(s+=60),s},enumerable:!1},rgbToAnsi:{value:(t,r,n)=>e0.ansi256ToAnsi(e0.rgbToAnsi256(t,r,n)),enumerable:!1},hexToAnsi:{value:t=>e0.ansi256ToAnsi(e0.hexToAnsi256(t)),enumerable:!1}}),e0}var _Eh=LEh(),$lu=_Eh;var Orn=new Set(["\x1B","\x9B"]),UEh=39,DYo="\x07",ruu="[",VEh="]",nuu="m",RYo=`${VEh}8;;`,euu=e=>`${Orn.values().next().value}${ruu}${e}${nuu}`,tuu=e=>`${Orn.values().next().value}${RYo}${e}${DYo}`,GEh=e=>e.split(" ").map(t=>_T(t)),BYo=(e,t,r)=>{let n=[...t],i=!1,o=!1,s=_T(w7(e[e.length-1]));for(let[a,c]of n.entries()){let l=_T(c);if(s+l<=r?e[e.length-1]+=c:(e.push(c),s=0),Orn.has(c)&&(i=!0,o=n.slice(a+1).join("").startsWith(RYo)),i){o?c===DYo&&(i=!1,o=!1):c===nuu&&(i=!1);continue}s+=l,s===r&&a<n.length-1&&(e.push(""),s=0)}!s&&e[e.length-1].length>0&&e.length>1&&(e[e.length-2]+=e.pop())},qEh=e=>{let t=e.split(" "),r=t.length;for(;r>0&&!(_T(t[r-1])>0);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},WEh=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let n="",i,o,s=GEh(e),a=[""];for(let[l,u]of e.split(" ").entries()){r.trim!==!1&&(a[a.length-1]=a[a.length-1].trimStart());let p=_T(a[a.length-1]);if(l!==0&&(p>=t&&(r.wordWrap===!1||r.trim===!1)&&(a.push(""),p=0),(p>0||r.trim===!1)&&(a[a.length-1]+=" ",p++)),r.hard&&s[l]>t){let d=t-p,f=1+Math.floor((s[l]-d-1)/t);Math.floor((s[l]-1)/t)<f&&a.push(""),BYo(a,u,t);continue}if(p+s[l]>t&&p>0&&s[l]>0){if(r.wordWrap===!1&&p<t){BYo(a,u,t);continue}a.push("")}if(p+s[l]>t&&r.wordWrap===!1){BYo(a,u,t);continue}a[a.length-1]+=u}r.trim!==!1&&(a=a.map(l=>qEh(l)));let c=[...a.join(`
|
|
3500
3500
|
`)];for(let[l,u]of c.entries()){if(n+=u,Orn.has(u)){let{groups:d}=new RegExp(`(?:\\${ruu}(?<code>\\d+)m|\\${RYo}(?<uri>.*)${DYo})`).exec(c.slice(l).join(""))||{groups:{}};if(d.code!==void 0){let f=Number.parseFloat(d.code);i=f===UEh?void 0:f}else d.uri!==void 0&&(o=d.uri.length===0?void 0:d.uri)}let p=$lu.codes.get(Number(i));c[l+1]===`
|
|
3501
3501
|
`?(o&&(n+=tuu("")),i&&p&&(n+=euu(p))):u===`
|
|
@@ -4165,7 +4165,7 @@ ${ut.stack}`),ee&&m?.({event:"reload",ok:!1,durationMs:Date.now()-we,error:rn(ut
|
|
|
4165
4165
|
|
|
4166
4166
|
`),o.add(u),l.on("close",()=>o.delete(u));return}s.requestStarted(),u.once("close",()=>s.requestFinished());let d=iTp(l.url,i),f=Q2s.default.request(d!=null?{host:"127.0.0.1",port:n,method:l.method,path:d,headers:l.headers}:{host:"127.0.0.1",port:t,method:l.method,path:l.url,headers:{...l.headers,[cTp]:r}},m=>{let g={...m.headers};if(!((g["content-type"]??"").includes("text/html")&&g["content-encoding"]==null)){u.writeHead(m.statusCode??502,g),m.pipe(u);return}let b=[];m.on("data",I=>b.push(I)),m.on("end",()=>{let I=Buffer.concat(b).toString("utf-8"),C=I.lastIndexOf("</body>"),x=C>=0?`${I.slice(0,C)}${sTp}${I.slice(C)}`:`${I}${sTp}`,S=Buffer.from(x,"utf-8");delete g["transfer-encoding"],g["content-length"]=S.byteLength.toString(),u.writeHead(m.statusCode??502,g),u.end(S)}),m.on("error",()=>u.destroy())});f.on("error",m=>{u.headersSent||u.writeHead(502,{"content-type":"text/plain"}),u.end(`Astro preview server unavailable: ${m.message}
|
|
4167
4167
|
`)}),l.pipe(f)})}function inA({req:e,res:t,pathname:r,port:n,serverInfo:i,onShutdownRequest:o}){let s=(c,l,u={})=>{t.writeHead(c,{"content-type":"application/json","cache-control":"no-store",...u}),t.end(`${JSON.stringify(l)}
|
|
4168
|
-
`)},a=i_u({remoteAddress:e.socket.remoteAddress,host:e.headers.host,origin:e.headers.origin,controlHeader:e.headers[lSt],serverPort:n});if(a!=null){s(403,{error:a});return}if(r===aSt){if(e.method!=="GET"){s(405,{error:"use GET"},{allow:"GET"});return}s(200,i);return}if(e.method!=="POST"){s(405,{error:"use POST"},{allow:"POST"});return}t.once("finish",o),s(202,{stopping:!0},{connection:"close"})}function onA(){return new Promise((e,t)=>{let r=M2s.default.createServer();r.once("error",t),r.listen(0,"127.0.0.1",()=>{let n=r.address(),i=typeof n=="object"&&n!=null?n.port:void 0;r.close(()=>i!=null?e(i):t(new Error("could not allocate a port")))})})}function snA(e,t,r){let n=Date.now()+r;return new Promise((i,o)=>{let s=!1;t.on("exit",c=>{s=!0,o(new Error(`Astro preview server exited with code ${c} before becoming ready`))});let a=()=>{if(s)return;if(Date.now()>n){o(new Error("timed out waiting for the Astro preview server to become ready"));return}let c=M2s.default.connect(e,"127.0.0.1");c.once("connect",()=>{c.destroy(),i()}),c.once("error",()=>{c.destroy(),setTimeout(a,200)})};a()})}mt();Bt();var fTp=/^[a-z0-9-]+-preview-[a-z0-9-]+\.docs\.buildwithfern\.com$/i,uTp="docs.buildwithfern.com",pTp=62;function Fqe(e){let t=e.toLowerCase().trim();t.startsWith("https://")?t=t.slice(8):t.startsWith("http://")&&(t=t.slice(7));let r=t.indexOf("/");return r!==-1&&(t=t.slice(0,r)),fTp.test(t)}function Wtr({orgId:e,previewId:t}){let r=MX(t),n=`${e}-preview-${r}.${uTp}`;if(n.length<=pTp)return n;let i=`${e}-preview-`,o=pTp-i.length;if(o<8)throw new T({message:`Organization name "${e}" is too long to generate a valid preview URL`,code:T.Code.ValidationError});let a=r.slice(0,o).replace(/-+$/,"");return`${i}${a}.${uTp}`}mt();h0();sm();tr();UE();Bt();tn();var mNs=require("child_process"),SOp=Ae(mTp(),1),hNs=Ae(OCi(),1),gNs=Ae(require("fs"),1),yNs=require("fs/promises"),wOp=Ae(require("http"),1),TOp=Ae(require("os"),1),WCi=Ae(require("path"),1);lNs();h0();tr();var uNs=require("fs/promises");async function pNs(e,t){let r=new Map,{docsDefinition:n,translationPages:i,translationNavigationOverlays:o,translatedApiDefinitions:s,collectedFileIds:a,docsWorkspacePath:c,markdownFilesToPathName:l}=e,u=i!=null&&Object.keys(i).length>0,p=s!=null&&Object.keys(s).length>0;if(!u&&!p)return r;let d=n.config.translations?.defaultLocale,f=new Set([...Object.keys(i??{}),...Object.keys(s??{})]);for(let m of f){if(m===d)continue;let g=i?.[m]??{};try{let A=async le=>{let ae=go(c,le),he=Rn(c,be.of(`translations/${m}/${ae}`));return await Ut(he)?he:le},b=async le=>{let ae=await A(le),he=await(0,uNs.readFile)(ae,"utf-8"),xe=he.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/);return xe!=null?he.slice(xe[0].length):he},I=async le=>{let ae=await A(le);return(0,uNs.readFile)(ae,"utf-8")},C={};for(let[le,ae]of Object.entries(n.pages))ae!=null&&(C[le]=ae);for(let[le,ae]of Object.entries(g))try{let he=C[le],xe=Rn(c,be.of(le)),{markdown:Te}=await qk({markdown:ae,absolutePathToFernFolder:c,absolutePathToMarkdownFile:xe,context:t,markdownLoader:b}),pe=await G3({markdown:Te,absolutePathToFernFolder:c,absolutePathToMarkdownFile:xe,context:t,fileLoader:I}),ue=q3({markdown:pe,absolutePathToFernFolder:c,absolutePathToMarkdownFile:xe,context:t}),Pe=RO(ue);Pe=M3(Pe,a,l,{absolutePathToMarkdownFile:xe,absolutePathToFernFolder:c},t),C[le]={markdown:Pe,rawMarkdown:Pe,editThisPageUrl:he?.editThisPageUrl,editThisPageLaunch:he?.editThisPageLaunch}}catch(he){t.logger.warn(`Failed to process translated page "${le}" for locale "${m}": ${String(he)}. Falling back to base page.`)}let x=g8e(n.config.root,g,t),S=o?.[m],P=n.config.announcement,D=n.config.navbarLinks;S!=null&&(x=y8e(x,S),P=b8e(S)??P,S.navbarLinks!=null&&(D=S.navbarLinks));let R=n.apis,O=s?.[m],j=O,Y;if(O!=null&&x!=null){let le=m8e(x,R,O);le.size>0&&(t.logger.warn(`Translated API definition(s) [${Array.from(le).join(", ")}] for locale "${m}" diverge from the default-locale spec (e.g. changed OpenAPI tag names, operationIds, or paths, or a missing/added endpoint), so they can't be fully matched to the navigation tree. Serving the default-locale API for those (localized sidebar titles are still applied where they can be matched). For fully localized API reference content, translate only human-readable text and keep tag names/operationIds/paths identical to the base spec.`),j=Object.fromEntries(Object.entries(O).filter(([ae])=>!le.has(ae)))),Y=new Set(Object.keys(O).filter(ae=>!le.has(ae)))}let te=j!=null&&Object.keys(j).length>0?{...n.apis,...j}:n.apis;O!=null&&Object.keys(O).length>0&&x!=null&&(x=h8e(x,R,O,{rewritableApiIds:Y}));let ce={...n,apis:te,pages:C,config:{...n.config,root:x,announcement:P,navbarLinks:D,settings:E8e(n.config.settings,S)}};r.set(m,ce),t.logger.debug(`Computed translated definition for locale "${m}"`+(O!=null?` (with ${Object.keys(O).length} translated API(s))`:""))}catch(A){t.logger.warn(`Failed to compute translation for locale "${m}": ${String(A)}`)}}return r}tr();var RW=require("fs/promises"),bOp=require("os"),dNs=Ae(require("path"),1),kiA=".fern",FiA="logs",fNs=100*1024*1024;function NiA(){return"cli@5.226.
|
|
4168
|
+
`)},a=i_u({remoteAddress:e.socket.remoteAddress,host:e.headers.host,origin:e.headers.origin,controlHeader:e.headers[lSt],serverPort:n});if(a!=null){s(403,{error:a});return}if(r===aSt){if(e.method!=="GET"){s(405,{error:"use GET"},{allow:"GET"});return}s(200,i);return}if(e.method!=="POST"){s(405,{error:"use POST"},{allow:"POST"});return}t.once("finish",o),s(202,{stopping:!0},{connection:"close"})}function onA(){return new Promise((e,t)=>{let r=M2s.default.createServer();r.once("error",t),r.listen(0,"127.0.0.1",()=>{let n=r.address(),i=typeof n=="object"&&n!=null?n.port:void 0;r.close(()=>i!=null?e(i):t(new Error("could not allocate a port")))})})}function snA(e,t,r){let n=Date.now()+r;return new Promise((i,o)=>{let s=!1;t.on("exit",c=>{s=!0,o(new Error(`Astro preview server exited with code ${c} before becoming ready`))});let a=()=>{if(s)return;if(Date.now()>n){o(new Error("timed out waiting for the Astro preview server to become ready"));return}let c=M2s.default.connect(e,"127.0.0.1");c.once("connect",()=>{c.destroy(),i()}),c.once("error",()=>{c.destroy(),setTimeout(a,200)})};a()})}mt();Bt();var fTp=/^[a-z0-9-]+-preview-[a-z0-9-]+\.docs\.buildwithfern\.com$/i,uTp="docs.buildwithfern.com",pTp=62;function Fqe(e){let t=e.toLowerCase().trim();t.startsWith("https://")?t=t.slice(8):t.startsWith("http://")&&(t=t.slice(7));let r=t.indexOf("/");return r!==-1&&(t=t.slice(0,r)),fTp.test(t)}function Wtr({orgId:e,previewId:t}){let r=MX(t),n=`${e}-preview-${r}.${uTp}`;if(n.length<=pTp)return n;let i=`${e}-preview-`,o=pTp-i.length;if(o<8)throw new T({message:`Organization name "${e}" is too long to generate a valid preview URL`,code:T.Code.ValidationError});let a=r.slice(0,o).replace(/-+$/,"");return`${i}${a}.${uTp}`}mt();h0();sm();tr();UE();Bt();tn();var mNs=require("child_process"),SOp=Ae(mTp(),1),hNs=Ae(OCi(),1),gNs=Ae(require("fs"),1),yNs=require("fs/promises"),wOp=Ae(require("http"),1),TOp=Ae(require("os"),1),WCi=Ae(require("path"),1);lNs();h0();tr();var uNs=require("fs/promises");async function pNs(e,t){let r=new Map,{docsDefinition:n,translationPages:i,translationNavigationOverlays:o,translatedApiDefinitions:s,collectedFileIds:a,docsWorkspacePath:c,markdownFilesToPathName:l}=e,u=i!=null&&Object.keys(i).length>0,p=s!=null&&Object.keys(s).length>0;if(!u&&!p)return r;let d=n.config.translations?.defaultLocale,f=new Set([...Object.keys(i??{}),...Object.keys(s??{})]);for(let m of f){if(m===d)continue;let g=i?.[m]??{};try{let A=async le=>{let ae=go(c,le),he=Rn(c,be.of(`translations/${m}/${ae}`));return await Ut(he)?he:le},b=async le=>{let ae=await A(le),he=await(0,uNs.readFile)(ae,"utf-8"),xe=he.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/);return xe!=null?he.slice(xe[0].length):he},I=async le=>{let ae=await A(le);return(0,uNs.readFile)(ae,"utf-8")},C={};for(let[le,ae]of Object.entries(n.pages))ae!=null&&(C[le]=ae);for(let[le,ae]of Object.entries(g))try{let he=C[le],xe=Rn(c,be.of(le)),{markdown:Te}=await qk({markdown:ae,absolutePathToFernFolder:c,absolutePathToMarkdownFile:xe,context:t,markdownLoader:b}),pe=await G3({markdown:Te,absolutePathToFernFolder:c,absolutePathToMarkdownFile:xe,context:t,fileLoader:I}),ue=q3({markdown:pe,absolutePathToFernFolder:c,absolutePathToMarkdownFile:xe,context:t}),Pe=RO(ue);Pe=M3(Pe,a,l,{absolutePathToMarkdownFile:xe,absolutePathToFernFolder:c},t),C[le]={markdown:Pe,rawMarkdown:Pe,editThisPageUrl:he?.editThisPageUrl,editThisPageLaunch:he?.editThisPageLaunch}}catch(he){t.logger.warn(`Failed to process translated page "${le}" for locale "${m}": ${String(he)}. Falling back to base page.`)}let x=g8e(n.config.root,g,t),S=o?.[m],P=n.config.announcement,D=n.config.navbarLinks;S!=null&&(x=y8e(x,S),P=b8e(S)??P,S.navbarLinks!=null&&(D=S.navbarLinks));let R=n.apis,O=s?.[m],j=O,Y;if(O!=null&&x!=null){let le=m8e(x,R,O);le.size>0&&(t.logger.warn(`Translated API definition(s) [${Array.from(le).join(", ")}] for locale "${m}" diverge from the default-locale spec (e.g. changed OpenAPI tag names, operationIds, or paths, or a missing/added endpoint), so they can't be fully matched to the navigation tree. Serving the default-locale API for those (localized sidebar titles are still applied where they can be matched). For fully localized API reference content, translate only human-readable text and keep tag names/operationIds/paths identical to the base spec.`),j=Object.fromEntries(Object.entries(O).filter(([ae])=>!le.has(ae)))),Y=new Set(Object.keys(O).filter(ae=>!le.has(ae)))}let te=j!=null&&Object.keys(j).length>0?{...n.apis,...j}:n.apis;O!=null&&Object.keys(O).length>0&&x!=null&&(x=h8e(x,R,O,{rewritableApiIds:Y}));let ce={...n,apis:te,pages:C,config:{...n.config,root:x,announcement:P,navbarLinks:D,settings:E8e(n.config.settings,S)}};r.set(m,ce),t.logger.debug(`Computed translated definition for locale "${m}"`+(O!=null?` (with ${Object.keys(O).length} translated API(s))`:""))}catch(A){t.logger.warn(`Failed to compute translation for locale "${m}": ${String(A)}`)}}return r}tr();var RW=require("fs/promises"),bOp=require("os"),dNs=Ae(require("path"),1),kiA=".fern",FiA="logs",fNs=100*1024*1024;function NiA(){return"cli@5.226.2"}var Lqe=class{logFilePath=null;initialized=!1;sessionStartTime;consoleLogger;constructor(){this.sessionStartTime=Date.now()}async initialize(t,r){if(this.initialized)return;this.consoleLogger=t;let n=r??Re(Re(Zt.of((0,bOp.homedir)()),be.of(kiA)),be.of(FiA));await Ut(n)||await(0,RW.mkdir)(n,{recursive:!0});let o=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=Re(n,be.of(o));let s=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${dNs.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
|
|
4169
4169
|
`);await(0,RW.writeFile)(this.logFilePath,s,"utf-8"),this.initialized=!0,this.enforceLogSizeLimit(n)}getLogFilePath(){return this.logFilePath}async writeEntry(t){if(!this.initialized||!this.logFilePath)return;let r=JSON.stringify(t)+`
|
|
4170
4170
|
`;try{await(0,RW.appendFile)(this.logFilePath,r,"utf-8")}catch{}}async logFrontendMetrics(t){let r={timestamp:t.timestamp,source:t.source,level:t.level,eventType:this.getEventType(t.payload,t.isAggregate),isAggregate:t.isAggregate,data:t.payload};await this.writeEntry(r)}async logCliMetric(t,r="info"){let n={timestamp:t.timestamp,source:NiA(),level:r,eventType:t.type,data:{durationMs:t.durationMs,metadata:t.metadata}};await this.writeEntry(n)}async logCliMemory(){let t=process.memoryUsage(),r={type:"cli_memory",timestamp:new Date().toISOString(),metadata:{heapUsed:t.heapUsed,heapTotal:t.heapTotal,external:t.external,rss:t.rss,heapUsedMB:Math.round(t.heapUsed/1024/1024*100)/100,heapTotalMB:Math.round(t.heapTotal/1024/1024*100)/100,rssMB:Math.round(t.rss/1024/1024*100)/100}};await this.logCliMetric(r)}async logCliReloadStart(){let t={type:"cli_reload_start",timestamp:new Date().toISOString()};await this.logCliMetric(t)}async logCliReloadFinish(t,r){let n={type:"cli_reload_finish",timestamp:new Date().toISOString(),durationMs:t,metadata:r};await this.logCliMetric(n)}async logCliDocsGeneration(t,r){let n={type:"cli_docs_generation",timestamp:new Date().toISOString(),durationMs:t,metadata:r};await this.logCliMetric(n)}async logCliValidation(t,r){let n={type:"cli_validation",timestamp:new Date().toISOString(),durationMs:t,metadata:{success:r}};await this.logCliMetric(n)}async enforceLogSizeLimit(t){try{let n=(await(0,RW.readdir)(t)).filter(c=>c.endsWith(".log")),i=[];for(let c of n){let l=dNs.default.join(t,c);try{let u=await(0,RW.stat)(l);i.push({name:c,fullPath:l,size:u.size,mtimeMs:u.mtimeMs})}catch{}}let o=i.reduce((c,l)=>c+l.size,0),s=Math.round(o/1024/1024*100)/100,a=fNs/1024/1024;if(o<=fNs){this.consoleLogger?.debug(`Log directory size ${s} MB does not exceed ${a} MB cap`);return}this.consoleLogger?.info(`Rotating logs: total size ${s} MB exceeds ${a} MB cap`),i.sort((c,l)=>c.mtimeMs-l.mtimeMs);for(let c of i){if(o<=fNs)break;if(!(this.logFilePath!=null&&c.fullPath===this.logFilePath))try{await(0,RW.unlink)(c.fullPath),o-=c.size}catch{}}}catch{}}getEventType(t,r){return r?"aggregate_summary":"type"in t&&typeof t.type=="string"?t.type:"unknown"}static isMetricsMessage(t){if(typeof t!="object"||t===null)return!1;let r=t;return r.type==="metrics"&&typeof r.timestamp=="string"&&typeof r.source=="string"}};var qCi={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type"};function EOp(e){let t=jiA();if(t==null)return;let{port:r,debugLogger:n,getDocsLoadResponse:i,extractLocaleFromPath:o}=e,s=new Map;function a(l){let u=JSON.stringify(l),p=[];for(let[d]of s)try{d.send(u)}catch{p.push(d)}for(let d of p){let f=s.get(d);f&&(clearInterval(f.pingInterval),s.delete(d))}}let c=t.serve({port:r,async fetch(l,u){if(l.method==="OPTIONS")return new Response(null,{status:204,headers:qCi});let p=new URL(l.url);if(l.headers.get("upgrade")?.toLowerCase()==="websocket"){u.upgrade(l,{data:{connectionId:`${Date.now()}`}});return}if(l.method==="POST"&&p.pathname==="/v2/registry/docs/load-with-url")try{let f=await l.json(),m=o?.(f?.url);return new Response(JSON.stringify(i(m)),{headers:{"Content-Type":"application/json",...qCi}})}catch{return new Response(JSON.stringify(i()),{headers:{"Content-Type":"application/json",...qCi}})}let d=/^\/_local\/(.*)/.exec(p.pathname);return l.method==="GET"&&d!=null?new Response(t.file(`/${d[1]}`),{headers:qCi}):new Response("Not Found",{status:404})},websocket:{open(l){let{connectionId:u}=l.data,p=setInterval(()=>{let d=s.get(l);if(!d)return;let f=Date.now();if(f-d.lastPong>9e4){l.close();return}try{l.send(JSON.stringify({type:"ping",timestamp:f}))}catch{l.close()}},3e4);s.set(l,{pingInterval:p,lastPong:Date.now()});try{l.send(JSON.stringify({type:"connected",connectionId:u}))}catch{}},message(l,u){try{let p=JSON.parse(u.toString());if(p.type==="pong"){let d=s.get(l);d&&(d.lastPong=Date.now())}else Lqe.isMetricsMessage(p)&&n.logFrontendMetrics(p)}catch{}},close(l){let u=s.get(l);u&&(clearInterval(u.pingInterval),s.delete(l))}}});return{sendData:a,stop:l=>c.stop(l)}}function jiA(){return globalThis.Bun}var IOp=require("fs"),vOp=Ae(require("path"),1),ziA=`"use strict";
|
|
4171
4171
|
|
|
@@ -4503,7 +4503,7 @@ ${A}
|
|
|
4503
4503
|
|
|
4504
4504
|
Add a 'docs:' section to your fern.yml to get started.`,code:T.Code.ConfigError});let i=n.docs.raw.libraries;if(i==null)throw new T({message:`No libraries configured in docs.yml.
|
|
4505
4505
|
|
|
4506
|
-
Add a 'libraries' section to configure library documentation.`,code:T.Code.ConfigError});let o=await t.getTokenOrPrompt();await t.verifyOrgAccess({organization:n.org,token:o});let s=n.docs.absoluteFilePath??n.absoluteFilePath??t.cwd,a=Zt.of(Lr(s)),c=new Cd({context:t,logLevel:Un.Info});await cir({libraries:i,library:r.library,docsDirectoryPath:a,orgId:n.org,tokenValue:o.value,context:c,wrapStep:rP,docsConfig:n.docs.raw})}};function I4s(e){let t=new E4s;ni(e,"generate","[Beta] Generate MDX documentation from library source code. Requires 'libraries' config in docs.yml.",(r,n)=>t.handle(r,n),r=>r.option("library",{type:"string",description:"Name of a specific library defined in docs.yml to generate docs for"}))}function v4s(e){bA({cli:e,name:"md",subcommands:[I4s,V3s]})}Bt();function fPi(e,t,r,n,i,o){e.command(t,r,s=>{for(let a of o)a(s);return s.command("$0",!1,a=>{let c=a.version(!1);return i!=null?i(c):c},ein(n)),s.version(!1).usage(r)})}mt();h0();Bt();tn();mt();Bt();var dPi=class{context;task;project;docsWorkspace;ossWorkspaces;token;constructor({context:t,task:r,project:n,docsWorkspace:i,ossWorkspaces:o,token:s}){this.context=t,this.task=r,this.project=n,this.docsWorkspace=i,this.ossWorkspaces=o,this.token=s}async publish({instanceUrl:t,preview:r,previewId:n,skipUpload:i}){let o=new Cd({context:this.context,task:this.task});try{let s=await Itr({organization:this.project.config.organization,apiWorkspaces:this.project.apiWorkspaces,ossWorkspaces:this.ossWorkspaces,docsWorkspace:this.docsWorkspace,context:o,token:this.token,instanceUrl:t,preview:r,previewId:n,disableTemplates:void 0,skipUpload:i,cliVersion:"5.226.
|
|
4506
|
+
Add a 'libraries' section to configure library documentation.`,code:T.Code.ConfigError});let o=await t.getTokenOrPrompt();await t.verifyOrgAccess({organization:n.org,token:o});let s=n.docs.absoluteFilePath??n.absoluteFilePath??t.cwd,a=Zt.of(Lr(s)),c=new Cd({context:t,logLevel:Un.Info});await cir({libraries:i,library:r.library,docsDirectoryPath:a,orgId:n.org,tokenValue:o.value,context:c,wrapStep:rP,docsConfig:n.docs.raw})}};function I4s(e){let t=new E4s;ni(e,"generate","[Beta] Generate MDX documentation from library source code. Requires 'libraries' config in docs.yml.",(r,n)=>t.handle(r,n),r=>r.option("library",{type:"string",description:"Name of a specific library defined in docs.yml to generate docs for"}))}function v4s(e){bA({cli:e,name:"md",subcommands:[I4s,V3s]})}Bt();function fPi(e,t,r,n,i,o){e.command(t,r,s=>{for(let a of o)a(s);return s.command("$0",!1,a=>{let c=a.version(!1);return i!=null?i(c):c},ein(n)),s.version(!1).usage(r)})}mt();h0();Bt();tn();mt();Bt();var dPi=class{context;task;project;docsWorkspace;ossWorkspaces;token;constructor({context:t,task:r,project:n,docsWorkspace:i,ossWorkspaces:o,token:s}){this.context=t,this.task=r,this.project=n,this.docsWorkspace=i,this.ossWorkspaces=o,this.token=s}async publish({instanceUrl:t,preview:r,previewId:n,skipUpload:i}){let o=new Cd({context:this.context,task:this.task});try{let s=await Itr({organization:this.project.config.organization,apiWorkspaces:this.project.apiWorkspaces,ossWorkspaces:this.ossWorkspaces,docsWorkspace:this.docsWorkspace,context:o,token:this.token,instanceUrl:t,preview:r,previewId:n,disableTemplates:void 0,skipUpload:i,cliVersion:"5.226.2",loginCommand:"fern auth login"});return o.getResult()===gf.Failure?{success:!1}:{success:!0,url:s}}catch(s){return{success:!1,error:rn(s)}}}};mt();tn();var aBt=class e{static MAX_DISPLAYED_LOGS_TTY=10;static URL_PATTERN=/https?:\/\/[^\s]+/;context;stream;tasks={};taskOrder=[];startTime;isRegistered=!1;constructor(t){this.context=t.context,this.stream=t.stream??process.stderr}addTask(t){let r={...t,status:t.status??"pending"};return this.tasks[t.id]=r,this.taskOrder.push(t.id),this}async start(t){return this.startTime=Date.now(),t!=null&&await this.context.ttyAwareLogger.takeOverTerminal(()=>{this.stream.write(`
|
|
4507
4507
|
`),this.stream.write(`${oe.cyan("\u25C6")} ${oe.bold(t.title)}
|
|
4508
4508
|
`),t.subtitle!=null&&this.stream.write(` ${oe.dim(t.subtitle)}
|
|
4509
4509
|
`),this.stream.write(`
|
|
@@ -5595,7 +5595,7 @@ ${t}`),n}catch{return}}function Kfy(e){let t=e.split(`
|
|
|
5595
5595
|
`),g="";return c&&(g=u.style.error(c)),[`${p} ${f} ${s}`,[m,g].filter(Boolean).join(`
|
|
5596
5596
|
`)]});var wmy=cx((e,t)=>{let{validate:r=()=>!0}=e,n=jI(e.theme),[i,o]=cl("idle"),[s,a]=cl(),[c,l]=cl(""),u=sx({status:i,theme:n});ax(async(g,A)=>{if(i==="idle")if(ox(g)){let b=c;o("loading");let I=await r(b);I===!0?(l(b),o("done"),t(b)):(A.write(c),a(I||"You must provide a valid value"),o("idle"))}else l(A.line),a(void 0)});let p=n.style.message(e.message,i),d="",f;e.mask?d=(typeof e.mask=="string"?e.mask:"*").repeat(c.length):i!=="done"&&(f=`${n.style.help("[input is masked]")}${RDt}`),i==="done"&&(d=n.style.answer(d));let m="";return s&&(m=n.style.error(s)),[[u,p,e.mask?d:f].join(" "),m]});var aHe=Ae(Rw(),1);var Tmy={icon:{cursor:Xx.pointer},style:{disabled:e=>aHe.default.dim(`- ${e}`),searchTerm:e=>aHe.default.cyan(e),description:e=>aHe.default.cyan(e),keysHelpTip:e=>e.map(([t,r])=>`${aHe.default.bold(t)} ${aHe.default.dim(r)}`).join(aHe.default.dim(" \u2022 "))},helpMode:"always"};function Ita(e){return!Bd.isSeparator(e)&&!e.disabled}function Omy(e){return e.map(t=>{if(Bd.isSeparator(t))return t;if(typeof t=="string")return{value:t,name:t,short:t,disabled:!1};let r=t.name??String(t.value),n={value:t.value,name:r,short:t.short??r,disabled:t.disabled??!1};return t.description&&(n.description=t.description),n})}var Pmy=cx((e,t)=>{let{pageSize:r=7,validate:n=()=>!0}=e,i=jI(Tmy,e.theme),[o,s]=cl("loading"),[a,c]=cl(""),[l,u]=cl([]),[p,d]=cl(),f=sx({status:o,theme:i}),m=T6(()=>{let j=l.findIndex(Ita),Y=l.findLastIndex(Ita);return{first:j,last:Y}},[l]),[g=m.first,A]=cl();K4(()=>{let j=new AbortController;return s("loading"),d(void 0),(async()=>{try{let ee=await e.source(a||void 0,{signal:j.signal});j.signal.aborted||(A(void 0),d(void 0),u(Omy(ee)),s("idle"))}catch(ee){!j.signal.aborted&&ee instanceof Error&&d(ee.message)}})(),()=>{j.abort()}},[a]);let b=l[g];ax(async(j,Y)=>{if(ox(j))if(b){s("loading");let ee=await n(b.value);s("idle"),ee===!0?(s("done"),t(b.value)):b.name===a?d(ee||"You must provide a valid value"):(Y.write(b.name),c(b.name))}else Y.write(a);else if(mbe(j)&&b)Y.clearLine(0),Y.write(b.name),c(b.name);else if(o!=="loading"&&(uD(j)||w6(j))){if(Y.clearLine(0),uD(j)&&g!==m.first||w6(j)&&g!==m.last){let ee=uD(j)?-1:1,te=g;do te=(te+ee+l.length)%l.length;while(!Ita(l[te]));A(te)}}else c(Y.line)});let I=i.style.message(e.message,o),C;if(i.helpMode!=="never")if(e.instructions){let{pager:j,navigation:Y}=e.instructions;C=i.style.help(l.length>r?j:Y)}else C=i.style.keysHelpTip([["\u2191\u2193","navigate"],["\u23CE","select"]]);let x=nHe({items:l,active:g,renderItem({item:j,isActive:Y}){if(Bd.isSeparator(j))return` ${j.separator}`;if(j.disabled){let ce=typeof j.disabled=="string"?j.disabled:"(disabled)";return i.style.disabled(`${j.name} ${ce}`)}let ee=Y?i.style.highlight:ce=>ce,te=Y?i.icon.cursor:" ";return ee(`${te} ${j.name}`)},pageSize:r,loop:!1}),S;p?S=i.style.error(p):l.length===0&&a!==""&&o==="idle"&&(S=i.style.error("No results found"));let P;if(o==="done"&&b)return[f,I,i.style.answer(b.short)].filter(Boolean).join(" ").trimEnd();P=i.style.searchTerm(a);let D=b?.description,R=[f,I,P].filter(Boolean).join(" ").trimEnd(),O=[S??x," ",D?i.style.description(D):"",C].filter(Boolean).join(`
|
|
5597
5597
|
`).trimEnd();return[R,O]});var FDt=Ae(Rw(),1);var Bmy={icon:{cursor:Xx.pointer},style:{disabled:e=>FDt.default.dim(`- ${e}`),description:e=>FDt.default.cyan(e),keysHelpTip:e=>e.map(([t,r])=>`${FDt.default.bold(t)} ${FDt.default.dim(r)}`).join(FDt.default.dim(" \u2022 "))},helpMode:"always",indexMode:"hidden",keybindings:[]};function kDt(e){return!Bd.isSeparator(e)&&!e.disabled}function Dmy(e){return e.map(t=>{if(Bd.isSeparator(t))return t;if(typeof t=="string")return{value:t,name:t,short:t,disabled:!1};let r=t.name??String(t.value),n={value:t.value,name:r,short:t.short??r,disabled:t.disabled??!1};return t.description&&(n.description=t.description),n})}var vta=cx((e,t)=>{let{loop:r=!0,pageSize:n=7}=e,i=jI(Bmy,e.theme),{keybindings:o}=i,[s,a]=cl("idle"),c=sx({status:s,theme:i}),l=rHe(),u=!o.includes("vim"),p=T6(()=>Dmy(e.choices),[e.choices]),d=T6(()=>{let D=p.findIndex(kDt),R=p.findLastIndex(kDt);if(D===-1)throw new fue("[select prompt] No selectable choices. All choices are disabled.");return{first:D,last:R}},[p]),f=T6(()=>"default"in e?p.findIndex(D=>kDt(D)&&D.value===e.default):-1,[e.default,p]),[m,g]=cl(f===-1?d.first:f),A=p[m];ax((D,R)=>{if(clearTimeout(l.current),ox(D))a("done"),t(A.value);else if(uD(D,o)||w6(D,o)){if(R.clearLine(0),r||uD(D,o)&&m!==d.first||w6(D,o)&&m!==d.last){let O=uD(D,o)?-1:1,j=m;do j=(j+O+p.length)%p.length;while(!kDt(p[j]));g(j)}}else if(msr(D)&&!Number.isNaN(Number(R.line))){let O=Number(R.line)-1,j=-1,Y=p.findIndex(te=>Bd.isSeparator(te)?!1:(j++,j===O)),ee=p[Y];ee!=null&&kDt(ee)&&g(Y),l.current=setTimeout(()=>{R.clearLine(0)},700)}else if($7e(D))R.clearLine(0);else if(u){let O=R.line.toLowerCase(),j=p.findIndex(Y=>Bd.isSeparator(Y)||!kDt(Y)?!1:Y.name.toLowerCase().startsWith(O));j!==-1&&g(j),l.current=setTimeout(()=>{R.clearLine(0)},700)}}),K4(()=>()=>{clearTimeout(l.current)},[]);let b=i.style.message(e.message,s),I;if(i.helpMode!=="never")if(e.instructions){let{pager:D,navigation:R}=e.instructions;I=i.style.help(p.length>n?D:R)}else I=i.style.keysHelpTip([["\u2191\u2193","navigate"],["\u23CE","select"]]);let C=0,x=nHe({items:p,active:m,renderItem({item:D,isActive:R,index:O}){if(Bd.isSeparator(D))return C++,` ${D.separator}`;let j=i.indexMode==="number"?`${O+1-C}. `:"";if(D.disabled){let te=typeof D.disabled=="string"?D.disabled:"(disabled)";return i.style.disabled(`${j}${D.name} ${te}`)}let Y=R?i.style.highlight:te=>te,ee=R?i.icon.cursor:" ";return Y(`${ee} ${j}${D.name}`)},pageSize:n,loop:r});if(s==="done")return[c,b,i.style.answer(A.short)].filter(Boolean).join(" ");let{description:S}=A;return`${[[c,b].filter(Boolean).join(" "),x," ",S?i.style.description(S):"",I].filter(Boolean).join(`
|
|
5598
|
-
`).trimEnd()}${RDt}`});tn();xo();var due={GENERATION_STARTED:"generation_started",GENERATION_COMPLETED:"generation_completed",GENERATION_FAILED:"generation_failed",VERIFICATION_FAILED:"verification_failed",SDK_PR_CREATED:"sdk_pr_created",UPGRADE_APPLIED:"upgrade_applied",MAJOR_VERSION_BUMP:"major_version_bump"},Rmy={[due.GENERATION_STARTED]:!1,[due.GENERATION_COMPLETED]:!1,[due.GENERATION_FAILED]:!0,[due.VERIFICATION_FAILED]:!0,[due.SDK_PR_CREATED]:!1,[due.UPGRADE_APPLIED]:!1,[due.MAJOR_VERSION_BUMP]:!1};function r$p(e){return Rmy[e]}function n$p(e,t){return{automation_mode:!0,surface:"cli",action:t.action,run_id:t.run_id,github_run_id:t.github_run_id,github_run_url:t.github_run_url,org:t.org,config_repo:t.config_repo,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,trigger:t.trigger,cli_version:t.cli_version,...e.errorCode!==void 0?{error_code:e.errorCode}:{},...e.attributes??{}}}function i$p(e,t){function r(i,o,s){s!=null&&(i[o]=s)}let n={surface:"cli",automation_mode:"true"};return r(n,"event",e.event),r(n,"action",t.action),r(n,"run_id",t.run_id),r(n,"org",t.org),r(n,"config_repo",t.config_repo),r(n,"trigger",t.trigger),r(n,"error_code",e.errorCode??"none"),n}function o$p(e,t){return{github_run_id:t.github_run_id,github_run_url:t.github_run_url,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,cli_version:t.cli_version,...e.attributes??{}}}function s$p(e,t){return{event:e.event,timestamp:new Date().toISOString(),surface:"cli",action:t.action,run_id:t.run_id,github_run_id:t.github_run_id,github_run_url:t.github_run_url,org:t.org,config_repo:t.config_repo,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,trigger:t.trigger,cli_version:t.cli_version,...e.errorCode!==void 0?{error_code:e.errorCode}:{},...e.attributes??{}}}function a$p(e){let t=e.join(" ");return/\bautomations\s+generate\b/.test(t)?due.GENERATION_FAILED:/\bautomations\s+preview\b/.test(t)?due.VERIFICATION_FAILED:due.GENERATION_FAILED}var kmy="",Fmy="FERN_AUTOMATION_EVENTS_ORIGIN",Nmy=3e3,eFi=class e{static instance;origin;inflight=[];static getInstance(){return e.instance==null&&(e.instance=new e(process.env[Fmy]??kmy)),e.instance}constructor(t){this.origin=t}resolveEndpoint(){if(this.origin.length!==0)return`${this.origin.replace(/\/$/,"")}/v1/automation/events`}post(t,r){this.inflight.push(this.send(t,r))}async shutdown(){let t=this.inflight;this.inflight=[],t.length>0&&await Promise.allSettled(t)}async send(t,r){let n=this.resolveEndpoint();if(n==null)return;let i=new AbortController,o=setTimeout(()=>i.abort(),Nmy);try{let s={"content-type":"application/json"},a=await jz();a!=null&&a.value.length>0&&(s.Authorization=`Bearer ${a.value}`);let c=await fetch(n,{method:"POST",headers:s,body:JSON.stringify(s$p(t,r)),signal:i.signal})}catch{return}finally{clearTimeout(o)}}};function c$p(){let{fern_run_id:e,github_run_id:t}=Rfe();return{action:process.env.FERN_ACTION,run_id:e,github_run_id:t,github_run_url:process.env.FERN_GITHUB_RUN_URL,org:void 0,config_repo:process.env.FERN_CONFIG_REPO,config_commit_sha:process.env.FERN_CONFIG_COMMIT_SHA,config_branch:process.env.FERN_CONFIG_BRANCH,config_pr_number:process.env.FERN_CONFIG_PR_NUMBER,trigger:process.env.GITHUB_EVENT_NAME,cli_version:"5.226.
|
|
5598
|
+
`).trimEnd()}${RDt}`});tn();xo();var due={GENERATION_STARTED:"generation_started",GENERATION_COMPLETED:"generation_completed",GENERATION_FAILED:"generation_failed",VERIFICATION_FAILED:"verification_failed",SDK_PR_CREATED:"sdk_pr_created",UPGRADE_APPLIED:"upgrade_applied",MAJOR_VERSION_BUMP:"major_version_bump"},Rmy={[due.GENERATION_STARTED]:!1,[due.GENERATION_COMPLETED]:!1,[due.GENERATION_FAILED]:!0,[due.VERIFICATION_FAILED]:!0,[due.SDK_PR_CREATED]:!1,[due.UPGRADE_APPLIED]:!1,[due.MAJOR_VERSION_BUMP]:!1};function r$p(e){return Rmy[e]}function n$p(e,t){return{automation_mode:!0,surface:"cli",action:t.action,run_id:t.run_id,github_run_id:t.github_run_id,github_run_url:t.github_run_url,org:t.org,config_repo:t.config_repo,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,trigger:t.trigger,cli_version:t.cli_version,...e.errorCode!==void 0?{error_code:e.errorCode}:{},...e.attributes??{}}}function i$p(e,t){function r(i,o,s){s!=null&&(i[o]=s)}let n={surface:"cli",automation_mode:"true"};return r(n,"event",e.event),r(n,"action",t.action),r(n,"run_id",t.run_id),r(n,"org",t.org),r(n,"config_repo",t.config_repo),r(n,"trigger",t.trigger),r(n,"error_code",e.errorCode??"none"),n}function o$p(e,t){return{github_run_id:t.github_run_id,github_run_url:t.github_run_url,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,cli_version:t.cli_version,...e.attributes??{}}}function s$p(e,t){return{event:e.event,timestamp:new Date().toISOString(),surface:"cli",action:t.action,run_id:t.run_id,github_run_id:t.github_run_id,github_run_url:t.github_run_url,org:t.org,config_repo:t.config_repo,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,trigger:t.trigger,cli_version:t.cli_version,...e.errorCode!==void 0?{error_code:e.errorCode}:{},...e.attributes??{}}}function a$p(e){let t=e.join(" ");return/\bautomations\s+generate\b/.test(t)?due.GENERATION_FAILED:/\bautomations\s+preview\b/.test(t)?due.VERIFICATION_FAILED:due.GENERATION_FAILED}var kmy="",Fmy="FERN_AUTOMATION_EVENTS_ORIGIN",Nmy=3e3,eFi=class e{static instance;origin;inflight=[];static getInstance(){return e.instance==null&&(e.instance=new e(process.env[Fmy]??kmy)),e.instance}constructor(t){this.origin=t}resolveEndpoint(){if(this.origin.length!==0)return`${this.origin.replace(/\/$/,"")}/v1/automation/events`}post(t,r){this.inflight.push(this.send(t,r))}async shutdown(){let t=this.inflight;this.inflight=[],t.length>0&&await Promise.allSettled(t)}async send(t,r){let n=this.resolveEndpoint();if(n==null)return;let i=new AbortController,o=setTimeout(()=>i.abort(),Nmy);try{let s={"content-type":"application/json"},a=await jz();a!=null&&a.value.length>0&&(s.Authorization=`Bearer ${a.value}`);let c=await fetch(n,{method:"POST",headers:s,body:JSON.stringify(s$p(t,r)),signal:i.signal})}catch{return}finally{clearTimeout(o)}}};function c$p(){let{fern_run_id:e,github_run_id:t}=Rfe();return{action:process.env.FERN_ACTION,run_id:e,github_run_id:t,github_run_url:process.env.FERN_GITHUB_RUN_URL,org:void 0,config_repo:process.env.FERN_CONFIG_REPO,config_commit_sha:process.env.FERN_CONFIG_COMMIT_SHA,config_branch:process.env.FERN_CONFIG_BRANCH,config_pr_number:process.env.FERN_CONFIG_PR_NUMBER,trigger:process.env.GITHUB_EVENT_NAME,cli_version:"5.226.2"}}function l$p(){return process.env.FERN_AUTOMATION==="true"}var jmy=3e3,tFi=class{constructor(t,r=eFi.getInstance()){this.reporter=t;this.automationEventApiClient=r;this.context=c$p()}reporter;automationEventApiClient;context;setOrganization(t){this.context={...this.context,org:t}}emit(t,r){let n=this.captureSentryForFailure({event:t,context:this.context,error:r?.error}),i=n==null?t:{...t,attributes:{...t.attributes??{},sentry_event_id:n}};this.capturePostHogEvent({event:i,context:this.context}),this.captureAutomationEventApiEvent(i,this.context)}async flush(){let t;try{await Promise.race([this.automationEventApiClient.shutdown(),new Promise(r=>{t=setTimeout(r,jmy)})])}finally{clearTimeout(t)}}capturePostHogEvent({event:t,context:r}){this.reporter.instrumentPostHogAutomationEvent({distinctId:r.run_id??void 0,event:t.event,properties:n$p(t,r)})}captureSentryForFailure({event:t,context:r,error:n}){if(!(!r$p(t.event)||t.errorCode==null))return this.reporter.captureException(n,{tags:i$p(t,r),context:{automation:o$p(t,r)}})}captureAutomationEventApiEvent(t,r){this.automationEventApiClient.post(t,r)}};Bt();function rFi(e,t,r){if(t instanceof rc)return;let n=Cfe(t,r?.code),i=r?.argv??process.argv,o=i.join(" "),s=r?.message??(t instanceof Error?t.message:void 0)??"",a=t??new T({message:s,code:n});l$p()?Qmy(i,e,n,s,a):zmy(e,o,n,a)}function zmy(e,t,r,n){e.instrumentPostHogEvent({command:t,properties:{failed:!0,errorCode:r}}),NLe(r)&&e.captureException(n,{tags:{"error.code":r}})}function Qmy(e,t,r,n,i){let o=a$p(e);t.emitAutomationTelemetryEvent({event:o,errorCode:r,attributes:{error_message:n}},{error:i})}Bt();function cHe(){return process.env.FERN_DISABLE_TELEMETRY==="true"}function nFi({cliName:e,packageVersion:t,isLocal:r}){return cHe()||r?!1:!(t==="0.0.0")&&(e==="fern"&&!0)}var iFi=class{sentry;constructor({release:t,telemetry:r}){let n="https://84f58b5e457f06999d92f11ce4b79158@o4509504076185600.ingest.us.sentry.io/4511021546602496";if(nFi(r)&&n!=null&&n.length>0){let i="production";if(i==null||i.length===0)throw new T({message:"SENTRY_ENVIRONMENT must be set when SENTRY_DSN is configured",code:T.Code.ConfigError});this.sentry=l_t({dsn:n,release:t,environment:i,defaultIntegrations:!1,integrations:[U$e(),mve(),hve(),ZIe(),dve()],tracesSampleRate:0,attachStacktrace:!0,sendClientReports:!1}),u_t()}}captureException(t,r){if(this.sentry!=null)try{let n=r?.tags,i=r?.context,o=n!=null&&Object.keys(n).length>0,s=i!=null&&Object.values(i).some(a=>a!=null);return!o&&!s?this.sentry.captureException(t):VP(a=>{if(o&&a.setTags(n),i!=null)for(let[c,l]of Object.entries(i))l!=null&&a.setContext(c,l);return this.sentry?.captureException(t,void 0,a)})}catch{return}}async flush(){this.sentry!=null&&await Promise.resolve(this.sentry.flush(2e3)).catch(()=>{})}};Bt();var oFi=class{originalWrite;redirected=!1;redirect(){if(this.redirected)throw new T({message:"StdoutRedirector: already redirected \u2014 did you forget to restore()?",code:T.Code.InternalError});this.originalWrite=process.stdout.write,process.stdout.write=process.stderr.write.bind(process.stderr),this.redirected=!0}restore(){!this.redirected||this.originalWrite==null||(process.stdout.write=this.originalWrite,this.originalWrite=void 0,this.redirected=!1)}async withRedirect(t){this.redirect();try{return await t()}finally{this.restore()}}};dee();mt();Ey();Bt();tn();var ysr=class{result=gf.Success;lastFailureMessage=void 0;logImmediately;logPrefix;title;subtasks=[];shouldBufferLogs;bufferedLogs=[];status="notStarted";onResult;instrumentPostHogEventImpl;captureExceptionImpl;emitAutomationTelemetryEventImpl;constructor({logImmediately:t,logPrefix:r,title:n,takeOverTerminal:i,onResult:o,shouldBufferLogs:s,instrumentPostHogEvent:a,captureException:c,emitAutomationTelemetryEvent:l}){this.logImmediately=t,this.logPrefix=r??"",this.title=n,this.takeOverTerminal=i,this.onResult=o,this.shouldBufferLogs=s,this.instrumentPostHogEventImpl=a,this.captureExceptionImpl=c,this.emitAutomationTelemetryEventImpl=l}start(){return this.status="running",this}isStarted(){return this.status!=="notStarted"}finish(){this.status!=="finished"&&(this.status="finished",this.flushLogs(),this.onResult?.(this.getResult()))}isFinished(){return this.status==="finished"}takeOverTerminal;failAndThrow(t,r,n){throw this.failWithoutThrowing(t,r,n),this.finish(),new rc(t??(r instanceof rc?r.failureMessage:this.lastFailureMessage))}failWithoutThrowing(t,r,n){this.result=gf.Failure,!(r instanceof rc)&&(t!=null&&(this.lastFailureMessage=t),$Le({message:t,error:r,logger:this.logger,instructionsTopic:n?.instructionsTopic}),rFi(this,r,{...n,message:t}))}getLastFailureMessage(){return this.lastFailureMessage}captureException(t,r){return this.captureExceptionImpl?.(t,r)}emitAutomationTelemetryEvent(t,r){this.emitAutomationTelemetryEventImpl(t,r)}getResult(){return this.result}instrumentPostHogEvent(t){this.instrumentPostHogEventImpl(t)}logAtLevel(t,...r){this.logAtLevelWithOverrides(t,r)}logAtLevelWithOverrides(t,r,n={}){this.log({parts:r,level:t,time:new Date,...n})}log(t){this.bufferedLogs.push({...t,prefix:this.logPrefix}),this.shouldBufferLogs||this.flushLogs()}flushLogs(){this.logImmediately(this.bufferedLogs),this.bufferedLogs=[]}logger=L0(this.logAtLevel.bind(this));addInteractiveTask({name:t,subtitle:r}){let n=new Cta({name:t,subtitle:r,logImmediately:i=>this.logImmediately(i),logPrefix:`${this.logPrefix}${oe.blackBright(t)} `,takeOverTerminal:this.takeOverTerminal,onResult:this.onResult,shouldBufferLogs:this.shouldBufferLogs,instrumentPostHogEvent:i=>this.instrumentPostHogEventImpl(i),captureException:this.captureExceptionImpl,emitAutomationTelemetryEvent:this.emitAutomationTelemetryEventImpl});return this.subtasks.push(n),n}async runInteractiveTask(t,r){let n=this.addInteractiveTask(t).start();try{await r(n)}catch(o){n.failWithoutThrowing(void 0,o)}finally{n.finish()}let i=n.getResult()===gf.Success;return i||(this.lastFailureMessage=n.getLastFailureMessage()??this.lastFailureMessage),i}printInteractiveTasks({spinner:t}){return this.subtasks.map(r=>r.print({spinner:t})).join(`
|
|
5599
5599
|
`)}},Cta=class extends ysr{name;subtitle;constructor({name:t,subtitle:r,...n}){super(n),this.name=t,this.subtitle=r}start(){return super.start(),this.logAtLevelWithOverrides(Un.Info,["Started."],{omitOnTTY:!0}),this.flushLogs(),this}isStarted(){return this.status!=="notStarted"}finish(){this.status!=="finished"&&(this.result===gf.Success?this.logAtLevelWithOverrides(Un.Info,["Finished."],{omitOnTTY:!0}):this.logAtLevelWithOverrides(Un.Error,["Failed."],{omitOnTTY:!0}),super.finish())}setSubtitle(t){this.subtitle=t}print({spinner:t}){let r=[this.name];return this.subtitle!=null&&r.push(oe.dim(this.subtitle)),r.push(...this.subtasks.map(n=>n.print({spinner:t}))),Hj({prefix:this.getIcon({spinner:t}),content:r.join(`
|
|
5600
5600
|
`)})}printInteractiveTasks({spinner:t}){return this.print({spinner:t})}getIcon({spinner:t}){let r=this.subtasks.length>0;switch(this.status){case"notStarted":return r?oe.dim("\u25B8 "):oe.dim("\u25E6 ");case"running":return r?oe.cyan("\u25BE "):t;case"finished":switch(this.getResult()){case gf.Success:return r?oe.green("\u25BE "):oe.green("\u2713 ");case gf.Failure:return r?oe.red("\u25BE "):oe.red("x ")}}}getResult(){if(this.result===gf.Failure)return gf.Failure;for(let t of this.subtasks)if(t.getResult()===gf.Failure)return gf.Failure;return gf.Success}};Bt();var u$p=Ae(lLe(),1);tn();function p$p(e){return e.filter(t=>t.isUpgradeAvailable).length>0}function Mmy(e){return(e.cliUpgradeInfo?.isUpgradeAvailable??!1)||p$p(e.generatorUpgradeInfo)}async function f$p({cliEnvironment:e,upgradeInfo:t}){if(!Mmy(t)||e.packageVersion==t.cliUpgradeInfo?.latestVersion)return;let r=`${oe.underline("Upgrades available")}
|
|
5601
5601
|
|
|
@@ -5604,7 +5604,7 @@ ${t}`),n}catch{return}}function Kfy(e){let t=e.split(`
|
|
|
5604
5604
|
Run ${oe.cyan("fern generator upgrade")} to upgrade your generators.`),i.length>2&&(r+=`
|
|
5605
5605
|
Run ${oe.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),Mwe(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function xta({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:n=!0}){if(!p$p(e))return;let i=t??"",o=e.filter(a=>a.isUpgradeAvailable);r!=null&&(o=o.slice(0,r+1));let s=o.sort((a,c)=>a.generatorName.localeCompare(c.generatorName)||a.currentVersion.localeCompare(c.currentVersion));for(let a of s)i+=`
|
|
5606
5606
|
${await Lmy(a.generatorName)} (${a.apiName!=null?"API: "+a.apiName+", ":""}Group: ${a.generatorGroup}) `+oe.dim(a.currentVersion)+oe.reset(" \u2192 ")+oe.green(a.latestVersion);return i+=`
|
|
5607
|
-
`,n?Mwe(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function Lmy(e){let r=await new u$p.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new T({message:`Generator ${e} not found`,code:T.Code.ConfigError});return r.body.displayName}qn();Dme();Bt();var bsr=Ae(QA(),1);function NDt(e){let t;return()=>(t??=e.runTask(r=>Vu(r)),t)}function sFi({generatorId:e,candidateVersion:t,currentVersion:r}){if(!d$p(t)||!d$p(r))throw new T({message:`Cannot compare versions for generator "${e}": configured version "${r}", candidate version "${t}". Use valid semantic versions such as 1.2.3.`,code:T.Code.VersionError});try{return t===r?0:Pw(t,r)?1:Pw(r,t)?-1:0}catch{let n=bsr.default.valid(t),i=bsr.default.valid(r);if(n!=null&&i!=null)return Math.sign(bsr.default.compare(n,i));throw new T({message:`Cannot compare versions for generator "${e}": configured version "${r}", candidate version "${t}". Use valid semantic versions such as 1.2.3.`,code:T.Code.VersionError})}}function d$p(e){if(e==="latest"||bsr.default.valid(e)!=null)return!0;try{return GK(e),!0}catch{return!1}}async function aFi({generatorId:e,currentVersion:t,includeMajor:r,channel:n,organization:i,getToken:o,context:s}){if(n!=null)throw new Error(`SDK Gen API generator version discovery does not support the requested upgrade channel "${n}". Remove --channel to use executable index versions; FDR channel metadata is used only when the ${ser} feature flag is off for this organization.`);let a=Tae();if(a==null)throw new Error("FERN_SDK_GEN_API_ORIGIN is required when sdk-gen-api generation is enabled");let c=wv(e);if(c==null)return s.logger.error(`SDK Gen API cannot discover versions for unsupported generator ${e}. Use a canonical first-party SDK generator name.`),{};let l=await o(),u=await YIs({origin:a,organization:i,token:l,generatorId:e,language:c,currentVersion:t,includeMajor:r});return u.state==="UNAVAILABLE"?(s.logger.error(`SDK Gen API cannot resolve an executable version for ${e}@${t} (${u.reason}). Publish the coordinate to this environment or choose a supported generator version.`),{}):{compatibleVersion:u.compatibleVersion,withheldMajorVersion:u.withheldMajorVersion}}async function _my({cliContext:e,project:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s}){let{apiWorkspaces:a}=t,l=s!==!0||await Iy().catch(()=>{})!=null?NDt(e):void 0;if(a.length===1){let p={type:"singleApi",versions:{}};return await m$p({cliContext:e,apiWorkspaces:a,perGeneratorAction:async(d,f,m,g)=>{p.versions[f]==null&&(p.versions[f]={});let A=j4e(m.name);if(A==null){g.logger.debug(`Skipping unknown generator: ${m.name}`);return}let b=await g$p({generatorName:m.name,normalizedGeneratorName:A,cliVersion:e.environment.packageVersion,currentGeneratorVersion:m.version,channel:i,includeMajor:o,organization:t.config.organization,skipFeatureFlagRequest:s,getSdkGenApiToken:l,context:g});b!=null&&(p.versions[f][m.name]={previousVersion:m.version,latestVersion:b})},generatorFilter:r,groupFilter:n}),p}let u={type:"multiApi",versions:{}};return await m$p({cliContext:e,apiWorkspaces:a,perGeneratorAction:async(p,d,f,m)=>{if(p==null)return;u.versions[p]==null&&(u.versions[p]={}),u.versions[p][d]==null&&(u.versions[p][d]={});let g=j4e(f.name);if(g==null){m.logger.debug(`Skipping unknown generator: ${f.name}`);return}let A=await g$p({generatorName:f.name,normalizedGeneratorName:g,cliVersion:e.environment.packageVersion,currentGeneratorVersion:f.version,channel:i,includeMajor:o,organization:t.config.organization,skipFeatureFlagRequest:s,getSdkGenApiToken:l,context:m});A!=null&&(u.versions[p][d][f.name]={previousVersion:f.version,latestVersion:A})},generatorFilter:r,groupFilter:n}),u}async function m$p({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:n,groupFilter:i}){await Promise.all(t.map(async o=>{await e.runTaskForWorkspace(o,async s=>{let a=await Z_({absolutePathToWorkspace:o.absoluteFilePath,context:s});if(a==null||a.groups==null)return;let c=n!=null?nh(n):void 0;for(let l of a.groups)if(!(i!=null&&l.groupName!==i))for(let u of l.generators)c!=null&&u.name!==c||await r(o.workspaceName,l.groupName,u,s)})}))}function h$p(e,t,r){let n=[];for(let[i,o]of Object.entries(e))for(let[s,a]of Object.entries(o)){r.debug(`Checking if ${s} in group ${i} has an upgrade available...`);let c=sFi({generatorId:s,candidateVersion:a.latestVersion,currentVersion:a.previousVersion})===1;r.debug(`Latest version: ${a.latestVersion}. `+(c?"Upgrade available.":"No upgrade available.")),n.push({generatorName:s,generatorGroup:i,apiName:t,isUpgradeAvailable:c,currentVersion:a.previousVersion,latestVersion:a.latestVersion})}return n}async function g$p({generatorName:e,normalizedGeneratorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,organization:s,skipFeatureFlagRequest:a,getSdkGenApiToken:c,context:l}){return n==="latest"?"latest":await Umy({organization:s,generatorName:nh(e),skipFeatureFlagRequest:a})?c==null?void 0:(await aFi({generatorId:nh(e),currentVersion:n,includeMajor:o??!1,channel:i,organization:s,getToken:c,context:l})).compatibleVersion:gB({generatorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,context:l})}async function cFi({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s}){let a=[];if(e!=null){let c=await _my({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s});if(c.type==="multiApi")for(let[l,u]of Object.entries(c.versions))a.push(...h$p(u,l,t.logger));else a.push(...h$p(c.versions,void 0,t.logger))}return a}async function Umy({organization:e,generatorName:t,skipFeatureFlagRequest:r}){return r===!0?ROs({organization:e,generatorName:t})??!1:$wt({organization:e,generatorName:t})}mt();Bt();pUt();async function J4({cliEnvironment:e,includePreReleases:t=!1}){if(e.packageName!=="fern-api"||e.packageVersion==="0.0.0")return e.packageVersion;try{return await Wde(e.packageName,{version:t?"prerelease":"latest"})}catch(r){throw new T({message:`Failed to resolve latest CLI version: ${Wn(r)}`,code:T.Code.NetworkError})}}var A$p=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],lFi=class e{environment;sentryClient;posthogManager;automationTelemetryManager;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Un.Info;isLocal;stdoutRedirector=new oFi;jsonMode=!1;linesAfterTasks=[];static async create(t,r,{isLocal:n}){let i=await zWt();return new e(t,r,{isLocal:n,posthogManager:i})}constructor(t,r,{isLocal:n,posthogManager:i}){this.ttyAwareLogger=new OMt(t,r),this.isLocal=n??!1,this.posthogManager=i;let o=this.getPackageName(),s=this.getPackageVersion(),a=this.getCliName();(o==null||s==null||a==null)&&this.exitProgram(),this.environment={packageName:o,packageVersion:s,cliName:a},this.sentryClient=new iFi({release:`cli@${this.environment.packageVersion}`,telemetry:{cliName:this.environment.cliName,packageVersion:this.environment.packageVersion,isLocal:this.isLocal}}),this.automationTelemetryManager=new tFi(this)}getPackageName(){return"fern-api"}getPackageVersion(){return"5.226.
|
|
5607
|
+
`,n?Mwe(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function Lmy(e){let r=await new u$p.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new T({message:`Generator ${e} not found`,code:T.Code.ConfigError});return r.body.displayName}qn();Dme();Bt();var bsr=Ae(QA(),1);function NDt(e){let t;return()=>(t??=e.runTask(r=>Vu(r)),t)}function sFi({generatorId:e,candidateVersion:t,currentVersion:r}){if(!d$p(t)||!d$p(r))throw new T({message:`Cannot compare versions for generator "${e}": configured version "${r}", candidate version "${t}". Use valid semantic versions such as 1.2.3.`,code:T.Code.VersionError});try{return t===r?0:Pw(t,r)?1:Pw(r,t)?-1:0}catch{let n=bsr.default.valid(t),i=bsr.default.valid(r);if(n!=null&&i!=null)return Math.sign(bsr.default.compare(n,i));throw new T({message:`Cannot compare versions for generator "${e}": configured version "${r}", candidate version "${t}". Use valid semantic versions such as 1.2.3.`,code:T.Code.VersionError})}}function d$p(e){if(e==="latest"||bsr.default.valid(e)!=null)return!0;try{return GK(e),!0}catch{return!1}}async function aFi({generatorId:e,currentVersion:t,includeMajor:r,channel:n,organization:i,getToken:o,context:s}){if(n!=null)throw new Error(`SDK Gen API generator version discovery does not support the requested upgrade channel "${n}". Remove --channel to use executable index versions; FDR channel metadata is used only when the ${ser} feature flag is off for this organization.`);let a=Tae();if(a==null)throw new Error("FERN_SDK_GEN_API_ORIGIN is required when sdk-gen-api generation is enabled");let c=wv(e);if(c==null)return s.logger.error(`SDK Gen API cannot discover versions for unsupported generator ${e}. Use a canonical first-party SDK generator name.`),{};let l=await o(),u=await YIs({origin:a,organization:i,token:l,generatorId:e,language:c,currentVersion:t,includeMajor:r});return u.state==="UNAVAILABLE"?(s.logger.error(`SDK Gen API cannot resolve an executable version for ${e}@${t} (${u.reason}). Publish the coordinate to this environment or choose a supported generator version.`),{}):{compatibleVersion:u.compatibleVersion,withheldMajorVersion:u.withheldMajorVersion}}async function _my({cliContext:e,project:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s}){let{apiWorkspaces:a}=t,l=s!==!0||await Iy().catch(()=>{})!=null?NDt(e):void 0;if(a.length===1){let p={type:"singleApi",versions:{}};return await m$p({cliContext:e,apiWorkspaces:a,perGeneratorAction:async(d,f,m,g)=>{p.versions[f]==null&&(p.versions[f]={});let A=j4e(m.name);if(A==null){g.logger.debug(`Skipping unknown generator: ${m.name}`);return}let b=await g$p({generatorName:m.name,normalizedGeneratorName:A,cliVersion:e.environment.packageVersion,currentGeneratorVersion:m.version,channel:i,includeMajor:o,organization:t.config.organization,skipFeatureFlagRequest:s,getSdkGenApiToken:l,context:g});b!=null&&(p.versions[f][m.name]={previousVersion:m.version,latestVersion:b})},generatorFilter:r,groupFilter:n}),p}let u={type:"multiApi",versions:{}};return await m$p({cliContext:e,apiWorkspaces:a,perGeneratorAction:async(p,d,f,m)=>{if(p==null)return;u.versions[p]==null&&(u.versions[p]={}),u.versions[p][d]==null&&(u.versions[p][d]={});let g=j4e(f.name);if(g==null){m.logger.debug(`Skipping unknown generator: ${f.name}`);return}let A=await g$p({generatorName:f.name,normalizedGeneratorName:g,cliVersion:e.environment.packageVersion,currentGeneratorVersion:f.version,channel:i,includeMajor:o,organization:t.config.organization,skipFeatureFlagRequest:s,getSdkGenApiToken:l,context:m});A!=null&&(u.versions[p][d][f.name]={previousVersion:f.version,latestVersion:A})},generatorFilter:r,groupFilter:n}),u}async function m$p({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:n,groupFilter:i}){await Promise.all(t.map(async o=>{await e.runTaskForWorkspace(o,async s=>{let a=await Z_({absolutePathToWorkspace:o.absoluteFilePath,context:s});if(a==null||a.groups==null)return;let c=n!=null?nh(n):void 0;for(let l of a.groups)if(!(i!=null&&l.groupName!==i))for(let u of l.generators)c!=null&&u.name!==c||await r(o.workspaceName,l.groupName,u,s)})}))}function h$p(e,t,r){let n=[];for(let[i,o]of Object.entries(e))for(let[s,a]of Object.entries(o)){r.debug(`Checking if ${s} in group ${i} has an upgrade available...`);let c=sFi({generatorId:s,candidateVersion:a.latestVersion,currentVersion:a.previousVersion})===1;r.debug(`Latest version: ${a.latestVersion}. `+(c?"Upgrade available.":"No upgrade available.")),n.push({generatorName:s,generatorGroup:i,apiName:t,isUpgradeAvailable:c,currentVersion:a.previousVersion,latestVersion:a.latestVersion})}return n}async function g$p({generatorName:e,normalizedGeneratorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,organization:s,skipFeatureFlagRequest:a,getSdkGenApiToken:c,context:l}){return n==="latest"?"latest":await Umy({organization:s,generatorName:nh(e),skipFeatureFlagRequest:a})?c==null?void 0:(await aFi({generatorId:nh(e),currentVersion:n,includeMajor:o??!1,channel:i,organization:s,getToken:c,context:l})).compatibleVersion:gB({generatorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,context:l})}async function cFi({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s}){let a=[];if(e!=null){let c=await _my({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s});if(c.type==="multiApi")for(let[l,u]of Object.entries(c.versions))a.push(...h$p(u,l,t.logger));else a.push(...h$p(c.versions,void 0,t.logger))}return a}async function Umy({organization:e,generatorName:t,skipFeatureFlagRequest:r}){return r===!0?ROs({organization:e,generatorName:t})??!1:$wt({organization:e,generatorName:t})}mt();Bt();pUt();async function J4({cliEnvironment:e,includePreReleases:t=!1}){if(e.packageName!=="fern-api"||e.packageVersion==="0.0.0")return e.packageVersion;try{return await Wde(e.packageName,{version:t?"prerelease":"latest"})}catch(r){throw new T({message:`Failed to resolve latest CLI version: ${Wn(r)}`,code:T.Code.NetworkError})}}var A$p=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],lFi=class e{environment;sentryClient;posthogManager;automationTelemetryManager;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Un.Info;isLocal;stdoutRedirector=new oFi;jsonMode=!1;linesAfterTasks=[];static async create(t,r,{isLocal:n}){let i=await zWt();return new e(t,r,{isLocal:n,posthogManager:i})}constructor(t,r,{isLocal:n,posthogManager:i}){this.ttyAwareLogger=new OMt(t,r),this.isLocal=n??!1,this.posthogManager=i;let o=this.getPackageName(),s=this.getPackageVersion(),a=this.getCliName();(o==null||s==null||a==null)&&this.exitProgram(),this.environment={packageName:o,packageVersion:s,cliName:a},this.sentryClient=new iFi({release:`cli@${this.environment.packageVersion}`,telemetry:{cliName:this.environment.cliName,packageVersion:this.environment.packageVersion,isLocal:this.isLocal}}),this.automationTelemetryManager=new tFi(this)}getPackageName(){return"fern-api"}getPackageVersion(){return"5.226.2"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${oe.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r,n){throw this.failWithoutThrowing(t,r,n),new rc(t??(r instanceof rc?r.failureMessage:r!=null?rn(r):void 0))}failWithoutThrowing(t,r,n){this.didSucceed=!1,!(r instanceof rc)&&($Le({message:t,error:r,logger:this.logger,instructionsTopic:n?.instructionsTopic}),rFi(this,r,{...n,message:t}))}enableJsonMode(){this.jsonMode||(this.jsonMode=!0,this.stdoutRedirector.redirect())}get isJsonMode(){return this.jsonMode}get isTTY(){return this.ttyAwareLogger.isTTY}writeJsonToStdout(t){this.writeTextToStdout(JSON.stringify(t,null,2)+`
|
|
5608
5608
|
`)}writeTextToStdout(t){this.stdoutRedirector.restore(),process.stdout.write(t),this.jsonMode&&this.stdoutRedirector.redirect()}async withRealStdout(t){this.stdoutRedirector.restore();try{return await t()}finally{this.jsonMode&&this.stdoutRedirector.redirect()}}logAfterTasks(t){this.isTTY?this.linesAfterTasks.push(t):this.logger.info(t)}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish();for(let r of this.linesAfterTasks)process.stdout.write(`${r}
|
|
5609
5609
|
`);try{await Promise.all([this.posthogManager.flush(),xYo()])}catch{}await this.sentryClient.flush(),await this.automationTelemetryManager.flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable({skipFeatureFlagRequest:!0}),new Promise((n,i)=>setTimeout(()=>i("Request timed out"),300))]),r=await f$p({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
5610
5610
|
`)||(r+=`
|