fern-api 5.172.0 → 5.172.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.cjs +7 -7
- package/package.json +1 -1
package/cli.cjs
CHANGED
|
@@ -536,7 +536,7 @@ For more information, see https://buildwithfern.com/learn/api-definition/introdu
|
|
|
536
536
|
`,s+1),c=a===-1?"":o.slice(a+1);String(n.stack).endsWith(c)||(n.stack+=`
|
|
537
537
|
`+o)}}catch{}}throw n}}_request(t,r){typeof t=="string"?(r=r||{},r.url=t):r=t||{},r=hJ(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:o}=r;n!==void 0&&c9t.assertOptions(n,{silentJSONParsing:v8.transitional(v8.boolean),forcedJSONParsing:v8.transitional(v8.boolean),clarifyTimeoutError:v8.transitional(v8.boolean),legacyInterceptorReqResOrdering:v8.transitional(v8.boolean)},!1),i!=null&&(cr.isFunction(i)?r.paramsSerializer={serialize:i}:c9t.assertOptions(i,{encode:v8.function,serialize:v8.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),c9t.assertOptions(r,{baseUrl:v8.spelling("baseURL"),withXsrfToken:v8.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let s=o&&cr.merge(o.common,o[r.method]);o&&cr.forEach(["delete","get","head","post","put","patch","query","common"],m=>{delete o[m]}),r.headers=y0.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||_Se;A&&A.legacyInterceptorReqResOrdering?a.unshift(g.fulfilled,g.rejected):a.push(g.fulfilled,g.rejected)});let u=[];this.interceptors.response.forEach(function(g){u.push(g.fulfilled,g.rejected)});let l,p=0,d;if(!c){let m=[vKr.bind(this),void 0];for(m.unshift(...a),m.push(...u),d=m.length,l=Promise.resolve(r);p<d;)l=l.then(m[p++],m[p++]);return l}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{l=vKr.call(this,f)}catch(m){return Promise.reject(m)}for(p=0,d=u.length;p<d;)l=l.then(u[p++],u[p++]);return l}getUri(t){t=hJ(this.defaults,t);let r=LUe(t.baseURL,t.url,t.allowAbsoluteUrls);return QUe(r,t.params,t.paramsSerializer)}};cr.forEach(["delete","get","head","options"],function(t){Out.prototype[t]=function(r,n){return this.request(hJ(n||{},{method:t,url:r,data:(n||{}).data}))}});cr.forEach(["post","put","patch","query"],function(t){function r(n){return function(o,s,a){return this.request(hJ(a||{},{method:t,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:s}))}}Out.prototype[t]=r(),t!=="query"&&(Out.prototype[t+"Form"]=r(!0))});u9t=Out});var WVo,e4u,t4u=h(()=>{"use strict";MUe();WVo=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 w4(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}}},e4u=WVo});function HVo(e){return function(r){return e.apply(null,r)}}var r4u=h(()=>{"use strict"});function KVo(e){return cr.isObject(e)&&e.isAxiosError===!0}var n4u=h(()=>{"use strict";sb()});var JVo,i4u,o4u=h(()=>{"use strict";JVo={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(JVo).forEach(([e,t])=>{JVo[t]=e});i4u=JVo});function s4u(e){let t=new u9t(e),r=qqt(u9t.prototype.request,t);return cr.extend(r,u9t.prototype,t,{allOwnKeys:!0}),cr.extend(r,t,null,{allOwnKeys:!0}),r.create=function(i){return s4u(hJ(e,i))},r}var mS,Cg,a4u=h(()=>{"use strict";sb();HUo();$3u();yKr();fKr();aVo();MUe();t4u();uVo();i9t();Yqt();S4();r4u();n4u();dJ();GVo();o4u();mS=s4u(Sut);mS.Axios=u9t;mS.CanceledError=w4;mS.CancelToken=e4u;mS.isCancel=$qt;mS.VERSION=ohe;mS.toFormData=LSe;mS.AxiosError=hi;mS.Cancel=mS.CanceledError;mS.all=function(t){return Promise.all(t)};mS.spread=HVo;mS.isAxiosError=KVo;mS.mergeConfig=hJ;mS.AxiosHeaders=y0;mS.formToJSON=e=>pKr(cr.isHTMLForm(e)?new FormData(e):e);mS.getAdapter=IKr.getAdapter;mS.HttpStatusCode=i4u;mS.default=mS;Cg=mS});var Ogv,l9t,Pgv,Bgv,Rgv,Dgv,kgv,Fgv,Ngv,jgv,zgv,Qgv,Mgv,Lgv,_gv,Ugv,Vgv,C8=h(()=>{"use strict";a4u();({Axios:Ogv,AxiosError:l9t,CanceledError:Pgv,isCancel:Bgv,CancelToken:Rgv,VERSION:Dgv,all:kgv,Cancel:Fgv,isAxiosError:Ngv,spread:jgv,toFormData:zgv,AxiosHeaders:Qgv,HttpStatusCode:Mgv,formToJSON:Lgv,getAdapter:_gv,mergeConfig:Ugv,create:Vgv}=Cg)});function LTm(e,t,r){let n=t,i=t?t.next:e.head,o=new Z5o(r,n,i,e);return o.next===void 0&&(e.tail=o),o.prev===void 0&&(e.head=o),e.length++,o}function _Tm(e,t){e.tail=new Z5o(t,e.tail,void 0,e),e.head||(e.head=e.tail),e.length++}function UTm(e,t){e.head=new Z5o(t,void 0,e.head,e),e.tail||(e.tail=e.head),e.length++}var L4u,SN,eJr,G5o,_4u,W5o,$Ue,rJr,G4u,YKr,XSe,f4u,q4u,ZUe,Z4u,F9t,bJ,w5o,r_u,F5o,e8o,c_u,t8o,zd,gS,r8o,z9t,Qut,gM,A_u,N9t,n8o,hM,o8o,T1m,O1m,c4u,P1m,B1m,R1m,che,uhe,USe,xKr,p9t,SKr,u4u,wKr,l4u,gJ,Put,KT,f9t,kut,JT,xN,YT,YVo,TKr,YD,LC,XVo,ZVo,p4u,$Vo,qre,e5o,OKr,d9t,GUe,T4,m9t,D1m,k1m,F1m,N1m,U4u,j1m,z1m,Q1m,nVe,M1m,$Se,IJ,h9t,xg,t5o,dhe,r5o,v5o,C5o,w9t,PKr,zut,Mut,n5o,Fut,ewe,EJ,HSe,Wre,Nut,i5o,fhe,g9t,o5o,MKr,qUe,LKr,eVe,q5o,L1m,tJr,V4u,_1m,U1m,V1m,G1m,q1m,W1m,H1m,H5o,j9t,K1m,Jre,J1m,d4u,Y1m,s5o,tVe,BKr,a5o,K5o,W4u,X1m,Z1m,H4u,$1m,eTm,K4u,tTm,rTm,nTm,iTm,oTm,sTm,aTm,cTm,J4u,Y4u,uTm,_Kr,lTm,X4u,nJr,J5o,rVe,pTm,WUe,c5o,fTm,KSe,dTm,mTm,hTm,JSe,gTm,ATm,yTm,u5o,bTm,HUe,XKr,ETm,ITm,vTm,CTm,Ef,xTm,iJr,STm,x5o,S5o,wTm,x8,KUe,lhe,l5o,m4u,Hre,A9t,VSe,h4u,b0,phe,GSe,p5o,JUe,hS,RKr,DKr,f5o,g4u,A4u,y9t,d5o,kKr,But,qSe,FKr,YUe,NKr,jKr,y4u,TTm,k9t,T9t,OTm,e_u,PTm,BTm,oJr,t_u,RTm,b4u,Y5o,sJr,X5o,DTm,kTm,E4u,FTm,n_u,NTm,I4u,v4u,C4u,T5o,x4u,b9t,UKr,O5o,VKr,P5o,B5o,R5o,D5o,YSe,ZKr,k5o,m5o,Kre,i_u,jTm,zTm,QTm,MTm,Z5o,S4u,w4u,GKr,E9t,AJ,I9t,WSe,XUe,v9t,zKr,yJ,h5o,qKr,T4u,N5o,j5o,WKr,HKr,O4u,g5o,KKr,o_u,A5o,aJr,$5o,VTm,GTm,s_u,a_u,qTm,WTm,cJr,HTm,u_u,l_u,P4u,p_u,f_u,d_u,KTm,JTm,YTm,B4u,m_u,z5o,$Kr,XTm,h_u,ZTm,g_u,y_u,uJr,$Tm,eOm,Q5o,b_u,tOm,rOm,y5o,R4u,Rut,nOm,iOm,oOm,sOm,aOm,cOm,D4u,M5o,k4u,L5o,S8,_5o,U5o,JKr,F4u,N4u,S9t,j4u,z4u,b5o,ZSe,XT,QKr,Q4u,Dut,E5o,I5o,V5o,O9t,P9t,B9t,R9t,uOm,D9t,lOm,pOm,fOm,M4u,i8o,C9t,E_u,dOm,mOm,I_u,hOm,gOm,AOm,yOm,bOm,x9t,qgv,EOm,lJr=h(()=>{"use strict";L4u=Ae(require("events"),1),SN=Ae(require("fs"),1),eJr=require("events"),G5o=Ae(require("stream"),1),_4u=require("string_decoder"),W5o=Ae(require("path"),1),$Ue=Ae(require("fs"),1),rJr=require("path"),G4u=require("events"),YKr=Ae(require("assert"),1),XSe=require("buffer"),f4u=Ae(require("zlib"),1),q4u=Ae(require("zlib"),1),ZUe=require("path"),Z4u=require("path"),F9t=Ae(require("fs"),1),bJ=Ae(require("fs"),1),w5o=Ae(require("path"),1),r_u=require("path"),F5o=Ae(require("path"),1),e8o=Ae(require("fs"),1),c_u=Ae(require("assert"),1),t8o=require("crypto"),zd=Ae(require("fs"),1),gS=Ae(require("path"),1),r8o=Ae(require("fs"),1),z9t=Ae(require("fs"),1),Qut=Ae(require("path"),1),gM=Ae(require("fs"),1),A_u=Ae(require("fs/promises"),1),N9t=Ae(require("path"),1),n8o=require("path"),hM=Ae(require("fs"),1),o8o=Ae(require("path"),1),T1m=Object.defineProperty,O1m=(e,t)=>{for(var r in t)T1m(e,r,{get:t[r],enumerable:!0})},c4u=typeof process=="object"&&process?process:{stdout:null,stderr:null},P1m=e=>!!e&&typeof e=="object"&&(e instanceof nVe||e instanceof G5o.default||B1m(e)||R1m(e)),B1m=e=>!!e&&typeof e=="object"&&e instanceof eJr.EventEmitter&&typeof e.pipe=="function"&&e.pipe!==G5o.default.Writable.prototype.pipe,R1m=e=>!!e&&typeof e=="object"&&e instanceof eJr.EventEmitter&&typeof e.write=="function"&&typeof e.end=="function",che=Symbol("EOF"),uhe=Symbol("maybeEmitEnd"),USe=Symbol("emittedEnd"),xKr=Symbol("emittingEnd"),p9t=Symbol("emittedError"),SKr=Symbol("closed"),u4u=Symbol("read"),wKr=Symbol("flush"),l4u=Symbol("flushChunk"),gJ=Symbol("encoding"),Put=Symbol("decoder"),KT=Symbol("flowing"),f9t=Symbol("paused"),kut=Symbol("resume"),JT=Symbol("buffer"),xN=Symbol("pipes"),YT=Symbol("bufferLength"),YVo=Symbol("bufferPush"),TKr=Symbol("bufferShift"),YD=Symbol("objectMode"),LC=Symbol("destroyed"),XVo=Symbol("error"),ZVo=Symbol("emitData"),p4u=Symbol("emitEnd"),$Vo=Symbol("emitEnd2"),qre=Symbol("async"),e5o=Symbol("abort"),OKr=Symbol("aborted"),d9t=Symbol("signal"),GUe=Symbol("dataListeners"),T4=Symbol("discarded"),m9t=e=>Promise.resolve().then(e),D1m=e=>e(),k1m=e=>e==="end"||e==="finish"||e==="prefinish",F1m=e=>e instanceof ArrayBuffer||!!e&&typeof e=="object"&&e.constructor&&e.constructor.name==="ArrayBuffer"&&e.byteLength>=0,N1m=e=>!Buffer.isBuffer(e)&&ArrayBuffer.isView(e),U4u=class{src;dest;opts;ondrain;constructor(e,t,r){this.src=e,this.dest=t,this.opts=r,this.ondrain=()=>e[kut](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},j1m=class extends U4u{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)}},z1m=e=>!!e.objectMode,Q1m=e=>!e.objectMode&&!!e.encoding&&e.encoding!=="buffer",nVe=class extends eJr.EventEmitter{[KT]=!1;[f9t]=!1;[xN]=[];[JT]=[];[YD];[gJ];[qre];[Put];[che]=!1;[USe]=!1;[xKr]=!1;[SKr]=!1;[p9t]=null;[YT]=0;[LC]=!1;[d9t];[OKr]=!1;[GUe]=0;[T4]=!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");z1m(t)?(this[YD]=!0,this[gJ]=null):Q1m(t)?(this[gJ]=t.encoding,this[YD]=!1):(this[YD]=!1,this[gJ]=null),this[qre]=!!t.async,this[Put]=this[gJ]?new _4u.StringDecoder(this[gJ]):null,t&&t.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[JT]}),t&&t.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[xN]});let{signal:r}=t;r&&(this[d9t]=r,r.aborted?this[e5o]():r.addEventListener("abort",()=>this[e5o]()))}get bufferLength(){return this[YT]}get encoding(){return this[gJ]}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[YD]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[qre]}set async(e){this[qre]=this[qre]||!!e}[e5o](){this[OKr]=!0,this.emit("abort",this[d9t]?.reason),this.destroy(this[d9t]?.reason)}get aborted(){return this[OKr]}set aborted(e){}write(e,t,r){if(this[OKr])return!1;if(this[che])throw new Error("write after end");if(this[LC])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[qre]?m9t:D1m;if(!this[YD]&&!Buffer.isBuffer(e)){if(N1m(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(F1m(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[YD]?(this[KT]&&this[YT]!==0&&this[wKr](!0),this[KT]?this.emit("data",e):this[YVo](e),this[YT]!==0&&this.emit("readable"),r&&n(r),this[KT]):e.length?(typeof e=="string"&&!(t===this[gJ]&&!this[Put]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[gJ]&&(e=this[Put].write(e)),this[KT]&&this[YT]!==0&&this[wKr](!0),this[KT]?this.emit("data",e):this[YVo](e),this[YT]!==0&&this.emit("readable"),r&&n(r),this[KT]):(this[YT]!==0&&this.emit("readable"),r&&n(r),this[KT])}read(e){if(this[LC])return null;if(this[T4]=!1,this[YT]===0||e===0||e&&e>this[YT])return this[uhe](),null;this[YD]&&(e=null),this[JT].length>1&&!this[YD]&&(this[JT]=[this[gJ]?this[JT].join(""):Buffer.concat(this[JT],this[YT])]);let t=this[u4u](e||null,this[JT][0]);return this[uhe](),t}[u4u](e,t){if(this[YD])this[TKr]();else{let r=t;e===r.length||e===null?this[TKr]():typeof r=="string"?(this[JT][0]=r.slice(e),t=r.slice(0,e),this[YT]-=e):(this[JT][0]=r.subarray(e),t=r.subarray(0,e),this[YT]-=e)}return this.emit("data",t),!this[JT].length&&!this[che]&&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[che]=!0,this.writable=!1,(this[KT]||!this[f9t])&&this[uhe](),this}[kut](){this[LC]||(!this[GUe]&&!this[xN].length&&(this[T4]=!0),this[f9t]=!1,this[KT]=!0,this.emit("resume"),this[JT].length?this[wKr]():this[che]?this[uhe]():this.emit("drain"))}resume(){return this[kut]()}pause(){this[KT]=!1,this[f9t]=!0,this[T4]=!1}get destroyed(){return this[LC]}get flowing(){return this[KT]}get paused(){return this[f9t]}[YVo](e){this[YD]?this[YT]+=1:this[YT]+=e.length,this[JT].push(e)}[TKr](){return this[YD]?this[YT]-=1:this[YT]-=this[JT][0].length,this[JT].shift()}[wKr](e=!1){do;while(this[l4u](this[TKr]())&&this[JT].length);!e&&!this[JT].length&&!this[che]&&this.emit("drain")}[l4u](e){return this.emit("data",e),this[KT]}pipe(e,t){if(this[LC])return e;this[T4]=!1;let r=this[USe];return t=t||{},e===c4u.stdout||e===c4u.stderr?t.end=!1:t.end=t.end!==!1,t.proxyErrors=!!t.proxyErrors,r?t.end&&e.end():(this[xN].push(t.proxyErrors?new j1m(this,e,t):new U4u(this,e,t)),this[qre]?m9t(()=>this[kut]()):this[kut]()),e}unpipe(e){let t=this[xN].find(r=>r.dest===e);t&&(this[xN].length===1?(this[KT]&&this[GUe]===0&&(this[KT]=!1),this[xN]=[]):this[xN].splice(this[xN].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[T4]=!1,this[GUe]++,!this[xN].length&&!this[KT]&&this[kut]();else if(e==="readable"&&this[YT]!==0)super.emit("readable");else if(k1m(e)&&this[USe])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[p9t]){let n=t;this[qre]?m9t(()=>n.call(this,this[p9t])):n.call(this,this[p9t])}return r}removeListener(e,t){return this.off(e,t)}off(e,t){let r=super.off(e,t);return e==="data"&&(this[GUe]=this.listeners("data").length,this[GUe]===0&&!this[T4]&&!this[xN].length&&(this[KT]=!1)),r}removeAllListeners(e){let t=super.removeAllListeners(e);return(e==="data"||e===void 0)&&(this[GUe]=0,!this[T4]&&!this[xN].length&&(this[KT]=!1)),t}get emittedEnd(){return this[USe]}[uhe](){!this[xKr]&&!this[USe]&&!this[LC]&&this[JT].length===0&&this[che]&&(this[xKr]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[SKr]&&this.emit("close"),this[xKr]=!1)}emit(e,...t){let r=t[0];if(e!=="error"&&e!=="close"&&e!==LC&&this[LC])return!1;if(e==="data")return!this[YD]&&!r?!1:this[qre]?(m9t(()=>this[ZVo](r)),!0):this[ZVo](r);if(e==="end")return this[p4u]();if(e==="close"){if(this[SKr]=!0,!this[USe]&&!this[LC])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(e==="error"){this[p9t]=r,super.emit(XVo,r);let i=!this[d9t]||this.listeners("error").length?super.emit("error",r):!1;return this[uhe](),i}else if(e==="resume"){let i=super.emit("resume");return this[uhe](),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[uhe](),n}[ZVo](e){for(let r of this[xN])r.dest.write(e)===!1&&this.pause();let t=this[T4]?!1:super.emit("data",e);return this[uhe](),t}[p4u](){return this[USe]?!1:(this[USe]=!0,this.readable=!1,this[qre]?(m9t(()=>this[$Vo]()),!0):this[$Vo]())}[$Vo](){if(this[Put]){let t=this[Put].end();if(t){for(let r of this[xN])r.dest.write(t);this[T4]||super.emit("data",t)}}for(let t of this[xN])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[YD]||(e.dataLength=0);let t=this.promise();return this.on("data",r=>{e.push(r),this[YD]||(e.dataLength+=r.length)}),await t,e}async concat(){if(this[YD])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[gJ]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(LC,()=>t(new Error("stream destroyed"))),this.on("error",r=>t(r)),this.on("end",()=>e())})}[Symbol.asyncIterator](){this[T4]=!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[che])return t();let n,i,o=u=>{this.off("data",s),this.off("end",a),this.off(LC,c),t(),i(u)},s=u=>{this.off("error",o),this.off("end",a),this.off(LC,c),this.pause(),n({value:u,done:!!this[che]})},a=()=>{this.off("error",o),this.off("data",s),this.off(LC,c),t(),n({done:!0,value:void 0})},c=()=>o(new Error("stream destroyed"));return new Promise((u,l)=>{i=l,n=u,this.once(LC,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[T4]=!1;let e=!1,t=()=>(this.pause(),this.off(XVo,t),this.off(LC,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(XVo,t),this.once(LC,t),{next:r,throw:t,return:t,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(e){if(this[LC])return e?this.emit("error",e):this.emit(LC),this;this[LC]=!0,this[T4]=!0,this[JT].length=0,this[YT]=0;let t=this;return typeof t.close=="function"&&!this[SKr]&&t.close(),e?this.emit("error",e):this.emit(LC),this}static get isStream(){return P1m}},M1m=SN.default.writev,$Se=Symbol("_autoClose"),IJ=Symbol("_close"),h9t=Symbol("_ended"),xg=Symbol("_fd"),t5o=Symbol("_finished"),dhe=Symbol("_flags"),r5o=Symbol("_flush"),v5o=Symbol("_handleChunk"),C5o=Symbol("_makeBuf"),w9t=Symbol("_mode"),PKr=Symbol("_needDrain"),zut=Symbol("_onerror"),Mut=Symbol("_onopen"),n5o=Symbol("_onread"),Fut=Symbol("_onwrite"),ewe=Symbol("_open"),EJ=Symbol("_path"),HSe=Symbol("_pos"),Wre=Symbol("_queue"),Nut=Symbol("_read"),i5o=Symbol("_readSize"),fhe=Symbol("_reading"),g9t=Symbol("_remain"),o5o=Symbol("_size"),MKr=Symbol("_write"),qUe=Symbol("_writing"),LKr=Symbol("_defaultFlag"),eVe=Symbol("_errored"),q5o=class extends nVe{[eVe]=!1;[xg];[EJ];[i5o];[fhe]=!1;[o5o];[g9t];[$Se];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[eVe]=!1,this[xg]=typeof t.fd=="number"?t.fd:void 0,this[EJ]=e,this[i5o]=t.readSize||16*1024*1024,this[fhe]=!1,this[o5o]=typeof t.size=="number"?t.size:1/0,this[g9t]=this[o5o],this[$Se]=typeof t.autoClose=="boolean"?t.autoClose:!0,typeof this[xg]=="number"?this[Nut]():this[ewe]()}get fd(){return this[xg]}get path(){return this[EJ]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[ewe](){SN.default.open(this[EJ],"r",(e,t)=>this[Mut](e,t))}[Mut](e,t){e?this[zut](e):(this[xg]=t,this.emit("open",t),this[Nut]())}[C5o](){return Buffer.allocUnsafe(Math.min(this[i5o],this[g9t]))}[Nut](){if(!this[fhe]){this[fhe]=!0;let e=this[C5o]();if(e.length===0)return process.nextTick(()=>this[n5o](null,0,e));SN.default.read(this[xg],e,0,e.length,null,(t,r,n)=>this[n5o](t,r,n))}}[n5o](e,t,r){this[fhe]=!1,e?this[zut](e):this[v5o](t,r)&&this[Nut]()}[IJ](){if(this[$Se]&&typeof this[xg]=="number"){let e=this[xg];this[xg]=void 0,SN.default.close(e,t=>t?this.emit("error",t):this.emit("close"))}}[zut](e){this[fhe]=!0,this[IJ](),this.emit("error",e)}[v5o](e,t){let r=!1;return this[g9t]-=e,e>0&&(r=super.write(e<t.length?t.subarray(0,e):t)),(e===0||this[g9t]<=0)&&(r=!1,this[IJ](),super.end()),r}emit(e,...t){switch(e){case"prefinish":case"finish":return!1;case"drain":return typeof this[xg]=="number"&&this[Nut](),!1;case"error":return this[eVe]?!1:(this[eVe]=!0,super.emit(e,...t));default:return super.emit(e,...t)}}},L1m=class extends q5o{[ewe](){let e=!0;try{this[Mut](null,SN.default.openSync(this[EJ],"r")),e=!1}finally{e&&this[IJ]()}}[Nut](){let e=!0;try{if(!this[fhe]){this[fhe]=!0;do{let t=this[C5o](),r=t.length===0?0:SN.default.readSync(this[xg],t,0,t.length,null);if(!this[v5o](r,t))break}while(!0);this[fhe]=!1}e=!1}finally{e&&this[IJ]()}}[IJ](){if(this[$Se]&&typeof this[xg]=="number"){let e=this[xg];this[xg]=void 0,SN.default.closeSync(e),this.emit("close")}}},tJr=class extends L4u.default{readable=!1;writable=!0;[eVe]=!1;[qUe]=!1;[h9t]=!1;[Wre]=[];[PKr]=!1;[EJ];[w9t];[$Se];[xg];[LKr];[dhe];[t5o]=!1;[HSe];constructor(e,t){t=t||{},super(t),this[EJ]=e,this[xg]=typeof t.fd=="number"?t.fd:void 0,this[w9t]=t.mode===void 0?438:t.mode,this[HSe]=typeof t.start=="number"?t.start:void 0,this[$Se]=typeof t.autoClose=="boolean"?t.autoClose:!0;let r=this[HSe]!==void 0?"r+":"w";this[LKr]=t.flags===void 0,this[dhe]=t.flags===void 0?r:t.flags,this[xg]===void 0&&this[ewe]()}emit(e,...t){if(e==="error"){if(this[eVe])return!1;this[eVe]=!0}return super.emit(e,...t)}get fd(){return this[xg]}get path(){return this[EJ]}[zut](e){this[IJ](),this[qUe]=!0,this.emit("error",e)}[ewe](){SN.default.open(this[EJ],this[dhe],this[w9t],(e,t)=>this[Mut](e,t))}[Mut](e,t){this[LKr]&&this[dhe]==="r+"&&e&&e.code==="ENOENT"?(this[dhe]="w",this[ewe]()):e?this[zut](e):(this[xg]=t,this.emit("open",t),this[qUe]||this[r5o]())}end(e,t){return e&&this.write(e,t),this[h9t]=!0,!this[qUe]&&!this[Wre].length&&typeof this[xg]=="number"&&this[Fut](null,0),this}write(e,t){return typeof e=="string"&&(e=Buffer.from(e,t)),this[h9t]?(this.emit("error",new Error("write() after end()")),!1):this[xg]===void 0||this[qUe]||this[Wre].length?(this[Wre].push(e),this[PKr]=!0,!1):(this[qUe]=!0,this[MKr](e),!0)}[MKr](e){SN.default.write(this[xg],e,0,e.length,this[HSe],(t,r)=>this[Fut](t,r))}[Fut](e,t){e?this[zut](e):(this[HSe]!==void 0&&typeof t=="number"&&(this[HSe]+=t),this[Wre].length?this[r5o]():(this[qUe]=!1,this[h9t]&&!this[t5o]?(this[t5o]=!0,this[IJ](),this.emit("finish")):this[PKr]&&(this[PKr]=!1,this.emit("drain"))))}[r5o](){if(this[Wre].length===0)this[h9t]&&this[Fut](null,0);else if(this[Wre].length===1)this[MKr](this[Wre].pop());else{let e=this[Wre];this[Wre]=[],M1m(this[xg],e,this[HSe],(t,r)=>this[Fut](t,r))}}[IJ](){if(this[$Se]&&typeof this[xg]=="number"){let e=this[xg];this[xg]=void 0,SN.default.close(e,t=>t?this.emit("error",t):this.emit("close"))}}},V4u=class extends tJr{[ewe](){let e;if(this[LKr]&&this[dhe]==="r+")try{e=SN.default.openSync(this[EJ],this[dhe],this[w9t])}catch(t){if(t?.code==="ENOENT")return this[dhe]="w",this[ewe]();throw t}else e=SN.default.openSync(this[EJ],this[dhe],this[w9t]);this[Mut](null,e)}[IJ](){if(this[$Se]&&typeof this[xg]=="number"){let e=this[xg];this[xg]=void 0,SN.default.closeSync(e),this.emit("close")}}[MKr](e){let t=!0;try{this[Fut](null,SN.default.writeSync(this[xg],e,0,e.length,this[HSe])),t=!1}finally{if(t)try{this[IJ]()}catch{}}}},_1m=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"]]),U1m=e=>!!e.sync&&!!e.file,V1m=e=>!e.sync&&!!e.file,G1m=e=>!!e.sync&&!e.file,q1m=e=>!e.sync&&!e.file,W1m=e=>!!e.file,H1m=e=>_1m.get(e)||e,H5o=(e={})=>{if(!e)return{};let t={};for(let[r,n]of Object.entries(e)){let i=H1m(r);t[i]=n}return t.chmod===void 0&&t.noChmod===!1&&(t.chmod=!0),delete t.noChmod,t},j9t=(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=H5o(o);if(i?.(c,s),U1m(c)){if(typeof a=="function")throw new TypeError("callback not supported for sync tar functions");return e(c,s)}else if(V1m(c)){let u=t(c,s);return a?u.then(()=>a(),a):u}else if(G1m(c)){if(typeof a=="function")throw new TypeError("callback not supported for sync tar functions");return r(c,s)}else if(q1m(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}),K1m=q4u.default.constants||{ZLIB_VERNUM:4736},Jre=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},K1m)),J1m=XSe.Buffer.concat,d4u=Object.getOwnPropertyDescriptor(XSe.Buffer,"concat"),Y1m=e=>e,s5o=d4u?.writable===!0||d4u?.set!==void 0?e=>{XSe.Buffer.concat=e?Y1m:J1m}:e=>{},tVe=Symbol("_superWrite"),BKr=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"}},a5o=Symbol("flushFlag"),K5o=class extends nVe{#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 f4u[t]!="function")throw new TypeError("Compression method not supported: "+t);try{this.#o=new f4u[t](e)}catch(r){throw new BKr(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 BKr(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,YKr.default)(this.#o,"zlib binding closed"),this.#o.reset?.()}flush(e){this.ended||(typeof e!="number"&&(e=this.#i),this.write(Object.assign(XSe.Buffer.alloc(0),{[a5o]: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}[tVe](e){return super.write(e)}write(e,t,r){if(typeof t=="function"&&(r=t,t="utf8"),typeof e=="string"&&(e=XSe.Buffer.from(e,t)),this.#e)return;(0,YKr.default)(this.#o,"zlib binding closed");let n=this.#o._handle,i=n.close;n.close=()=>{};let o=this.#o.close;this.#o.close=()=>{},s5o(!0);let s;try{let c=typeof e[a5o]=="number"?e[a5o]:this.#r;s=this.#o._processChunk(e,c),s5o(!1)}catch(c){s5o(!1),this.#s(new BKr(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 BKr(c,this.write)));let a;if(s)if(Array.isArray(s)&&s.length>0){let c=s[0];a=this[tVe](XSe.Buffer.from(c));for(let u=1;u<s.length;u++)a=this[tVe](s[u])}else a=this[tVe](XSe.Buffer.from(s));return r&&r(),a}},W4u=class extends K5o{#e;#t;constructor(e,t){e=e||{},e.flush=e.flush||Jre.Z_NO_FLUSH,e.finishFlush=e.finishFlush||Jre.Z_FINISH,e.fullFlushFlag=Jre.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(Jre.Z_SYNC_FLUSH),(0,YKr.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)}}}},X1m=class extends W4u{#e;constructor(e){super(e,"Gzip"),this.#e=e&&!!e.portable}[tVe](e){return this.#e?(this.#e=!1,e[9]=255,super[tVe](e)):super[tVe](e)}},Z1m=class extends W4u{constructor(e){super(e,"Unzip")}},H4u=class extends K5o{constructor(e,t){e=e||{},e.flush=e.flush||Jre.BROTLI_OPERATION_PROCESS,e.finishFlush=e.finishFlush||Jre.BROTLI_OPERATION_FINISH,e.fullFlushFlag=Jre.BROTLI_OPERATION_FLUSH,super(e,t)}},$1m=class extends H4u{constructor(e){super(e,"BrotliCompress")}},eTm=class extends H4u{constructor(e){super(e,"BrotliDecompress")}},K4u=class extends K5o{constructor(e,t){e=e||{},e.flush=e.flush||Jre.ZSTD_e_continue,e.finishFlush=e.finishFlush||Jre.ZSTD_e_end,e.fullFlushFlag=Jre.ZSTD_e_flush,super(e,t)}},tTm=class extends K4u{constructor(e){super(e,"ZstdCompress")}},rTm=class extends K4u{constructor(e){super(e,"ZstdDecompress")}},nTm=(e,t)=>{if(Number.isSafeInteger(e))e<0?oTm(e,t):iTm(e,t);else throw Error("cannot encode number outside of javascript safe integer range");return t},iTm=(e,t)=>{t[0]=128;for(var r=t.length;r>1;r--)t[r-1]=e&255,e=Math.floor(e/256)},oTm=(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]=J4u(i):i===0?t[n-1]=0:(r=!0,t[n-1]=Y4u(i))}},sTm=e=>{let t=e[0],r=t===128?cTm(e.subarray(1,e.length)):t===255?aTm(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},aTm=e=>{for(var t=e.length,r=0,n=!1,i=t-1;i>-1;i--){var o=Number(e[i]),s;n?s=J4u(o):o===0?s=o:(n=!0,s=Y4u(o)),s!==0&&(r-=s*Math.pow(256,t-i-1))}return r},cTm=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},J4u=e=>(255^e)&255,Y4u=e=>(255^e)+1&255,uTm={};O1m(uTm,{code:()=>J5o,isCode:()=>_Kr,isName:()=>lTm,name:()=>nJr,normalFsTypes:()=>X4u});_Kr=e=>nJr.has(e),lTm=e=>J5o.has(e),X4u=new Set(["0","","1","2","3","4","5","6","7","D"]),nJr=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"]]),J5o=new Map(Array.from(nJr).map(e=>[e[1],e[0]])),rVe=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=WUe(e,t+156,1),o=X4u.has(i),s=o?r:void 0,a=o?n:void 0;if(this.path=s?.path??WUe(e,t,100),this.mode=s?.mode??a?.mode??KSe(e,t+100,8),this.uid=s?.uid??a?.uid??KSe(e,t+108,8),this.gid=s?.gid??a?.gid??KSe(e,t+116,8),this.size=s?.size??a?.size??KSe(e,t+124,12),this.mtime=s?.mtime??a?.mtime??c5o(e,t+136,12),this.cksum=KSe(e,t+148,12),a&&this.#t(a,!0),s&&this.#t(s),_Kr(i)&&(this.#e=i||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=WUe(e,t+157,100),e.subarray(t+257,t+265).toString()==="ustar\x0000")if(this.uname=s?.uname??a?.uname??WUe(e,t+265,32),this.gname=s?.gname??a?.gname??WUe(e,t+297,32),this.devmaj=s?.devmaj??a?.devmaj??KSe(e,t+329,8)??0,this.devmin=s?.devmin??a?.devmin??KSe(e,t+337,8)??0,e[t+475]!==0){let u=WUe(e,t+345,155);this.path=u+"/"+this.path}else{let u=WUe(e,t+345,130);u&&(this.path=u+"/"+this.path),this.atime=r?.atime??n?.atime??c5o(e,t+476,12),this.ctime=r?.ctime??n?.ctime??c5o(e,t+488,12)}let c=256;for(let u=t;u<t+148;u++)c+=e[u];for(let u=t+156;u<t+512;u++)c+=e[u];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=pTm(this.path||"",r),i=n[0],o=n[1];this.needPax=!!n[2],this.needPax=HUe(e,t,100,i)||this.needPax,this.needPax=JSe(e,t+100,8,this.mode)||this.needPax,this.needPax=JSe(e,t+108,8,this.uid)||this.needPax,this.needPax=JSe(e,t+116,8,this.gid)||this.needPax,this.needPax=JSe(e,t+124,12,this.size)||this.needPax,this.needPax=u5o(e,t+136,12,this.mtime)||this.needPax,e[t+156]=Number(this.#e.codePointAt(0)),this.needPax=HUe(e,t+157,100,this.linkpath)||this.needPax,e.write("ustar\x0000",t+257,8),this.needPax=HUe(e,t+265,32,this.uname)||this.needPax,this.needPax=HUe(e,t+297,32,this.gname)||this.needPax,this.needPax=JSe(e,t+329,8,this.devmaj)||this.needPax,this.needPax=JSe(e,t+337,8,this.devmin)||this.needPax,this.needPax=HUe(e,t+345,r,o)||this.needPax,e[t+475]!==0?this.needPax=HUe(e,t+345,155,o)||this.needPax:(this.needPax=HUe(e,t+345,130,o)||this.needPax,this.needPax=u5o(e,t+476,12,this.atime)||this.needPax,this.needPax=u5o(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,JSe(e,t+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:nJr.get(this.#e)}get typeKey(){return this.#e}set type(e){let t=String(J5o.get(e));if(_Kr(t)||t==="Unsupported")this.#e=t;else if(_Kr(e))this.#e=e;else throw new TypeError("invalid entry type: "+e)}},pTm=(e,t)=>{let r=e,n="",i,o=ZUe.posix.parse(e).root||".";if(Buffer.byteLength(r)<100)i=[r,n,!1];else{n=ZUe.posix.dirname(r),r=ZUe.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=ZUe.posix.join(ZUe.posix.basename(n),r),n=ZUe.posix.dirname(n));while(n!==o&&i===void 0);i||(i=[e.slice(0,99),"",!0])}return i},WUe=(e,t,r)=>e.subarray(t,t+r).toString("utf8").replace(/\0.*/,""),c5o=(e,t,r)=>fTm(KSe(e,t,r)),fTm=e=>e===void 0?void 0:new Date(e*1e3),KSe=(e,t,r)=>Number(e[t])&128?sTm(e.subarray(t,t+r)):mTm(e,t,r),dTm=e=>isNaN(e)?void 0:e,mTm=(e,t,r)=>dTm(parseInt(e.subarray(t,t+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),hTm={12:8589934591,8:2097151},JSe=(e,t,r,n)=>n===void 0?!1:n>hTm[r]||n<0?(nTm(n,e.subarray(t,t+r)),!0):(gTm(e,t,r,n),!1),gTm=(e,t,r,n)=>e.write(ATm(n,r),t,r,"ascii"),ATm=(e,t)=>yTm(Math.floor(e).toString(8),t),yTm=(e,t)=>(e.length===t-1?e:new Array(t-e.length-1).join("0")+e+" ")+"\0",u5o=(e,t,r,n)=>n===void 0?!1:JSe(e,t,r,n.getTime()/1e3),bTm=new Array(156).join("\0"),HUe=(e,t,r,n)=>n===void 0?!1:(e.write(n+bTm,t,r,"utf8"),n.length!==Buffer.byteLength(n)||n.length>r),XKr=class $4u{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 rVe({path:("PaxHeader/"+(0,Z4u.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+`
|
|
538
538
|
`,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 $4u(ETm(ITm(t),r),n)}},ETm=(e,t)=>t?Object.assign({},t,e):e,ITm=e=>e.replace(/\n$/,"").split(`
|
|
539
|
-
`).reduce(vTm,Object.create(null)),vTm=(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},CTm=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Ef=CTm!=="win32"?e=>e:e=>e&&e.replaceAll(/\\/g,"/"),xTm=class extends nVe{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=Ef(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?Ef(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=Ef(e.path)),e.linkpath&&(e.linkpath=Ef(e.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(e).filter(([r,n])=>!(n==null||r==="path"&&t))))}},iJr=(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))},STm=1024*1024,x5o=Buffer.from([31,139]),S5o=Buffer.from([40,181,47,253]),wTm=Math.max(x5o.length,S5o.length),x8=Symbol("state"),KUe=Symbol("writeEntry"),lhe=Symbol("readEntry"),l5o=Symbol("nextEntry"),m4u=Symbol("processEntry"),Hre=Symbol("extendedHeader"),A9t=Symbol("globalExtendedHeader"),VSe=Symbol("meta"),h4u=Symbol("emitMeta"),b0=Symbol("buffer"),phe=Symbol("queue"),GSe=Symbol("ended"),p5o=Symbol("emittedEnd"),JUe=Symbol("emit"),hS=Symbol("unzip"),RKr=Symbol("consumeChunk"),DKr=Symbol("consumeChunkSub"),f5o=Symbol("consumeBody"),g4u=Symbol("consumeMeta"),A4u=Symbol("consumeHeader"),y9t=Symbol("consuming"),d5o=Symbol("bufferConcat"),kKr=Symbol("maybeEnd"),But=Symbol("writing"),qSe=Symbol("aborted"),FKr=Symbol("onDone"),YUe=Symbol("sawValidEntry"),NKr=Symbol("sawNullBlock"),jKr=Symbol("sawEOF"),y4u=Symbol("closeStream"),TTm=()=>!0,k9t=class extends G4u.EventEmitter{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[phe]=[];[b0];[lhe];[KUe];[x8]="begin";[VSe]="";[Hre];[A9t];[GSe]=!1;[hS];[qSe]=!1;[YUe];[NKr]=!1;[jKr]=!1;[But]=!1;[y9t]=!1;[p5o]=!1;constructor(e={}){super(),this.file=e.file||"",this.on(FKr,()=>{(this[x8]==="begin"||this[YUe]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),e.ondone?this.on(FKr,e.ondone):this.on(FKr,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!e.strict,this.maxMetaEntrySize=e.maxMetaEntrySize||STm,this.filter=typeof e.filter=="function"?e.filter:TTm;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[y4u]()),typeof e.onwarn=="function"&&this.on("warn",e.onwarn),typeof e.onReadEntry=="function"&&this.on("entry",e.onReadEntry)}warn(e,t,r={}){iJr(this,e,t,r)}[A4u](e,t){this[YUe]===void 0&&(this[YUe]=!1);let r;try{r=new rVe(e,t,this[Hre],this[A9t])}catch(n){return this.warn("TAR_ENTRY_INVALID",n)}if(r.nullBlock)this[NKr]?(this[jKr]=!0,this[x8]==="begin"&&(this[x8]="header"),this[JUe]("eof")):(this[NKr]=!0,this[JUe]("nullBlock"));else if(this[NKr]=!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[KUe]=new xTm(r,this[Hre],this[A9t]);if(!this[YUe])if(i.remain){let o=()=>{i.invalid||(this[YUe]=!0)};i.on("end",o)}else this[YUe]=!0;i.meta?i.size>this.maxMetaEntrySize?(i.ignore=!0,this[JUe]("ignoredEntry",i),this[x8]="ignore",i.resume()):i.size>0&&(this[VSe]="",i.on("data",o=>this[VSe]+=o),this[x8]="meta"):(this[Hre]=void 0,i.ignore=i.ignore||!this.filter(i.path,i),i.ignore?(this[JUe]("ignoredEntry",i),this[x8]=i.remain?"ignore":"header",i.resume()):(i.remain?this[x8]="body":(this[x8]="header",i.end()),this[lhe]?this[phe].push(i):(this[phe].push(i),this[l5o]())))}}}[y4u](){queueMicrotask(()=>this.emit("close"))}[m4u](e){let t=!0;if(!e)this[lhe]=void 0,t=!1;else if(Array.isArray(e)){let[r,...n]=e;this.emit(r,...n)}else this[lhe]=e,this.emit("entry",e),e.emittedEnd||(e.on("end",()=>this[l5o]()),t=!1);return t}[l5o](){do;while(this[m4u](this[phe].shift()));if(this[phe].length===0){let e=this[lhe];!e||e.flowing||e.size===e.remain?this[But]||this.emit("drain"):e.once("drain",()=>this.emit("drain"))}}[f5o](e,t){let r=this[KUe];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[x8]="header",this[KUe]=void 0,r.end()),i.length}[g4u](e,t){let r=this[KUe],n=this[f5o](e,t);return!this[KUe]&&r&&this[h4u](r),n}[JUe](e,t,r){this[phe].length===0&&!this[lhe]?this.emit(e,t,r):this[phe].push([e,t,r])}[h4u](e){switch(this[JUe]("meta",this[VSe]),e.type){case"ExtendedHeader":case"OldExtendedHeader":this[Hre]=XKr.parse(this[VSe],this[Hre],!1);break;case"GlobalExtendedHeader":this[A9t]=XKr.parse(this[VSe],this[A9t],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let t=this[Hre]??Object.create(null);this[Hre]=t,t.path=this[VSe].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let t=this[Hre]||Object.create(null);this[Hre]=t,t.linkpath=this[VSe].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+e.type)}}abort(e){this[qSe]=!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[qSe])return r?.(),!1;if((this[hS]===void 0||this.brotli===void 0&&this[hS]===!1)&&e){if(this[b0]&&(e=Buffer.concat([this[b0],e]),this[b0]=void 0),e.length<wTm)return this[b0]=e,r?.(),!0;for(let s=0;this[hS]===void 0&&s<x5o.length;s++)e[s]!==x5o[s]&&(this[hS]=!1);let i=!1;if(this[hS]===!1&&this.zstd!==!1){i=!0;for(let s=0;s<S5o.length;s++)if(e[s]!==S5o[s]){i=!1;break}}let o=this.brotli===void 0&&!i;if(this[hS]===!1&&o)if(e.length<512)if(this[GSe])this.brotli=!0;else return this[b0]=e,r?.(),!0;else try{new rVe(e.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[hS]===void 0||this[hS]===!1&&(this.brotli||i)){let s=this[GSe];this[GSe]=!1,this[hS]=this[hS]===void 0?new Z1m({}):i?new rTm({}):new eTm({}),this[hS].on("data",c=>this[RKr](c)),this[hS].on("error",c=>this.abort(c)),this[hS].on("end",()=>{this[GSe]=!0,this[RKr]()}),this[But]=!0;let a=!!this[hS][s?"end":"write"](e);return this[But]=!1,r?.(),a}}this[But]=!0,this[hS]?this[hS].write(e):this[RKr](e),this[But]=!1;let n=this[phe].length>0?!1:this[lhe]?this[lhe].flowing:!0;return!n&&this[phe].length===0&&this[lhe]?.once("drain",()=>this.emit("drain")),r?.(),n}[d5o](e){e&&!this[qSe]&&(this[b0]=this[b0]?Buffer.concat([this[b0],e]):e)}[kKr](){if(this[GSe]&&!this[p5o]&&!this[qSe]&&!this[y9t]){this[p5o]=!0;let e=this[KUe];if(e&&e.blockRemain){let t=this[b0]?this[b0].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${e.blockRemain} more bytes, only ${t} available)`,{entry:e}),this[b0]&&e.write(this[b0]),e.end()}this[JUe](FKr)}}[RKr](e){if(this[y9t]&&e)this[d5o](e);else if(!e&&!this[b0])this[kKr]();else if(e){if(this[y9t]=!0,this[b0]){this[d5o](e);let t=this[b0];this[b0]=void 0,this[DKr](t)}else this[DKr](e);for(;this[b0]&&this[b0]?.length>=512&&!this[qSe]&&!this[jKr];){let t=this[b0];this[b0]=void 0,this[DKr](t)}this[y9t]=!1}(!this[b0]||this[GSe])&&this[kKr]()}[DKr](e){let t=0,r=e.length;for(;t+512<=r&&!this[qSe]&&!this[jKr];)switch(this[x8]){case"begin":case"header":this[A4u](e,t),t+=512;break;case"ignore":case"body":t+=this[f5o](e,t);break;case"meta":t+=this[g4u](e,t);break;default:throw new Error("invalid state: "+this[x8])}t<r&&(this[b0]=this[b0]?Buffer.concat([e.subarray(t),this[b0]]):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[qSe]||(this[hS]?(e&&this[hS].write(e),this[hS].end()):(this[GSe]=!0,(this.brotli===void 0||this.zstd===void 0)&&(e=e||Buffer.alloc(0)),e&&this.write(e),this[kKr]())),this}},T9t=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)},OTm=e=>{let t=e.onReadEntry;e.onReadEntry=t?r=>{t(r),r.resume()}:r=>r.resume()},e_u=(e,t)=>{let r=new Map(t.map(o=>[T9t(o),!0])),n=e.filter,i=(o,s="")=>{let a=s||(0,rJr.parse)(o).root||".",c;if(o===a)c=!1;else{let u=r.get(o);c=u!==void 0?u:i((0,rJr.dirname)(o),a)}return r.set(o,c),c};e.filter=n?(o,s)=>n(o,s)&&i(T9t(o)):o=>i(T9t(o))},PTm=e=>{let t=new k9t(e),r=e.file,n;try{n=$Ue.default.openSync(r,"r");let i=$Ue.default.fstatSync(n),o=e.maxReadSize||16*1024*1024;if(i.size<o){let s=Buffer.allocUnsafe(i.size),a=$Ue.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=$Ue.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{$Ue.default.closeSync(n)}catch{}}},BTm=(e,t)=>{let r=new k9t(e),n=e.maxReadSize||16*1024*1024,i=e.file;return new Promise((o,s)=>{r.on("error",s),r.on("end",o),$Ue.default.stat(i,(a,c)=>{if(a)s(a);else{let u=new q5o(i,{readSize:n,size:c.size});u.on("error",s),u.pipe(r)}})})},oJr=j9t(PTm,BTm,e=>new k9t(e),e=>new k9t(e),(e,t)=>{t?.length&&e_u(e,t),e.noResume||OTm(e)}),t_u=(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:RTm,parse:b4u}=r_u.win32,Y5o=e=>{let t="",r=b4u(e);for(;RTm(e)||r.root;){let n=e.charAt(0)==="/"&&e.slice(0,4)!=="//?/"?"/":r.root;e=e.slice(n.length),t+=n,r=b4u(e)}return[t,e]},sJr=["|","<",">","?",":"],X5o=sJr.map(e=>String.fromCodePoint(61440+Number(e.codePointAt(0)))),DTm=new Map(sJr.map((e,t)=>[e,X5o[t]])),kTm=new Map(X5o.map((e,t)=>[e,sJr[t]])),E4u=e=>sJr.reduce((t,r)=>t.split(r).join(DTm.get(r)),e),FTm=e=>X5o.reduce((t,r)=>t.split(r).join(kTm.get(r)),e),n_u=(e,t)=>t?(e=Ef(e).replace(/^\.(\/|$)/,""),T9t(t)+"/"+e):Ef(e),NTm=16*1024*1024,I4u=Symbol("process"),v4u=Symbol("file"),C4u=Symbol("directory"),T5o=Symbol("symlink"),x4u=Symbol("hardlink"),b9t=Symbol("header"),UKr=Symbol("read"),O5o=Symbol("lstat"),VKr=Symbol("onlstat"),P5o=Symbol("onread"),B5o=Symbol("onreadlink"),R5o=Symbol("openfile"),D5o=Symbol("onopenfile"),YSe=Symbol("close"),ZKr=Symbol("mode"),k5o=Symbol("awaitDrain"),m5o=Symbol("ondrain"),Kre=Symbol("prefix"),i_u=class extends nVe{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=H5o(t);super(),this.path=Ef(e),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||NTm,this.linkCache=r.linkCache||new Map,this.statCache=r.statCache||new Map,this.preservePaths=!!r.preservePaths,this.cwd=Ef(r.cwd||process.cwd()),this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.mtime=r.mtime,this.prefix=r.prefix?Ef(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]=Y5o(this.path);o&&typeof s=="string"&&(this.path=s,n=o)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=FTm(this.path.replaceAll(/\\/g,"/")),e=e.replaceAll(/\\/g,"/")),this.absolute=Ef(r.absolute||w5o.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[VKr](i):this[O5o]()}warn(e,t,r={}){return iJr(this,e,t,r)}emit(e,...t){return e==="error"&&(this.#e=!0),super.emit(e,...t)}[O5o](){bJ.default.lstat(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[VKr](t)})}[VKr](e){this.statCache.set(this.absolute,e),this.stat=e,e.isFile()||(e.size=0),this.type=QTm(e),this.emit("stat",e),this[I4u]()}[I4u](){switch(this.type){case"File":return this[v4u]();case"Directory":return this[C4u]();case"SymbolicLink":return this[T5o]();default:return this.end()}}[ZKr](e){return t_u(e,this.type==="Directory",this.portable)}[Kre](e){return n_u(e,this.prefix)}[b9t](){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 rVe({path:this[Kre](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Kre](this.linkpath):this.linkpath,mode:this[ZKr](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 XKr({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[Kre](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Kre](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)}[C4u](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[b9t](),this.end()}[T5o](){bJ.default.readlink(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[B5o](t)})}[B5o](e){this.linkpath=Ef(e),this[b9t](),this.end()}[x4u](e){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=Ef(w5o.default.relative(this.cwd,e)),this.stat.size=0,this[b9t](),this.end()}[v4u](){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[x4u](t);this.linkCache.set(e,this.absolute)}if(this[b9t](),this.stat.size===0)return this.end();this[R5o]()}[R5o](){bJ.default.open(this.absolute,"r",(e,t)=>{if(e)return this.emit("error",e);this[D5o](t)})}[D5o](e){if(this.fd=e,this.#e)return this[YSe]();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[UKr]()}[UKr](){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");bJ.default.read(e,t,r,n,i,(o,s)=>{if(o)return this[YSe](()=>this.emit("error",o));this[P5o](s)})}[YSe](e=()=>{}){this.fd!==void 0&&bJ.default.close(this.fd,e)}[P5o](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[YSe](()=>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[YSe](()=>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[m5o]():this[k5o](()=>this[m5o]())}[k5o](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)}[m5o](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[YSe](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[UKr]()}},jTm=class extends i_u{sync=!0;[O5o](){this[VKr](bJ.default.lstatSync(this.absolute))}[T5o](){this[B5o](bJ.default.readlinkSync(this.absolute))}[R5o](){this[D5o](bJ.default.openSync(this.absolute,"r"))}[UKr](){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=bJ.default.readSync(t,r,n,i,o);this[P5o](s),e=!1}finally{if(e)try{this[YSe](()=>{})}catch{}}}[k5o](e){e()}[YSe](e=()=>{}){this.fd!==void 0&&bJ.default.closeSync(this.fd),e()}},zTm=class extends nVe{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 iJr(this,e,t,r)}constructor(e,t={}){let r=H5o(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=Ef(e.path),this.mode=e.mode!==void 0?this[ZKr](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?Ef(e.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let i=!1;if(!this.preservePaths){let[s,a]=Y5o(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 rVe({path:this[Kre](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Kre](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 XKr({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[Kre](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Kre](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)}[Kre](e){return n_u(e,this.prefix)}[ZKr](e){return t_u(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}},QTm=e=>e.isFile()?"File":e.isDirectory()?"Directory":e.isSymbolicLink()?"SymbolicLink":"Unsupported",MTm=class jut{tail;head;length=0;static create(t=[]){return new jut(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++)_Tm(this,t[r]);return this.length}unshift(...t){for(var r=0,n=t.length;r<n;r++)UTm(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 jut;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 jut;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 jut;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 jut;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=LTm(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}};Z5o=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}},S4u=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(e,t){this.path=e||"./",this.absolute=t}},w4u=Buffer.alloc(1024),GKr=Symbol("onStat"),E9t=Symbol("ended"),AJ=Symbol("queue"),I9t=Symbol("pendingLinks"),WSe=Symbol("current"),XUe=Symbol("process"),v9t=Symbol("processing"),zKr=Symbol("processJob"),yJ=Symbol("jobs"),h5o=Symbol("jobDone"),qKr=Symbol("addFSEntry"),T4u=Symbol("addTarEntry"),N5o=Symbol("stat"),j5o=Symbol("readdir"),WKr=Symbol("onreaddir"),HKr=Symbol("pipe"),O4u=Symbol("entry"),g5o=Symbol("entryOpt"),KKr=Symbol("writeEntryClass"),o_u=Symbol("write"),A5o=Symbol("ondrain"),aJr=class extends nVe{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[KKr];onWriteEntry;[AJ];[I9t]=new Map;[yJ]=0;[v9t]=!1;[E9t]=!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=Ef(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[KKr]=i_u,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 X1m(e.gzip)),e.brotli&&(typeof e.brotli!="object"&&(e.brotli={}),this.zip=new $1m(e.brotli)),e.zstd&&(typeof e.zstd!="object"&&(e.zstd={}),this.zip=new tTm(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[A5o]()),this.on("resume",()=>t.resume())}else this.on("drain",this[A5o]);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[AJ]=new MTm,this[yJ]=0,this.jobs=Number(e.jobs)||4,this[v9t]=!1,this[E9t]=!1}[o_u](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[E9t]=!0,this[XUe](),r&&r(),this}write(e){if(this[E9t])throw new Error("write after end");return typeof e=="string"?this[qKr](e):this[T4u](e),this.flowing}[T4u](e){let t=Ef(F5o.default.resolve(this.cwd,e.path));if(!this.filter(e.path,e))e.resume();else{let r=new S4u(e.path,t);r.entry=new zTm(e,this[g5o](r)),r.entry.on("end",()=>this[h5o](r)),this[yJ]+=1,this[AJ].push(r)}this[XUe]()}[qKr](e){let t=Ef(F5o.default.resolve(this.cwd,e));this[AJ].push(new S4u(e,t)),this[XUe]()}[N5o](e){e.pending=!0,this[yJ]+=1;let t=this.follow?"stat":"lstat";F9t.default[t](e.absolute,(r,n)=>{e.pending=!1,this[yJ]-=1,r?this.emit("error",r):this[GKr](e,n)})}[GKr](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[WSe])this[zKr](e);else{let r=`${t.dev}:${t.ino}`,n=this[I9t].get(r);n?n.push(e):this[I9t].set(r,[e]),e.pendingLink=!0,e.pending=!0}this[XUe]()}[j5o](e){e.pending=!0,this[yJ]+=1,F9t.default.readdir(e.absolute,(t,r)=>{if(e.pending=!1,this[yJ]-=1,t)return this.emit("error",t);this[WKr](e,r)})}[WKr](e,t){this.readdirCache.set(e.absolute,t),e.readdir=t,this[XUe]()}[XUe](){if(!this[v9t]){this[v9t]=!0;for(let e=this[AJ].head;e&&this[yJ]<this.jobs;e=e.next)if(this[zKr](e.value),e.value.ignore){let t=e.next;this[AJ].removeNode(e),e.next=t}this[v9t]=!1,this[E9t]&&this[AJ].length===0&&this[yJ]===0&&(this.zip?this.zip.end(w4u):(super.write(w4u),super.end()))}}get[WSe](){return this[AJ]&&this[AJ].head&&this[AJ].head.value}[h5o](e){this[AJ].shift(),this[yJ]-=1;let{stat:t}=e;if(t&&t.isFile()&&t.nlink>1){let r=`${t.dev}:${t.ino}`,n=this[I9t].get(r);if(n){this[I9t].delete(r);for(let i of n)i.pending=!1,this[zKr](i)}}this[XUe]()}[zKr](e){if(e.pending&&e.pendingLink&&e===this[WSe]&&(e.pending=!1,e.pendingLink=!1),!e.pending){if(e.entry){e===this[WSe]&&!e.piped&&this[HKr](e);return}if(!e.stat){let t=this.statCache.get(e.absolute);t?this[GKr](e,t):this[N5o](e)}if(e.stat&&!e.ignore){if(!this.noDirRecurse&&e.stat.isDirectory()&&!e.readdir){let t=this.readdirCache.get(e.absolute);if(t?this[WKr](e,t):this[j5o](e),!e.readdir)return}if(e.entry=this[O4u](e),!e.entry){e.ignore=!0;return}e===this[WSe]&&!e.piped&&this[HKr](e)}}}[g5o](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}}[O4u](e){this[yJ]+=1;try{return new this[KKr](e.path,this[g5o](e)).on("end",()=>this[h5o](e)).on("error",t=>this.emit("error",t))}catch(t){this.emit("error",t)}}[A5o](){this[WSe]&&this[WSe].entry&&this[WSe].entry.resume()}[HKr](e){e.piped=!0,e.readdir&&e.readdir.forEach(n=>{let i=e.path,o=i==="./"?"":i.replace(/\/*$/,"/");this[qKr](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={}){iJr(this,e,t,r)}},$5o=class extends aJr{sync=!0;constructor(e){super(e),this[KKr]=jTm}pause(){}resume(){}[N5o](e){let t=this.follow?"statSync":"lstatSync";this[GKr](e,F9t.default[t](e.absolute))}[j5o](e){this[WKr](e,F9t.default.readdirSync(e.absolute))}[HKr](e){let t=e.entry,r=this.zip;if(e.readdir&&e.readdir.forEach(n=>{let i=e.path,o=i==="./"?"":i.replace(/\/*$/,"/");this[qKr](o+n)}),!t)throw new Error("Cannot pipe without source");r?t.on("data",n=>{r.write(n)}):t.on("data",n=>{super[o_u](n)})}},VTm=(e,t)=>{let r=new $5o(e),n=new V4u(e.file,{mode:e.mode||438});r.pipe(n),s_u(r,t)},GTm=(e,t)=>{let r=new aJr(e),n=new tJr(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 a_u(r,t).catch(o=>r.emit("error",o)),i},s_u=(e,t)=>{t.forEach(r=>{r.charAt(0)==="@"?oJr({file:W5o.default.resolve(e.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r)}),e.end()},a_u=async(e,t)=>{for(let r of t)r.charAt(0)==="@"?await oJr({file:W5o.default.resolve(String(e.cwd),r.slice(1)),noResume:!0,onReadEntry:n=>{e.add(n)}}):e.add(r);e.end()},qTm=(e,t)=>{let r=new $5o(e);return s_u(r,t),r},WTm=(e,t)=>{let r=new aJr(e);return a_u(r,t).catch(n=>r.emit("error",n)),r},cJr=j9t(VTm,GTm,qTm,WTm,(e,t)=>{if(!t?.length)throw new TypeError("no paths specified to add to archive")}),HTm=process.env.__FAKE_PLATFORM__||process.platform,u_u=HTm==="win32",{O_CREAT:l_u,O_NOFOLLOW:P4u,O_TRUNC:p_u,O_WRONLY:f_u}=r8o.default.constants,d_u=Number(process.env.__FAKE_FS_O_FILENAME__)||r8o.default.constants.UV_FS_O_FILEMAP||0,KTm=u_u&&!!d_u,JTm=512*1024,YTm=d_u|p_u|l_u|f_u,B4u=!u_u&&typeof P4u=="number"?P4u|p_u|l_u|f_u:null,m_u=B4u!==null?()=>B4u:KTm?e=>e<JTm?YTm:"w":()=>"w",z5o=(e,t,r)=>{try{return z9t.default.lchownSync(e,t,r)}catch(n){if(n?.code!=="ENOENT")throw n}},$Kr=(e,t,r,n)=>{z9t.default.lchown(e,t,r,i=>{n(i&&i?.code!=="ENOENT"?i:null)})},XTm=(e,t,r,n,i)=>{if(t.isDirectory())h_u(Qut.default.resolve(e,t.name),r,n,o=>{if(o)return i(o);let s=Qut.default.resolve(e,t.name);$Kr(s,r,n,i)});else{let o=Qut.default.resolve(e,t.name);$Kr(o,r,n,i)}},h_u=(e,t,r,n)=>{z9t.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 $Kr(e,t,r,n);let s=o.length,a=null,c=u=>{if(!a){if(u)return n(a=u);if(--s===0)return $Kr(e,t,r,n)}};for(let u of o)XTm(e,u,t,r,c)})},ZTm=(e,t,r,n)=>{t.isDirectory()&&g_u(Qut.default.resolve(e,t.name),r,n),z5o(Qut.default.resolve(e,t.name),r,n)},g_u=(e,t,r)=>{let n;try{n=z9t.default.readdirSync(e,{withFileTypes:!0})}catch(i){let o=i;if(o?.code==="ENOENT")return;if(o?.code==="ENOTDIR"||o?.code==="ENOTSUP")return z5o(e,t,r);throw o}for(let i of n)ZTm(e,i,t,r);return z5o(e,t,r)},y_u=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"}},uJr=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"}},$Tm=(e,t)=>{gM.default.stat(e,(r,n)=>{(r||!n.isDirectory())&&(r=new y_u(e,r?.code||"ENOTDIR")),t(r)})},eOm=(e,t,r)=>{e=Ef(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),u=t.preserve,l=t.unlink,p=Ef(t.cwd),d=(m,g)=>{m?r(m):g&&c?h_u(g,s,a,A=>d(A)):o?gM.default.chmod(e,i,r):r()};if(e===p)return $Tm(e,d);if(u)return A_u.default.mkdir(e,{mode:i,recursive:!0}).then(m=>d(null,m??void 0),d);let f=Ef(N9t.default.relative(p,e)).split("/");Q5o(p,f,i,l,p,void 0,d)},Q5o=(e,t,r,n,i,o,s)=>{if(t.length===0)return s(null,o);let a=t.shift(),c=Ef(N9t.default.resolve(e+"/"+a));gM.default.mkdir(c,r,b_u(c,t,r,n,i,o,s))},b_u=(e,t,r,n,i,o,s)=>a=>{a?gM.default.lstat(e,(c,u)=>{if(c)c.path=c.path&&Ef(c.path),s(c);else if(u.isDirectory())Q5o(e,t,r,n,i,o,s);else if(n)gM.default.unlink(e,l=>{if(l)return s(l);gM.default.mkdir(e,r,b_u(e,t,r,n,i,o,s))});else{if(u.isSymbolicLink())return s(new uJr(e,e+"/"+t.join("/")));s(a)}}):(o=o||e,Q5o(e,t,r,n,i,o,s))},tOm=e=>{let t=!1,r;try{t=gM.default.statSync(e).isDirectory()}catch(n){r=n?.code}finally{if(!t)throw new y_u(e,r??"ENOTDIR")}},rOm=(e,t)=>{e=Ef(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,u=t.unlink,l=Ef(t.cwd),p=m=>{m&&a&&g_u(m,o,s),i&&gM.default.chmodSync(e,n)};if(e===l)return tOm(l),p();if(c)return p(gM.default.mkdirSync(e,{mode:n,recursive:!0})??void 0);let d=Ef(N9t.default.relative(l,e)).split("/"),f;for(let m=d.shift(),g=l;m&&(g+="/"+m);m=d.shift()){g=Ef(N9t.default.resolve(g));try{gM.default.mkdirSync(g,n),f=f||g}catch{let A=gM.default.lstatSync(g);if(A.isDirectory())continue;if(u){gM.default.unlinkSync(g),gM.default.mkdirSync(g,n),f=f||g;continue}else if(A.isSymbolicLink())return new uJr(g,g+"/"+d.join("/"))}}return p(f)},y5o=Object.create(null),R4u=1e4,Rut=new Set,nOm=e=>{Rut.has(e)?Rut.delete(e):y5o[e]=e.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Rut.add(e);let t=y5o[e],r=Rut.size-R4u;if(r>R4u/10){for(let n of Rut)if(Rut.delete(n),delete y5o[n],--r<=0)break}return t},iOm=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,oOm=iOm==="win32",sOm=e=>e.split("/").slice(0,-1).reduce((t,r)=>{let n=t.at(-1);return n!==void 0&&(r=(0,n8o.join)(n,r)),t.push(r||"/"),t},[]),aOm=class{#e=new Map;#t=new Map;#r=new Set;reserve(e,t){e=oOm?["win32 parallelization disabled"]:e.map(n=>T9t((0,n8o.join)(nOm(n))));let r=new Set(e.map(n=>sOm(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}},cOm=()=>process.umask(),D4u=Symbol("onEntry"),M5o=Symbol("checkFs"),k4u=Symbol("checkFs2"),L5o=Symbol("isReusable"),S8=Symbol("makeFs"),_5o=Symbol("file"),U5o=Symbol("directory"),JKr=Symbol("link"),F4u=Symbol("symlink"),N4u=Symbol("hardlink"),S9t=Symbol("ensureNoSymlink"),j4u=Symbol("unsupported"),z4u=Symbol("checkPath"),b5o=Symbol("stripAbsolutePath"),ZSe=Symbol("mkdir"),XT=Symbol("onError"),QKr=Symbol("pending"),Q4u=Symbol("pend"),Dut=Symbol("unpend"),E5o=Symbol("ended"),I5o=Symbol("maybeClose"),V5o=Symbol("skip"),O9t=Symbol("doChown"),P9t=Symbol("uid"),B9t=Symbol("gid"),R9t=Symbol("checkedCwd"),uOm=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,D9t=uOm==="win32",lOm=1024,pOm=(e,t)=>{if(!D9t)return zd.default.unlink(e,t);let r=e+".DELETE."+(0,t8o.randomBytes)(16).toString("hex");zd.default.rename(e,r,n=>{if(n)return t(n);zd.default.unlink(r,t)})},fOm=e=>{if(!D9t)return zd.default.unlinkSync(e);let t=e+".DELETE."+(0,t8o.randomBytes)(16).toString("hex");zd.default.renameSync(e,t),zd.default.unlinkSync(t)},M4u=(e,t,r)=>e!==void 0&&e===e>>>0?e:t!==void 0&&t===t>>>0?t:r,i8o=class extends k9t{[E5o]=!1;[R9t]=!1;[QKr]=0;reservations=new aOm;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[E5o]=!0,this[I5o]()},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:lOm,this.forceChown=e.forceChown===!0,this.win32=!!e.win32||D9t,this.newer=!!e.newer,this.keep=!!e.keep,this.noMtime=!!e.noMtime,this.preservePaths=!!e.preservePaths,this.unlink=!!e.unlink,this.cwd=Ef(gS.default.resolve(e.cwd||process.cwd())),this.strip=Number(e.strip)||0,this.processUmask=this.chmod?typeof e.processUmask=="number"?e.processUmask:cOm():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[D4u](t))}warn(e,t,r={}){return(e==="TAR_BAD_ARCHIVE"||e==="TAR_ABORT")&&(r.recoverable=!1),super.warn(e,t,r)}[I5o](){this[E5o]&&this[QKr]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[b5o](e,t){let r=e[t],{type:n}=e;if(!r||this.preservePaths)return!0;let[i,o]=Y5o(r),s=o.replaceAll(/\\/g,"/").split("/");if(s.includes("..")||D9t&&/^[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=gS.default.posix.dirname(e.path),c=gS.default.posix.normalize(gS.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}[z4u](e){let t=Ef(e.path),r=t.split("/");if(this.strip){if(r.length<this.strip)return!1;if(e.type==="Link"){let n=Ef(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[b5o](e,"path")||!this[b5o](e,"linkpath"))return!1;if(e.absolute=gS.default.isAbsolute(e.path)?Ef(gS.default.resolve(e.path)):Ef(gS.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:Ef(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}=gS.default.win32.parse(String(e.absolute));e.absolute=n+E4u(String(e.absolute).slice(n.length));let{root:i}=gS.default.win32.parse(e.path);e.path=i+E4u(e.path.slice(i.length))}return!0}[D4u](e){if(!this[z4u](e))return e.resume();switch(c_u.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[M5o](e);default:return this[j4u](e)}}[XT](e,t){e.name==="CwdError"?this.emit("error",e):(this.warn("TAR_ENTRY_ERROR",e,{entry:t}),this[Dut](),t.resume())}[ZSe](e,t,r){eOm(Ef(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)}[O9t](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}[P9t](e){return M4u(this.uid,e.uid,this.processUid)}[B9t](e){return M4u(this.gid,e.gid,this.processGid)}[_5o](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.fmode,n=new tJr(String(e.absolute),{flags:m_u(e.size),mode:r,autoClose:!1});n.on("error",a=>{n.fd&&zd.default.close(n.fd,()=>{}),n.write=()=>!0,this[XT](a,e),t()});let i=1,o=a=>{if(a){n.fd&&zd.default.close(n.fd,()=>{}),this[XT](a,e),t();return}--i===0&&n.fd!==void 0&&zd.default.close(n.fd,c=>{c?this[XT](c,e):this[Dut](),t()})};n.on("finish",()=>{let a=String(e.absolute),c=n.fd;if(typeof c=="number"&&e.mtime&&!this.noMtime){i++;let u=e.atime||new Date,l=e.mtime;zd.default.futimes(c,u,l,p=>p?zd.default.utimes(a,u,l,d=>o(d&&p)):o())}if(typeof c=="number"&&this[O9t](e)){i++;let u=this[P9t](e),l=this[B9t](e);typeof u=="number"&&typeof l=="number"&&zd.default.fchown(c,u,l,p=>p?zd.default.chown(a,u,l,d=>o(d&&p)):o())}o()});let s=this.transform&&this.transform(e)||e;s!==e&&(s.on("error",a=>{this[XT](a,e),t()}),e.pipe(s)),s.pipe(n)}[U5o](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.dmode;this[ZSe](String(e.absolute),r,n=>{if(n){this[XT](n,e),t();return}let i=1,o=()=>{--i===0&&(t(),this[Dut](),e.resume())};e.mtime&&!this.noMtime&&(i++,zd.default.utimes(String(e.absolute),e.atime||new Date,e.mtime,o)),this[O9t](e)&&(i++,zd.default.chown(String(e.absolute),Number(this[P9t](e)),Number(this[B9t](e)),o)),o()})}[j4u](e){e.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${e.type}`,{entry:e}),e.resume()}[F4u](e,t){let r=Ef(gS.default.relative(this.cwd,gS.default.resolve(gS.default.dirname(String(e.absolute)),String(e.linkpath)))).split("/");this[S9t](e,this.cwd,r,()=>this[JKr](e,String(e.linkpath),"symlink",t),n=>{this[XT](n,e),t()})}[N4u](e,t){let r=Ef(gS.default.resolve(this.cwd,String(e.linkpath))),n=Ef(String(e.linkpath)).split("/");this[S9t](e,this.cwd,n,()=>this[JKr](e,r,"link",t),i=>{this[XT](i,e),t()})}[S9t](e,t,r,n,i){let o=r.shift();if(this.preservePaths||o===void 0)return n();let s=gS.default.resolve(t,o);zd.default.lstat(s,(a,c)=>{if(a)return n();if(c?.isSymbolicLink())return i(new uJr(s,gS.default.resolve(s,r.join("/"))));this[S9t](e,s,r,n,i)})}[Q4u](){this[QKr]++}[Dut](){this[QKr]--,this[I5o]()}[V5o](e){this[Dut](),e.resume()}[L5o](e,t){return e.type==="File"&&!this.unlink&&t.isFile()&&t.nlink<=1&&!D9t}[M5o](e){this[Q4u]();let t=[e.path];e.linkpath&&t.push(e.linkpath),this.reservations.reserve(t,r=>this[k4u](e,r))}[k4u](e,t){let r=s=>{t(s)},n=()=>{this[ZSe](this.cwd,this.dmode,s=>{if(s){this[XT](s,e),r();return}this[R9t]=!0,i()})},i=()=>{if(e.absolute!==this.cwd){let s=Ef(gS.default.dirname(String(e.absolute)));if(s!==this.cwd)return this[ZSe](s,this.dmode,a=>{if(a){this[XT](a,e),r();return}o()})}o()},o=()=>{zd.default.lstat(String(e.absolute),(s,a)=>{if(a&&(this.keep||this.newer&&a.mtime>(e.mtime??a.mtime))){this[V5o](e),r();return}if(s||this[L5o](e,a))return this[S8](null,e,r);if(a.isDirectory()){if(e.type==="Directory"){let c=this.chmod&&e.mode&&(a.mode&4095)!==e.mode,u=l=>this[S8](l??null,e,r);return c?zd.default.chmod(String(e.absolute),Number(e.mode),u):u()}if(e.absolute!==this.cwd)return zd.default.rmdir(String(e.absolute),c=>this[S8](c??null,e,r))}if(e.absolute===this.cwd)return this[S8](null,e,r);pOm(String(e.absolute),c=>this[S8](c??null,e,r))})};this[R9t]?i():n()}[S8](e,t,r){if(e){this[XT](e,t),r();return}switch(t.type){case"File":case"OldFile":case"ContiguousFile":return this[_5o](t,r);case"Link":return this[N4u](t,r);case"SymbolicLink":return this[F4u](t,r);case"Directory":case"GNUDumpDir":return this[U5o](t,r)}}[JKr](e,t,r,n){zd.default[r](t,String(e.absolute),i=>{i?this[XT](i,e):(this[Dut](),e.resume()),n()})}},C9t=e=>{try{return[null,e()]}catch(t){return[t,null]}},E_u=class extends i8o{sync=!0;[S8](e,t){return super[S8](e,t,()=>{})}[M5o](e){if(!this[R9t]){let i=this[ZSe](this.cwd,this.dmode);if(i)return this[XT](i,e);this[R9t]=!0}if(e.absolute!==this.cwd){let i=Ef(gS.default.dirname(String(e.absolute)));if(i!==this.cwd){let o=this[ZSe](i,this.dmode);if(o)return this[XT](o,e)}}let[t,r]=C9t(()=>zd.default.lstatSync(String(e.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(e.mtime??r.mtime)))return this[V5o](e);if(t||this[L5o](e,r))return this[S8](null,e);if(r.isDirectory()){if(e.type==="Directory"){let o=this.chmod&&e.mode&&(r.mode&4095)!==e.mode,[s]=o?C9t(()=>{zd.default.chmodSync(String(e.absolute),Number(e.mode))}):[];return this[S8](s,e)}let[i]=C9t(()=>zd.default.rmdirSync(String(e.absolute)));this[S8](i,e)}let[n]=e.absolute===this.cwd?[]:C9t(()=>fOm(String(e.absolute)));this[S8](n,e)}[_5o](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.fmode,n=s=>{let a;try{zd.default.closeSync(i)}catch(c){a=c}(s||a)&&this[XT](s||a,e),t()},i;try{i=zd.default.openSync(String(e.absolute),m_u(e.size),r)}catch(s){return n(s)}let o=this.transform&&this.transform(e)||e;o!==e&&(o.on("error",s=>this[XT](s,e)),e.pipe(o)),o.on("data",s=>{try{zd.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{zd.default.futimesSync(i,a,c)}catch(u){try{zd.default.utimesSync(String(e.absolute),a,c)}catch{s=u}}}if(this[O9t](e)){let a=this[P9t](e),c=this[B9t](e);try{zd.default.fchownSync(i,Number(a),Number(c))}catch(u){try{zd.default.chownSync(String(e.absolute),Number(a),Number(c))}catch{s=s||u}}}n(s)})}[U5o](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.dmode,n=this[ZSe](String(e.absolute),r);if(n){this[XT](n,e),t();return}if(e.mtime&&!this.noMtime)try{zd.default.utimesSync(String(e.absolute),e.atime||new Date,e.mtime)}catch{}if(this[O9t](e))try{zd.default.chownSync(String(e.absolute),Number(this[P9t](e)),Number(this[B9t](e)))}catch{}t(),e.resume()}[ZSe](e,t){try{return rOm(Ef(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}}[S9t](e,t,r,n,i){if(this.preservePaths||r.length===0)return n();let o=t;for(let s of r){o=gS.default.resolve(o,s);let[a,c]=C9t(()=>zd.default.lstatSync(o));if(a)return n();if(c.isSymbolicLink())return i(new uJr(o,gS.default.resolve(t,r.join("/"))))}n()}[JKr](e,t,r,n){let i=`${r}Sync`;try{zd.default[i](t,String(e.absolute)),n(),e.resume()}catch(o){return this[XT](o,e)}}},dOm=e=>{let t=new E_u(e),r=e.file,n=e8o.default.statSync(r),i=e.maxReadSize||16*1024*1024;new L1m(r,{readSize:i,size:n.size}).pipe(t)},mOm=(e,t)=>{let r=new i8o(e),n=e.maxReadSize||16*1024*1024,i=e.file;return new Promise((o,s)=>{r.on("error",s),r.on("close",o),e8o.default.stat(i,(a,c)=>{if(a)s(a);else{let u=new q5o(i,{readSize:n,size:c.size});u.on("error",s),u.pipe(r)}})})},I_u=j9t(dOm,mOm,e=>new E_u(e),e=>new i8o(e),(e,t)=>{t?.length&&e_u(e,t)}),hOm=(e,t)=>{let r=new $5o(e),n=!0,i,o;try{try{i=hM.default.openSync(e.file,"r+")}catch(c){if(c?.code==="ENOENT")i=hM.default.openSync(e.file,"w+");else throw c}let s=hM.default.fstatSync(i),a=Buffer.alloc(512);e:for(o=0;o<s.size;o+=512){for(let l=0,p=0;l<512;l+=p){if(p=hM.default.readSync(i,a,l,a.length-l,o+l),o===0&&a[0]===31&&a[1]===139)throw new Error("cannot append to compressed archives");if(!p)break e}let c=new rVe(a);if(!c.cksumValid)break;let u=512*Math.ceil((c.size||0)/512);if(o+u+512>s.size)break;o+=u,e.mtimeCache&&c.mtime&&e.mtimeCache.set(String(c.path),c.mtime)}n=!1,gOm(e,r,o,i,t)}finally{if(n)try{hM.default.closeSync(i)}catch{}}},gOm=(e,t,r,n,i)=>{let o=new V4u(e.file,{fd:n,start:r});t.pipe(o),yOm(t,i)},AOm=(e,t)=>{t=Array.from(t);let r=new aJr(e),n=(i,o,s)=>{let a=(d,f)=>{d?hM.default.close(i,m=>s(d)):s(null,f)},c=0;if(o===0)return a(null,0);let u=0,l=Buffer.alloc(512),p=(d,f)=>{if(d||f===void 0)return a(d);if(u+=f,u<512&&f)return hM.default.read(i,l,u,l.length-u,c+u,p);if(c===0&&l[0]===31&&l[1]===139)return a(new Error("cannot append to compressed archives"));if(u<512)return a(null,c);let m=new rVe(l);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),u=0,hM.default.read(i,l,0,512,c,p)};hM.default.read(i,l,0,512,c,p)};return new Promise((i,o)=>{r.on("error",o);let s="r+",a=(c,u)=>{if(c&&c.code==="ENOENT"&&s==="r+")return s="w+",hM.default.open(e.file,s,a);if(c||!u)return o(c);hM.default.fstat(u,(l,p)=>{if(l)return hM.default.close(u,()=>o(l));n(u,p.size,(d,f)=>{if(d)return o(d);let m=new tJr(e.file,{fd:u,start:f});r.pipe(m),m.on("error",o),m.on("close",i),bOm(r,t)})})};hM.default.open(e.file,s,a)})},yOm=(e,t)=>{t.forEach(r=>{r.charAt(0)==="@"?oJr({file:o8o.default.resolve(e.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r)}),e.end()},bOm=async(e,t)=>{for(let r of t)r.charAt(0)==="@"?await oJr({file:o8o.default.resolve(String(e.cwd),r.slice(1)),noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r);e.end()},x9t=j9t(hOm,AOm,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(e,t)=>{if(!W1m(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")}),qgv=j9t(x9t.syncFile,x9t.asyncFile,x9t.syncNoFile,x9t.asyncNoFile,(e,t=[])=>{x9t.validate?.(e,t),EOm(e)}),EOm=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 io,pJr=h(()=>{"use strict";Hn();io=class e{breadcrumbs=[];context;static STRING=Xt.TypeReference.primitive({v1:"STRING",v2:Xt.PrimitiveTypeV2.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=Xt.TypeReference.container(Xt.ContainerType.optional(e.STRING));constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r}}});var s8o,v_u,C_u=h(()=>{"use strict";s8o=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,u=>{a.has(u.position)||(c--,a.add(u.position),this._path.length===1?this.resolveNode(u,`${o}.${c}`):(s.children.push({...u,path:c.toString()}),s.line=u.line,s.position=u.position,s.lineStart=u.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}}},v_u=s8o});var x_u,AE,Yre,a8o,Q9t=h(()=>{"use strict";tr();qy();x_u=require("fs/promises");is();C_u();(function(e){e.WARNING="warning",e.ERROR="error"})(AE||(AE={}));Yre=class{errors=[];logger;breadcrumbToLineNumberMapper;relativeFilepathToSpec;constructor({logger:t,relativeFilepathToSpec:r}){this.logger=t,this.relativeFilepathToSpec=r,r&&(this.breadcrumbToLineNumberMapper=new a8o({logger:t,relativePathToFile:ye.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||AE.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===AE.ERROR?t++:(n.level===AE.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??AE.WARNING;if(!(n===AE.WARNING&&!t))switch(n){case AE.ERROR:if(this.logger.log(Zn.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(Zn.Debug,` - at location (${o})`)}break;case AE.WARNING:if(this.logger.log(Zn.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(Zn.Warn,` - at location (${o})`)}r.resolution&&this.logger.log(Zn.Warn,` - resolution: ${r.resolution}`);break}}}},a8o=class{logger;relativePathToFile;map=new v_u;initialized=!1;constructor({relativePathToFile:t,logger:r}){this.relativePathToFile=t,this.logger=r}async initialize(){if(!this.initialized)try{let t=await(0,x_u.readFile)(this.relativePathToFile,"utf-8");vr.load(t,{listener:this.map.listen()}),this.initialized=!0}catch(t){this.logger.log(Zn.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 vOm(e){return"deprecated"in e&&e.deprecated===!0}async function COm(e){let t=await fetch(e);if(t.ok)try{let r=await t.text();try{return JSON.parse(r)}catch{return vr.load(r)}}catch{return}}var E0,S_u=h(()=>{"use strict";c8();ct();Hn();is();Gi();Q9t();Xo();E0=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=Gw({generationLanguage:t.generationLanguage,keywords:void 0,smartCasing:t.smartCasing}),this.exampleGenerationArgs=t.exampleGenerationArgs,this.authOverrides=t.authOverrides,this.environmentOverrides=t.environmentOverrides,this.globalHeaderOverrides=t.globalHeaderOverrides,this.enableUniqueErrorsPerEndpoint=t.enableUniqueErrorsPerEndpoint,this.generateV1Examples=t.generateV1Examples,this.documentBaseDir=t.documentBaseDir}static BREADCRUMBS_TO_IGNORE=["properties","allOf","anyOf"];convertBreadcrumbsToName(t){let r=t.filter((i,o)=>!(/^\d+$/.test(i)||e.BREADCRUMBS_TO_IGNORE.includes(i)||o===0&&i==="components"||o===1&&i==="schemas"||t[0]==="paths"&&(o===0||o===1&&["get","post","put","delete","patch"].includes(i)||o===2&&t[1]!=null&&["get","post","put","delete","patch"].includes(t[1])&&i==="parameters"))),n=ri(r.join("_"));return CH(n)}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:AE.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1};i=i[s]}return i==null?(n||this.errorCollector.collect({level:AE.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 u=t.$ref.split("#"),l=u[0];if(n=u[1],!l)return{resolved:!1};if(s=l,o=await this.loadExternalDocument(l),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(u=>u.replace(/~1/g,"/"));for(let u of c){if(typeof r!="object"||r==null)return{resolved:!1};r=r[u]}if(r==null)return{resolved:!1};if(i&&typeof r=="object"&&r!==null){let u=new Set;u.add(t.$ref),r=await this.resolveNestedExternalReferences(r,o,u,s)}return{resolved:!0,value:r}}async loadExternalDocument(t){let r=this.externalDocuments.get(t);r==null&&(r=COm(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,u=s.substring(2).split("/").map(cI);for(let l of u){if(typeof c!="object"||c===null)return t;c=c[l]}if(c!=null){let l=await this.resolveNestedExternalReferences(c,r,n,i);return n.delete(s),l}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 Xt.ObjectPropertyAccess.ReadOnly;if(i)return Xt.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 _C.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 _C.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(i!=null)return{status:i,message:void 0};if(vOm(t))return{status:mh.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 $r.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"&&Ag(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(jr(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 es,XD=h(()=>{"use strict";es=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 Lut,c8o=h(()=>{"use strict";XD();Lut=class extends es{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 fJr,w_u=h(()=>{"use strict";Hn();XD();fJr=class extends es{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 mh.InDevelopment;case"PRE_RELEASE":return mh.PreRelease;case"GENERAL_AVAILABILITY":case"GENERALLY_AVAILABLE":case"GA":case"STABLE":return mh.GeneralAvailability;case"DEPRECATED":return mh.Deprecated;case"ALPHA":return mh.Alpha;case"BETA":return mh.Beta;case"PREVIEW":return mh.Preview;case"LEGACY":return mh.Legacy;default:return}}}});var _ut,u8o=h(()=>{"use strict";XD();_ut=class extends es{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 Uut,l8o=h(()=>{"use strict";XD();Uut=class extends es{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 xOm,SOm,T_u,O_u=h(()=>{"use strict";an();xOm=Fe.object({snake:Fe.string().optional(),camel:Fe.string().optional(),screamingSnake:Fe.string().optional(),pascal:Fe.string().optional()}),SOm=Fe.object({description:Fe.string().optional(),name:Fe.string().optional(),casing:xOm.optional()}),T_u=Fe.record(SOm)});var Vut,p8o=h(()=>{"use strict";XD();O_u();Vut=class extends es{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=T_u.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 iVe,P_u=h(()=>{"use strict";XD();iVe=class extends es{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 dJr,B_u=h(()=>{"use strict";XD();dJr=class extends es{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 mJr,R_u=h(()=>{"use strict";XD();mJr=class extends es{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 hJr,D_u=h(()=>{"use strict";XD();hJr=class extends es{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 gJr,k_u=h(()=>{"use strict";XD();gJr=class extends es{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 AJr,F_u=h(()=>{"use strict";XD();AJr=class extends es{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 yJr,N_u=h(()=>{"use strict";XD();yJr=class extends es{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 wOm({isText:e,isAttribute:t}){return e?cQ.Text:t?cQ.Attribute:cQ.Element}function Q_u(e){return typeof e=="object"&&e!=null}function bJr(e,t){if(!(typeof e!="object"||e==null))return e[t]}function f8o(...e){return e.find(t=>t!=null)}var j_u,z_u,Gut,qut,EJr=h(()=>{"use strict";Hn();XD();j_u="x-fern-xml-text",z_u="x-fern-xml-list-separator",Gut=class extends es{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(Q_u(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}}},qut=class extends es{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=f8o(this.getExtensionValue(t),this.getExtensionValue(r)),i=f8o(bJr(t,j_u),bJr(r,j_u)),o=f8o(bJr(t,z_u),bJr(r,z_u)),s=Q_u(n)?n:{};return{kind:wOm({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 _C={};te(_C,{AudienceExtension:()=>Lut,FernAvailabilityExtension:()=>fJr,FernDiscriminatedExtension:()=>_ut,FernDiscriminatorContextExtension:()=>Uut,FernEnumExtension:()=>Vut,FernIgnoreExtension:()=>iVe,FernOptionalExtension:()=>dJr,FernTypeExtension:()=>AJr,FernTypeNameExtension:()=>yJr,SdkGroupNameExtension:()=>mJr,SdkMethodNameExtension:()=>hJr,ServerFromOperationNameExtension:()=>gJr,XmlPropertyExtension:()=>qut,XmlSchemaExtension:()=>Gut});var d8o=h(()=>{"use strict";c8o();w_u();u8o();l8o();p8o();P_u();B_u();R_u();D_u();k_u();F_u();N_u();EJr()});function L_u(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=>Sw.named({name:i.name,shape:a});switch(i.shape.type){case"object":return s(mD.Object);case"enum":return s(mD.Enum);case"union":return s(mD.Union);case"undiscriminatedUnion":return s(mD.UndiscriminatedUnion);case"alias":{let{resolvedType:a}=i.shape,c=M_u(a);return c!=null?r(c,o):a}default:return}};for(let[i,o]of Object.entries(e)){if(o.shape.type!=="alias"||M_u(o.shape.resolvedType)==null)continue;let s=r(i,new Set);s!=null&&(e[i]={...o,shape:pc.alias({aliasOf:o.shape.aliasOf,resolvedType:s})})}}function M_u(e){if(e.type!=="named")return;let t=e;return e.shape==null&&typeof t.typeId=="string"?t.typeId:void 0}var __u=h(()=>{"use strict";Hn()});var vJ,U_u=h(()=>{"use strict";Hn();fc();Gi();pJr();d8o();__u();vJ=class extends io{ir;audiences;irGraph;constructor({breadcrumbs:t=[],context:r,audiences:n}){super({breadcrumbs:t,context:r}),this.audiences=n,this.irGraph=new cUe(n),this.ir={auth:{docs:void 0,requirement:Xt.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:Xt.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 iVe({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 iVe({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},zGt(this.ir,{onWarning:a=>this.context.logger.warn(a)}),L_u(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)),DGt({ir:i});let o=this.context.exampleGenerationArgs,s=LMo({ir:i,exampleGeneration:o,logger:this.context.logger});if(this.context.generateV1Examples){let a=FGt({ir:i,exampleGeneration:o});return{...i,...a,...s}}return{...i,...s}}filterIrForAudiences(t){return{...jGt(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 u=this.context.getGroup({groupParts:n,namespace:this.context.namespace}),l=this.getOrCreatePackage({group:n});l!==this.ir.rootPackage&&l.docs==null&&o!=null&&(l.docs=o);let p=[...u].map(m=>this.context.casingsGenerator.generateName(m)),d=p[p.length-1];l.service==null&&(l.service=s??`service_${u.map(m=>ri(m)).join("/")}`),this.ir.services[l.service]==null&&(this.ir.services[l.service]=this.createNewService({allParts:p,finalpart:d,endpointGroupDisplayName:i})),this.ir.services[l.service]?.endpoints.push(t);let f=this.ir.services[l.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=ri(i?.join(".")),s=ri(r),a=this.context.namespace?`${ri(this.context.namespace)}/`:"",c=o?`channel_${a}${o}`:`channel_${a}${s}`,u=i?this.getOrCreatePackage({group:i}):this.getOrCreatePackage({group:[s]});this.ir.websocketChannels={...this.ir.websocketChannels,[c]:t},c!==""?u.websocket==null&&(u.websocket=c):this.ir.rootPackage.websocket="";let l=this.context.createFernFilepath();this.irGraph.addChannel(l,c,t),n!=null&&this.irGraph.markChannelForAudiences(l,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:nb(""),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=>ri(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 oVe(e){return typeof e=="object"&&e!==null&&!("$ref"in e)}function POm(e){if(!oVe(e))return!1;if("nullable"in e&&e.nullable===!0)return!0;let t=r=>Array.isArray(r)&&r.some(n=>oVe(n)&&n.type==="null");return t(e.anyOf)||t(e.oneOf)}function BOm(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 G_u(e){if(e.const!==void 0)return e.const;if(Array.isArray(e.enum)&&e.enum.length>0)return e.enum[0]}var TOm,V_u,OOm,Jw,twe=h(()=>{"use strict";ct();Xo();TOm=/^literal<\s*(?:"(.*)"|(true|false))\s*>$/,V_u=new WeakMap,OOm=new Set(["type","properties","required","allOf","description","title","deprecated","readOnly","writeOnly","xml","externalDocs","discriminator"]);Jw=class e extends io{MAX_DEPTH=12;EXAMPLE_STRING=qo.STRING;EXAMPLE_NUMBER=qo.DOUBLE;EXAMPLE_BOOLEAN=qo.BOOLEAN;EXAMPLE_INTEGER=qo.INT;EXAMPLE_DATE=qo.DATE;EXAMPLE_DATE_TIME=qo.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 u=V_u.get(r);u!=null?this.sharedState=u:(this.sharedState={mergedAllOfProperties:new WeakMap,mergeOnlyAllOfSchemas:new WeakMap},V_u.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(([y,I])=>{if(typeof I!="object")return{key:y,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if(this.isDeprecatedProperty(I)&&!this.isRequiredProperty({key:y,resolvedSchema:t}))return{key:y,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:y,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("readOnly"in I&&I.readOnly===!0&&this.exampleGenerationStrategy==="request")return{key:y,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("writeOnly"in I&&I.writeOnly===!0&&this.exampleGenerationStrategy==="response")return{key:y,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};let x=POm(I),v=!(y in r)||!x&&r[y]==null||x&&r[y]===void 0,S=!o.includes(y);if(v&&S){if(this.example===void 0&&this.generateOptionalProperties){let B=this.maybeResolveSchemaExample(I),R=new e({breadcrumbs:[...this.breadcrumbs,y],context:this.context,schema:I,example:B,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()});return{key:y,result:R.convert()}}return{key:y,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}}}else{let B=r[y],R=B!==void 0?B:this.maybeResolveSchemaExample(I),O=new e({breadcrumbs:[...this.breadcrumbs,y],context:this.context,schema:I,example:R,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();return{key:y,result:O}}}),a=n?[]:(t.allOf??[]).map((y,I)=>{let x=this.context.resolveMaybeReference({schemaOrReference:y,breadcrumbs:[...this.breadcrumbs,`allOf[${I}]`],skipErrorCollector:!0});return x&&this.isConstraintOnlySchema(x)?{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,...y,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:y})=>y.usedProvidedExample)||a.some(y=>y.usedProvidedExample)),u=Object.fromEntries(s.map(({key:y,result:I})=>[y,I.validExample]).filter(([y,I])=>I!==void 0));for(let y of a)if(typeof y.validExample=="object"&&y.validExample!==null){let I=y.validExample,x=Object.fromEntries(Object.entries(I).filter(([v,S])=>S!==void 0));for(let[v,S]of Object.entries(x))(!(v in u)||u[v]==null)&&(u[v]=S)}let l=[],p=this.collectAllPropertyKeys(t),d=Object.keys(r).filter(y=>!p.has(y)),f=this.schemaHasPatternProperties(t),m=f?d:[],g=f?[]:d;if(m.forEach(y=>{l.push({key:y,result:{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:r[y],errors:[]}})}),g.length>0)if(t.additionalProperties===!1)g.forEach(y=>{let I=[...this.breadcrumbs,y].join("."),x={message:`Found unexpected property '${y}' in example. This property does not exist in the schema${I?` at path: ${I}`:""}`,path:[...this.breadcrumbs,y]};l.push({key:y,result:{isValid:!1,coerced:!1,usedProvidedExample:!0,validExample:void 0,errors:[x]}})});else if(t.additionalProperties===!0||t.additionalProperties===void 0)g.forEach(y=>{l.push({key:y,result:{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:r[y],errors:[]}})});else{let y=t.additionalProperties;g.forEach(I=>{let v=new e({breadcrumbs:[...this.breadcrumbs,I],context:this.context,schema:y,example:r[I],depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();l.push({key:I,result:v})})}for(let{key:y,result:I}of l)I.validExample!==void 0&&u[y]===void 0&&(u[y]=I.validExample);let A=s.every(y=>y.result.isValid)&&a.every(y=>y.isValid)&&l.every(({result:y})=>y.isValid);if(Object.keys(u).length===0){let y=a.find(I=>I.validExample!==void 0&&(typeof I.validExample!="object"||I.validExample===null));y&&(u=y.validExample)}return{isValid:A,coerced:!1,usedProvidedExample:c,validExample:u,errors:[...s.flatMap(({result:y})=>y.errors),...a.flatMap(y=>y.errors),...l.flatMap(({result:y})=>y.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=>BOm(m))){let m=d.findIndex(g=>G_u(g)!==void 0);if(m!==-1){let g=n[m],A=d[m];if(g&&A){let y=G_u(A),x=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${m}]`],context:this.context,schema:r==="oneOf"?{...t,...g,oneOf:void 0}:g,example:y,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(x.isValid)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:x.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),y=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(y.isValid&&!y.coerced&&y.usedProvidedExample)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:y.validExample,errors:[]};if(y.isValid&&!y.coerced&&this.example===void 0)return{isValid:!0,coerced:!1,usedProvidedExample:y.usedProvidedExample,validExample:y.validExample,errors:[]};o.push(y),y.isValid&&y.usedProvidedExample&&a===null&&(a=y),y.isValid&&s===null&&(s=y)}let c=a??s,u=c!==null,l=c?.validExample??o[0]?.validExample,p=c?.usedProvidedExample??!1;return{isValid:u,coerced:!1,usedProvidedExample:p,validExample:l,errors:u?[]: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(TOm);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,y]of Object.entries(g.mergedProperties))if(typeof y=="object"&&y!==null){let I=a[A];I!=null&&oVe(I)&&oVe(y)?a[A]={...I,...y}:a[A]=y}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&&oVe(A)&&oVe(g)?a[m]={...A,...g}:a[m]=g}}}}let u={...o};for(let[p,d]of Object.entries(u)){let f=a[p];if(f==null||!oVe(d))continue;let m="$ref"in f?this.context.resolveMaybeReference({schemaOrReference:f,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):f;m!=null&&(u[p]={...m,...d})}for(let[p,d]of Object.entries(a))p in u||(u[p]=d);let l={mergedProperties:u,mergedRequired:[...c]};return i&&this.cacheMergedAllOfProperties(t,n,l),l}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=>OOm.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 q_u(e){return IC({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return $r.primitive({v1:"BASE_64",v2:vi.base64({})});case"BOOLEAN":return $r.primitive({v1:"BOOLEAN",v2:vi.boolean({default:void 0})});case"DATE":return $r.primitive({v1:"DATE",v2:vi.date({})});case"DATE_TIME":return $r.primitive({v1:"DATE_TIME",v2:vi.dateTime({})});case"DATE_TIME_RFC_2822":return $r.primitive({v1:"DATE_TIME_RFC_2822",v2:vi.dateTimeRfc2822({})});case"FLOAT":return $r.primitive({v1:"FLOAT",v2:vi.float({default:void 0,validation:void 0})});case"DOUBLE":return $r.primitive({v1:"DOUBLE",v2:vi.double({default:void 0,validation:void 0})});case"UINT":return $r.primitive({v1:"UINT",v2:vi.uint({default:void 0,validation:void 0})});case"UINT_64":return $r.primitive({v1:"UINT_64",v2:vi.uint64({default:void 0,validation:void 0})});case"INTEGER":return $r.primitive({v1:"INTEGER",v2:vi.integer({default:void 0,validation:void 0})});case"LONG":return $r.primitive({v1:"LONG",v2:vi.long({default:void 0,validation:void 0})});case"STRING":return $r.primitive({v1:"STRING",v2:vi.string({default:void 0,validation:void 0})});case"UUID":return $r.primitive({v1:"UUID",v2:vi.uuid({})});case"BIG_INTEGER":return $r.primitive({v1:"BIG_INTEGER",v2:vi.bigInteger({default:void 0})});default:return}},unknown:()=>$r.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return $r.container(Cs.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return $r.container(Cs.list(t))},optional:t=>{if(t!=null)return $r.container(Cs.optional(t))},nullable:t=>{if(t!=null)return $r.container(Cs.nullable(t))},set:t=>{if(t!=null)return $r.container(Cs.set(t))},literal:t=>$r.container(Cs.literal(t._visit({string:r=>rE.string(r),boolean:r=>rE.boolean(r),_other:()=>{throw new T({message:"Unexpected literal type",code:T.Code.InternalError})}}))),named:()=>{}}})}var W_u=h(()=>{"use strict";Ao();Hn();Dt()});var rwe,IJr=h(()=>{"use strict";Hn();fc();Xo();rwe=class extends io{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:pc.enum({default:n!=null?r.find(i=>ar(i.name)===n):void 0,values:r,forwardCompatible:this.forwardCompatible||void 0})}}}});var vJr,H_u=h(()=>{"use strict";Hn();Xo();Wut();sVe();vJr=class extends io{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=$r.container(Cs.map({keyType:io.STRING,valueType:$r.unknown()}));return{type:pc.alias({aliasOf:t,resolvedType:t}),referencedTypes:new Set,inlinedTypes:{}}}}tryConvertTypedMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean")return;let r=new ZT({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schemaOrReferenceOrBoolean}).convert();if(r!=null){let n=$r.container(Cs.map({keyType:io.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 O4(r.type,i),{type:pc.alias({aliasOf:n,resolvedType:n}),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}}});function Y_u(e,t,r){let n=X_u(t,r),i={};for(let o of n)i=m8o(i,o);return jOm(i,e),i}function X_u(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 u of s)if("$ref"in u){if(t==null)continue;let l=u.$ref;if(n.has(l))continue;n.add(l);let p=t(u);p!=null&&c.push(p)}else c.push(u);i.push(...X_u(c,t,n)),Object.keys(a).length>0&&i.push(a)}else i.push(o);return i}function m8o(e,t){let r={...e};for(let[n,i]of Object.entries(t)){if(i===void 0||FOm.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]=NOm(o??{},i);continue}if(n==="items"){jr(o)&&jr(i)?r[n]=m8o(o,i):r[n]=i;continue}if(K_u.includes(n)){jr(o)&&jr(i)?r[n]=Z_u(o,i):r[n]=i;continue}if(J_u.includes(n)){r[n]=!!o||!!i;continue}if(DOm.includes(n)){typeof o=="number"&&typeof i=="number"?r[n]=Math.max(o,i):r[n]=i;continue}if(kOm.includes(n)){typeof o=="number"&&typeof i=="number"?r[n]=Math.min(o,i):r[n]=i;continue}r[n]=i}return r}function NOm(e,t){let r={...e};for(let[n,i]of Object.entries(t)){let o=r[n];jr(o)&&jr(i)?r[n]=m8o(o,i):r[n]=i}return r}function Z_u(e,t){let r={...e};for(let[n,i]of Object.entries(t)){let o=r[n];jr(o)&&jr(i)?r[n]=Z_u(o,i):r[n]=i}return r}function jOm(e,t){for(let r of ROm){let n=t[r];n!=null&&(e[r]=n)}for(let r of K_u){let n=t[r];n!=null&&(e[r]=n)}for(let r of J_u)t[r]===!0&&(e[r]=!0)}var ROm,K_u,J_u,DOm,kOm,FOm,$_u=h(()=>{"use strict";ct();ROm=["description","title","format","type","discriminator","xml","externalDocs","extensions"],K_u=["example","default"],J_u=["deprecated","readOnly","writeOnly","uniqueItems","nullable"],DOm=["minimum","exclusiveMinimum","minLength","minItems","minProperties"],kOm=["maximum","exclusiveMaximum","maxLength","maxItems","maxProperties"],FOm=["allOf","oneOf","anyOf"]});var Hut,h8o=h(()=>{"use strict";ct();Hn();fc();EJr();Xo();Wut();Hut=class extends io{schema;xmlEncoding;constructor({context:t,breadcrumbs:r,schema:n,id:i}){super({context:t,breadcrumbs:r}),this.schema=n,this.xmlEncoding=new Gut({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:pc.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}=aVe({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,u=n,l=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 R=this.context.resolveMaybeReference({schemaOrReference:f,breadcrumbs:m});if(R==null){this.context.logger.debug?.(`[ObjectSchemaConverter] allOf[${d}] reference could not be resolved. Skipping: ${JSON.stringify(f)}`);continue}if(g=R,typeof g.additionalProperties=="boolean"&&g.additionalProperties&&(t=!0),!c||Object.keys(g.properties??{}).every(D=>!this.schema.required?.includes(D))){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 y=g.oneOf??g.anyOf;if(y!=null&&g.type==null&&g.properties==null){let R=new Set(r.map(D=>ar(D.name)));for(let[D,O]of y.entries()){let z=[...m,g.oneOf!=null?"oneOf":"anyOf",D.toString()],Y=this.context.isReferenceObject(O)?this.context.resolveMaybeReference({schemaOrReference:O,breadcrumbs:z}):O;if(Y==null)continue;let $={};for(let[Re,ce]of Object.entries(Y.properties??{}))!this.context.isReferenceObject(ce)&&"not"in ce||($[Re]=ce);let ee=Object.keys($).filter(Re=>!R.has(Re));if(ee.length===0)continue;let ae={};for(let Re of ee){let ce=$[Re];ce!=null&&(ae[Re]=ce,R.add(Re))}let{convertedProperties:pe,inlinedTypesFromProperties:oe,referencedTypes:me,propertiesByAudience:Se}=aVe({properties:ae,required:[],breadcrumbs:z,context:this.context,errorCollector:this.context.errorCollector,withinXmlElement:this.xmlEncoding!=null});r.push(...pe),u={...u,...oe},l={...l,...Se},me.forEach(Re=>{a.add(Re)})}continue}let I=g.properties??{};if(A){I={};for(let[R,D]of Object.entries(g.properties??{})){let O=p[R];O!=null&&!this.context.isReferenceObject(D)?I[R]={...O,...D}:I[R]=D}}let{convertedProperties:x,inlinedTypesFromProperties:v,referencedTypes:S,propertiesByAudience:B}=aVe({properties:I,required:[...this.schema.required??[],...g.required??[],...ufe(g)],breadcrumbs:m,context:this.context,errorCollector:this.context.errorCollector,withinXmlElement:this.xmlEncoding!=null});r.push(...x),u={...u,...v},l={...l,...B},S.forEach(R=>{a.add(R)})}for(let d of Object.keys(u))a.add(d);return{type:pc.object({properties:r,extends:s.map(d=>this.context.typeReferenceToDeclaredTypeName(d)).filter(fa),extendedProperties:[],extraProperties:t,deferredUnionBaseProperties:void 0}),propertiesByAudience:l,referencedTypes:a,inlinedTypes:u,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 zOm(e){return e.type==="union"&&e.types.length===0}function QOm({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 cVe,g8o=h(()=>{"use strict";Hn();u8o();l8o();p8o();Xo();Wut();IJr();CJr();sVe();cVe=class extends io{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 _ut({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&&!zOm(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 u;if(this.context.isReferenceObject(c)){let l=this.context.resolveReference({reference:c,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});l.resolved&&(u=l.value)}else u=c;u!=null&&(u.enum!=null&&u.enum.length>1&&(u.type==="string"||u.type==null)?r=u:u.type==="string"&&u.enum==null&&(n=!0))}if(r==null||!n)return;let o=new Vut({breadcrumbs:this.breadcrumbs,schema:r,context:this.context}).convert(),a=new rwe({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?QOm({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 u=s.$ref,l=u.split("/").pop(),p=this.context.getTypeIdFromSchemaReference(s),d=c??l;if(p==null||d==null)return[];i.push({discriminant:d,typeId:p,ref:u,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:l,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),y=d!=null&&d===this.getEnclosingComponentRef(),I=f?.properties!=null&&t in f.properties&&!((A||y)&&d!=null);if(I&&f!=null&&(g=this.filterDiscriminantFromSchema(f,t)),g==null)continue;let x=new ZT({context:this.context,schemaOrReference:g,schemaIdOverride:p??void 0,breadcrumbs:m});p!=null&&n.add(p);let v=I&&p!=null&&!A;v&&this.context.discriminatedVariantsInProgress.add(p);let S;try{S=x.convert()}finally{v&&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 B=this.context.casingsGenerator.generateNameAndWireValue({name:l,wireValue:l}),R=d?.split("/").pop()??p,D=f?.title,O=f?.description,z=D??l??R;S.schema?.typeDeclaration!=null&&D!=null&&(S.schema.typeDeclaration.name.displayName=D),r.push({docs:O,discriminantValue:B,availability:S.availability,displayName:z,shape:tT.samePropertiesAsObject({typeId:p,name:this.context.casingsGenerator.generateName(R),fernFilepath:{allParts:[],packagePath:[],file:void 0},displayName:z})}),i={...i,...S.inlinedTypes}}}let{convertedProperties:o,referencedTypes:s,inlinedTypesFromProperties:a}=aVe({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[l,p]of(this.schema.allOf??[]).entries()){let d=[...this.breadcrumbs,"allOf",l.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 l of Object.keys({...i,...a}))n.add(l);let u=new Uut({context:this.context,breadcrumbs:[...this.breadcrumbs,"discriminator"],node:this.schema.discriminator});return{type:pc.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:u.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 y=this.getDiscriminatorKeyForRef(c);y!=null?g=this.context.convertReferenceToTypeReference({reference:c,displayNameOverride:y,displayNameOverrideSource:"discriminator_key"}):g=this.context.convertReferenceToTypeReference({reference:c,breadcrumbs:this.breadcrumbs})}if(g.ok){let y=this.context.resolveReference({reference:c,breadcrumbs:this.breadcrumbs}),I=y.resolved?y.value.description:void 0;t.push({type:g.reference,docs:I})}let A=this.context.getTypeIdFromSchemaReference(c);A!=null&&r.add(A);continue}let l=Object.keys(this.schema.properties??{}).length>0?void 0:this.extendSubSchema(c),p=this.context.convertBreadcrumbsToName([`${this.id}_${a}`]),d=c.title,m=new nwe({context:this.context,id:p,nameOverride:d,breadcrumbs:[...this.breadcrumbs,`oneOf[${a}]`],schema:l??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:$r.container(Cs.map({keyType:io.STRING,valueType:$r.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 y of Object.keys(m.inlinedTypes))r.add(y)}m.convertedSchema.typeDeclaration.referencedTypes.forEach(A=>{r.add(A)})}}let{convertedProperties:i,referencedTypes:o,inlinedTypesFromProperties:s}=aVe({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:pc.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 ZT({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(n==null)return;let i=this.wrapInNullable(n.type);return{type:pc.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 $r.container(Cs.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 Kut,A8o=h(()=>{"use strict";Hn();Xo();Kut=class extends io{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 $r.container(Cs.literal(rE.string(t)));if(this.schema.format==="date-time-rfc-2822")return $r.primitive({v1:ds.DateTimeRfc2822,v2:vi.dateTimeRfc2822({})});if(this.context.settings.typeDatesAsStrings===!1){if(this.schema.format==="date")return $r.primitive({v1:ds.Date,v2:vi.date({})});if(this.schema.format==="date-time")return $r.primitive({v1:ds.DateTime,v2:vi.dateTime({})})}return $r.primitive({v1:"STRING",v2:vi.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":switch(this.schema.format){case"double":return $r.primitive({v1:"DOUBLE",v2:vi.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return $r.primitive({v1:"FLOAT",v2:vi.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return $r.primitive({v1:"INTEGER",v2:vi.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return $r.primitive({v1:"LONG",v2:vi.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return $r.primitive({v1:"UINT",v2:vi.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return $r.primitive({v1:"UINT_64",v2:vi.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return $r.primitive({v1:"DOUBLE",v2:vi.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"integer":switch(this.schema.format){case"double":return $r.primitive({v1:"DOUBLE",v2:vi.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return $r.primitive({v1:"FLOAT",v2:vi.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return $r.primitive({v1:"INTEGER",v2:vi.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return $r.primitive({v1:"LONG",v2:vi.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return $r.primitive({v1:"UINT",v2:vi.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return $r.primitive({v1:"UINT_64",v2:vi.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return $r.primitive({v1:"INTEGER",v2:vi.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?$r.container(Cs.literal(rE.boolean(t))):$r.primitive({v1:"BOOLEAN",v2:vi.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 LOm(e){let t=ufe(e);return t.length===0?e:{...e,required:[...new Set([...e.required??[],...t])]}}var MOm,nwe,CJr=h(()=>{"use strict";ct();Hn();Xo();Wut();W_u();twe();y8o();IJr();H_u();$_u();h8o();g8o();A8o();MOm=["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],nwe=class e extends io{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 u=this.tryConvertSiblingAnyOfConstraint();if(u!=null)return u;let l=this.tryConvertSiblingOneOfConstraint();if(l!=null)return l;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 O4(r.reference,n),{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:pc.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 _C.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),i=new rwe({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 u;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;u=d}else u=c;let l=u.oneOf??u.anyOf;if(!this.context.isReferenceObject(c)&&l!=null&&u.type==null&&u.properties==null){let p={};for(let d of l){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(LOm(u))}if(i)return;let o=Y_u(this.schema,n,c=>{let u=this.context.resolveMaybeReference({schemaOrReference:c,breadcrumbs:this.breadcrumbs});if(!(u!=null&&this.context.isReferenceObject(u)))return u}),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,u)=>c*u.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,u)=>u!==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 u=this.getVariantTitle(c);return{...u!=null?{title:u}:{},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 Kut({context:this.context,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:pc.alias({aliasOf:r,resolvedType:r}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertArraySchema(){if(this.schema.type==="array"){let r=new Jut({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:pc.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||!UMe(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(!VMe(this.schema)||new _C.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=ufe(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 cVe({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 vJr({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 cVe({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 Hut({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:pc.alias({aliasOf:$r.unknown(),resolvedType:$r.unknown()}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertFernTypeDeclaration(){let r=new _C.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r==null)return;let n=q_u(r);if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:pc.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=[...MOm,...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 Jw({breadcrumbs:this.breadcrumbs,context:this.context,schema:this.schema,example:t}),{validExample:n}=r.convert();return n}}});function UOm(e){return Object.keys(e).every(t=>_Om.has(t))}var ZT,_Om,sVe=h(()=>{"use strict";Hn();Xo();CJr();ZT=class extends io{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=>UOm(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 nwe({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 $r.container(Cs.optional(t))}wrapInNullable(t){return $r.container(Cs.nullable(t))}},_Om=new Set(["description","title","deprecated","readOnly","writeOnly","xml","externalDocs","x-fern-type-name"])});function aVe({properties:e,required:t,breadcrumbs:r,context:n,errorCollector:i,withinXmlElement:o=!1}){let s=[],a={},c={},u=new Set;for(let[l,p]of Object.entries(e??{})){let d=[...r,"properties",l];if(typeof p!="object"){i.collect({message:`Schema property ${l} should be an object`,path:d});continue}let f=GOm(r,p,n)??n.convertBreadcrumbsToName(d),m="nullable"in p?p.nullable:!1,A=new ZT({context:n,breadcrumbs:d,schemaOrReference:p,schemaIdOverride:f,wrapAsOptional:!t.includes(l),wrapAsNullable:m}).convert();if(A!=null){let y=n.resolveMaybeReference({schemaOrReference:p,breadcrumbs:d,skipErrorCollector:!0});s.push({name:n.casingsGenerator.generateNameAndWireValue({name:l,wireValue:l}),valueType:A.type,docs:p.description??A.schema?.typeDeclaration.docs,availability:A.availability,propertyAccess:n.getPropertyAccess(p),defaultValue:y?.default,xml:o?new qut({breadcrumbs:d,propertySchema:p,resolvedPropertySchema:y??void 0,context:n}).convert():void 0,v2Examples:A.schema?.typeDeclaration?.v2Examples??VOm({propertySchema:p,breadcrumbs:d,context:n,propertyId:f})}),a={...a,...A.inlinedTypes},A.schema?.typeDeclaration.referencedTypes!=null&&A.schema.typeDeclaration.referencedTypes.forEach(I=>{u.add(I)}),O4(A.type,u);for(let I of A.schema?.audiences??[])c[I]==null&&(c[I]=new Set),c[I].add(l)}}for(let l of Object.keys(a))u.add(l);return{convertedProperties:s,propertiesByAudience:c,inlinedTypesFromProperties:a,referencedTypes:u}}function VOm({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 u={};for(let[l,p]of o.entries()){let d=r.resolveExample(p),f=`${n}_example_${l}`,m=new Jw({breadcrumbs:t,context:r,schema:e,example:d}),{validExample:g}=m.convert();u[f]=g}return{userSpecifiedExamples:u,autogeneratedExamples:{}}}let s=`${n}_example_autogenerated`,a=new Jw({breadcrumbs:t,context:r,schema:e,example:void 0,generateOptionalProperties:!0}),{validExample:c}=a.convert();return{userSpecifiedExamples:{},autogeneratedExamples:{[s]:c}}}function GOm(e,t,r){return r.isReferenceObject(t)?void 0:new _C.FernTypeNameExtension({breadcrumbs:e,schema:t,context:r}).convert()}function O4(e,t){switch(e.type){case"named":t.add(e.typeId);return;case"primitive":case"unknown":return;case"container":qOm(e.container,t);return}}function qOm(e,t){switch(e.type){case"list":O4(e.list,t);return;case"set":O4(e.set,t);return;case"optional":O4(e.optional,t);return;case"nullable":O4(e.nullable,t);return;case"map":O4(e.keyType,t),O4(e.valueType,t);return;case"literal":return}}var Wut=h(()=>{"use strict";twe();sVe();EJr();Xo()});var Jut,y8o=h(()=>{"use strict";Hn();Xo();Wut();sVe();Jut=class e extends io{static LIST_UNKNOWN=$r.container(Cs.list($r.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 ZT({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)})}),O4(r.type,n),{typeReference:$r.container(Cs.list(r.type)),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}}});var b8o={};te(b8o,{ArraySchemaConverter:()=>Jut,EnumSchemaConverter:()=>rwe,ObjectSchemaConverter:()=>Hut,OneOfSchemaConverter:()=>cVe,PrimitiveSchemaConverter:()=>Kut,SchemaConverter:()=>nwe,SchemaOrReferenceConverter:()=>ZT});var E8o=h(()=>{"use strict";y8o();IJr();h8o();g8o();A8o();CJr();sVe()});var xJr,eUu=h(()=>{"use strict";Gi();Xo();twe();E8o();xJr=class extends io{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 ZT({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,u])=>{if(this.context.isReferenceObject(u)){let l=this.context.resolveReference({reference:u,breadcrumbs:[...this.breadcrumbs,"content",n,"examples"],skipErrorCollector:!0});return l.resolved?[c,l.value.value??l.value]:null}return[c,u.value??u]}).filter(c=>c!=null)):void 0;return{...s,examples:a}}parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:r}){let i=new ZT({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,u]of s){let l=this.context.resolveExampleWithValue(u),p=this.context.resolveExampleRecursively({example:u,breadcrumbs:this.breadcrumbs}),d=this.getIdForExample({key:c,example:p,usedExampleNames:a});a.add(d),l!=null&&(o!=null?i.userSpecifiedExamples[d]=this.generateOrValidateExample({schema:o,example:l,exampleGenerationStrategy:n,exampleName:d}):i.userSpecifiedExamples[d]=l)}if(o!=null&&Object.keys(i.userSpecifiedExamples).length===0){let c=this.getExamplesFromSchemaOrReference(o);c.length>1&&c.forEach((u,l)=>{let p=`Example ${l+1}`;i.userSpecifiedExamples[p]=this.generateOrValidateExample({schema:o,example:u,exampleGenerationStrategy:n,exampleName:p})})}if(Object.keys(i.userSpecifiedExamples).length===0&&o!=null){let c=ri(`${[...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 Jw({breadcrumbs:this.breadcrumbs,context:this.context,schema:o,example:r??s[0],generateOptionalProperties:n??!1,exampleGenerationStrategy:i}),{validExample:c}=a.convert();return c}}});var SJr,tUu=h(()=>{"use strict";Xo();twe();SJr=class extends io{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??io.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??io.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??io.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 Jw({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 I8o={};te(I8o,{AbstractMediaTypeObjectConverter:()=>xJr,AbstractParameterConverter:()=>SJr});var rUu=h(()=>{"use strict";eUu();tUu()});function Yut({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 u=WOm({context:e,header:c}),l=u?.schema,p=c.required===!0,d=y=>p?y:$r.container(Cs.optional(y)),f=d(io.STRING),m,g=e.getAvailability({node:c,breadcrumbs:[...o,"headers",s]});if(l!=null)if(m=e.resolveMaybeReference({schemaOrReference:l,breadcrumbs:[...o,"headers",s,"schema"]}),m?.type==="number"||m?.type==="integer")f=d($r.primitive({v1:m.type==="integer"?"INTEGER":"DOUBLE",v2:m.type==="integer"?vi.integer({default:void 0,validation:void 0}):vi.double({default:void 0,validation:void 0})}));else if(m?.type==="boolean")f=d($r.primitive({v1:"BOOLEAN",v2:vi.boolean({default:void 0})}));else{let y=new ZT({context:e,breadcrumbs:[...o,"headers",s,"schema"],schemaOrReference:l,wrapAsOptional:!p,schemaIdOverride:e.convertBreadcrumbsToName([...o,"headers",s])}).convert();if(y!=null){f=y.type;for(let[I,x]of Object.entries(y.inlinedTypes))i[I]=x}}let A=HOm({context:e,breadcrumbs:o,header:c,headerName:s,schema:l,mediaTypeObject:u?.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 WOm({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&&Zp.parse(r)?.isJSON())return{schema:n.schema,mediaTypeObject:n}}}function HOm({context:e,breadcrumbs:t,header:r,headerName:n,schema:i,mediaTypeObject:o}){let s={userSpecifiedExamples:{},autogeneratedExamples:{}},a=r.example,c=r.examples;for(let[u,l]of Object.entries(c??{})){let p=e.resolveExampleWithValue(l);p!=null&&(s.userSpecifiedExamples[u]=M9t({context:e,breadcrumbs:t,schema:i,example:p}))}if(a!=null){let u=e.generateUniqueName({prefix:`${n}_example`,existingNames:Object.keys(s.userSpecifiedExamples)});s.userSpecifiedExamples[u]=M9t({context:e,breadcrumbs:t,schema:i,example:a})}if(Object.keys(s.userSpecifiedExamples).length===0&&o!=null)for(let[u,l]of e.getNamedExamplesFromMediaTypeObject({mediaTypeObject:o,breadcrumbs:[...t,"headers",n,"content"],defaultExampleName:`${n}_example`})){let p=e.resolveExampleWithValue(l);if(p!=null){let d=e.generateUniqueName({prefix:u,existingNames:Object.keys(s.userSpecifiedExamples)});s.userSpecifiedExamples[d]=M9t({context:e,breadcrumbs:t,schema:i,example:p})}}if(Object.keys(s.userSpecifiedExamples).length===0&&i!=null){let u=e.getExamplesFromSchema({schema:KOm({context:e,schema:i,breadcrumbs:[...t,"headers",n,"schema"]}),breadcrumbs:[...t,"headers",n,"schema"]});for(let l of u){let p=e.generateUniqueName({prefix:`${n}_example`,existingNames:Object.keys(s.userSpecifiedExamples)});s.userSpecifiedExamples[p]=M9t({context:e,breadcrumbs:t,schema:i,example:e.resolveExample(l)})}}if(Object.keys(s.userSpecifiedExamples).length===0&&i!=null){let u=`${n}_example`;s.autogeneratedExamples[u]=M9t({context:e,breadcrumbs:t,schema:i,example:void 0,ignoreErrors:!0})}return s}function KOm({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 M9t({context:e,breadcrumbs:t,schema:r,example:n,ignoreErrors:i}){if(r==null)return n;let o=new Jw({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 nUu=h(()=>{"use strict";ct();Hn();pJr();twe();sVe()});var wJr,iUu=h(()=>{"use strict";XD();wJr=class extends es{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 oUu,JOm,P4,sUu=h(()=>{"use strict";ct();Hn();c8o();iUu();Xo();oUu="Base",JOm="x-fern-default-url",P4=class e extends io{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 u=e.getServerName({server:c,context:this.context});return{id:u,name:this.context.casingsGenerator.generateName(u)}}).filter((c,u,l)=>l.findIndex(p=>p.id===c.id)===u),s=[i,...o],a=this.servers.map(c=>{let u=e.getServerName({server:c,context:this.context}),l=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:u,name:this.context.casingsGenerator.generateName(u),urls:{[n]:this.getServerUrl(c),...Object.fromEntries(l??[])},docs:c.description,audiences:p,defaultUrls:d,urlTemplates:f,urlVariables:m}});return{value:{defaultEnvironment:a[0]?.id,baseUrlEnvVar:this.baseUrlEnvVar,environments:eE.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(fa);return{value:{defaultEnvironment:r[0]?.id,baseUrlEnvVar:this.baseUrlEnvVar,environments:eE.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 wJr({breadcrumbs:[],server:t,context:r}).convert()}static getServerAudiences({server:t,context:r}){return new Lut({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?oUu:e.getServerExtensionName({server:this.servers[0],context:this.context})??oUu}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 u=e.getServerName({server:c,context:this.context});if(c.variables!=null&&Object.keys(c.variables).length>0){a=!0;let l=this.extractFernDefaultUrlFromServer(c);l!=null&&(i[u]=l),o[u]=this.maybeRemoveTrailingSlashIfNotEmpty(c.url),s[u]=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[JOm];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 Um={};te(Um,{AbstractConverters:()=>I8o,ExampleConverter:()=>Jw,SchemaConverters:()=>b8o,ServersConverter:()=>P4,convertResponseHeaders:()=>Yut});var v8o=h(()=>{"use strict";rUu();twe();nUu();E8o();sUu()});var L9t,aUu=h(()=>{"use strict";twe();Q9t();L9t=class{context;constructor({context:t}){this.context=t}validateExample({example:t,schema:r,breadcrumbs:n,exampleGenerationStrategy:i}){return new Jw({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 u=this.validateExample({example:t.requestExample,schema:t.requestSchema,breadcrumbs:[...a,"request"],exampleGenerationStrategy:"request"});if(!u.isValid){i=!1;let l=t.exampleSource==="human"?AE.WARNING:AE.ERROR;r.push(...u.errors.map(p=>({...p,level:l,message:`Invalid request example: ${p.message}`})))}u.coerced&&(o=!0,n.push({level:AE.WARNING,message:"Request example was coerced to match schema",path:[...a,"request"]})),s={request:u.validExample}}let c=this.getResponseSchemaForValidation(t);if(t.responseExample!==void 0&&c!==void 0){let u=this.validateExample({example:t.responseExample,schema:c,breadcrumbs:[...a,"response"],exampleGenerationStrategy:"response"});if(!u.isValid){i=!1;let l=t.exampleSource==="human"?AE.WARNING:AE.ERROR;r.push(...u.errors.map(p=>({...p,level:l,message:`Invalid response example: ${p.message}`})))}u.coerced&&(o=!0,n.push({level:AE.WARNING,message:"Response example was coerced to match schema",path:[...a,"response"]})),s={...typeof s=="object"&&s!==null?s:{},response:u.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}),u={endpointPath:o.endpointPath,method:o.method,exampleSource:"ai",requestExample:o.request?.body,responseExample:o.response?.body,requestSchema:s,responseSchema:a,responseSchemas:c},l=this.validateEndpointExample({exampleToValidate:u}),p=this.hasUnexpectedProperties({requestExample:o.request?.body,responseExample:o.response?.body,requestSchema:s,responseSchema:a}),d=l.errors.length>0||l.warnings.length>0;!l.isValid||d||p?i.push({example:o,validationResult:l}):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,u]of Object.entries(t.paths)){if(!u)continue;let l=["get","post","put","delete","patch","options","head","trace"];for(let p of l){let d=u[p];if(!d)continue;let f=[],{requestSchema:m,responseSchema:g,responseSchemas:A}=this.getSchemasForOperation({operation:d}),y=this.extractExamplesFromOperation({operation:d,path:c,method:p});for(let I of y){n++;let x={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},v=this.validateEndpointExample({exampleToValidate:x});f.push(v),v.isValid?i++:(o++,I.source==="human"?s.push(v):I.source==="ai"&&a.push(v))}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,u]of Object.entries(a.examples)){let l=this.context.isReferenceObject(u)?this.context.resolveExample(u):u;l&&typeof l=="object"&&"value"in l&&i.push({name:c,source:"human",request:l.value})}}if(t.responses)for(let[s,a]of Object.entries(t.responses)){if(!a||this.context.isReferenceObject(a))continue;let u=a.content?.["application/json"];if(u?.example!==void 0){let l=i.find(p=>p.request!==void 0&&p.response===void 0);l?(l.response=u.example,l.statusCode=s):i.push({name:`${n}_${r}_response_${s}_example`,source:"openapi",response:u.example,statusCode:s})}if(u?.examples)for(let[l,p]of Object.entries(u.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===l);f?(f.response=d.value,f.statusCode=s):i.push({name:l,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 cUu({tags:e,errorCollector:t}){for(let r of e)if(Xut.test(r.name)){let n=[...r.name].filter(i=>Xut.test(i));t.collect({level:AE.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(Xut,"").trim()}".`})}}function uUu({description:e,path:t,errorCollector:r}){YOm.test(e)&&r.collect({level:AE.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 C8o({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");cUu({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 u=c;if(typeof u.description=="string"&&uUu({description:u.description,path:["paths",i,a,"description"],errorCollector:t}),Array.isArray(u.tags)&&!Array.isArray(e.tags)){for(let l of u.tags)if(typeof l=="string"&&!n.has(l)&&Xut.test(l)){n.add(l);let p=[...l].filter(d=>Xut.test(d));t.collect({level:AE.ERROR,message:`Tag name "${l}" 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 "${l}" to "${l.replace(Xut,"").trim()}".`})}}}}}}var Xut,YOm,lUu=h(()=>{"use strict";Q9t();Xut=new RegExp("[^\\x00-\\x7F]"),YOm=/(?:^|\n)\s*---\s*(?:\n|$)/});var TJr,XOm,pUu=h(()=>{"use strict";TJr={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"},XOm=new Set(Object.values(TJr))});function x8o(e){if(e!=null)return e.map(t=>Object.fromEntries(Object.entries(t).map(([r,n])=>[r,n??[]])))}var fUu=h(()=>{"use strict"});var Xo=h(()=>{"use strict";pJr();S_u();XD();U_u();v8o();v8o();Q9t();aUu();d8o();lUu();pUu();fUu()});var ZOm,$Om,dUu,mUu=h(()=>{"use strict";an();ZOm=Fe.object({type:Fe.string(),channelId:Fe.string().optional(),messageId:Fe.string(),value:Fe.any()}),$Om=Fe.object({summary:Fe.string().optional(),description:Fe.string().optional(),"query-parameters":Fe.record(Fe.string()).optional(),headers:Fe.record(Fe.string()).optional(),messages:Fe.array(ZOm)}),dUu=Fe.array($Om)});var OJr,hUu=h(()=>{"use strict";Xo();mUu();OJr=class extends es{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=dUu.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 Zut,S8o=h(()=>{"use strict";Xo();hUu();Zut=class extends io{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 OJr({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 ePm,CJ,_9t=h(()=>{"use strict";Hn();Xo();ePm="x-fern-server-name",CJ=class e extends io{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:eE.singleBaseUrl({environments:t})}}static getServerName(t,r){if(r!=null&&typeof r=="object"){let n=r[ePm];if(typeof n=="string"&&n.length>0)return n}return t}constructServerUrl(t,r){return r.includes("://")?r:`${t}://${r}`}}});var iwe,w8o=h(()=>{"use strict";Xo();iwe=class extends Um.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 _C.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 Um.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 PJr,gUu=h(()=>{"use strict";Xo();PJr=class extends es{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 owe,T8o=h(()=>{"use strict";Xo();owe=class extends es{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 swe,O8o=h(()=>{"use strict";Xo();swe=class extends es{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 BJr,AUu=h(()=>{"use strict";Xo();BJr=class extends es{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 RJr,yUu=h(()=>{"use strict";Hn();fc();Xo();Gi();S8o();_9t();w8o();gUu();T8o();O8o();AUu();RJr=class extends Zut{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 owe({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 l=new PJr({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert(),p=this.transformToValidPath(l??this.channelPath),d=this.resolveServerName(this.channel.servers?.[0])??this.resolveServerName(Object.keys(this.context.spec.servers??{})[0]),f=nb(p),m=ri(this.channelPath),g=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[],A=this.hasServerSecurity()||this.context.authOverrides?.auth!=null,y=new swe({context:this.context,breadcrumbs:this.breadcrumbs,node:this.context.spec}).convert(),x=new swe({context:this.context,breadcrumbs:this.breadcrumbs,node:this.channel}).convert()??y;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:x},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=$Me(ri(`${this.channelPath}_${o}`)).replace(/ /g,"");if("oneOf"in r.message){let l=new Um.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:s,schemaOrReference:r.message,schemaIdOverride:c}).convert();l!=null&&l.schema!=null&&(i=l.schema,this.inlinedTypes={...this.inlinedTypes,...l.inlinedTypes})}else if(t.isMessageWithPayload(r.message)){let u=t.resolveMaybeReference({schemaOrReference:r.message.payload,breadcrumbs:s});if(u!=null){let p=new Um.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:s,schemaOrReference:u,schemaIdOverride:c}).convert();p!=null&&p.schema!=null&&(i=p.schema,this.inlinedTypes={...this.inlinedTypes,...p.inlinedTypes})}}if(i!=null){let u=i,l=$r.named({fernFilepath:t.createFernFilepath(),name:u.typeDeclaration.name.name,typeId:u.typeDeclaration.name.typeId,displayName:void 0,default:void 0,inline:!1}),p=uB.reference({bodyType:l,docs:r.description}),d=n==="server"?"subscribe":"publish",m=new owe({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 iwe({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 iwe({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 CJ.getServerName(t,n)}return t}getOperationMethodName(t){return new BJr({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 iwe({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 DJr,bUu=h(()=>{"use strict";_9t();DJr=class extends CJ{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 P8o,EUu,B8o,kJr,IUu=h(()=>{"use strict";Hn();fc();Dt();S8o();_9t();w8o();T8o();O8o();P8o="$message.",EUu="#/channels/",B8o="#/servers/",kJr=class extends Zut{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 owe({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,[y,I])=>{try{this.getChannelPathFromOperation(I)===this.channelPath&&(A[y]=I)}catch{}return A},{}),a=[];for(let[A,y]of Object.entries(s)){let x=new owe({breadcrumbs:[...this.breadcrumbs,A],node:y,context:this.context}).convert()??A;for(let v of y.messages){let S=this.context.convertReferenceToTypeReference({reference:v});if(S.ok){let B=this.resolveMessageDocs(v)??y.description,R=uB.reference({bodyType:S.reference,docs:B});a.push({type:A,displayName:x,origin:y.action==="send"?"client":"server",body:R,availability:this.context.getAvailability({node:y,breadcrumbs:this.breadcrumbs}),docs:B,methodName:void 0})}}}let c=this.resolveChannelServersFromReference(this.channel.servers??[])??this.resolveFirstServerName(),u=this.transformToValidPath(this.channel.address??this.channelPath),l=nb(u),p=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[],d=this.hasServerSecurity()||this.context.authOverrides?.auth!=null,f=new swe({context:this.context,breadcrumbs:this.breadcrumbs,node:this.context.spec}).convert(),g=new swe({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:l,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:u,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(B8o,""),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:u}=a,p=new iwe({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...s,name:u,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(P8o)){this.context.errorCollector.collect({message:`Invalid location format: ${t}; expected ${P8o} prefix`,path:this.breadcrumbs});return}let i=r.substring(P8o.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(B8o)){this.context.errorCollector.collect({message:`Failed to resolve server name from server ref ${r.$ref}`,path:this.breadcrumbs});return}let n=r.$ref.substring(B8o.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 CJ.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 CJ.getServerName(r,n)}getChannelPathFromOperation(t){if(!t.channel.$ref.startsWith(EUu))throw new T({message:`Failed to resolve channel path from operation ${t.channel.$ref}`,code:T.Code.ReferenceError});return t.channel.$ref.substring(EUu.length)}}});var FJr,vUu=h(()=>{"use strict";_9t();FJr=class extends CJ{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 U9t,CUu=h(()=>{"use strict";Hn();fc();Xo();yUu();bUu();IUu();vUu();U9t=class extends vJ{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 u=`${r}_${i}`;this.convertSchema({id:u,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 Um.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 FJr({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}else{let r=this.context.spec.servers;t=new DJr({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}this.addEnvironmentsToIr({environmentConfig:t})}convertSecuritySchemes(){if(this.context.authOverrides){let r=OGt({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 _p.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 _p.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 _p.header({key:r,name:{name:this.context.casingsGenerator.generateName("apiKey"),wireValue:t.name},valueType:io.OPTIONAL_STRING,prefix:void 0,headerEnvVar:void 0,headerPlaceholder:void 0,docs:t.description,playgroundDocs:void 0});break}case"oauth2":return _p.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 _C.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 kJr({context:this.context,breadcrumbs:["channels",t],websocketGroup:i,channel:r,channelPath:t,operations:a}).convert()}else o=new RJr({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 V9t,xUu=h(()=>{"use strict";Hn();Xo();V9t=class extends E0{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 u=a[1],l=a[2];return o=`${u}_${l}`,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:$r.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:$r.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:$r.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}}});var SUu=h(()=>{"use strict";CUu();xUu()});function rPm(e){let t=new Set,r,n=new RegExp(tPm.source,"g");for(;(r=n.exec(e))!=null;)r[1]!=null&&t.add(r[1]);return t}var tPm,NJr,wUu=h(()=>{"use strict";Xo();tPm=/\{([^}]+)\}/g,NJr=class extends es{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=rPm(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 u=o[c];if(u==null){s.push({name:c,type:"string",default:void 0,docs:void 0});continue}if(typeof u!="object"||Array.isArray(u)){this.context.errorCollector.collect({message:`Parameter '${c}' must be an object`,path:[...this.breadcrumbs,"parameters",c]});return}let l=u,p=typeof l.type=="string"?l.type:"string",d=typeof l.docs=="string"?l.docs:void 0;s.push({name:c,type:p,default:l.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 jJr,TUu=h(()=>{"use strict";Xo();jJr=class extends es{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 zJr,OUu=h(()=>{"use strict";Xo();zJr=class extends es{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 nPm(e){let r=e["x-fern-default"]??e.default;if(typeof r=="string"||typeof r=="boolean"||typeof r=="number")return r}var QJr,PUu=h(()=>{"use strict";Xo();QJr=class extends es{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:nPm(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 iPm(e){if(e!=null){if(typeof e=="string")return Xt.Literal.string(e);if(typeof e=="boolean")return Xt.Literal.boolean(e)}}function BUu({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:io.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:io.STRING,env:i.env,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}},availability:void 0,docs:i.docs,clientDefault:iPm(i.default),defaultValue:i.default})}return r}var RUu=h(()=>{"use strict";Hn();Xo()});function oPm(e){if(e!=null){if(typeof e=="string")return Xt.Literal.string(e);if(typeof e=="boolean")return Xt.Literal.boolean(e)}}function DUu({globalHeaders:e,context:t}){return e.map(r=>({name:t.casingsGenerator.generateNameAndWireValue({name:r.name??"",wireValue:r.header}),valueType:r.optional?io.OPTIONAL_STRING:io.STRING,env:r.env,v2Examples:r.optional?void 0:sPm({header:r,context:t}),availability:void 0,docs:void 0,clientDefault:oPm(r["x-fern-default"]),defaultValue:void 0}))}function sPm({header:e,context:t}){let r=new Jw({breadcrumbs:[],context:t,schema:{type:"string"},example:e.header}),{validExample:n}=r.convert();return{userSpecifiedExamples:{},autogeneratedExamples:{globalHeaderExample:n}}}var kUu=h(()=>{"use strict";Hn();Xo()});function aPm(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 Xt.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 Xt.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 Xt.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 cPm(e,t,r){switch(e){case void 0:case"body":return Xt.GlobalParameterLocation.Body;case"query":return Xt.GlobalParameterLocation.Query;case"header":return Xt.GlobalParameterLocation.Header;case"path":return Xt.GlobalParameterLocation.Path;default:return r.errorCollector.collect({message:`Invalid global parameter location '${e}'; expected one of: body, query, header, path`,path:t}),Xt.GlobalParameterLocation.Body}}function uPm(e,t,r){switch(e){case void 0:return;case"explicit":return Xt.GlobalParameterApplyMode.Explicit;case"auto":return Xt.GlobalParameterApplyMode.Auto;default:r.errorCollector.collect({message:`Invalid global parameter apply mode '${e}'; expected one of: explicit, auto`,path:t});return}}function lPm(e,t){let r=pPm(e);return t===!0?Xt.TypeReference.container(Xt.ContainerType.optional(r)):r}function pPm(e){switch(e){case"boolean":return Xt.TypeReference.primitive({v1:"BOOLEAN",v2:Xt.PrimitiveTypeV2.boolean({default:void 0})});case"integer":return Xt.TypeReference.primitive({v1:"INTEGER",v2:Xt.PrimitiveTypeV2.integer({default:void 0,validation:void 0})});case"double":case"number":return Xt.TypeReference.primitive({v1:"DOUBLE",v2:Xt.PrimitiveTypeV2.double({default:void 0,validation:void 0})});default:return io.STRING}}function fPm(e){return e.target!=null?e.target:e.name}function FUu({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=cPm(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:fPm(n),valueType:lPm(n.type,n.optional),env:n.env,clientDefault:aPm(n.default,n.type,o,t),optional:n.optional,apply:uPm(n.apply,[...o,"apply"],t),docs:n.docs}})}var NUu=h(()=>{"use strict";Hn();Xo()});var MJr,jUu=h(()=>{"use strict";ct();Xo();MJr=class extends Um.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 Um.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&&Zp.parse(t)?.isJSON())return r.schema}}}});function mPm({encoding:e}){if(e){if(e.explode)return"exploded";if(e.style==="form")return"form";if(e.contentType)return dPm[e.contentType]}}var LJr,dPm,zUu=h(()=>{"use strict";ct();Hn();fc();Xo();LJr=class extends Um.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:u,queryParameters:l}){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=u,this.queryParameters=l??[]}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(Zp.parse(this.contentType)?.isMultipart())return this.handleMultipartContent({contentType:this.contentType});if(this.isBinaryContentType())return this.handleBinaryContent({contentType:this.contentType})}isOrderedJsonOrFormContentType(){let t=Zp.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=Zp.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:Cd.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:Cd.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:Cd.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 u=this.context.resolveExampleWithValue(c),l=this.context.resolveExampleRecursively({example:c,breadcrumbs:this.breadcrumbs}),p=a;if(this.context.isExampleWithSummary(l)){let d=l.summary;s.has(d)||(p=d)}s.add(p),u!=null&&(i.userSpecifiedExamples[p]=u)}return{requestBody:Cd.reference({contentType:t,docs:this.description,requestBodyType:$r.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:Cd.fileUpload({contentType:t,docs:this.description,name:this.context.casingsGenerator.generateName(this.schemaId),properties:i.properties.map(o=>{let s=r.encoding?.[ar(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:Cd.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?Hx.file(sQ.fileArray({key:t.name,isOptional:o,contentType:r,docs:t.docs})):Hx.file(sQ.file({key:t.name,isOptional:o,contentType:r,docs:t.docs})):Hx.bodyProperty({...t,contentType:n?.contentType??r,style:mPm({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 u=c.schema?.typeDeclaration.shape;return u?.type==="object"?{requestBody:Cd.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:u.extendedProperties,extends:u.extends,properties:u.properties,extraProperties:u.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:a,exampleGenerationStrategy:"request"})}),inlinedTypes:c.inlinedTypes}:{requestBody:Cd.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=>ar(n.name).toLowerCase()));return t.some(n=>r.has(ar(n.name).toLowerCase()))}},dPm={"application/json":"json"}});function APm(e){return e?.header!=null}var hPm,gPm,$ut,R8o=h(()=>{"use strict";ct();Hn();fc();Xo();Gi();jUu();zUu();hPm=/{([^}]+)}/g,gPm=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]),$ut=class extends io{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 xm.Get;case"post":return xm.Post;case"put":return xm.Put;case"delete":return xm.Delete;case"patch":return xm.Patch;case"head":return xm.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 u=new MJr({context:this.context,breadcrumbs:t,parameter:a}).convert();if(u!=null)switch(this.inlinedTypes={...this.inlinedTypes,...u.inlinedTypes},u.type){case"path":r.push(u.parameter);break;case"query":n.push(u.parameter);break;case"header":{let l=Vr(u.parameter.name),p=ar(u.parameter.name),d=!1,f=this.context.authOverrides?.["auth-schemes"];if(f!=null){for(let g of Object.values(f))if(APm(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}}!gPm.has(l.toLowerCase())&&!d&&i.push(u.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(hPm)].map(i=>i[1]).filter(i=>!t.some(o=>Vr(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:io.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,u]of Object.entries(s.content)){let p=new LJr({context:this.context,breadcrumbs:t,contentType:c,mediaType:u,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 _C.SdkMethodNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.methodName,i=new _C.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?ri(this.operation.summary):ri(`${this.method}_${this.path.split("/").join("_")}`))}sanitizeMethodName(t){return t.includes(".")?ri(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=xH(t,n),o=xH(r,n);return Y0(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:ri(s.join("_"))}}generateStringParameterExample({example:t}){let r=new Um.ExampleConverter({breadcrumbs:this.breadcrumbs,context:this.context,schema:{type:"string"},example:t}),{validExample:n}=r.convert();return n}}});var elt,D8o=h(()=>{"use strict";Hn();R8o();elt=class extends $ut{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 u=c.type==="inlinedRequestBody"?a[0]?.inlinedPropertiesByAudience:void 0,l,p;if(c.type==="inlinedRequestBody")l=rT.inlinedPayload({name:c.name,extends:c.extends,properties:c.properties});else if(c.type==="reference")l=rT.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},l=rT.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:u,webhook:{id:`${r?.join(".")??""}.${n}`,name:this.context.casingsGenerator.generateName(n),displayName:this.operation.summary,method:t,headers:o,payload:l,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 QUu,MUu=h(()=>{"use strict";QUu=["get","post","put","delete","patch","head"]});var _Jr,LUu=h(()=>{"use strict";Xo();_Jr=class extends es{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 UJr,_Uu=h(()=>{"use strict";Xo();UJr=class extends es{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 yPm,bPm,EPm,IPm,k8o,UUu=h(()=>{"use strict";an();yPm=Fe.object({cursor:Fe.string(),next_cursor:Fe.string(),results:Fe.string()}),bPm=Fe.object({offset:Fe.string(),results:Fe.string(),step:Fe.string().optional(),"has-next-page":Fe.string().optional()}),EPm=Fe.object({next_uri:Fe.string(),results:Fe.string()}),IPm=Fe.object({next_path:Fe.string(),results:Fe.string()}),k8o=Fe.union([Fe.boolean(),yPm,bPm,EPm,IPm])});var F8o,awe,VJr,VUu=h(()=>{"use strict";Xo();UUu();F8o="$request.",awe="$response.",VJr=class extends es{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=k8o.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=k8o.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:E0.maybeTrimPrefix(r.cursor,F8o),nextCursor:E0.maybeTrimPrefix(r.next_cursor,awe),results:E0.maybeTrimPrefix(r.results,awe)};let n=t;if("next_uri"in n)return{type:"uri",nextUri:E0.maybeTrimPrefix(n.next_uri,awe),results:E0.maybeTrimPrefix(n.results,awe)};let i=t;if("next_path"in i)return{type:"path",nextPath:E0.maybeTrimPrefix(i.next_path,awe),results:E0.maybeTrimPrefix(i.results,awe)};let o=t;return{type:"offset",offset:E0.maybeTrimPrefix(o.offset,F8o),results:E0.maybeTrimPrefix(o.results,awe),step:o.step!=null?E0.maybeTrimPrefix(o.step,F8o):void 0,hasNextPage:o["has-next-page"]!=null?E0.maybeTrimPrefix(o["has-next-page"],awe):void 0}}}});function N8o(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 vPm,CPm,xPm,GJr,GUu=h(()=>{"use strict";Xo();an();vPm="$request.",CPm=Fe.object({"stream-condition":Fe.string().optional(),format:Fe.enum(["sse","json"]).optional(),"stream-description":Fe.string().optional(),"stream-request-name":Fe.string().optional(),"response-stream":Fe.any(),response:Fe.any(),terminator:Fe.string().optional(),resumable:Fe.boolean().optional()}),xPm=Fe.union([Fe.boolean(),CPm]),GJr=class extends es{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=xPm.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??N8o(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:E0.maybeTrimPrefix(r.data["stream-condition"],vPm),streamRequestName:r.data["stream-request-name"],responseStream:r.data["response-stream"],response:r.data.response,resumable:n}}}});var qJr,qUu=h(()=>{"use strict";Xo();qJr=class extends es{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 WJr,WUu=h(()=>{"use strict";Xo();WJr=class extends es{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 SPm(e){return Fi(e)&&typeof e.$ref=="string"}function wPm(e,t){if(e!=null){if(typeof e=="string")return e;if(SPm(e)){let r=(0,HUu.resolve)(t??process.cwd(),e.$ref);if((0,KJr.existsSync)(r))try{return(0,KJr.readFileSync)(r,"utf-8")}catch{return}}}}var KJr,HUu,HJr,KUu=h(()=>{"use strict";ct();Xo();KJr=require("fs"),HUu=require("path");HJr=class extends es{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=Fi(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(!Fi(c))continue;let u=c,l=u.lang,p=u.label,d=u.source;if(typeof l!="string")continue;let f=wPm(d,this.baseDir);f!=null&&a.push({name:typeof p=="string"?p:l,language:l,code:f,install:void 0,docs:void 0})}if(a.length!==0)return[{"code-samples":a}]}}});function TPm(e){return Fi(e)&&typeof e.$ref=="string"}function OPm(e,t){if(e!=null){if(typeof e=="string")return e;if(TPm(e)){let r=(0,JUu.resolve)(t??process.cwd(),e.$ref);if((0,YJr.existsSync)(r))try{return(0,YJr.readFileSync)(r,"utf-8")}catch{return}}}}function PPm(e,t){if(!Array.isArray(e))return[];let r=[];for(let n of e){if(!Fi(n))continue;let o=OPm(n.code,t);o!=null&&r.push({...n,code:o})}return r}var YJr,JUu,JJr,YUu=h(()=>{"use strict";ct();Ao();Xo();YJr=require("fs"),JUu=require("path");JJr=class extends es{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(!Fi(o))return o;let a=o["code-samples"];if(a!=null){let c=PPm(a,this.baseDir);return{...o,"code-samples":c}}return o}).filter(o=>{let s=$d.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 G9t,XUu=h(()=>{"use strict";Xo();G9t=class extends es{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 q9t,ZUu=h(()=>{"use strict";ct();Hn();Xo();q9t=class extends Um.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:Qu.json(fI.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:r.schema?.typeDeclaration.v2Examples})),streamResponseBody:Qu.streaming(Av.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:Qu.streaming(Av.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:Qu.streaming(Av.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:Qu.json(fI.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:Qu.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:Qu.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:Qu.text({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"}),contentType:Zp.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 Zp.parse(t)?.isText()??!1}convertResponseHeaders(){return this.convertedResponseHeaders??=Yut({context:this.context,breadcrumbs:this.breadcrumbs,headers:this.responseBody.headers}),this.convertedResponseHeaders}}});var XJr,$Uu=h(()=>{"use strict";ct();Hn();Xo();XJr=class extends Um.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:$r.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:CH(`${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}),u=this.getIdForErrorExample({key:o,example:c,usedExampleNames:n});n.add(u),a!=null&&(i[u]=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 TJr[t]}getErrorIdFromErrorName(t){return this.context.enableUniqueErrorsPerEndpoint?CH(`${this.methodName}Request${t}`):t}convertResponseHeaders(){return this.convertedResponseHeaders??=Yut({context:this.context,breadcrumbs:this.breadcrumbs,headers:this.responseError.headers}),this.convertedResponseHeaders}}});var ZJr,eVu=h(()=>{"use strict";Ao();Hn();fc();E5();Xo();Gi();KUu();YUu();XUu();ZUu();$Uu();R8o();ZJr=class e extends $ut{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:u,idToAuthScheme:l,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=u,this.idToAuthScheme=l,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"]}),u=this.collectQueryParameterAudiences({breadcrumbs:[...this.breadcrumbs,"parameters"]}),l=this.convertRequestBody({breadcrumbs:[...this.breadcrumbs,"requestBody"],group:r,method:n,streamingExtension:this.streamingExtension,queryParameters:c}),p=l?.[0]?.requestBody,d=l?.[0]?.streamRequestBody,f=l?.[0]?.inlinedPropertiesByAudience,m={requestBodies:l?.map(ue=>ue.requestBody)},g=this.convertResponseBody({breadcrumbs:[...this.breadcrumbs,"responses"],group:r,method:n,streamingExtension:this.streamingExtension}),A=g?.response,y=g?.streamResponse,I=g!=null?g.errors:[],x={},v=I.map(ue=>ue.error),S=nb(this.path),B=this.context.perSpecBasePath,R=this.getEndpointBaseUrl(),D=this.getEndpointBaseUrls(),O=this.convertExamples({httpPath:S,httpMethod:t,baseUrl:R});if(Object.keys(O.examples).length===0&&Object.keys(O.streamExamples).length===0){let ue=this.synthesizeEndpointExamplesFromNativeRequestBody({httpPath:S,httpMethod:t,baseUrl:R});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&&l!=null&&l.length>1){let ue=this.synthesizeEndpointExamplesFromPerContentTypeRequestBodies({convertedRequestBodies:l,httpPath:S,httpMethod:t,baseUrl:R});if(ue!=null)for(let[Pe,Ie]of Object.entries(ue))O.examples[Pe]=Ie}let z=new Set(this.operation.security?.flatMap(ue=>Object.keys(ue))??[]),Y=this.authSchemeToHeaders(Array.from(z));Y.length>0&&s.push(...Y);for(let ue of I){let Pe=ue.error,Ie=ue.errorType,Be=Pe.error.errorId,_e=ue.examples;x[Be]={name:Pe.error,displayName:ue.displayName,discriminantValue:{name:Pe.error.name,wireValue:Be},type:Ie,statusCode:ue.statusCode,isWildcardStatusCode:ue.isWildcardStatusCode,docs:Pe.docs,examples:[],v2Examples:{userSpecifiedExamples:_e??{},autogeneratedExamples:{}},headers:ue.headers}}let $=this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],ae=new G9t({context:this.context,breadcrumbs:this.breadcrumbs,document:this.context.spec}).convert(),me=new G9t({context:this.context,breadcrumbs:this.breadcrumbs,document:this.operation}).convert()??ae,Se={displayName:this.operation.summary,subtitle:this.subtitle,method:t,baseUrl:R,v2BaseUrls:D,path:S,pathParameters:a,queryParameters:c,headers:s.filter((ue,Pe,Ie)=>Pe===Ie.findIndex(Be=>ar(Be.name)===ar(ue.name))),responseHeaders:g?.responseHeaders,sdkRequest:void 0,errors:v,auth:this.computeEndpointAuth(),security:this.computeEndpointSecurity(),availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),userSpecifiedExamples:[],autogeneratedExamples:[],idempotent:this.idempotent??!1,basePath:B!=null?nb(B):void 0,fullPath:B!=null?nb(`${B}${this.path}`):S,allPathParameters:a,pagination:void 0,transport:void 0,source:dD.openapi(),audiences:$,retries:void 0,globalParameters:this.globalParameterIds,apiPlayground:me},Re=this.context.namespace!=null?[this.context.namespace]:[],ce=r?.map(ue=>ri(ue));return Re.push(...ce??[]),{audiences:$,group:r,groupDisplayName:i,groupDescription:o,errors:x,endpoint:{...Se,id:`endpoint_${Re.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:y!=null&&y.body!=null?{...Se,id:`endpoint_${Re.join("/")}.${n}_stream`,name:this.context.casingsGenerator.generateName(`${n}_stream`),requestBody:d,v2RequestBodies:void 0,response:y,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:y.body,docs:y.docs}]}}:void 0,inlinedTypes:this.inlinedTypes,servers:this.filterOutTopLevelServers(this.operation.servers??this.pathLevelServers??[]),inlinedRequestPropertiesByAudience:f,queryParametersByAudience:u}}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,u]of Object.entries(this.operation.responses)){let l=/^[45]XX$/i.test(c),p,d=!1;if(l)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:u,breadcrumbs:[...t,c]});if(f==null)continue;let g=new q9t({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:l?!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:l?!0:void 0,body:g.responseBody,docs:f.description},o.streamResponse={statusCode:p,isWildcardStatusCode:l?!0:void 0,body:g.streamResponseBody,docs:f.description},g.headers!=null&&(o.responseHeaders=g.headers)),o.v2Responses=[...o.v2Responses??[],{statusCode:p,isWildcardStatusCode:l?!0:void 0,body:g.responseBody,docs:f.description}])}if(d){let f=this.context.resolveMaybeReference({schemaOrReference:u,breadcrumbs:[...t,c]});if(f==null)continue;let g=new XJr({context:this.context,breadcrumbs:[...t,c],responseError:f,group:r??[],method:n,methodName:this.evaluateMethodNameFromOperation(),statusCode:p,isWildcardStatusCode:l?!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 u=new q9t({context:this.context,breadcrumbs:[...t,"stream"],responseBody:{description:""},group:r??[],method:n,statusCode:"stream",streamingExtension:i}).convert();u!=null&&(this.inlinedTypes={...this.inlinedTypes,...u.inlinedTypes},o.response={statusCode:200,isWildcardStatusCode:void 0,body:u.responseBody,docs:void 0},o.streamResponse={statusCode:200,isWildcardStatusCode:void 0,body:u.streamResponseBody,docs:void 0},o.v2Responses=[{statusCode:200,isWildcardStatusCode:void 0,body:u.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 u=c.value.responseBodyType;(u.type!=="container"||u.container.type!=="optional")&&(o.response={...o.response,body:Qu.json(fI.response({...c.value,responseBodyType:$r.container(Cs.optional(u))}))})}}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():x8o(this.operation.security??this.context.spec.security)}usesEndpointSecurity(){let t=this.context.authOverrides?.auth;return t!=null&&Btt(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:io.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 JJr({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],a=new HJr({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],u=o.some(l=>Array.isArray(l["code-samples"])&&l["code-samples"].length>0)?o:[...o,...a];return u.length===0?{examples:{},streamExamples:{}}:this.streamingExtension?.type==="streamCondition"?this.convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:u}):{examples:this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:u}),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[u,l]of c){let p=this.context.resolveExampleWithValue(l);p!=null&&(s[u]={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:Xt.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,u=c.contentType,l=c.v2Examples;if(l==null)continue;let p=l.userSpecifiedExamples;if(Object.keys(p).length===0)continue;let d=u!=null?s.get(u):void 0;for(let[f,m]of Object.entries(p)){let g=t.length>1&&u!=null?`${f} (${u})`:f;o[g]={displayName:t.length>1?g:void 0,contentType:u??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[,u]of c){let l=this.context.resolveExampleWithValue(u);if(l!=null){t.set(s,{docs:void 0,statusCode:i,body:Xt.V2HttpEndpointResponseBody.json(l)});break}}}}return t}convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:i}){let o=i.filter(u=>!(u.response!=null&&"stream"in u.response)),s=i.filter(u=>u.response!=null&&"stream"in u.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 Xt.V2HttpEndpointResponseBody.stream(t.response.stream);if("body"in t.response)return Xt.V2HttpEndpointResponseBody.json(t.response.body)}}getEndpointBaseUrl(){let r=new _C.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 "${mn.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 P4.getServerName({server:o,context:this.context})}getEndpointBaseUrls(){if(new _C.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 P4.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)&&ri(r)===ri(n))return i}getGroupDescription(t){let r=this.operation.tags?.[0],n=t?.[t.length-1];if(!(r==null||n==null)&&ri(r)===ri(n))return this.context.getDescriptionForTag(r)}}});var j8o,$Jr,tVu=h(()=>{"use strict";Xo();j8o=Ae(A4t(),1);MUu();LUu();_Uu();VUu();GUu();qUu();WUu();eVu();D8o();$Jr=class extends io{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 QUu){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 u=new GJr({breadcrumbs:s,document:this.context.spec,operation:o,context:this.context}).convert();u==null&&this.operationHasTextEventStreamResponse(o)&&(u={type:"stream",format:"sse",terminator:void 0,resumable:N8o(this.context.spec)??!1});let l=this.tryParseAsHttpEndpoint({operationBreadcrumbs:s,operation:o,method:i,streamingExtension:u});l!=null&&(t.push(l),Object.assign(n,l.inlinedTypes))}return{endpoints:t,webhooks:r,inlinedTypes:n}}tryParseAsWebhook({operation:t,method:r,operationBreadcrumbs:n,context:i}){return new WJr({breadcrumbs:n,operation:t,context:i}).convert()?new elt({context:this.context,breadcrumbs:n,operation:t,method:j8o.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 VJr({breadcrumbs:n,operation:t,document:this.context.spec,context:this.context}).convert()!=null;let c=new UJr({breadcrumbs:n,operation:t,context:this.context}).convert(),l=new qJr({breadcrumbs:n,operation:t,context:this.context}).convert(),d=new _Jr({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 ZJr({context:this.context,breadcrumbs:n,operation:t,method:j8o.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path,pathItemParameters:this.pathItem.parameters,idempotent:c,subtitle:l,globalParameterIds:d,idToAuthScheme:this.idToAuthScheme,topLevelServers:this.topLevelServers,pathLevelServers:this.pathItem.servers,streamingExtension:i}).convert()}}});var eYr,rVu=h(()=>{"use strict";Hn();Xo();eYr=class extends io{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 _p.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 _p.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 _p.header({key:this.schemeId,name:{name:this.context.casingsGenerator.generateName(n),wireValue:this.securityScheme.name},valueType:io.OPTIONAL_STRING,prefix:o,headerEnvVar:i,headerPlaceholder:s,docs:this.securityScheme.description,playgroundDocs:t})}break}case"oauth2":return _p.bearer({key:this.schemeId,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,tokenPlaceholder:void 0,docs:this.securityScheme.description,playgroundDocs:t})}}}});function BPm(e){if(e!=null){if(typeof e=="string")return rE.string(e);if(typeof e=="boolean")return rE.boolean(e)}}var nVu,W9t,iVu=h(()=>{"use strict";ct();Ao();Hn();fc();E5();Xo();nVu=Ae(A4t(),1);wUu();TUu();OUu();PUu();RUu();kUu();NUu();D8o();tVu();rVu();W9t=class extends vJ{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=y4t({document:this.context.spec,options:this.context.settings,logger:this.context.logger}),C8o({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=BUu({globalHeaderOverrides:this.context.globalHeaderOverrides,context:this.context});this.addGlobalHeadersToIr(n),this.context.setGlobalHeaders(n);return}let r=new zJr({breadcrumbs:["x-fern-global-headers"],document:this.context.spec,context:this.context}).convert();if(r!=null){let n=DUu({globalHeaders:r,context:this.context});this.addGlobalHeadersToIr(n),this.context.setGlobalHeaders(n)}}convertGlobalParameters(){let r=new QJr({breadcrumbs:["x-fern-global-parameters"],document:this.context.spec,context:this.context}).convert();if(r!=null){let n=FUu({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 NJr({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=Gy(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=nb(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:io.STRING,docs:n.docs,location:Xt.PathParameterLocation.Root,variable:void 0,clientDefault:BPm(n.default),v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}},explode:void 0});if(r.pathsIncludeBasePath){let n=g4t({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=OGt({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 eYr({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 jJr({breadcrumbs:["x-fern-base-url-env"],document:this.context.spec,context:this.context}).convert();if(this.context.environmentOverrides){let s=PGt({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 P4({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 Um.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 elt({context:this.context,breadcrumbs:["webhooks",n],operation:i,method:nVu.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 $Jr({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 u of c.servers)this.shouldAddServerToCollectedServers({server:u,currentServers:t})&&t.push(u);if(c.errors)for(let[u,l]of Object.entries(c.errors))r[u]=l}for(let c of a.webhooks){let u=this.context.getGroup({groupParts:c.group,namespace:this.context.namespace});this.addWebhookToIr({webhook:c.webhook,operationId:u.join("."),group:u,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&&Btt(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 tYr,oVu=h(()=>{"use strict";Xo();tYr=class extends es{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 uVe,sVu=h(()=>{"use strict";Hn();fc();Xo();oVu();uVe=class extends E0{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 u;if(o.includes("/")){let p=new Um.SchemaConverters.SchemaConverter({context:this,breadcrumbs:r??[],schema:a.value,id:o}).convert();p!=null&&(u={[o]:p.convertedSchema})}return{ok:!0,reference:$r.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(s),typeId:o,default:void 0,inline:!1,displayName:c}),inlinedTypes:u}}setGlobalHeaders(t){this.globalHeaderNames=t.map(r=>ar(r.name))}getDisplayNameForTag(t){if(Object.keys(this.tagToDisplayName).length===0)for(let r of this.spec.tags??[]){let i=new tYr({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 Q8o({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=Lfe(o,{header:()=>{},basic:()=>{},tokenBearer:()=>{},inferredBearer:()=>{},oauth:a=>DPm({ir:e,key:i.key,oauthScheme:a})});n.push(s??i)}return{...e,auth:{...e.auth,schemes:n}}}function DPm({ir:e,key:t,oauthScheme:r}){if(r.type!=="client-credentials")return;let n=r["get-token"];if(n==null)return;let i=aVu({ir:e,endpointRef:n.endpoint});if(i==null)return;let{endpoint:o,serviceId:s,subpackageId:a}=i,c=n["request-properties"],u=n["response-properties"],l=z8o({ir:e,endpoint:o,wireValue:xJ(c?.["client-id"],"client_id")}),p=z8o({ir:e,endpoint:o,wireValue:xJ(c?.["client-secret"],"client_secret")}),d=tlt({ir:e,endpoint:o,wireValue:xJ(u?.["access-token"],"access_token")});if(!(l==null||p==null||d==null))return _p.oauth({key:t,docs:r.docs,playgroundDocs:r["playground-docs"],configuration:pD.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:l,clientSecret:p,scopes:void 0,customProperties:NPm({ir:e,endpoint:o,excludeWireValues:[xJ(c?.["client-id"],"client_id"),xJ(c?.["client-secret"],"client_secret")]})},responseProperties:{accessToken:d,expiresIn:tlt({ir:e,endpoint:o,wireValue:xJ(u?.["expires-in"],"expires_in")}),refreshToken:tlt({ir:e,endpoint:o,wireValue:xJ(u?.["refresh-token"],"refresh_token")})}},refreshEndpoint:r["refresh-token"]!=null?kPm({ir:e,refreshTokenConfig:r["refresh-token"]}):void 0})})}function kPm({ir:e,refreshTokenConfig:t}){let r=aVu({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=z8o({ir:e,endpoint:n,wireValue:xJ(s?.["refresh-token"],"refresh_token")}),u=tlt({ir:e,endpoint:n,wireValue:xJ(a?.["access-token"],"access_token")});if(!(c==null||u==null))return{endpointReference:{endpointId:n.id,serviceId:i,subpackageId:o},requestProperties:{refreshToken:c},responseProperties:{accessToken:u,expiresIn:tlt({ir:e,endpoint:n,wireValue:xJ(a?.["expires-in"],"expires_in")}),refreshToken:tlt({ir:e,endpoint:n,wireValue:xJ(a?.["refresh-token"],"refresh_token")})}}}function aVu({ir:e,endpointRef:t}){let r=t.trim().split(/\s+/);if(r.length!==2)return;let n=RPm[r[0]?.toUpperCase()??""],i=Gy(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(FPm(a.fullPath)===i){let u=Object.entries(e.subpackages).find(([,l])=>l.service===o)?.[0];return{endpoint:a,serviceId:o,subpackageId:u}}}}function FPm(e){let t=e.head;for(let r of e.parts)t+=`{${r.pathParameter}}${r.tail}`;return Gy(t)}function xJ(e,t){return e==null?t:e.match(/^\$(?:request|response)\.(.+)$/)?.[1]??e}function cVu(e,t){return e.find(r=>ar(r.name)===t)}function M8o(e,t){let r=e.types[t];if(r?.shape.type==="object")return r.shape.properties}function z8o({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=M8o(e,t.requestBody.requestBodyType.typeId));let i=n!=null?cVu(n,r):void 0;if(i!=null)return{propertyPath:void 0,property:aB.body({...i})}}function NPm({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=M8o(e,t.requestBody.requestBodyType.typeId)),n==null)return;let i=new Set(r),o=n.filter(s=>!i.has(ar(s.name))).map(s=>({propertyPath:void 0,property:aB.body({...s})}));return o.length>0?o:void 0}function tlt({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=M8o(e,n.typeId),o=i!=null?cVu(i,r):void 0;if(o!=null)return{propertyPath:void 0,property:o}}var RPm,uVu=h(()=>{"use strict";ct();Ao();Hn();fc();RPm={GET:xm.Get,POST:xm.Post,PUT:xm.Put,PATCH:xm.Patch,DELETE:xm.Delete}});var L8o=h(()=>{"use strict";iVu();sVu();uVu()});var jPm,zPm,QPm,rYr,lVu=h(()=>{"use strict";ct();Xo();an();jPm=Fe.object({description:Fe.string().optional(),required:Fe.boolean().optional(),deprecated:Fe.boolean().optional(),allowEmptyValue:Fe.boolean().optional(),style:Fe.string().optional(),explode:Fe.boolean().optional(),allowReserved:Fe.boolean().optional(),schema:Fe.any().optional(),example:Fe.any().optional(),examples:Fe.record(Fe.string(),Fe.any()).optional(),content:Fe.record(Fe.string(),Fe.any()).optional()}),zPm=jPm.extend({name:Fe.string(),in:Fe.string()}),QPm=Fe.array(zPm),rYr=class extends es{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 QPm.parse(t)}catch(r){this.context.errorCollector.collect({message:`Failed to parse x-fern-parameters extension: ${Sn(r)}`,path:this.breadcrumbs});return}}}});var nYr,pVu=h(()=>{"use strict";Hn();fc();Xo();nYr=class extends io{method;pathParameters;queryParameters;headers;topLevelServers;constructor({context:t,breadcrumbs:r,method:n,pathParameters:i=[],queryParameters:o=[],headers:s=[],topLevelServers:a=[]}){super({context:t,breadcrumbs:r}),this.method=n,this.pathParameters=i,this.queryParameters=o,this.headers=s,this.topLevelServers=a}convert(){let t={},r="";for(let u of this.pathParameters)r+=`/{${Vr(u.name)}}`;let n=nb(r),i=[];for(let[u,l]of this.method.params.entries()){let p;if(this.context.isReferenceObject(l)){let g=this.context.resolveReference({reference:l});if(g.resolved)p=g.value;else continue}else p=l;let d=[this.method.name,"Param",p.name].join("_"),m=new Um.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:l,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 u=this.context.resolveMaybeReference({schemaOrReference:this.method.result,breadcrumbs:[...this.breadcrumbs,"result"]});if(u!=null){let l=new Um.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"result"],context:this.context,schemaOrReference:u.schema}),p=[this.method.name,"Result"].join("_"),d=l.convert();d!=null&&(o={docs:u.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?Cd.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:Qu.json(fI.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:dD.openrpc(),audiences:a,retries:void 0,globalParameters:void 0,apiPlayground:void 0,responseHeaders:[]},audiences:a,inlinedTypes:t,servers:this.filterOutTopLevelServers(this.method.servers??[])}}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 P4.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[Vr(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 l=this.context.resolveReference({reference:o});if(l.resolved)s=l.value;else continue}else s=o;let a;if(s.result)if(this.context.isReferenceObject(s.result)){let l=this.context.resolveReference({reference:s.result});l.resolved&&(a=l.value)}else a=s.result;let c=s.name??`Example ${i+1}`,u=[];if(s.params&&Array.isArray(s.params)){u=[];for(let l of s.params)if(this.context.isReferenceObject(l)){let p=this.context.resolveReference({reference:l});if(p.resolved)u.push(p.value);else continue}else u.push(l)}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:u.map(l=>l.value)??void 0},response:{docs:void 0,statusCode:void 0,body:a?.value?Xt.V2HttpEndpointResponseBody.json({jsonrpc:"2.0",id:s.examplePairedRequest?.id||"1",result:a.value}):void 0},codeSamples:[]}}++i}return r}}});var iYr,fVu=h(()=>{"use strict";Xo();iYr=class extends Um.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 Um.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 H9t,dVu=h(()=>{"use strict";Xo();lVu();pVu();fVu();H9t=class extends vJ{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 P4({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 Um.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 rYr({context:this.context,breadcrumbs:["methods"],operation:this.context.spec}).convert(),i=[],o=[],s=[];if(n&&n.length>0)for(let[c,u]of n.entries()){let p=new iYr({context:this.context,breadcrumbs:[...this.breadcrumbs,`x-fern-parameters[${c}]`],parameter:u}).convert();if(p!=null)switch(p.type){case"path":{i.push(p.parameter);break}case"query":{o.push(p.parameter);break}case"header":{s.push(p.parameter);break}}}let a=this.context.getGroup({groupParts:[],namespace:this.context.namespace});for(let c of this.context.spec.methods??[]){let u=this.context.resolveMaybeReference({schemaOrReference:c,breadcrumbs:["methods"]});if(u==null)continue;let p=new nYr({context:this.context,breadcrumbs:["methods"],method:u,pathParameters:i,queryParameters:o,headers:s,topLevelServers:this.context.spec.servers}).convert();if(p!=null&&(this.addEndpointToIr({endpoint:p.endpoint,audiences:p.audiences,endpointGroup:a,serviceName:"service_root"}),this.addTypesToIr(p.inlinedTypes),p.servers))for(let d of p.servers)this.shouldAddServerToCollectedServers({server:d,currentServers:t,specType:"openrpc"})&&t.push(this.maybeDeduplicateServerName(d))}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 K9t,mVu=h(()=>{"use strict";Hn();Xo();K9t=class extends E0{isReferenceObject(t){return t!=null&&"$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:$r.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}}});var hVu=h(()=>{"use strict";dVu();mVu()});var gVu,AVu=h(()=>{"use strict";gVu=/^(?:[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 MPm(e){return typeof e=="string"&&gVu.test(e)}var _8o,yVu=h(()=>{"use strict";AVu();_8o=MPm});function bVu(e,t=0){return(HB[e[t+0]]+HB[e[t+1]]+HB[e[t+2]]+HB[e[t+3]]+"-"+HB[e[t+4]]+HB[e[t+5]]+"-"+HB[e[t+6]]+HB[e[t+7]]+"-"+HB[e[t+8]]+HB[e[t+9]]+"-"+HB[e[t+10]]+HB[e[t+11]]+HB[e[t+12]]+HB[e[t+13]]+HB[e[t+14]]+HB[e[t+15]]).toLowerCase()}var HB,EVu=h(()=>{"use strict";HB=[];for(let e=0;e<256;++e)HB.push((e+256).toString(16).slice(1))});function U8o(){return crypto.getRandomValues(LPm)}var LPm,IVu=h(()=>{"use strict";LPm=new Uint8Array(16)});function _Pm(e,t,r){return!t&&!e&&crypto.randomUUID?crypto.randomUUID():UPm(e,t,r)}function UPm(e,t,r){e=e||{};let n=e.random??e.rng?.()??U8o();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 bVu(n)}var Yw,vVu=h(()=>{"use strict";IVu();EVu();Yw=_Pm});var lVe=h(()=>{"use strict";vVu();yVu()});async function rlt({absoluteFilePathToOverrides:e,data:t,context:r,allowNullKeys:n}){let i=null;try{let o=(await(0,CVu.readFile)(e,"utf8")).toString();try{i=JSON.parse(o)}catch{i=vr.load(o,{json:!0})}}catch{return r.failAndThrow(`Failed to read overrides from file ${e}`,void 0,{code:T.Code.ParseError})}return KZ({data:t,overrides:i,allowNullKeys:n})}var CVu,oYr=h(()=>{"use strict";ct();Dt();CVu=require("fs/promises");is()});async function V8o({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let n=(await(0,xVu.readFile)(t)).toString(),i;try{i=JSON.parse(n)}catch{i=vr.load(n)}let o=[];r!=null&&(Array.isArray(r)?o=r:o=[r]);let s=i;for(let a of o)s=await rlt({absoluteFilePathToOverrides:a,context:e,data:s});return s}var xVu,SVu=h(()=>{"use strict";xVu=require("fs/promises");is();oYr()});async function G8o({document:e,settings:t}){let r=t?.errorResponses;if(r==null)return{document:e,errorResponses:void 0};let n=typeof r.schema=="string"?await VPm(Zt.of(r.schema)):r.schema;return{document:fxo({document:e,errorResponses:r,schema:n}),errorResponses:{...r,schema:n}}}async function VPm(e){let t=(await(0,wVu.readFile)(e)).toString(),r=vr.load(t);if(!jr(r))throw new T({message:`Expected ${e} to contain an OpenAPI schema object.`,code:T.Code.ConfigError});return r}var wVu,TVu=h(()=>{"use strict";Dc();ct();tr();Dt();wVu=require("fs/promises");is()});var PVu=E((dxv,OVu)=>{"use strict";function GPm(){return typeof process=="object"&&typeof process.nextTick=="function"?process.nextTick:typeof setImmediate=="function"?setImmediate:function(t){setTimeout(t,0)}}OVu.exports=GPm()});var DVu=E((mxv,RVu)=>{"use strict";var BVu=PVu();RVu.exports=function(t,r){if(t){r.then(function(n){BVu(function(){t(null,n)})},function(n){BVu(function(){t(n)})});return}else return r}});var W8o=E((hxv,FVu)=>{"use strict";var q8o=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))}},sYr=class extends TypeError{constructor(t,r,n){let i=t.includes(".")?"property":"argument",o=`The "${t}" ${i} ${determiner} ${r}`}};function kVu(e,t,r="Object"){if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e))){let n=new sYr(t,r,e);throw Error.captureStackTrace(n,kVu),n}}FVu.exports={ERR_INVALID_ARG_TYPE:sYr,assertIsObject:kVu,DebounceTimers:q8o}});var zVu=E((gxv,jVu)=>{"use strict";var{assertIsObject:NVu}=W8o();function qPm(e){return NVu(e,"options"),e=Object.assign({},e),e.allowHalfOpen=!0,e.rejectUnauthorized=!1,NVu(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 WPm(e,t){e=qPm.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}jVu.exports={initializeTLSOptions:WPm}});var lYr=E((yxv,_Vu)=>{"use strict";var{URL:aYr}=require("url"),{EventEmitter:MVu}=require("events"),cYr=require("util")._extend,{DebounceTimers:HPm,assertIsObject:QVu,ERR_INVALID_ARG_TYPE:Axv}=W8o(),{initializeTLSOptions:KPm}=zVu(),J9t=require("http"),H8o=require("https"),{Stream:JPm}=require("stream");function uYr(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 mhe=[];uYr(mhe,J9t.ClientRequest);uYr(mhe,J9t.OutgoingMessage);uYr(mhe,MVu);uYr(mhe,JPm);var YPm=["httpVersionMajor","httpVersionMinor","httpVersion"],XPm=["host","connection"],cwe=Symbol("stubs");function Y9t(){this.http2Mimic=!0,this[cwe]=[];for(var e=0;e<mhe.length;e++){let u=mhe[e];Y9t.prototype[u]||(this[u]=function(){return this.genericStubber(u,arguments)}.bind(this))}var t,r,n,i;let o=arguments[0]instanceof X9t;var s,a;if(o){let u=arguments[0];u.method&&(s=u.method),u.protocol&&(a=u.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=K8o(new aYr(t)),!t.hostname)throw new Error("Unable to determine the domain name")}else n?t=cYr(K8o(new aYr(n)),t):t=cYr({},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)}Y9t.prototype={getGlobalManager(e){return e.agent?e.agent.protocol=="https:"?lwe.globalManager:pwe.globalManager:uwe.globalManager},genericStubber(e,t){return this[cwe]?(this[cwe].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[cwe])this[cwe].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<mhe.length;t++){let n=mhe[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[cwe].length;n++){var r=this[cwe][n];e[r[0]](...r[1])}this[cwe]=null},proxyProps(e){function t(){return e[this]}function r(c){e[this]=c}let n=["on","_on","_once","once","http2Mimic"].concat(mhe),i=Object.keys(this),o=[].concat(YPm);i.forEach(function(u){n.indexOf(u)==-1&&o.indexOf(u)==-1&&o.push(u)});let s=Object.getOwnPropertyDescriptors(e);for(var a=0;a<o.length;a++){let c=o[a],u=s[c],l;u||(l=!0),u&&(u.writable||u)&&(l=!0),l&&(e[c]=this[c]),Object.defineProperty(this,c,{get:t.bind(c),set:r.bind(c)})}}};var uwe=class e extends MVu{constructor(t){super(),this.httpsAgent=H8o.globalAgent,this.httpAgent=J9t.globalAgent,this.init(t)}log(){}init(t){t=t||{},this.http2Clients={},this.cachedHTTP1Result={},this.setModules(),this.http2Debouncer=new HPm(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 X9t(arguments);return this.enforceProtocol&&(i.protocol=this.enforceProtocol),new Y9t(i)}get(){var t=new X9t(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 u={createConnection(){return o}};if(c=="h2"&&this.http2Support){var l=this.http2.connect(r,u);this.setHttp2Client(t,l)}else this.cachedHTTP1Result[t]=Date.now();n(null,u),this.emit(i,u)}.bind(this))}}makeHttpRequest(t,r,n,i,o){n instanceof aYr&&(n=K8o(n));let s=cYr({},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(l){this.emit("http1.response",l)})}makeHttp2Request(t,r,n,i,o){var s=this.http2Debouncer;s.pause(t);var a=cYr({},i.headers||{});i.method&&(a[":method"]=i.method),i.path&&(a[":path"]=i.path),Object.keys(a).forEach(d=>{XPm.indexOf((d+"").toLowerCase())!=-1&&delete a[d]}),i.headers=a;var c=n.request(a);r.emit("socket",i.createConnection());let u,l=0;c.on("data",function(f){l+=f.length,l>=u&&s.unpauseAndTime(t)}),r.take(c);function p(d){u=parseInt(d["content-length"]),u<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),QVu(r,"options"),r=Object.assign({},r),typeof t=="string"&&(t=new aYr(t)),QVu(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,KPm.call(this,r,s),n);break;default:throw new Error("Not supprted"+i)}return a}};function K8o(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 X9t=class e{constructor(t){if(t[0]instanceof e)return t[0];this.args=t,this.method=null,this.protocol=null}},lwe=class extends uwe{constructor(){super(...arguments),this.Agent=H8o.Agent,this.globalAgent=H8o.globalAgent,this.enforceProtocol="https:"}},ZPm=new lwe;lwe.globalManager=ZPm;lwe.Manager=lwe;var pwe=class extends uwe{constructor(){super(...arguments),this.Agent=J9t.Agent,this.globalAgent=J9t.globalAgent,this.enforceProtocol="http:"}},$Pm=new pwe;pwe.globalManager=$Pm;pwe.Manager=pwe;var LVu=new uwe;LVu.enforceProtocol="detect";uwe.globalManager=LVu;_Vu.exports={HttpRequest:pwe,HttpsRequest:lwe,HTTP2OutgoingMessage:Y9t,ClientRequest:Y9t,HttpRequestManager:uwe}});var VVu=E((bxv,UVu)=>{"use strict";var{HttpRequest:eBm,ClientRequest:tBm}=lYr(),Z9t=eBm.globalManager,rBm=Z9t.request.bind(Z9t),nBm=Z9t.get.bind(Z9t),iBm=Object.assign({},require("http"));UVu.exports=Object.assign(iBm,{ClientRequest:tBm,globalManager:Z9t,request:rBm,get:nBm})});var qVu=E((Exv,GVu)=>{"use strict";var{HttpsRequest:oBm,ClientRequest:sBm}=lYr(),$9t=oBm.globalManager,aBm=$9t.request.bind($9t),cBm=$9t.get.bind($9t),uBm=Object.assign({},require("https"));GVu.exports=Object.assign(uBm,{ClientRequest:sBm,globalManager:$9t,request:aBm,get:cBm})});var HVu=E((Ixv,WVu)=>{"use strict";var{HttpRequestManager:J8o,HTTP2OutgoingMessage:lBm,ClientRequest:pBm}=lYr(),fBm=VVu(),dBm=qVu(),eWt=new J8o;J8o.globalManager=eWt;var mBm=eWt.request.bind(eWt),hBm=eWt.get.bind(eWt);WVu.exports={HTTP2OutgoingMessage:lBm,ClientRequest:pBm,globalManager:J8o.globalManager,request:mBm,get:hBm,http:fBm,https:dBm}});var iGo={};te(iGo,{FetchError:()=>ZD,Headers:()=>w8,Request:()=>dwe,Response:()=>Xre,default:()=>wBm});function ZD(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 $T(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:$Vu(e)?e=Buffer.from(e.toString()):e instanceof dVe?e=e[fVe]: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 SJ.default||(e=Buffer.from(String(e)))),this[ghe]={body:e,disturbed:!1,error:null},this.size=i,this.timeout=s,e instanceof SJ.default&&e.on("error",function(a){let c=a.name==="AbortError"?a:new ZD(`Invalid response body while trying to fetch ${t.url}: ${a.message}`,"system",a);t[ghe].error=c})}function nlt(){var e=this;if(this[ghe].disturbed)return $T.Promise.reject(new TypeError(`body used already for: ${this.url}`));if(this[ghe].disturbed=!0,this[ghe].error)return $T.Promise.reject(this[ghe].error);if(this.body===null)return $T.Promise.resolve(Buffer.alloc(0));if(Buffer.isBuffer(this.body))return $T.Promise.resolve(this.body);if(!(this.body instanceof SJ.default))return $T.Promise.resolve(Buffer.alloc(0));let t=[],r=0,n=!1;return new $T.Promise(function(i,o){let s;e.timeout&&(s=setTimeout(function(){n=!0,o(new ZD(`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 ZD(`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 ZD(`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 ZD(`Could not create Buffer from response body for ${e.url}: ${a.message}`,"system",a))}}})})}function gBm(e,t){if(typeof $8o!="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")),$8o(e,"UTF-8",n).toString()}function $Vu(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 e5u(e){let t,r,n=e.body;if(e.bodyUsed)throw new Error("cannot clone body after it is used");return n instanceof SJ.default&&typeof n.getBoundary!="function"&&(t=new KVu,r=new KVu,n.pipe(t),n.pipe(r),e[ghe].body=t,n=r),n}function t5u(e){return e===null?null:typeof e=="string"?"text/plain;charset=UTF-8":$Vu(e)?"application/x-www-form-urlencoded;charset=UTF-8":e instanceof dVe?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 SJ.default?null:"text/plain;charset=UTF-8"}function r5u(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 ABm(e,t){let r=t.body;r===null?e.end():Buffer.isBuffer(r)?(e.write(r),e.end()):r.pipe(e)}function tWt(e){if(e=`${e}`,n5u.test(e))throw new TypeError(`${e} is not a legal HTTP header name`)}function JVu(e){if(e=`${e}`,eGo.test(e))throw new TypeError(`${e} is not a legal HTTP header value`)}function olt(e,t){t=t.toLowerCase();for(let r in e)if(r.toLowerCase()===t)return r}function tGo(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"key+value";return Object.keys(e[UC]).sort().map(t==="key"?function(n){return n.toLowerCase()}:t==="value"?function(n){return e[UC][n].join(", ")}:function(n){return[n.toLowerCase(),e[UC][n].join(", ")]})}function X8o(e,t){let r=Object.create(nGo);return r[rGo]={target:e,kind:t,index:0},r}function yBm(e){let t=Object.assign({__proto__:null},e[UC]),r=olt(e[UC],"Host");return r!==void 0&&(t[r]=t[r][0]),t}function bBm(e){let t=new w8;for(let r of Object.keys(e))if(!n5u.test(r))if(Array.isArray(e[r]))for(let n of e[r])eGo.test(n)||(t[UC][r]===void 0?t[UC][r]=[n]:t[UC][r].push(n));else eGo.test(e[r])||(t[UC][r]=[e[r]]);return t}function pYr(e){return typeof e=="object"&&typeof e[hhe]=="object"}function CBm(e){let t=e&&typeof e=="object"&&Object.getPrototypeOf(e);return!!(t&&t.constructor.name==="AbortSignal")}function xBm(e){let t=e[hhe].parsedURL,r=new w8(e[hhe].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 SJ.default.Readable&&!vBm)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=r5u(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:yBm(r),agent:e.agent})}function rWt(e){Error.call(this,e),this.type="aborted",this.message=e,Error.captureStackTrace(this,this.constructor)}function fwe(e,t){if(!fwe.Promise)throw new Error("native promise missing, set fetch.Promise to your favorite alternative");return $T.Promise=fwe.Promise,new fwe.Promise(function(r,n){let i=new dwe(e,t),o=xBm(i),s=ZVu.default.request,a=i.signal,c=null,u=function(){let g=new rWt("The user aborted a request.");n(g),i.body&&i.body instanceof SJ.default.Readable&&i.body.destroy(g),!(!c||!c.body)&&c.body.emit("error",g)};if(a&&a.aborted){u();return}let l=function(){u(),f()},p=s(o),d;a&&a.addEventListener("abort",l);function f(){p.abort(),a&&a.removeEventListener("abort",l),clearTimeout(d)}i.timeout&&p.once("socket",function(m){d=setTimeout(function(){n(new ZD(`network timeout at: ${i.url}`,"request-timeout")),f()},i.timeout)}),p.on("error",function(m){n(new ZD(`request to ${i.url} failed, reason: ${m.message}`,"system",m)),f()}),p.on("response",function(m){clearTimeout(d);let g=bBm(m.headers);if(fwe.isRedirect(m.statusCode)){let v=g.get("Location"),S=v===null?null:SBm(i.url,v);switch(i.redirect){case"error":n(new ZD(`redirect mode is set to error: ${i.url}`,"no-redirect")),f();return;case"manual":if(S!==null)try{g.set("Location",S)}catch(R){n(R)}break;case"follow":if(S===null)break;if(i.counter>=i.follow){n(new ZD(`maximum redirect reached at: ${i.url}`,"max-redirect")),f();return}let B={headers:new w8(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&&r5u(i)===null){n(new ZD("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")&&(B.method="GET",B.body=void 0,B.headers.delete("content-length")),r(fwe(new dwe(S,B))),f();return}}m.once("end",function(){a&&a.removeEventListener("abort",l)});let A=m.pipe(new YVu),y={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 Xre(A,y),r(c);return}let x={flush:ilt.default.Z_SYNC_FLUSH,finishFlush:ilt.default.Z_SYNC_FLUSH};if(I=="gzip"||I=="x-gzip"){A=A.pipe(ilt.default.createGunzip(x)),c=new Xre(A,y),r(c);return}if(I=="deflate"||I=="x-deflate"){m.pipe(new YVu).once("data",function(S){(S[0]&15)===8?A=A.pipe(ilt.default.createInflate()):A=A.pipe(ilt.default.createInflateRaw()),c=new Xre(A,y),r(c)});return}c=new Xre(A,y),r(c)}),ABm(p,i)})}var SJ,XVu,fYr,ZVu,ilt,fVe,Y8o,dVe,$8o,ghe,KVu,n5u,eGo,UC,w8,rGo,nGo,pVe,EBm,Xre,hhe,Z8o,IBm,vBm,dwe,YVu,SBm,wBm,oGo=h(()=>{"use strict";SJ=Ae(require("stream"),1),XVu=Ae(require("http"),1),fYr=Ae(require("url"),1),ZVu=Ae(HVu(),1),ilt=Ae(require("zlib"),1),fVe=Symbol("buffer"),Y8o=Symbol("type"),dVe=class e{constructor(){this[Y8o]="";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],u;c instanceof Buffer?u=c:ArrayBuffer.isView(c)?u=Buffer.from(c.buffer,c.byteOffset,c.byteLength):c instanceof ArrayBuffer?u=Buffer.from(c):c instanceof e?u=c[fVe]:u=Buffer.from(typeof c=="string"?c:String(c)),n.push(u)}}this[fVe]=Buffer.concat(n);let i=r&&r.type!==void 0&&String(r.type).toLowerCase();i&&!/[^\u0020-\u007E]/.test(i)&&(this[Y8o]=i)}get size(){return this[fVe].length}get type(){return this[Y8o]}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[fVe].slice(i,i+s),u=new e([],{type:arguments[2]});return u[fVe]=c,u}};Object.defineProperties(dVe.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});Object.defineProperty(dVe.prototype,Symbol.toStringTag,{value:"Blob",writable:!1,enumerable:!1,configurable:!0});ZD.prototype=Object.create(Error.prototype);ZD.prototype.constructor=ZD;ZD.prototype.name="FetchError";try{$8o=require("encoding").convert}catch{}ghe=Symbol("Body internals"),KVu=SJ.default.PassThrough;$T.prototype={get body(){return this[ghe].body},get bodyUsed(){return this[ghe].disturbed},arrayBuffer(){return nlt.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 nlt.call(this).then(function(t){return Object.assign(new dVe([],{type:e.toLowerCase()}),{[fVe]:t})})},json(){var e=this;return nlt.call(this).then(function(t){try{return JSON.parse(t.toString())}catch(r){return $T.Promise.reject(new ZD(`invalid json response body at ${e.url} reason: ${r.message}`,"invalid-json"))}})},text(){return nlt.call(this).then(function(e){return e.toString()})},buffer(){return nlt.call(this)},textConverted(){var e=this;return nlt.call(this).then(function(t){return gBm(t,e.headers)})}};Object.defineProperties($T.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0}});$T.mixIn=function(e){for(let t of Object.getOwnPropertyNames($T.prototype))if(!(t in e)){let r=Object.getOwnPropertyDescriptor($T.prototype,t);Object.defineProperty(e,t,r)}};$T.Promise=global.Promise;n5u=/[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/,eGo=/[^\t\x20-\x7e\x80-\xff]/;UC=Symbol("map"),w8=class e{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:void 0;if(this[UC]=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}`,tWt(t);let r=olt(this[UC],t);return r===void 0?null:this[UC][r].join(", ")}forEach(t){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:void 0,n=tGo(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=tGo(this),i++}}set(t,r){t=`${t}`,r=`${r}`,tWt(t),JVu(r);let n=olt(this[UC],t);this[UC][n!==void 0?n:t]=[r]}append(t,r){t=`${t}`,r=`${r}`,tWt(t),JVu(r);let n=olt(this[UC],t);n!==void 0?this[UC][n].push(r):this[UC][t]=[r]}has(t){return t=`${t}`,tWt(t),olt(this[UC],t)!==void 0}delete(t){t=`${t}`,tWt(t);let r=olt(this[UC],t);r!==void 0&&delete this[UC][r]}raw(){return this[UC]}keys(){return X8o(this,"key")}values(){return X8o(this,"value")}[Symbol.iterator](){return X8o(this,"key+value")}};w8.prototype.entries=w8.prototype[Symbol.iterator];Object.defineProperty(w8.prototype,Symbol.toStringTag,{value:"Headers",writable:!1,enumerable:!1,configurable:!0});Object.defineProperties(w8.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}});rGo=Symbol("internal");nGo=Object.setPrototypeOf({next(){if(!this||Object.getPrototypeOf(this)!==nGo)throw new TypeError("Value of `this` is not a HeadersIterator");var e=this[rGo];let t=e.target,r=e.kind,n=e.index,i=tGo(t,r),o=i.length;return n>=o?{value:void 0,done:!0}:(this[rGo].index=n+1,{value:i[n],done:!1})}},Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));Object.defineProperty(nGo,Symbol.toStringTag,{value:"HeadersIterator",writable:!1,enumerable:!1,configurable:!0});pVe=Symbol("Response internals"),EBm=XVu.default.STATUS_CODES,Xre=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]:{};$T.call(this,t,r);let n=r.status||200,i=new w8(r.headers);if(t!=null&&!i.has("Content-Type")){let o=t5u(t);o&&i.append("Content-Type",o)}this[pVe]={url:r.url,status:n,statusText:r.statusText||EBm[n],headers:i}}get url(){return this[pVe].url}get status(){return this[pVe].status}get ok(){return this[pVe].status>=200&&this[pVe].status<300}get statusText(){return this[pVe].statusText}get headers(){return this[pVe].headers}clone(){return new e(e5u(this),{url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok})}};$T.mixIn(Xre.prototype);Object.defineProperties(Xre.prototype,{url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});Object.defineProperty(Xre.prototype,Symbol.toStringTag,{value:"Response",writable:!1,enumerable:!1,configurable:!0});hhe=Symbol("Request internals"),Z8o=fYr.default.parse,IBm=fYr.default.format,vBm="destroy"in SJ.default.Readable.prototype;dwe=class e{constructor(t){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n;pYr(t)?n=Z8o(t.url):(t&&t.href?n=Z8o(t.href):n=Z8o(`${t}`),t={});let i=r.method||t.method||"GET";if(i=i.toUpperCase(),(r.body!=null||pYr(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:pYr(t)&&t.body!==null?e5u(t):null;$T.call(this,o,{timeout:r.timeout||t.timeout||0,size:r.size||t.size||0});let s=new w8(r.headers||t.headers||{});if(o!=null&&!s.has("Content-Type")){let c=t5u(o);c&&s.append("Content-Type",c)}let a=pYr(t)?t.signal:null;if("signal"in r&&(a=r.signal),a!=null&&!CBm(a))throw new TypeError("Expected signal to be an instanceof AbortSignal");this[hhe]={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[hhe].method}get url(){return IBm(this[hhe].parsedURL)}get headers(){return this[hhe].headers}get redirect(){return this[hhe].redirect}get signal(){return this[hhe].signal}clone(){return new e(this)}};$T.mixIn(dwe.prototype);Object.defineProperty(dwe.prototype,Symbol.toStringTag,{value:"Request",writable:!1,enumerable:!1,configurable:!0});Object.defineProperties(dwe.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0}});rWt.prototype=Object.create(Error.prototype);rWt.prototype.constructor=rWt;rWt.prototype.name="AbortError";YVu=SJ.default.PassThrough,SBm=fYr.default.resolve;fwe.isRedirect=function(e){return e===301||e===302||e===303||e===307||e===308};fwe.Promise=global.Promise;wBm=fwe});var hVe=E(AM=>{"use strict";var Ahe={ANCHOR:"&",COMMENT:"#",TAG:"!",DIRECTIVES_END:"-",DOCUMENT_END:"."},nWt={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"},TBm="tag:yaml.org,2002:",OBm={MAP:"tag:yaml.org,2002:map",SEQ:"tag:yaml.org,2002:seq",STR:"tag:yaml.org,2002:str"};function i5u(e){let t=[0],r=e.indexOf(`
|
|
539
|
+
`).reduce(vTm,Object.create(null)),vTm=(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},CTm=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Ef=CTm!=="win32"?e=>e:e=>e&&e.replaceAll(/\\/g,"/"),xTm=class extends nVe{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=Ef(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?Ef(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=Ef(e.path)),e.linkpath&&(e.linkpath=Ef(e.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(e).filter(([r,n])=>!(n==null||r==="path"&&t))))}},iJr=(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))},STm=1024*1024,x5o=Buffer.from([31,139]),S5o=Buffer.from([40,181,47,253]),wTm=Math.max(x5o.length,S5o.length),x8=Symbol("state"),KUe=Symbol("writeEntry"),lhe=Symbol("readEntry"),l5o=Symbol("nextEntry"),m4u=Symbol("processEntry"),Hre=Symbol("extendedHeader"),A9t=Symbol("globalExtendedHeader"),VSe=Symbol("meta"),h4u=Symbol("emitMeta"),b0=Symbol("buffer"),phe=Symbol("queue"),GSe=Symbol("ended"),p5o=Symbol("emittedEnd"),JUe=Symbol("emit"),hS=Symbol("unzip"),RKr=Symbol("consumeChunk"),DKr=Symbol("consumeChunkSub"),f5o=Symbol("consumeBody"),g4u=Symbol("consumeMeta"),A4u=Symbol("consumeHeader"),y9t=Symbol("consuming"),d5o=Symbol("bufferConcat"),kKr=Symbol("maybeEnd"),But=Symbol("writing"),qSe=Symbol("aborted"),FKr=Symbol("onDone"),YUe=Symbol("sawValidEntry"),NKr=Symbol("sawNullBlock"),jKr=Symbol("sawEOF"),y4u=Symbol("closeStream"),TTm=()=>!0,k9t=class extends G4u.EventEmitter{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[phe]=[];[b0];[lhe];[KUe];[x8]="begin";[VSe]="";[Hre];[A9t];[GSe]=!1;[hS];[qSe]=!1;[YUe];[NKr]=!1;[jKr]=!1;[But]=!1;[y9t]=!1;[p5o]=!1;constructor(e={}){super(),this.file=e.file||"",this.on(FKr,()=>{(this[x8]==="begin"||this[YUe]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),e.ondone?this.on(FKr,e.ondone):this.on(FKr,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!e.strict,this.maxMetaEntrySize=e.maxMetaEntrySize||STm,this.filter=typeof e.filter=="function"?e.filter:TTm;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[y4u]()),typeof e.onwarn=="function"&&this.on("warn",e.onwarn),typeof e.onReadEntry=="function"&&this.on("entry",e.onReadEntry)}warn(e,t,r={}){iJr(this,e,t,r)}[A4u](e,t){this[YUe]===void 0&&(this[YUe]=!1);let r;try{r=new rVe(e,t,this[Hre],this[A9t])}catch(n){return this.warn("TAR_ENTRY_INVALID",n)}if(r.nullBlock)this[NKr]?(this[jKr]=!0,this[x8]==="begin"&&(this[x8]="header"),this[JUe]("eof")):(this[NKr]=!0,this[JUe]("nullBlock"));else if(this[NKr]=!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[KUe]=new xTm(r,this[Hre],this[A9t]);if(!this[YUe])if(i.remain){let o=()=>{i.invalid||(this[YUe]=!0)};i.on("end",o)}else this[YUe]=!0;i.meta?i.size>this.maxMetaEntrySize?(i.ignore=!0,this[JUe]("ignoredEntry",i),this[x8]="ignore",i.resume()):i.size>0&&(this[VSe]="",i.on("data",o=>this[VSe]+=o),this[x8]="meta"):(this[Hre]=void 0,i.ignore=i.ignore||!this.filter(i.path,i),i.ignore?(this[JUe]("ignoredEntry",i),this[x8]=i.remain?"ignore":"header",i.resume()):(i.remain?this[x8]="body":(this[x8]="header",i.end()),this[lhe]?this[phe].push(i):(this[phe].push(i),this[l5o]())))}}}[y4u](){queueMicrotask(()=>this.emit("close"))}[m4u](e){let t=!0;if(!e)this[lhe]=void 0,t=!1;else if(Array.isArray(e)){let[r,...n]=e;this.emit(r,...n)}else this[lhe]=e,this.emit("entry",e),e.emittedEnd||(e.on("end",()=>this[l5o]()),t=!1);return t}[l5o](){do;while(this[m4u](this[phe].shift()));if(this[phe].length===0){let e=this[lhe];!e||e.flowing||e.size===e.remain?this[But]||this.emit("drain"):e.once("drain",()=>this.emit("drain"))}}[f5o](e,t){let r=this[KUe];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[x8]="header",this[KUe]=void 0,r.end()),i.length}[g4u](e,t){let r=this[KUe],n=this[f5o](e,t);return!this[KUe]&&r&&this[h4u](r),n}[JUe](e,t,r){this[phe].length===0&&!this[lhe]?this.emit(e,t,r):this[phe].push([e,t,r])}[h4u](e){switch(this[JUe]("meta",this[VSe]),e.type){case"ExtendedHeader":case"OldExtendedHeader":this[Hre]=XKr.parse(this[VSe],this[Hre],!1);break;case"GlobalExtendedHeader":this[A9t]=XKr.parse(this[VSe],this[A9t],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let t=this[Hre]??Object.create(null);this[Hre]=t,t.path=this[VSe].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let t=this[Hre]||Object.create(null);this[Hre]=t,t.linkpath=this[VSe].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+e.type)}}abort(e){this[qSe]=!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[qSe])return r?.(),!1;if((this[hS]===void 0||this.brotli===void 0&&this[hS]===!1)&&e){if(this[b0]&&(e=Buffer.concat([this[b0],e]),this[b0]=void 0),e.length<wTm)return this[b0]=e,r?.(),!0;for(let s=0;this[hS]===void 0&&s<x5o.length;s++)e[s]!==x5o[s]&&(this[hS]=!1);let i=!1;if(this[hS]===!1&&this.zstd!==!1){i=!0;for(let s=0;s<S5o.length;s++)if(e[s]!==S5o[s]){i=!1;break}}let o=this.brotli===void 0&&!i;if(this[hS]===!1&&o)if(e.length<512)if(this[GSe])this.brotli=!0;else return this[b0]=e,r?.(),!0;else try{new rVe(e.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[hS]===void 0||this[hS]===!1&&(this.brotli||i)){let s=this[GSe];this[GSe]=!1,this[hS]=this[hS]===void 0?new Z1m({}):i?new rTm({}):new eTm({}),this[hS].on("data",c=>this[RKr](c)),this[hS].on("error",c=>this.abort(c)),this[hS].on("end",()=>{this[GSe]=!0,this[RKr]()}),this[But]=!0;let a=!!this[hS][s?"end":"write"](e);return this[But]=!1,r?.(),a}}this[But]=!0,this[hS]?this[hS].write(e):this[RKr](e),this[But]=!1;let n=this[phe].length>0?!1:this[lhe]?this[lhe].flowing:!0;return!n&&this[phe].length===0&&this[lhe]?.once("drain",()=>this.emit("drain")),r?.(),n}[d5o](e){e&&!this[qSe]&&(this[b0]=this[b0]?Buffer.concat([this[b0],e]):e)}[kKr](){if(this[GSe]&&!this[p5o]&&!this[qSe]&&!this[y9t]){this[p5o]=!0;let e=this[KUe];if(e&&e.blockRemain){let t=this[b0]?this[b0].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${e.blockRemain} more bytes, only ${t} available)`,{entry:e}),this[b0]&&e.write(this[b0]),e.end()}this[JUe](FKr)}}[RKr](e){if(this[y9t]&&e)this[d5o](e);else if(!e&&!this[b0])this[kKr]();else if(e){if(this[y9t]=!0,this[b0]){this[d5o](e);let t=this[b0];this[b0]=void 0,this[DKr](t)}else this[DKr](e);for(;this[b0]&&this[b0]?.length>=512&&!this[qSe]&&!this[jKr];){let t=this[b0];this[b0]=void 0,this[DKr](t)}this[y9t]=!1}(!this[b0]||this[GSe])&&this[kKr]()}[DKr](e){let t=0,r=e.length;for(;t+512<=r&&!this[qSe]&&!this[jKr];)switch(this[x8]){case"begin":case"header":this[A4u](e,t),t+=512;break;case"ignore":case"body":t+=this[f5o](e,t);break;case"meta":t+=this[g4u](e,t);break;default:throw new Error("invalid state: "+this[x8])}t<r&&(this[b0]=this[b0]?Buffer.concat([e.subarray(t),this[b0]]):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[qSe]||(this[hS]?(e&&this[hS].write(e),this[hS].end()):(this[GSe]=!0,(this.brotli===void 0||this.zstd===void 0)&&(e=e||Buffer.alloc(0)),e&&this.write(e),this[kKr]())),this}},T9t=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)},OTm=e=>{let t=e.onReadEntry;e.onReadEntry=t?r=>{t(r),r.resume()}:r=>r.resume()},e_u=(e,t)=>{let r=new Map(t.map(o=>[T9t(o),!0])),n=e.filter,i=(o,s="")=>{let a=s||(0,rJr.parse)(o).root||".",c;if(o===a)c=!1;else{let u=r.get(o);c=u!==void 0?u:i((0,rJr.dirname)(o),a)}return r.set(o,c),c};e.filter=n?(o,s)=>n(o,s)&&i(T9t(o)):o=>i(T9t(o))},PTm=e=>{let t=new k9t(e),r=e.file,n;try{n=$Ue.default.openSync(r,"r");let i=$Ue.default.fstatSync(n),o=e.maxReadSize||16*1024*1024;if(i.size<o){let s=Buffer.allocUnsafe(i.size),a=$Ue.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=$Ue.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{$Ue.default.closeSync(n)}catch{}}},BTm=(e,t)=>{let r=new k9t(e),n=e.maxReadSize||16*1024*1024,i=e.file;return new Promise((o,s)=>{r.on("error",s),r.on("end",o),$Ue.default.stat(i,(a,c)=>{if(a)s(a);else{let u=new q5o(i,{readSize:n,size:c.size});u.on("error",s),u.pipe(r)}})})},oJr=j9t(PTm,BTm,e=>new k9t(e),e=>new k9t(e),(e,t)=>{t?.length&&e_u(e,t),e.noResume||OTm(e)}),t_u=(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:RTm,parse:b4u}=r_u.win32,Y5o=e=>{let t="",r=b4u(e);for(;RTm(e)||r.root;){let n=e.charAt(0)==="/"&&e.slice(0,4)!=="//?/"?"/":r.root;e=e.slice(n.length),t+=n,r=b4u(e)}return[t,e]},sJr=["|","<",">","?",":"],X5o=sJr.map(e=>String.fromCodePoint(61440+Number(e.codePointAt(0)))),DTm=new Map(sJr.map((e,t)=>[e,X5o[t]])),kTm=new Map(X5o.map((e,t)=>[e,sJr[t]])),E4u=e=>sJr.reduce((t,r)=>t.split(r).join(DTm.get(r)),e),FTm=e=>X5o.reduce((t,r)=>t.split(r).join(kTm.get(r)),e),n_u=(e,t)=>t?(e=Ef(e).replace(/^\.(\/|$)/,""),T9t(t)+"/"+e):Ef(e),NTm=16*1024*1024,I4u=Symbol("process"),v4u=Symbol("file"),C4u=Symbol("directory"),T5o=Symbol("symlink"),x4u=Symbol("hardlink"),b9t=Symbol("header"),UKr=Symbol("read"),O5o=Symbol("lstat"),VKr=Symbol("onlstat"),P5o=Symbol("onread"),B5o=Symbol("onreadlink"),R5o=Symbol("openfile"),D5o=Symbol("onopenfile"),YSe=Symbol("close"),ZKr=Symbol("mode"),k5o=Symbol("awaitDrain"),m5o=Symbol("ondrain"),Kre=Symbol("prefix"),i_u=class extends nVe{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=H5o(t);super(),this.path=Ef(e),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||NTm,this.linkCache=r.linkCache||new Map,this.statCache=r.statCache||new Map,this.preservePaths=!!r.preservePaths,this.cwd=Ef(r.cwd||process.cwd()),this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.mtime=r.mtime,this.prefix=r.prefix?Ef(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]=Y5o(this.path);o&&typeof s=="string"&&(this.path=s,n=o)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=FTm(this.path.replaceAll(/\\/g,"/")),e=e.replaceAll(/\\/g,"/")),this.absolute=Ef(r.absolute||w5o.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[VKr](i):this[O5o]()}warn(e,t,r={}){return iJr(this,e,t,r)}emit(e,...t){return e==="error"&&(this.#e=!0),super.emit(e,...t)}[O5o](){bJ.default.lstat(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[VKr](t)})}[VKr](e){this.statCache.set(this.absolute,e),this.stat=e,e.isFile()||(e.size=0),this.type=QTm(e),this.emit("stat",e),this[I4u]()}[I4u](){switch(this.type){case"File":return this[v4u]();case"Directory":return this[C4u]();case"SymbolicLink":return this[T5o]();default:return this.end()}}[ZKr](e){return t_u(e,this.type==="Directory",this.portable)}[Kre](e){return n_u(e,this.prefix)}[b9t](){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 rVe({path:this[Kre](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Kre](this.linkpath):this.linkpath,mode:this[ZKr](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 XKr({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[Kre](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Kre](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)}[C4u](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[b9t](),this.end()}[T5o](){bJ.default.readlink(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[B5o](t)})}[B5o](e){this.linkpath=Ef(e),this[b9t](),this.end()}[x4u](e){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=Ef(w5o.default.relative(this.cwd,e)),this.stat.size=0,this[b9t](),this.end()}[v4u](){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[x4u](t);this.linkCache.set(e,this.absolute)}if(this[b9t](),this.stat.size===0)return this.end();this[R5o]()}[R5o](){bJ.default.open(this.absolute,"r",(e,t)=>{if(e)return this.emit("error",e);this[D5o](t)})}[D5o](e){if(this.fd=e,this.#e)return this[YSe]();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[UKr]()}[UKr](){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");bJ.default.read(e,t,r,n,i,(o,s)=>{if(o)return this[YSe](()=>this.emit("error",o));this[P5o](s)})}[YSe](e=()=>{}){this.fd!==void 0&&bJ.default.close(this.fd,e)}[P5o](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[YSe](()=>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[YSe](()=>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[m5o]():this[k5o](()=>this[m5o]())}[k5o](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)}[m5o](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[YSe](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[UKr]()}},jTm=class extends i_u{sync=!0;[O5o](){this[VKr](bJ.default.lstatSync(this.absolute))}[T5o](){this[B5o](bJ.default.readlinkSync(this.absolute))}[R5o](){this[D5o](bJ.default.openSync(this.absolute,"r"))}[UKr](){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=bJ.default.readSync(t,r,n,i,o);this[P5o](s),e=!1}finally{if(e)try{this[YSe](()=>{})}catch{}}}[k5o](e){e()}[YSe](e=()=>{}){this.fd!==void 0&&bJ.default.closeSync(this.fd),e()}},zTm=class extends nVe{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 iJr(this,e,t,r)}constructor(e,t={}){let r=H5o(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=Ef(e.path),this.mode=e.mode!==void 0?this[ZKr](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?Ef(e.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let i=!1;if(!this.preservePaths){let[s,a]=Y5o(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 rVe({path:this[Kre](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Kre](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 XKr({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[Kre](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Kre](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)}[Kre](e){return n_u(e,this.prefix)}[ZKr](e){return t_u(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}},QTm=e=>e.isFile()?"File":e.isDirectory()?"Directory":e.isSymbolicLink()?"SymbolicLink":"Unsupported",MTm=class jut{tail;head;length=0;static create(t=[]){return new jut(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++)_Tm(this,t[r]);return this.length}unshift(...t){for(var r=0,n=t.length;r<n;r++)UTm(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 jut;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 jut;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 jut;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 jut;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=LTm(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}};Z5o=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}},S4u=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(e,t){this.path=e||"./",this.absolute=t}},w4u=Buffer.alloc(1024),GKr=Symbol("onStat"),E9t=Symbol("ended"),AJ=Symbol("queue"),I9t=Symbol("pendingLinks"),WSe=Symbol("current"),XUe=Symbol("process"),v9t=Symbol("processing"),zKr=Symbol("processJob"),yJ=Symbol("jobs"),h5o=Symbol("jobDone"),qKr=Symbol("addFSEntry"),T4u=Symbol("addTarEntry"),N5o=Symbol("stat"),j5o=Symbol("readdir"),WKr=Symbol("onreaddir"),HKr=Symbol("pipe"),O4u=Symbol("entry"),g5o=Symbol("entryOpt"),KKr=Symbol("writeEntryClass"),o_u=Symbol("write"),A5o=Symbol("ondrain"),aJr=class extends nVe{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[KKr];onWriteEntry;[AJ];[I9t]=new Map;[yJ]=0;[v9t]=!1;[E9t]=!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=Ef(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[KKr]=i_u,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 X1m(e.gzip)),e.brotli&&(typeof e.brotli!="object"&&(e.brotli={}),this.zip=new $1m(e.brotli)),e.zstd&&(typeof e.zstd!="object"&&(e.zstd={}),this.zip=new tTm(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[A5o]()),this.on("resume",()=>t.resume())}else this.on("drain",this[A5o]);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[AJ]=new MTm,this[yJ]=0,this.jobs=Number(e.jobs)||4,this[v9t]=!1,this[E9t]=!1}[o_u](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[E9t]=!0,this[XUe](),r&&r(),this}write(e){if(this[E9t])throw new Error("write after end");return typeof e=="string"?this[qKr](e):this[T4u](e),this.flowing}[T4u](e){let t=Ef(F5o.default.resolve(this.cwd,e.path));if(!this.filter(e.path,e))e.resume();else{let r=new S4u(e.path,t);r.entry=new zTm(e,this[g5o](r)),r.entry.on("end",()=>this[h5o](r)),this[yJ]+=1,this[AJ].push(r)}this[XUe]()}[qKr](e){let t=Ef(F5o.default.resolve(this.cwd,e));this[AJ].push(new S4u(e,t)),this[XUe]()}[N5o](e){e.pending=!0,this[yJ]+=1;let t=this.follow?"stat":"lstat";F9t.default[t](e.absolute,(r,n)=>{e.pending=!1,this[yJ]-=1,r?this.emit("error",r):this[GKr](e,n)})}[GKr](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[WSe])this[zKr](e);else{let r=`${t.dev}:${t.ino}`,n=this[I9t].get(r);n?n.push(e):this[I9t].set(r,[e]),e.pendingLink=!0,e.pending=!0}this[XUe]()}[j5o](e){e.pending=!0,this[yJ]+=1,F9t.default.readdir(e.absolute,(t,r)=>{if(e.pending=!1,this[yJ]-=1,t)return this.emit("error",t);this[WKr](e,r)})}[WKr](e,t){this.readdirCache.set(e.absolute,t),e.readdir=t,this[XUe]()}[XUe](){if(!this[v9t]){this[v9t]=!0;for(let e=this[AJ].head;e&&this[yJ]<this.jobs;e=e.next)if(this[zKr](e.value),e.value.ignore){let t=e.next;this[AJ].removeNode(e),e.next=t}this[v9t]=!1,this[E9t]&&this[AJ].length===0&&this[yJ]===0&&(this.zip?this.zip.end(w4u):(super.write(w4u),super.end()))}}get[WSe](){return this[AJ]&&this[AJ].head&&this[AJ].head.value}[h5o](e){this[AJ].shift(),this[yJ]-=1;let{stat:t}=e;if(t&&t.isFile()&&t.nlink>1){let r=`${t.dev}:${t.ino}`,n=this[I9t].get(r);if(n){this[I9t].delete(r);for(let i of n)i.pending=!1,this[zKr](i)}}this[XUe]()}[zKr](e){if(e.pending&&e.pendingLink&&e===this[WSe]&&(e.pending=!1,e.pendingLink=!1),!e.pending){if(e.entry){e===this[WSe]&&!e.piped&&this[HKr](e);return}if(!e.stat){let t=this.statCache.get(e.absolute);t?this[GKr](e,t):this[N5o](e)}if(e.stat&&!e.ignore){if(!this.noDirRecurse&&e.stat.isDirectory()&&!e.readdir){let t=this.readdirCache.get(e.absolute);if(t?this[WKr](e,t):this[j5o](e),!e.readdir)return}if(e.entry=this[O4u](e),!e.entry){e.ignore=!0;return}e===this[WSe]&&!e.piped&&this[HKr](e)}}}[g5o](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}}[O4u](e){this[yJ]+=1;try{return new this[KKr](e.path,this[g5o](e)).on("end",()=>this[h5o](e)).on("error",t=>this.emit("error",t))}catch(t){this.emit("error",t)}}[A5o](){this[WSe]&&this[WSe].entry&&this[WSe].entry.resume()}[HKr](e){e.piped=!0,e.readdir&&e.readdir.forEach(n=>{let i=e.path,o=i==="./"?"":i.replace(/\/*$/,"/");this[qKr](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={}){iJr(this,e,t,r)}},$5o=class extends aJr{sync=!0;constructor(e){super(e),this[KKr]=jTm}pause(){}resume(){}[N5o](e){let t=this.follow?"statSync":"lstatSync";this[GKr](e,F9t.default[t](e.absolute))}[j5o](e){this[WKr](e,F9t.default.readdirSync(e.absolute))}[HKr](e){let t=e.entry,r=this.zip;if(e.readdir&&e.readdir.forEach(n=>{let i=e.path,o=i==="./"?"":i.replace(/\/*$/,"/");this[qKr](o+n)}),!t)throw new Error("Cannot pipe without source");r?t.on("data",n=>{r.write(n)}):t.on("data",n=>{super[o_u](n)})}},VTm=(e,t)=>{let r=new $5o(e),n=new V4u(e.file,{mode:e.mode||438});r.pipe(n),s_u(r,t)},GTm=(e,t)=>{let r=new aJr(e),n=new tJr(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 a_u(r,t).catch(o=>r.emit("error",o)),i},s_u=(e,t)=>{t.forEach(r=>{r.charAt(0)==="@"?oJr({file:W5o.default.resolve(e.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r)}),e.end()},a_u=async(e,t)=>{for(let r of t)r.charAt(0)==="@"?await oJr({file:W5o.default.resolve(String(e.cwd),r.slice(1)),noResume:!0,onReadEntry:n=>{e.add(n)}}):e.add(r);e.end()},qTm=(e,t)=>{let r=new $5o(e);return s_u(r,t),r},WTm=(e,t)=>{let r=new aJr(e);return a_u(r,t).catch(n=>r.emit("error",n)),r},cJr=j9t(VTm,GTm,qTm,WTm,(e,t)=>{if(!t?.length)throw new TypeError("no paths specified to add to archive")}),HTm=process.env.__FAKE_PLATFORM__||process.platform,u_u=HTm==="win32",{O_CREAT:l_u,O_NOFOLLOW:P4u,O_TRUNC:p_u,O_WRONLY:f_u}=r8o.default.constants,d_u=Number(process.env.__FAKE_FS_O_FILENAME__)||r8o.default.constants.UV_FS_O_FILEMAP||0,KTm=u_u&&!!d_u,JTm=512*1024,YTm=d_u|p_u|l_u|f_u,B4u=!u_u&&typeof P4u=="number"?P4u|p_u|l_u|f_u:null,m_u=B4u!==null?()=>B4u:KTm?e=>e<JTm?YTm:"w":()=>"w",z5o=(e,t,r)=>{try{return z9t.default.lchownSync(e,t,r)}catch(n){if(n?.code!=="ENOENT")throw n}},$Kr=(e,t,r,n)=>{z9t.default.lchown(e,t,r,i=>{n(i&&i?.code!=="ENOENT"?i:null)})},XTm=(e,t,r,n,i)=>{if(t.isDirectory())h_u(Qut.default.resolve(e,t.name),r,n,o=>{if(o)return i(o);let s=Qut.default.resolve(e,t.name);$Kr(s,r,n,i)});else{let o=Qut.default.resolve(e,t.name);$Kr(o,r,n,i)}},h_u=(e,t,r,n)=>{z9t.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 $Kr(e,t,r,n);let s=o.length,a=null,c=u=>{if(!a){if(u)return n(a=u);if(--s===0)return $Kr(e,t,r,n)}};for(let u of o)XTm(e,u,t,r,c)})},ZTm=(e,t,r,n)=>{t.isDirectory()&&g_u(Qut.default.resolve(e,t.name),r,n),z5o(Qut.default.resolve(e,t.name),r,n)},g_u=(e,t,r)=>{let n;try{n=z9t.default.readdirSync(e,{withFileTypes:!0})}catch(i){let o=i;if(o?.code==="ENOENT")return;if(o?.code==="ENOTDIR"||o?.code==="ENOTSUP")return z5o(e,t,r);throw o}for(let i of n)ZTm(e,i,t,r);return z5o(e,t,r)},y_u=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"}},uJr=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"}},$Tm=(e,t)=>{gM.default.stat(e,(r,n)=>{(r||!n.isDirectory())&&(r=new y_u(e,r?.code||"ENOTDIR")),t(r)})},eOm=(e,t,r)=>{e=Ef(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),u=t.preserve,l=t.unlink,p=Ef(t.cwd),d=(m,g)=>{m?r(m):g&&c?h_u(g,s,a,A=>d(A)):o?gM.default.chmod(e,i,r):r()};if(e===p)return $Tm(e,d);if(u)return A_u.default.mkdir(e,{mode:i,recursive:!0}).then(m=>d(null,m??void 0),d);let f=Ef(N9t.default.relative(p,e)).split("/");Q5o(p,f,i,l,p,void 0,d)},Q5o=(e,t,r,n,i,o,s)=>{if(t.length===0)return s(null,o);let a=t.shift(),c=Ef(N9t.default.resolve(e+"/"+a));gM.default.mkdir(c,r,b_u(c,t,r,n,i,o,s))},b_u=(e,t,r,n,i,o,s)=>a=>{a?gM.default.lstat(e,(c,u)=>{if(c)c.path=c.path&&Ef(c.path),s(c);else if(u.isDirectory())Q5o(e,t,r,n,i,o,s);else if(n)gM.default.unlink(e,l=>{if(l)return s(l);gM.default.mkdir(e,r,b_u(e,t,r,n,i,o,s))});else{if(u.isSymbolicLink())return s(new uJr(e,e+"/"+t.join("/")));s(a)}}):(o=o||e,Q5o(e,t,r,n,i,o,s))},tOm=e=>{let t=!1,r;try{t=gM.default.statSync(e).isDirectory()}catch(n){r=n?.code}finally{if(!t)throw new y_u(e,r??"ENOTDIR")}},rOm=(e,t)=>{e=Ef(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,u=t.unlink,l=Ef(t.cwd),p=m=>{m&&a&&g_u(m,o,s),i&&gM.default.chmodSync(e,n)};if(e===l)return tOm(l),p();if(c)return p(gM.default.mkdirSync(e,{mode:n,recursive:!0})??void 0);let d=Ef(N9t.default.relative(l,e)).split("/"),f;for(let m=d.shift(),g=l;m&&(g+="/"+m);m=d.shift()){g=Ef(N9t.default.resolve(g));try{gM.default.mkdirSync(g,n),f=f||g}catch{let A=gM.default.lstatSync(g);if(A.isDirectory())continue;if(u){gM.default.unlinkSync(g),gM.default.mkdirSync(g,n),f=f||g;continue}else if(A.isSymbolicLink())return new uJr(g,g+"/"+d.join("/"))}}return p(f)},y5o=Object.create(null),R4u=1e4,Rut=new Set,nOm=e=>{Rut.has(e)?Rut.delete(e):y5o[e]=e.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Rut.add(e);let t=y5o[e],r=Rut.size-R4u;if(r>R4u/10){for(let n of Rut)if(Rut.delete(n),delete y5o[n],--r<=0)break}return t},iOm=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,oOm=iOm==="win32",sOm=e=>e.split("/").slice(0,-1).reduce((t,r)=>{let n=t.at(-1);return n!==void 0&&(r=(0,n8o.join)(n,r)),t.push(r||"/"),t},[]),aOm=class{#e=new Map;#t=new Map;#r=new Set;reserve(e,t){e=oOm?["win32 parallelization disabled"]:e.map(n=>T9t((0,n8o.join)(nOm(n))));let r=new Set(e.map(n=>sOm(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}},cOm=()=>process.umask(),D4u=Symbol("onEntry"),M5o=Symbol("checkFs"),k4u=Symbol("checkFs2"),L5o=Symbol("isReusable"),S8=Symbol("makeFs"),_5o=Symbol("file"),U5o=Symbol("directory"),JKr=Symbol("link"),F4u=Symbol("symlink"),N4u=Symbol("hardlink"),S9t=Symbol("ensureNoSymlink"),j4u=Symbol("unsupported"),z4u=Symbol("checkPath"),b5o=Symbol("stripAbsolutePath"),ZSe=Symbol("mkdir"),XT=Symbol("onError"),QKr=Symbol("pending"),Q4u=Symbol("pend"),Dut=Symbol("unpend"),E5o=Symbol("ended"),I5o=Symbol("maybeClose"),V5o=Symbol("skip"),O9t=Symbol("doChown"),P9t=Symbol("uid"),B9t=Symbol("gid"),R9t=Symbol("checkedCwd"),uOm=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,D9t=uOm==="win32",lOm=1024,pOm=(e,t)=>{if(!D9t)return zd.default.unlink(e,t);let r=e+".DELETE."+(0,t8o.randomBytes)(16).toString("hex");zd.default.rename(e,r,n=>{if(n)return t(n);zd.default.unlink(r,t)})},fOm=e=>{if(!D9t)return zd.default.unlinkSync(e);let t=e+".DELETE."+(0,t8o.randomBytes)(16).toString("hex");zd.default.renameSync(e,t),zd.default.unlinkSync(t)},M4u=(e,t,r)=>e!==void 0&&e===e>>>0?e:t!==void 0&&t===t>>>0?t:r,i8o=class extends k9t{[E5o]=!1;[R9t]=!1;[QKr]=0;reservations=new aOm;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[E5o]=!0,this[I5o]()},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:lOm,this.forceChown=e.forceChown===!0,this.win32=!!e.win32||D9t,this.newer=!!e.newer,this.keep=!!e.keep,this.noMtime=!!e.noMtime,this.preservePaths=!!e.preservePaths,this.unlink=!!e.unlink,this.cwd=Ef(gS.default.resolve(e.cwd||process.cwd())),this.strip=Number(e.strip)||0,this.processUmask=this.chmod?typeof e.processUmask=="number"?e.processUmask:cOm():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[D4u](t))}warn(e,t,r={}){return(e==="TAR_BAD_ARCHIVE"||e==="TAR_ABORT")&&(r.recoverable=!1),super.warn(e,t,r)}[I5o](){this[E5o]&&this[QKr]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[b5o](e,t){let r=e[t],{type:n}=e;if(!r||this.preservePaths)return!0;let[i,o]=Y5o(r),s=o.replaceAll(/\\/g,"/").split("/");if(s.includes("..")||D9t&&/^[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=gS.default.posix.dirname(e.path),c=gS.default.posix.normalize(gS.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}[z4u](e){let t=Ef(e.path),r=t.split("/");if(this.strip){if(r.length<this.strip)return!1;if(e.type==="Link"){let n=Ef(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[b5o](e,"path")||!this[b5o](e,"linkpath"))return!1;if(e.absolute=gS.default.isAbsolute(e.path)?Ef(gS.default.resolve(e.path)):Ef(gS.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:Ef(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}=gS.default.win32.parse(String(e.absolute));e.absolute=n+E4u(String(e.absolute).slice(n.length));let{root:i}=gS.default.win32.parse(e.path);e.path=i+E4u(e.path.slice(i.length))}return!0}[D4u](e){if(!this[z4u](e))return e.resume();switch(c_u.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[M5o](e);default:return this[j4u](e)}}[XT](e,t){e.name==="CwdError"?this.emit("error",e):(this.warn("TAR_ENTRY_ERROR",e,{entry:t}),this[Dut](),t.resume())}[ZSe](e,t,r){eOm(Ef(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)}[O9t](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}[P9t](e){return M4u(this.uid,e.uid,this.processUid)}[B9t](e){return M4u(this.gid,e.gid,this.processGid)}[_5o](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.fmode,n=new tJr(String(e.absolute),{flags:m_u(e.size),mode:r,autoClose:!1});n.on("error",a=>{n.fd&&zd.default.close(n.fd,()=>{}),n.write=()=>!0,this[XT](a,e),t()});let i=1,o=a=>{if(a){n.fd&&zd.default.close(n.fd,()=>{}),this[XT](a,e),t();return}--i===0&&n.fd!==void 0&&zd.default.close(n.fd,c=>{c?this[XT](c,e):this[Dut](),t()})};n.on("finish",()=>{let a=String(e.absolute),c=n.fd;if(typeof c=="number"&&e.mtime&&!this.noMtime){i++;let u=e.atime||new Date,l=e.mtime;zd.default.futimes(c,u,l,p=>p?zd.default.utimes(a,u,l,d=>o(d&&p)):o())}if(typeof c=="number"&&this[O9t](e)){i++;let u=this[P9t](e),l=this[B9t](e);typeof u=="number"&&typeof l=="number"&&zd.default.fchown(c,u,l,p=>p?zd.default.chown(a,u,l,d=>o(d&&p)):o())}o()});let s=this.transform&&this.transform(e)||e;s!==e&&(s.on("error",a=>{this[XT](a,e),t()}),e.pipe(s)),s.pipe(n)}[U5o](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.dmode;this[ZSe](String(e.absolute),r,n=>{if(n){this[XT](n,e),t();return}let i=1,o=()=>{--i===0&&(t(),this[Dut](),e.resume())};e.mtime&&!this.noMtime&&(i++,zd.default.utimes(String(e.absolute),e.atime||new Date,e.mtime,o)),this[O9t](e)&&(i++,zd.default.chown(String(e.absolute),Number(this[P9t](e)),Number(this[B9t](e)),o)),o()})}[j4u](e){e.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${e.type}`,{entry:e}),e.resume()}[F4u](e,t){let r=Ef(gS.default.relative(this.cwd,gS.default.resolve(gS.default.dirname(String(e.absolute)),String(e.linkpath)))).split("/");this[S9t](e,this.cwd,r,()=>this[JKr](e,String(e.linkpath),"symlink",t),n=>{this[XT](n,e),t()})}[N4u](e,t){let r=Ef(gS.default.resolve(this.cwd,String(e.linkpath))),n=Ef(String(e.linkpath)).split("/");this[S9t](e,this.cwd,n,()=>this[JKr](e,r,"link",t),i=>{this[XT](i,e),t()})}[S9t](e,t,r,n,i){let o=r.shift();if(this.preservePaths||o===void 0)return n();let s=gS.default.resolve(t,o);zd.default.lstat(s,(a,c)=>{if(a)return n();if(c?.isSymbolicLink())return i(new uJr(s,gS.default.resolve(s,r.join("/"))));this[S9t](e,s,r,n,i)})}[Q4u](){this[QKr]++}[Dut](){this[QKr]--,this[I5o]()}[V5o](e){this[Dut](),e.resume()}[L5o](e,t){return e.type==="File"&&!this.unlink&&t.isFile()&&t.nlink<=1&&!D9t}[M5o](e){this[Q4u]();let t=[e.path];e.linkpath&&t.push(e.linkpath),this.reservations.reserve(t,r=>this[k4u](e,r))}[k4u](e,t){let r=s=>{t(s)},n=()=>{this[ZSe](this.cwd,this.dmode,s=>{if(s){this[XT](s,e),r();return}this[R9t]=!0,i()})},i=()=>{if(e.absolute!==this.cwd){let s=Ef(gS.default.dirname(String(e.absolute)));if(s!==this.cwd)return this[ZSe](s,this.dmode,a=>{if(a){this[XT](a,e),r();return}o()})}o()},o=()=>{zd.default.lstat(String(e.absolute),(s,a)=>{if(a&&(this.keep||this.newer&&a.mtime>(e.mtime??a.mtime))){this[V5o](e),r();return}if(s||this[L5o](e,a))return this[S8](null,e,r);if(a.isDirectory()){if(e.type==="Directory"){let c=this.chmod&&e.mode&&(a.mode&4095)!==e.mode,u=l=>this[S8](l??null,e,r);return c?zd.default.chmod(String(e.absolute),Number(e.mode),u):u()}if(e.absolute!==this.cwd)return zd.default.rmdir(String(e.absolute),c=>this[S8](c??null,e,r))}if(e.absolute===this.cwd)return this[S8](null,e,r);pOm(String(e.absolute),c=>this[S8](c??null,e,r))})};this[R9t]?i():n()}[S8](e,t,r){if(e){this[XT](e,t),r();return}switch(t.type){case"File":case"OldFile":case"ContiguousFile":return this[_5o](t,r);case"Link":return this[N4u](t,r);case"SymbolicLink":return this[F4u](t,r);case"Directory":case"GNUDumpDir":return this[U5o](t,r)}}[JKr](e,t,r,n){zd.default[r](t,String(e.absolute),i=>{i?this[XT](i,e):(this[Dut](),e.resume()),n()})}},C9t=e=>{try{return[null,e()]}catch(t){return[t,null]}},E_u=class extends i8o{sync=!0;[S8](e,t){return super[S8](e,t,()=>{})}[M5o](e){if(!this[R9t]){let i=this[ZSe](this.cwd,this.dmode);if(i)return this[XT](i,e);this[R9t]=!0}if(e.absolute!==this.cwd){let i=Ef(gS.default.dirname(String(e.absolute)));if(i!==this.cwd){let o=this[ZSe](i,this.dmode);if(o)return this[XT](o,e)}}let[t,r]=C9t(()=>zd.default.lstatSync(String(e.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(e.mtime??r.mtime)))return this[V5o](e);if(t||this[L5o](e,r))return this[S8](null,e);if(r.isDirectory()){if(e.type==="Directory"){let o=this.chmod&&e.mode&&(r.mode&4095)!==e.mode,[s]=o?C9t(()=>{zd.default.chmodSync(String(e.absolute),Number(e.mode))}):[];return this[S8](s,e)}let[i]=C9t(()=>zd.default.rmdirSync(String(e.absolute)));this[S8](i,e)}let[n]=e.absolute===this.cwd?[]:C9t(()=>fOm(String(e.absolute)));this[S8](n,e)}[_5o](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.fmode,n=s=>{let a;try{zd.default.closeSync(i)}catch(c){a=c}(s||a)&&this[XT](s||a,e),t()},i;try{i=zd.default.openSync(String(e.absolute),m_u(e.size),r)}catch(s){return n(s)}let o=this.transform&&this.transform(e)||e;o!==e&&(o.on("error",s=>this[XT](s,e)),e.pipe(o)),o.on("data",s=>{try{zd.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{zd.default.futimesSync(i,a,c)}catch(u){try{zd.default.utimesSync(String(e.absolute),a,c)}catch{s=u}}}if(this[O9t](e)){let a=this[P9t](e),c=this[B9t](e);try{zd.default.fchownSync(i,Number(a),Number(c))}catch(u){try{zd.default.chownSync(String(e.absolute),Number(a),Number(c))}catch{s=s||u}}}n(s)})}[U5o](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.dmode,n=this[ZSe](String(e.absolute),r);if(n){this[XT](n,e),t();return}if(e.mtime&&!this.noMtime)try{zd.default.utimesSync(String(e.absolute),e.atime||new Date,e.mtime)}catch{}if(this[O9t](e))try{zd.default.chownSync(String(e.absolute),Number(this[P9t](e)),Number(this[B9t](e)))}catch{}t(),e.resume()}[ZSe](e,t){try{return rOm(Ef(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}}[S9t](e,t,r,n,i){if(this.preservePaths||r.length===0)return n();let o=t;for(let s of r){o=gS.default.resolve(o,s);let[a,c]=C9t(()=>zd.default.lstatSync(o));if(a)return n();if(c.isSymbolicLink())return i(new uJr(o,gS.default.resolve(t,r.join("/"))))}n()}[JKr](e,t,r,n){let i=`${r}Sync`;try{zd.default[i](t,String(e.absolute)),n(),e.resume()}catch(o){return this[XT](o,e)}}},dOm=e=>{let t=new E_u(e),r=e.file,n=e8o.default.statSync(r),i=e.maxReadSize||16*1024*1024;new L1m(r,{readSize:i,size:n.size}).pipe(t)},mOm=(e,t)=>{let r=new i8o(e),n=e.maxReadSize||16*1024*1024,i=e.file;return new Promise((o,s)=>{r.on("error",s),r.on("close",o),e8o.default.stat(i,(a,c)=>{if(a)s(a);else{let u=new q5o(i,{readSize:n,size:c.size});u.on("error",s),u.pipe(r)}})})},I_u=j9t(dOm,mOm,e=>new E_u(e),e=>new i8o(e),(e,t)=>{t?.length&&e_u(e,t)}),hOm=(e,t)=>{let r=new $5o(e),n=!0,i,o;try{try{i=hM.default.openSync(e.file,"r+")}catch(c){if(c?.code==="ENOENT")i=hM.default.openSync(e.file,"w+");else throw c}let s=hM.default.fstatSync(i),a=Buffer.alloc(512);e:for(o=0;o<s.size;o+=512){for(let l=0,p=0;l<512;l+=p){if(p=hM.default.readSync(i,a,l,a.length-l,o+l),o===0&&a[0]===31&&a[1]===139)throw new Error("cannot append to compressed archives");if(!p)break e}let c=new rVe(a);if(!c.cksumValid)break;let u=512*Math.ceil((c.size||0)/512);if(o+u+512>s.size)break;o+=u,e.mtimeCache&&c.mtime&&e.mtimeCache.set(String(c.path),c.mtime)}n=!1,gOm(e,r,o,i,t)}finally{if(n)try{hM.default.closeSync(i)}catch{}}},gOm=(e,t,r,n,i)=>{let o=new V4u(e.file,{fd:n,start:r});t.pipe(o),yOm(t,i)},AOm=(e,t)=>{t=Array.from(t);let r=new aJr(e),n=(i,o,s)=>{let a=(d,f)=>{d?hM.default.close(i,m=>s(d)):s(null,f)},c=0;if(o===0)return a(null,0);let u=0,l=Buffer.alloc(512),p=(d,f)=>{if(d||f===void 0)return a(d);if(u+=f,u<512&&f)return hM.default.read(i,l,u,l.length-u,c+u,p);if(c===0&&l[0]===31&&l[1]===139)return a(new Error("cannot append to compressed archives"));if(u<512)return a(null,c);let m=new rVe(l);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),u=0,hM.default.read(i,l,0,512,c,p)};hM.default.read(i,l,0,512,c,p)};return new Promise((i,o)=>{r.on("error",o);let s="r+",a=(c,u)=>{if(c&&c.code==="ENOENT"&&s==="r+")return s="w+",hM.default.open(e.file,s,a);if(c||!u)return o(c);hM.default.fstat(u,(l,p)=>{if(l)return hM.default.close(u,()=>o(l));n(u,p.size,(d,f)=>{if(d)return o(d);let m=new tJr(e.file,{fd:u,start:f});r.pipe(m),m.on("error",o),m.on("close",i),bOm(r,t)})})};hM.default.open(e.file,s,a)})},yOm=(e,t)=>{t.forEach(r=>{r.charAt(0)==="@"?oJr({file:o8o.default.resolve(e.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r)}),e.end()},bOm=async(e,t)=>{for(let r of t)r.charAt(0)==="@"?await oJr({file:o8o.default.resolve(String(e.cwd),r.slice(1)),noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r);e.end()},x9t=j9t(hOm,AOm,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(e,t)=>{if(!W1m(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")}),qgv=j9t(x9t.syncFile,x9t.asyncFile,x9t.syncNoFile,x9t.asyncNoFile,(e,t=[])=>{x9t.validate?.(e,t),EOm(e)}),EOm=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 io,pJr=h(()=>{"use strict";Hn();io=class e{breadcrumbs=[];context;static STRING=Xt.TypeReference.primitive({v1:"STRING",v2:Xt.PrimitiveTypeV2.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=Xt.TypeReference.container(Xt.ContainerType.optional(e.STRING));constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r}}});var s8o,v_u,C_u=h(()=>{"use strict";s8o=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,u=>{a.has(u.position)||(c--,a.add(u.position),this._path.length===1?this.resolveNode(u,`${o}.${c}`):(s.children.push({...u,path:c.toString()}),s.line=u.line,s.position=u.position,s.lineStart=u.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}}},v_u=s8o});var x_u,AE,Yre,a8o,Q9t=h(()=>{"use strict";tr();qy();x_u=require("fs/promises");is();C_u();(function(e){e.WARNING="warning",e.ERROR="error"})(AE||(AE={}));Yre=class{errors=[];logger;breadcrumbToLineNumberMapper;relativeFilepathToSpec;constructor({logger:t,relativeFilepathToSpec:r}){this.logger=t,this.relativeFilepathToSpec=r,r&&(this.breadcrumbToLineNumberMapper=new a8o({logger:t,relativePathToFile:ye.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||AE.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===AE.ERROR?t++:(n.level===AE.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??AE.WARNING;if(!(n===AE.WARNING&&!t))switch(n){case AE.ERROR:if(this.logger.log(Zn.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(Zn.Debug,` - at location (${o})`)}break;case AE.WARNING:if(this.logger.log(Zn.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(Zn.Warn,` - at location (${o})`)}r.resolution&&this.logger.log(Zn.Warn,` - resolution: ${r.resolution}`);break}}}},a8o=class{logger;relativePathToFile;map=new v_u;initialized=!1;constructor({relativePathToFile:t,logger:r}){this.relativePathToFile=t,this.logger=r}async initialize(){if(!this.initialized)try{let t=await(0,x_u.readFile)(this.relativePathToFile,"utf-8");vr.load(t,{listener:this.map.listen()}),this.initialized=!0}catch(t){this.logger.log(Zn.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 vOm(e){return"deprecated"in e&&e.deprecated===!0}async function COm(e){let t=await fetch(e);if(t.ok)try{let r=await t.text();try{return JSON.parse(r)}catch{return vr.load(r)}}catch{return}}var E0,S_u=h(()=>{"use strict";c8();ct();Hn();is();Gi();Q9t();Xo();E0=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=Gw({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=ri(n.join("_"));return CH(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:AE.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1};i=i[s]}return i==null?(n||this.errorCollector.collect({level:AE.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 u=t.$ref.split("#"),l=u[0];if(n=u[1],!l)return{resolved:!1};if(s=l,o=await this.loadExternalDocument(l),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(u=>u.replace(/~1/g,"/"));for(let u of c){if(typeof r!="object"||r==null)return{resolved:!1};r=r[u]}if(r==null)return{resolved:!1};if(i&&typeof r=="object"&&r!==null){let u=new Set;u.add(t.$ref),r=await this.resolveNestedExternalReferences(r,o,u,s)}return{resolved:!0,value:r}}async loadExternalDocument(t){let r=this.externalDocuments.get(t);r==null&&(r=COm(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,u=s.substring(2).split("/").map(cI);for(let l of u){if(typeof c!="object"||c===null)return t;c=c[l]}if(c!=null){let l=await this.resolveNestedExternalReferences(c,r,n,i);return n.delete(s),l}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 Xt.ObjectPropertyAccess.ReadOnly;if(i)return Xt.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 _C.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 _C.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(i!=null)return{status:i,message:void 0};if(vOm(t))return{status:mh.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 $r.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"&&Ag(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(jr(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 es,XD=h(()=>{"use strict";es=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 Lut,c8o=h(()=>{"use strict";XD();Lut=class extends es{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 fJr,w_u=h(()=>{"use strict";Hn();XD();fJr=class extends es{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 mh.InDevelopment;case"PRE_RELEASE":return mh.PreRelease;case"GENERAL_AVAILABILITY":case"GENERALLY_AVAILABLE":case"GA":case"STABLE":return mh.GeneralAvailability;case"DEPRECATED":return mh.Deprecated;case"ALPHA":return mh.Alpha;case"BETA":return mh.Beta;case"PREVIEW":return mh.Preview;case"LEGACY":return mh.Legacy;default:return}}}});var _ut,u8o=h(()=>{"use strict";XD();_ut=class extends es{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 Uut,l8o=h(()=>{"use strict";XD();Uut=class extends es{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 xOm,SOm,T_u,O_u=h(()=>{"use strict";an();xOm=Fe.object({snake:Fe.string().optional(),camel:Fe.string().optional(),screamingSnake:Fe.string().optional(),pascal:Fe.string().optional()}),SOm=Fe.object({description:Fe.string().optional(),name:Fe.string().optional(),casing:xOm.optional()}),T_u=Fe.record(SOm)});var Vut,p8o=h(()=>{"use strict";XD();O_u();Vut=class extends es{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=T_u.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 iVe,P_u=h(()=>{"use strict";XD();iVe=class extends es{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 dJr,B_u=h(()=>{"use strict";XD();dJr=class extends es{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 mJr,R_u=h(()=>{"use strict";XD();mJr=class extends es{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 hJr,D_u=h(()=>{"use strict";XD();hJr=class extends es{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 gJr,k_u=h(()=>{"use strict";XD();gJr=class extends es{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 AJr,F_u=h(()=>{"use strict";XD();AJr=class extends es{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 yJr,N_u=h(()=>{"use strict";XD();yJr=class extends es{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 wOm({isText:e,isAttribute:t}){return e?cQ.Text:t?cQ.Attribute:cQ.Element}function Q_u(e){return typeof e=="object"&&e!=null}function bJr(e,t){if(!(typeof e!="object"||e==null))return e[t]}function f8o(...e){return e.find(t=>t!=null)}var j_u,z_u,Gut,qut,EJr=h(()=>{"use strict";Hn();XD();j_u="x-fern-xml-text",z_u="x-fern-xml-list-separator",Gut=class extends es{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(Q_u(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}}},qut=class extends es{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=f8o(this.getExtensionValue(t),this.getExtensionValue(r)),i=f8o(bJr(t,j_u),bJr(r,j_u)),o=f8o(bJr(t,z_u),bJr(r,z_u)),s=Q_u(n)?n:{};return{kind:wOm({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 _C={};te(_C,{AudienceExtension:()=>Lut,FernAvailabilityExtension:()=>fJr,FernDiscriminatedExtension:()=>_ut,FernDiscriminatorContextExtension:()=>Uut,FernEnumExtension:()=>Vut,FernIgnoreExtension:()=>iVe,FernOptionalExtension:()=>dJr,FernTypeExtension:()=>AJr,FernTypeNameExtension:()=>yJr,SdkGroupNameExtension:()=>mJr,SdkMethodNameExtension:()=>hJr,ServerFromOperationNameExtension:()=>gJr,XmlPropertyExtension:()=>qut,XmlSchemaExtension:()=>Gut});var d8o=h(()=>{"use strict";c8o();w_u();u8o();l8o();p8o();P_u();B_u();R_u();D_u();k_u();F_u();N_u();EJr()});function L_u(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=>Sw.named({name:i.name,shape:a});switch(i.shape.type){case"object":return s(mD.Object);case"enum":return s(mD.Enum);case"union":return s(mD.Union);case"undiscriminatedUnion":return s(mD.UndiscriminatedUnion);case"alias":{let{resolvedType:a}=i.shape,c=M_u(a);return c!=null?r(c,o):a}default:return}};for(let[i,o]of Object.entries(e)){if(o.shape.type!=="alias"||M_u(o.shape.resolvedType)==null)continue;let s=r(i,new Set);s!=null&&(e[i]={...o,shape:pc.alias({aliasOf:o.shape.aliasOf,resolvedType:s})})}}function M_u(e){if(e.type!=="named")return;let t=e;return e.shape==null&&typeof t.typeId=="string"?t.typeId:void 0}var __u=h(()=>{"use strict";Hn()});var vJ,U_u=h(()=>{"use strict";Hn();fc();Gi();pJr();d8o();__u();vJ=class extends io{ir;audiences;irGraph;constructor({breadcrumbs:t=[],context:r,audiences:n}){super({breadcrumbs:t,context:r}),this.audiences=n,this.irGraph=new cUe(n),this.ir={auth:{docs:void 0,requirement:Xt.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:Xt.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 iVe({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 iVe({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},zGt(this.ir,{onWarning:a=>this.context.logger.warn(a)}),L_u(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)),DGt({ir:i});let o=this.context.exampleGenerationArgs,s=LMo({ir:i,exampleGeneration:o,logger:this.context.logger});if(this.context.generateV1Examples){let a=FGt({ir:i,exampleGeneration:o});return{...i,...a,...s}}return{...i,...s}}filterIrForAudiences(t){return{...jGt(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 u=this.context.getGroup({groupParts:n,namespace:this.context.namespace}),l=this.getOrCreatePackage({group:n});l!==this.ir.rootPackage&&l.docs==null&&o!=null&&(l.docs=o);let p=[...u].map(m=>this.context.casingsGenerator.generateName(m)),d=p[p.length-1];l.service==null&&(l.service=s??`service_${u.map(m=>ri(m)).join("/")}`),this.ir.services[l.service]==null&&(this.ir.services[l.service]=this.createNewService({allParts:p,finalpart:d,endpointGroupDisplayName:i})),this.ir.services[l.service]?.endpoints.push(t);let f=this.ir.services[l.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=ri(i?.join(".")),s=ri(r),a=this.context.namespace?`${ri(this.context.namespace)}/`:"",c=o?`channel_${a}${o}`:`channel_${a}${s}`,u=i?this.getOrCreatePackage({group:i}):this.getOrCreatePackage({group:[s]});this.ir.websocketChannels={...this.ir.websocketChannels,[c]:t},c!==""?u.websocket==null&&(u.websocket=c):this.ir.rootPackage.websocket="";let l=this.context.createFernFilepath();this.irGraph.addChannel(l,c,t),n!=null&&this.irGraph.markChannelForAudiences(l,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:nb(""),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=>ri(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 oVe(e){return typeof e=="object"&&e!==null&&!("$ref"in e)}function POm(e){if(!oVe(e))return!1;if("nullable"in e&&e.nullable===!0)return!0;let t=r=>Array.isArray(r)&&r.some(n=>oVe(n)&&n.type==="null");return t(e.anyOf)||t(e.oneOf)}function BOm(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 G_u(e){if(e.const!==void 0)return e.const;if(Array.isArray(e.enum)&&e.enum.length>0)return e.enum[0]}var TOm,V_u,OOm,Jw,twe=h(()=>{"use strict";ct();Xo();TOm=/^literal<\s*(?:"(.*)"|(true|false))\s*>$/,V_u=new WeakMap,OOm=new Set(["type","properties","required","allOf","description","title","deprecated","readOnly","writeOnly","xml","externalDocs","discriminator"]);Jw=class e extends io{MAX_DEPTH=12;EXAMPLE_STRING=qo.STRING;EXAMPLE_NUMBER=qo.DOUBLE;EXAMPLE_BOOLEAN=qo.BOOLEAN;EXAMPLE_INTEGER=qo.INT;EXAMPLE_DATE=qo.DATE;EXAMPLE_DATE_TIME=qo.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 u=V_u.get(r);u!=null?this.sharedState=u:(this.sharedState={mergedAllOfProperties:new WeakMap,mergeOnlyAllOfSchemas:new WeakMap},V_u.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(([y,I])=>{if(typeof I!="object")return{key:y,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if(this.isDeprecatedProperty(I)&&!this.isRequiredProperty({key:y,resolvedSchema:t}))return{key:y,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:y,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("readOnly"in I&&I.readOnly===!0&&this.exampleGenerationStrategy==="request")return{key:y,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("writeOnly"in I&&I.writeOnly===!0&&this.exampleGenerationStrategy==="response")return{key:y,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};let x=POm(I),v=!(y in r)||!x&&r[y]==null||x&&r[y]===void 0,S=!o.includes(y);if(v&&S){if(this.example===void 0&&this.generateOptionalProperties){let B=this.maybeResolveSchemaExample(I),R=new e({breadcrumbs:[...this.breadcrumbs,y],context:this.context,schema:I,example:B,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()});return{key:y,result:R.convert()}}return{key:y,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}}}else{let B=r[y],R=B!==void 0?B:this.maybeResolveSchemaExample(I),O=new e({breadcrumbs:[...this.breadcrumbs,y],context:this.context,schema:I,example:R,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();return{key:y,result:O}}}),a=n?[]:(t.allOf??[]).map((y,I)=>{let x=this.context.resolveMaybeReference({schemaOrReference:y,breadcrumbs:[...this.breadcrumbs,`allOf[${I}]`],skipErrorCollector:!0});return x&&this.isConstraintOnlySchema(x)?{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,...y,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:y})=>y.usedProvidedExample)||a.some(y=>y.usedProvidedExample)),u=Object.fromEntries(s.map(({key:y,result:I})=>[y,I.validExample]).filter(([y,I])=>I!==void 0));for(let y of a)if(typeof y.validExample=="object"&&y.validExample!==null){let I=y.validExample,x=Object.fromEntries(Object.entries(I).filter(([v,S])=>S!==void 0));for(let[v,S]of Object.entries(x))(!(v in u)||u[v]==null)&&(u[v]=S)}let l=[],p=this.collectAllPropertyKeys(t),d=Object.keys(r).filter(y=>!p.has(y)),f=this.schemaHasPatternProperties(t),m=f?d:[],g=f?[]:d;if(m.forEach(y=>{l.push({key:y,result:{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:r[y],errors:[]}})}),g.length>0)if(t.additionalProperties===!1)g.forEach(y=>{let I=[...this.breadcrumbs,y].join("."),x={message:`Found unexpected property '${y}' in example. This property does not exist in the schema${I?` at path: ${I}`:""}`,path:[...this.breadcrumbs,y]};l.push({key:y,result:{isValid:!1,coerced:!1,usedProvidedExample:!0,validExample:void 0,errors:[x]}})});else if(t.additionalProperties===!0||t.additionalProperties===void 0)g.forEach(y=>{l.push({key:y,result:{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:r[y],errors:[]}})});else{let y=t.additionalProperties;g.forEach(I=>{let v=new e({breadcrumbs:[...this.breadcrumbs,I],context:this.context,schema:y,example:r[I],depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();l.push({key:I,result:v})})}for(let{key:y,result:I}of l)I.validExample!==void 0&&u[y]===void 0&&(u[y]=I.validExample);let A=s.every(y=>y.result.isValid)&&a.every(y=>y.isValid)&&l.every(({result:y})=>y.isValid);if(Object.keys(u).length===0){let y=a.find(I=>I.validExample!==void 0&&(typeof I.validExample!="object"||I.validExample===null));y&&(u=y.validExample)}return{isValid:A,coerced:!1,usedProvidedExample:c,validExample:u,errors:[...s.flatMap(({result:y})=>y.errors),...a.flatMap(y=>y.errors),...l.flatMap(({result:y})=>y.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=>BOm(m))){let m=d.findIndex(g=>G_u(g)!==void 0);if(m!==-1){let g=n[m],A=d[m];if(g&&A){let y=G_u(A),x=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${m}]`],context:this.context,schema:r==="oneOf"?{...t,...g,oneOf:void 0}:g,example:y,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(x.isValid)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:x.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),y=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(y.isValid&&!y.coerced&&y.usedProvidedExample)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:y.validExample,errors:[]};if(y.isValid&&!y.coerced&&this.example===void 0)return{isValid:!0,coerced:!1,usedProvidedExample:y.usedProvidedExample,validExample:y.validExample,errors:[]};o.push(y),y.isValid&&y.usedProvidedExample&&a===null&&(a=y),y.isValid&&s===null&&(s=y)}let c=a??s,u=c!==null,l=c?.validExample??o[0]?.validExample,p=c?.usedProvidedExample??!1;return{isValid:u,coerced:!1,usedProvidedExample:p,validExample:l,errors:u?[]: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(TOm);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,y]of Object.entries(g.mergedProperties))if(typeof y=="object"&&y!==null){let I=a[A];I!=null&&oVe(I)&&oVe(y)?a[A]={...I,...y}:a[A]=y}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&&oVe(A)&&oVe(g)?a[m]={...A,...g}:a[m]=g}}}}let u={...o};for(let[p,d]of Object.entries(u)){let f=a[p];if(f==null||!oVe(d))continue;let m="$ref"in f?this.context.resolveMaybeReference({schemaOrReference:f,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):f;m!=null&&(u[p]={...m,...d})}for(let[p,d]of Object.entries(a))p in u||(u[p]=d);let l={mergedProperties:u,mergedRequired:[...c]};return i&&this.cacheMergedAllOfProperties(t,n,l),l}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=>OOm.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 q_u(e){return IC({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return $r.primitive({v1:"BASE_64",v2:vi.base64({})});case"BOOLEAN":return $r.primitive({v1:"BOOLEAN",v2:vi.boolean({default:void 0})});case"DATE":return $r.primitive({v1:"DATE",v2:vi.date({})});case"DATE_TIME":return $r.primitive({v1:"DATE_TIME",v2:vi.dateTime({})});case"DATE_TIME_RFC_2822":return $r.primitive({v1:"DATE_TIME_RFC_2822",v2:vi.dateTimeRfc2822({})});case"FLOAT":return $r.primitive({v1:"FLOAT",v2:vi.float({default:void 0,validation:void 0})});case"DOUBLE":return $r.primitive({v1:"DOUBLE",v2:vi.double({default:void 0,validation:void 0})});case"UINT":return $r.primitive({v1:"UINT",v2:vi.uint({default:void 0,validation:void 0})});case"UINT_64":return $r.primitive({v1:"UINT_64",v2:vi.uint64({default:void 0,validation:void 0})});case"INTEGER":return $r.primitive({v1:"INTEGER",v2:vi.integer({default:void 0,validation:void 0})});case"LONG":return $r.primitive({v1:"LONG",v2:vi.long({default:void 0,validation:void 0})});case"STRING":return $r.primitive({v1:"STRING",v2:vi.string({default:void 0,validation:void 0})});case"UUID":return $r.primitive({v1:"UUID",v2:vi.uuid({})});case"BIG_INTEGER":return $r.primitive({v1:"BIG_INTEGER",v2:vi.bigInteger({default:void 0})});default:return}},unknown:()=>$r.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return $r.container(Cs.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return $r.container(Cs.list(t))},optional:t=>{if(t!=null)return $r.container(Cs.optional(t))},nullable:t=>{if(t!=null)return $r.container(Cs.nullable(t))},set:t=>{if(t!=null)return $r.container(Cs.set(t))},literal:t=>$r.container(Cs.literal(t._visit({string:r=>rE.string(r),boolean:r=>rE.boolean(r),_other:()=>{throw new T({message:"Unexpected literal type",code:T.Code.InternalError})}}))),named:()=>{}}})}var W_u=h(()=>{"use strict";Ao();Hn();Dt()});var rwe,IJr=h(()=>{"use strict";Hn();fc();Xo();rwe=class extends io{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:pc.enum({default:n!=null?r.find(i=>ar(i.name)===n):void 0,values:r,forwardCompatible:this.forwardCompatible||void 0})}}}});var vJr,H_u=h(()=>{"use strict";Hn();Xo();Wut();sVe();vJr=class extends io{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=$r.container(Cs.map({keyType:io.STRING,valueType:$r.unknown()}));return{type:pc.alias({aliasOf:t,resolvedType:t}),referencedTypes:new Set,inlinedTypes:{}}}}tryConvertTypedMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean")return;let r=new ZT({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schemaOrReferenceOrBoolean}).convert();if(r!=null){let n=$r.container(Cs.map({keyType:io.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 O4(r.type,i),{type:pc.alias({aliasOf:n,resolvedType:n}),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}}});function Y_u(e,t,r){let n=X_u(t,r),i={};for(let o of n)i=m8o(i,o);return jOm(i,e),i}function X_u(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 u of s)if("$ref"in u){if(t==null)continue;let l=u.$ref;if(n.has(l))continue;n.add(l);let p=t(u);p!=null&&c.push(p)}else c.push(u);i.push(...X_u(c,t,n)),Object.keys(a).length>0&&i.push(a)}else i.push(o);return i}function m8o(e,t){let r={...e};for(let[n,i]of Object.entries(t)){if(i===void 0||FOm.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]=NOm(o??{},i);continue}if(n==="items"){jr(o)&&jr(i)?r[n]=m8o(o,i):r[n]=i;continue}if(K_u.includes(n)){jr(o)&&jr(i)?r[n]=Z_u(o,i):r[n]=i;continue}if(J_u.includes(n)){r[n]=!!o||!!i;continue}if(DOm.includes(n)){typeof o=="number"&&typeof i=="number"?r[n]=Math.max(o,i):r[n]=i;continue}if(kOm.includes(n)){typeof o=="number"&&typeof i=="number"?r[n]=Math.min(o,i):r[n]=i;continue}r[n]=i}return r}function NOm(e,t){let r={...e};for(let[n,i]of Object.entries(t)){let o=r[n];jr(o)&&jr(i)?r[n]=m8o(o,i):r[n]=i}return r}function Z_u(e,t){let r={...e};for(let[n,i]of Object.entries(t)){let o=r[n];jr(o)&&jr(i)?r[n]=Z_u(o,i):r[n]=i}return r}function jOm(e,t){for(let r of ROm){let n=t[r];n!=null&&(e[r]=n)}for(let r of K_u){let n=t[r];n!=null&&(e[r]=n)}for(let r of J_u)t[r]===!0&&(e[r]=!0)}var ROm,K_u,J_u,DOm,kOm,FOm,$_u=h(()=>{"use strict";ct();ROm=["description","title","format","type","discriminator","xml","externalDocs","extensions"],K_u=["example","default"],J_u=["deprecated","readOnly","writeOnly","uniqueItems","nullable"],DOm=["minimum","exclusiveMinimum","minLength","minItems","minProperties"],kOm=["maximum","exclusiveMaximum","maxLength","maxItems","maxProperties"],FOm=["allOf","oneOf","anyOf"]});var Hut,h8o=h(()=>{"use strict";ct();Hn();fc();EJr();Xo();Wut();Hut=class extends io{schema;xmlEncoding;constructor({context:t,breadcrumbs:r,schema:n,id:i}){super({context:t,breadcrumbs:r}),this.schema=n,this.xmlEncoding=new Gut({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:pc.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}=aVe({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,u=n,l=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 R=this.context.resolveMaybeReference({schemaOrReference:f,breadcrumbs:m});if(R==null){this.context.logger.debug?.(`[ObjectSchemaConverter] allOf[${d}] reference could not be resolved. Skipping: ${JSON.stringify(f)}`);continue}if(g=R,typeof g.additionalProperties=="boolean"&&g.additionalProperties&&(t=!0),!c||Object.keys(g.properties??{}).every(D=>!this.schema.required?.includes(D))){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 y=g.oneOf??g.anyOf;if(y!=null&&g.type==null&&g.properties==null){let R=new Set(r.map(D=>ar(D.name)));for(let[D,O]of y.entries()){let z=[...m,g.oneOf!=null?"oneOf":"anyOf",D.toString()],Y=this.context.isReferenceObject(O)?this.context.resolveMaybeReference({schemaOrReference:O,breadcrumbs:z}):O;if(Y==null)continue;let $={};for(let[Re,ce]of Object.entries(Y.properties??{}))!this.context.isReferenceObject(ce)&&"not"in ce||($[Re]=ce);let ee=Object.keys($).filter(Re=>!R.has(Re));if(ee.length===0)continue;let ae={};for(let Re of ee){let ce=$[Re];ce!=null&&(ae[Re]=ce,R.add(Re))}let{convertedProperties:pe,inlinedTypesFromProperties:oe,referencedTypes:me,propertiesByAudience:Se}=aVe({properties:ae,required:[],breadcrumbs:z,context:this.context,errorCollector:this.context.errorCollector,withinXmlElement:this.xmlEncoding!=null});r.push(...pe),u={...u,...oe},l={...l,...Se},me.forEach(Re=>{a.add(Re)})}continue}let I=g.properties??{};if(A){I={};for(let[R,D]of Object.entries(g.properties??{})){let O=p[R];O!=null&&!this.context.isReferenceObject(D)?I[R]={...O,...D}:I[R]=D}}let{convertedProperties:x,inlinedTypesFromProperties:v,referencedTypes:S,propertiesByAudience:B}=aVe({properties:I,required:[...this.schema.required??[],...g.required??[],...ufe(g)],breadcrumbs:m,context:this.context,errorCollector:this.context.errorCollector,withinXmlElement:this.xmlEncoding!=null});r.push(...x),u={...u,...v},l={...l,...B},S.forEach(R=>{a.add(R)})}for(let d of Object.keys(u))a.add(d);return{type:pc.object({properties:r,extends:s.map(d=>this.context.typeReferenceToDeclaredTypeName(d)).filter(fa),extendedProperties:[],extraProperties:t,deferredUnionBaseProperties:void 0}),propertiesByAudience:l,referencedTypes:a,inlinedTypes:u,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 zOm(e){return e.type==="union"&&e.types.length===0}function QOm({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 cVe,g8o=h(()=>{"use strict";Hn();u8o();l8o();p8o();Xo();Wut();IJr();CJr();sVe();cVe=class extends io{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 _ut({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&&!zOm(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 u;if(this.context.isReferenceObject(c)){let l=this.context.resolveReference({reference:c,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});l.resolved&&(u=l.value)}else u=c;u!=null&&(u.enum!=null&&u.enum.length>1&&(u.type==="string"||u.type==null)?r=u:u.type==="string"&&u.enum==null&&(n=!0))}if(r==null||!n)return;let o=new Vut({breadcrumbs:this.breadcrumbs,schema:r,context:this.context}).convert(),a=new rwe({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?QOm({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 u=s.$ref,l=u.split("/").pop(),p=this.context.getTypeIdFromSchemaReference(s),d=c??l;if(p==null||d==null)return[];i.push({discriminant:d,typeId:p,ref:u,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:l,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),y=d!=null&&d===this.getEnclosingComponentRef(),I=f?.properties!=null&&t in f.properties&&!((A||y)&&d!=null);if(I&&f!=null&&(g=this.filterDiscriminantFromSchema(f,t)),g==null)continue;let x=new ZT({context:this.context,schemaOrReference:g,schemaIdOverride:p??void 0,breadcrumbs:m});p!=null&&n.add(p);let v=I&&p!=null&&!A;v&&this.context.discriminatedVariantsInProgress.add(p);let S;try{S=x.convert()}finally{v&&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 B=this.context.casingsGenerator.generateNameAndWireValue({name:l,wireValue:l}),R=d?.split("/").pop()??p,D=f?.title,O=f?.description,z=D??l??R;S.schema?.typeDeclaration!=null&&D!=null&&(S.schema.typeDeclaration.name.displayName=D),r.push({docs:O,discriminantValue:B,availability:S.availability,displayName:z,shape:tT.samePropertiesAsObject({typeId:p,name:this.context.casingsGenerator.generateName(R),fernFilepath:{allParts:[],packagePath:[],file:void 0},displayName:z})}),i={...i,...S.inlinedTypes}}}let{convertedProperties:o,referencedTypes:s,inlinedTypesFromProperties:a}=aVe({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[l,p]of(this.schema.allOf??[]).entries()){let d=[...this.breadcrumbs,"allOf",l.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 l of Object.keys({...i,...a}))n.add(l);let u=new Uut({context:this.context,breadcrumbs:[...this.breadcrumbs,"discriminator"],node:this.schema.discriminator});return{type:pc.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:u.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 y=this.getDiscriminatorKeyForRef(c);y!=null?g=this.context.convertReferenceToTypeReference({reference:c,displayNameOverride:y,displayNameOverrideSource:"discriminator_key"}):g=this.context.convertReferenceToTypeReference({reference:c,breadcrumbs:this.breadcrumbs})}if(g.ok){let y=this.context.resolveReference({reference:c,breadcrumbs:this.breadcrumbs}),I=y.resolved?y.value.description:void 0;t.push({type:g.reference,docs:I})}let A=this.context.getTypeIdFromSchemaReference(c);A!=null&&r.add(A);continue}let l=Object.keys(this.schema.properties??{}).length>0?void 0:this.extendSubSchema(c),p=this.context.convertBreadcrumbsToName([`${this.id}_${a}`]),d=c.title,m=new nwe({context:this.context,id:p,nameOverride:d,breadcrumbs:[...this.breadcrumbs,`oneOf[${a}]`],schema:l??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:$r.container(Cs.map({keyType:io.STRING,valueType:$r.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 y of Object.keys(m.inlinedTypes))r.add(y)}m.convertedSchema.typeDeclaration.referencedTypes.forEach(A=>{r.add(A)})}}let{convertedProperties:i,referencedTypes:o,inlinedTypesFromProperties:s}=aVe({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:pc.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 ZT({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(n==null)return;let i=this.wrapInNullable(n.type);return{type:pc.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 $r.container(Cs.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 Kut,A8o=h(()=>{"use strict";Hn();Xo();Kut=class extends io{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 $r.container(Cs.literal(rE.string(t)));if(this.schema.format==="date-time-rfc-2822")return $r.primitive({v1:ds.DateTimeRfc2822,v2:vi.dateTimeRfc2822({})});if(this.context.settings.typeDatesAsStrings===!1){if(this.schema.format==="date")return $r.primitive({v1:ds.Date,v2:vi.date({})});if(this.schema.format==="date-time")return $r.primitive({v1:ds.DateTime,v2:vi.dateTime({})})}return $r.primitive({v1:"STRING",v2:vi.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":switch(this.schema.format){case"double":return $r.primitive({v1:"DOUBLE",v2:vi.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return $r.primitive({v1:"FLOAT",v2:vi.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return $r.primitive({v1:"INTEGER",v2:vi.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return $r.primitive({v1:"LONG",v2:vi.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return $r.primitive({v1:"UINT",v2:vi.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return $r.primitive({v1:"UINT_64",v2:vi.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return $r.primitive({v1:"DOUBLE",v2:vi.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"integer":switch(this.schema.format){case"double":return $r.primitive({v1:"DOUBLE",v2:vi.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return $r.primitive({v1:"FLOAT",v2:vi.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return $r.primitive({v1:"INTEGER",v2:vi.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return $r.primitive({v1:"LONG",v2:vi.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return $r.primitive({v1:"UINT",v2:vi.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return $r.primitive({v1:"UINT_64",v2:vi.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return $r.primitive({v1:"INTEGER",v2:vi.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?$r.container(Cs.literal(rE.boolean(t))):$r.primitive({v1:"BOOLEAN",v2:vi.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 LOm(e){let t=ufe(e);return t.length===0?e:{...e,required:[...new Set([...e.required??[],...t])]}}var MOm,nwe,CJr=h(()=>{"use strict";ct();Hn();Xo();Wut();W_u();twe();y8o();IJr();H_u();$_u();h8o();g8o();A8o();MOm=["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],nwe=class e extends io{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 u=this.tryConvertSiblingAnyOfConstraint();if(u!=null)return u;let l=this.tryConvertSiblingOneOfConstraint();if(l!=null)return l;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 O4(r.reference,n),{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:pc.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 _C.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),i=new rwe({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 u;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;u=d}else u=c;let l=u.oneOf??u.anyOf;if(!this.context.isReferenceObject(c)&&l!=null&&u.type==null&&u.properties==null){let p={};for(let d of l){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(LOm(u))}if(i)return;let o=Y_u(this.schema,n,c=>{let u=this.context.resolveMaybeReference({schemaOrReference:c,breadcrumbs:this.breadcrumbs});if(!(u!=null&&this.context.isReferenceObject(u)))return u}),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,u)=>c*u.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,u)=>u!==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 u=this.getVariantTitle(c);return{...u!=null?{title:u}:{},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 Kut({context:this.context,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:pc.alias({aliasOf:r,resolvedType:r}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertArraySchema(){if(this.schema.type==="array"){let r=new Jut({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:pc.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||!UMe(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(!VMe(this.schema)||new _C.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=ufe(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 cVe({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 vJr({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 cVe({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 Hut({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:pc.alias({aliasOf:$r.unknown(),resolvedType:$r.unknown()}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertFernTypeDeclaration(){let r=new _C.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r==null)return;let n=q_u(r);if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:pc.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=[...MOm,...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 Jw({breadcrumbs:this.breadcrumbs,context:this.context,schema:this.schema,example:t}),{validExample:n}=r.convert();return n}}});function UOm(e){return Object.keys(e).every(t=>_Om.has(t))}var ZT,_Om,sVe=h(()=>{"use strict";Hn();Xo();CJr();ZT=class extends io{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=>UOm(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 nwe({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 $r.container(Cs.optional(t))}wrapInNullable(t){return $r.container(Cs.nullable(t))}},_Om=new Set(["description","title","deprecated","readOnly","writeOnly","xml","externalDocs","x-fern-type-name"])});function aVe({properties:e,required:t,breadcrumbs:r,context:n,errorCollector:i,withinXmlElement:o=!1}){let s=[],a={},c={},u=new Set;for(let[l,p]of Object.entries(e??{})){let d=[...r,"properties",l];if(typeof p!="object"){i.collect({message:`Schema property ${l} should be an object`,path:d});continue}let f=GOm(r,p,n)??n.convertBreadcrumbsToName(d),m="nullable"in p?p.nullable:!1,A=new ZT({context:n,breadcrumbs:d,schemaOrReference:p,schemaIdOverride:f,wrapAsOptional:!t.includes(l),wrapAsNullable:m}).convert();if(A!=null){let y=n.resolveMaybeReference({schemaOrReference:p,breadcrumbs:d,skipErrorCollector:!0});s.push({name:n.casingsGenerator.generateNameAndWireValue({name:l,wireValue:l}),valueType:A.type,docs:p.description??A.schema?.typeDeclaration.docs,availability:A.availability,propertyAccess:n.getPropertyAccess(p),defaultValue:y?.default,xml:o?new qut({breadcrumbs:d,propertySchema:p,resolvedPropertySchema:y??void 0,context:n}).convert():void 0,v2Examples:A.schema?.typeDeclaration?.v2Examples??VOm({propertySchema:p,breadcrumbs:d,context:n,propertyId:f})}),a={...a,...A.inlinedTypes},A.schema?.typeDeclaration.referencedTypes!=null&&A.schema.typeDeclaration.referencedTypes.forEach(I=>{u.add(I)}),O4(A.type,u);for(let I of A.schema?.audiences??[])c[I]==null&&(c[I]=new Set),c[I].add(l)}}for(let l of Object.keys(a))u.add(l);return{convertedProperties:s,propertiesByAudience:c,inlinedTypesFromProperties:a,referencedTypes:u}}function VOm({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 u={};for(let[l,p]of o.entries()){let d=r.resolveExample(p),f=`${n}_example_${l}`,m=new Jw({breadcrumbs:t,context:r,schema:e,example:d}),{validExample:g}=m.convert();u[f]=g}return{userSpecifiedExamples:u,autogeneratedExamples:{}}}let s=`${n}_example_autogenerated`,a=new Jw({breadcrumbs:t,context:r,schema:e,example:void 0,generateOptionalProperties:!0}),{validExample:c}=a.convert();return{userSpecifiedExamples:{},autogeneratedExamples:{[s]:c}}}function GOm(e,t,r){return r.isReferenceObject(t)?void 0:new _C.FernTypeNameExtension({breadcrumbs:e,schema:t,context:r}).convert()}function O4(e,t){switch(e.type){case"named":t.add(e.typeId);return;case"primitive":case"unknown":return;case"container":qOm(e.container,t);return}}function qOm(e,t){switch(e.type){case"list":O4(e.list,t);return;case"set":O4(e.set,t);return;case"optional":O4(e.optional,t);return;case"nullable":O4(e.nullable,t);return;case"map":O4(e.keyType,t),O4(e.valueType,t);return;case"literal":return}}var Wut=h(()=>{"use strict";twe();sVe();EJr();Xo()});var Jut,y8o=h(()=>{"use strict";Hn();Xo();Wut();sVe();Jut=class e extends io{static LIST_UNKNOWN=$r.container(Cs.list($r.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 ZT({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)})}),O4(r.type,n),{typeReference:$r.container(Cs.list(r.type)),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}}});var b8o={};te(b8o,{ArraySchemaConverter:()=>Jut,EnumSchemaConverter:()=>rwe,ObjectSchemaConverter:()=>Hut,OneOfSchemaConverter:()=>cVe,PrimitiveSchemaConverter:()=>Kut,SchemaConverter:()=>nwe,SchemaOrReferenceConverter:()=>ZT});var E8o=h(()=>{"use strict";y8o();IJr();h8o();g8o();A8o();CJr();sVe()});var xJr,eUu=h(()=>{"use strict";Gi();Xo();twe();E8o();xJr=class extends io{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 ZT({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,u])=>{if(this.context.isReferenceObject(u)){let l=this.context.resolveReference({reference:u,breadcrumbs:[...this.breadcrumbs,"content",n,"examples"],skipErrorCollector:!0});return l.resolved?[c,l.value.value??l.value]:null}return[c,u.value??u]}).filter(c=>c!=null)):void 0;return{...s,examples:a}}parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:r}){let i=new ZT({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,u]of s){let l=this.context.resolveExampleWithValue(u),p=this.context.resolveExampleRecursively({example:u,breadcrumbs:this.breadcrumbs}),d=this.getIdForExample({key:c,example:p,usedExampleNames:a});a.add(d),l!=null&&(o!=null?i.userSpecifiedExamples[d]=this.generateOrValidateExample({schema:o,example:l,exampleGenerationStrategy:n,exampleName:d}):i.userSpecifiedExamples[d]=l)}if(o!=null&&Object.keys(i.userSpecifiedExamples).length===0){let c=this.getExamplesFromSchemaOrReference(o);c.length>1&&c.forEach((u,l)=>{let p=`Example ${l+1}`;i.userSpecifiedExamples[p]=this.generateOrValidateExample({schema:o,example:u,exampleGenerationStrategy:n,exampleName:p})})}if(Object.keys(i.userSpecifiedExamples).length===0&&o!=null){let c=ri(`${[...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 Jw({breadcrumbs:this.breadcrumbs,context:this.context,schema:o,example:r??s[0],generateOptionalProperties:n??!1,exampleGenerationStrategy:i}),{validExample:c}=a.convert();return c}}});var SJr,tUu=h(()=>{"use strict";Xo();twe();SJr=class extends io{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??io.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??io.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??io.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 Jw({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 I8o={};te(I8o,{AbstractMediaTypeObjectConverter:()=>xJr,AbstractParameterConverter:()=>SJr});var rUu=h(()=>{"use strict";eUu();tUu()});function Yut({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 u=WOm({context:e,header:c}),l=u?.schema,p=c.required===!0,d=y=>p?y:$r.container(Cs.optional(y)),f=d(io.STRING),m,g=e.getAvailability({node:c,breadcrumbs:[...o,"headers",s]});if(l!=null)if(m=e.resolveMaybeReference({schemaOrReference:l,breadcrumbs:[...o,"headers",s,"schema"]}),m?.type==="number"||m?.type==="integer")f=d($r.primitive({v1:m.type==="integer"?"INTEGER":"DOUBLE",v2:m.type==="integer"?vi.integer({default:void 0,validation:void 0}):vi.double({default:void 0,validation:void 0})}));else if(m?.type==="boolean")f=d($r.primitive({v1:"BOOLEAN",v2:vi.boolean({default:void 0})}));else{let y=new ZT({context:e,breadcrumbs:[...o,"headers",s,"schema"],schemaOrReference:l,wrapAsOptional:!p,schemaIdOverride:e.convertBreadcrumbsToName([...o,"headers",s])}).convert();if(y!=null){f=y.type;for(let[I,x]of Object.entries(y.inlinedTypes))i[I]=x}}let A=HOm({context:e,breadcrumbs:o,header:c,headerName:s,schema:l,mediaTypeObject:u?.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 WOm({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&&Zp.parse(r)?.isJSON())return{schema:n.schema,mediaTypeObject:n}}}function HOm({context:e,breadcrumbs:t,header:r,headerName:n,schema:i,mediaTypeObject:o}){let s={userSpecifiedExamples:{},autogeneratedExamples:{}},a=r.example,c=r.examples;for(let[u,l]of Object.entries(c??{})){let p=e.resolveExampleWithValue(l);p!=null&&(s.userSpecifiedExamples[u]=M9t({context:e,breadcrumbs:t,schema:i,example:p}))}if(a!=null){let u=e.generateUniqueName({prefix:`${n}_example`,existingNames:Object.keys(s.userSpecifiedExamples)});s.userSpecifiedExamples[u]=M9t({context:e,breadcrumbs:t,schema:i,example:a})}if(Object.keys(s.userSpecifiedExamples).length===0&&o!=null)for(let[u,l]of e.getNamedExamplesFromMediaTypeObject({mediaTypeObject:o,breadcrumbs:[...t,"headers",n,"content"],defaultExampleName:`${n}_example`})){let p=e.resolveExampleWithValue(l);if(p!=null){let d=e.generateUniqueName({prefix:u,existingNames:Object.keys(s.userSpecifiedExamples)});s.userSpecifiedExamples[d]=M9t({context:e,breadcrumbs:t,schema:i,example:p})}}if(Object.keys(s.userSpecifiedExamples).length===0&&i!=null){let u=e.getExamplesFromSchema({schema:KOm({context:e,schema:i,breadcrumbs:[...t,"headers",n,"schema"]}),breadcrumbs:[...t,"headers",n,"schema"]});for(let l of u){let p=e.generateUniqueName({prefix:`${n}_example`,existingNames:Object.keys(s.userSpecifiedExamples)});s.userSpecifiedExamples[p]=M9t({context:e,breadcrumbs:t,schema:i,example:e.resolveExample(l)})}}if(Object.keys(s.userSpecifiedExamples).length===0&&i!=null){let u=`${n}_example`;s.autogeneratedExamples[u]=M9t({context:e,breadcrumbs:t,schema:i,example:void 0,ignoreErrors:!0})}return s}function KOm({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 M9t({context:e,breadcrumbs:t,schema:r,example:n,ignoreErrors:i}){if(r==null)return n;let o=new Jw({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 nUu=h(()=>{"use strict";ct();Hn();pJr();twe();sVe()});var wJr,iUu=h(()=>{"use strict";XD();wJr=class extends es{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 oUu,JOm,P4,sUu=h(()=>{"use strict";ct();Hn();c8o();iUu();Xo();oUu="Base",JOm="x-fern-default-url",P4=class e extends io{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 u=e.getServerName({server:c,context:this.context});return{id:u,name:this.context.casingsGenerator.generateName(u)}}).filter((c,u,l)=>l.findIndex(p=>p.id===c.id)===u),s=[i,...o],a=this.servers.map(c=>{let u=e.getServerName({server:c,context:this.context}),l=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:u,name:this.context.casingsGenerator.generateName(u),urls:{[n]:this.getServerUrl(c),...Object.fromEntries(l??[])},docs:c.description,audiences:p,defaultUrls:d,urlTemplates:f,urlVariables:m}});return{value:{defaultEnvironment:a[0]?.id,baseUrlEnvVar:this.baseUrlEnvVar,environments:eE.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(fa);return{value:{defaultEnvironment:r[0]?.id,baseUrlEnvVar:this.baseUrlEnvVar,environments:eE.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 wJr({breadcrumbs:[],server:t,context:r}).convert()}static getServerAudiences({server:t,context:r}){return new Lut({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?oUu:e.getServerExtensionName({server:this.servers[0],context:this.context})??oUu}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 u=e.getServerName({server:c,context:this.context});if(c.variables!=null&&Object.keys(c.variables).length>0){a=!0;let l=this.extractFernDefaultUrlFromServer(c);l!=null&&(i[u]=l),o[u]=this.maybeRemoveTrailingSlashIfNotEmpty(c.url),s[u]=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[JOm];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 Um={};te(Um,{AbstractConverters:()=>I8o,ExampleConverter:()=>Jw,SchemaConverters:()=>b8o,ServersConverter:()=>P4,convertResponseHeaders:()=>Yut});var v8o=h(()=>{"use strict";rUu();twe();nUu();E8o();sUu()});var L9t,aUu=h(()=>{"use strict";twe();Q9t();L9t=class{context;constructor({context:t}){this.context=t}validateExample({example:t,schema:r,breadcrumbs:n,exampleGenerationStrategy:i}){return new Jw({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 u=this.validateExample({example:t.requestExample,schema:t.requestSchema,breadcrumbs:[...a,"request"],exampleGenerationStrategy:"request"});if(!u.isValid){i=!1;let l=t.exampleSource==="human"?AE.WARNING:AE.ERROR;r.push(...u.errors.map(p=>({...p,level:l,message:`Invalid request example: ${p.message}`})))}u.coerced&&(o=!0,n.push({level:AE.WARNING,message:"Request example was coerced to match schema",path:[...a,"request"]})),s={request:u.validExample}}let c=this.getResponseSchemaForValidation(t);if(t.responseExample!==void 0&&c!==void 0){let u=this.validateExample({example:t.responseExample,schema:c,breadcrumbs:[...a,"response"],exampleGenerationStrategy:"response"});if(!u.isValid){i=!1;let l=t.exampleSource==="human"?AE.WARNING:AE.ERROR;r.push(...u.errors.map(p=>({...p,level:l,message:`Invalid response example: ${p.message}`})))}u.coerced&&(o=!0,n.push({level:AE.WARNING,message:"Response example was coerced to match schema",path:[...a,"response"]})),s={...typeof s=="object"&&s!==null?s:{},response:u.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}),u={endpointPath:o.endpointPath,method:o.method,exampleSource:"ai",requestExample:o.request?.body,responseExample:o.response?.body,requestSchema:s,responseSchema:a,responseSchemas:c},l=this.validateEndpointExample({exampleToValidate:u}),p=this.hasUnexpectedProperties({requestExample:o.request?.body,responseExample:o.response?.body,requestSchema:s,responseSchema:a}),d=l.errors.length>0||l.warnings.length>0;!l.isValid||d||p?i.push({example:o,validationResult:l}):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,u]of Object.entries(t.paths)){if(!u)continue;let l=["get","post","put","delete","patch","options","head","trace"];for(let p of l){let d=u[p];if(!d)continue;let f=[],{requestSchema:m,responseSchema:g,responseSchemas:A}=this.getSchemasForOperation({operation:d}),y=this.extractExamplesFromOperation({operation:d,path:c,method:p});for(let I of y){n++;let x={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},v=this.validateEndpointExample({exampleToValidate:x});f.push(v),v.isValid?i++:(o++,I.source==="human"?s.push(v):I.source==="ai"&&a.push(v))}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,u]of Object.entries(a.examples)){let l=this.context.isReferenceObject(u)?this.context.resolveExample(u):u;l&&typeof l=="object"&&"value"in l&&i.push({name:c,source:"human",request:l.value})}}if(t.responses)for(let[s,a]of Object.entries(t.responses)){if(!a||this.context.isReferenceObject(a))continue;let u=a.content?.["application/json"];if(u?.example!==void 0){let l=i.find(p=>p.request!==void 0&&p.response===void 0);l?(l.response=u.example,l.statusCode=s):i.push({name:`${n}_${r}_response_${s}_example`,source:"openapi",response:u.example,statusCode:s})}if(u?.examples)for(let[l,p]of Object.entries(u.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===l);f?(f.response=d.value,f.statusCode=s):i.push({name:l,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 cUu({tags:e,errorCollector:t}){for(let r of e)if(Xut.test(r.name)){let n=[...r.name].filter(i=>Xut.test(i));t.collect({level:AE.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(Xut,"").trim()}".`})}}function uUu({description:e,path:t,errorCollector:r}){YOm.test(e)&&r.collect({level:AE.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 C8o({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");cUu({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 u=c;if(typeof u.description=="string"&&uUu({description:u.description,path:["paths",i,a,"description"],errorCollector:t}),Array.isArray(u.tags)&&!Array.isArray(e.tags)){for(let l of u.tags)if(typeof l=="string"&&!n.has(l)&&Xut.test(l)){n.add(l);let p=[...l].filter(d=>Xut.test(d));t.collect({level:AE.ERROR,message:`Tag name "${l}" 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 "${l}" to "${l.replace(Xut,"").trim()}".`})}}}}}}var Xut,YOm,lUu=h(()=>{"use strict";Q9t();Xut=new RegExp("[^\\x00-\\x7F]"),YOm=/(?:^|\n)\s*---\s*(?:\n|$)/});var TJr,XOm,pUu=h(()=>{"use strict";TJr={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"},XOm=new Set(Object.values(TJr))});function x8o(e){if(e!=null)return e.map(t=>Object.fromEntries(Object.entries(t).map(([r,n])=>[r,n??[]])))}var fUu=h(()=>{"use strict"});var Xo=h(()=>{"use strict";pJr();S_u();XD();U_u();v8o();v8o();Q9t();aUu();d8o();lUu();pUu();fUu()});var ZOm,$Om,dUu,mUu=h(()=>{"use strict";an();ZOm=Fe.object({type:Fe.string(),channelId:Fe.string().optional(),messageId:Fe.string(),value:Fe.any()}),$Om=Fe.object({summary:Fe.string().optional(),description:Fe.string().optional(),"query-parameters":Fe.record(Fe.string()).optional(),headers:Fe.record(Fe.string()).optional(),messages:Fe.array(ZOm)}),dUu=Fe.array($Om)});var OJr,hUu=h(()=>{"use strict";Xo();mUu();OJr=class extends es{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=dUu.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 Zut,S8o=h(()=>{"use strict";Xo();hUu();Zut=class extends io{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 OJr({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 ePm,CJ,_9t=h(()=>{"use strict";Hn();Xo();ePm="x-fern-server-name",CJ=class e extends io{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:eE.singleBaseUrl({environments:t})}}static getServerName(t,r){if(r!=null&&typeof r=="object"){let n=r[ePm];if(typeof n=="string"&&n.length>0)return n}return t}constructServerUrl(t,r){return r.includes("://")?r:`${t}://${r}`}}});var iwe,w8o=h(()=>{"use strict";Xo();iwe=class extends Um.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 _C.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 Um.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 PJr,gUu=h(()=>{"use strict";Xo();PJr=class extends es{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 owe,T8o=h(()=>{"use strict";Xo();owe=class extends es{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 swe,O8o=h(()=>{"use strict";Xo();swe=class extends es{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 BJr,AUu=h(()=>{"use strict";Xo();BJr=class extends es{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 RJr,yUu=h(()=>{"use strict";Hn();fc();Xo();Gi();S8o();_9t();w8o();gUu();T8o();O8o();AUu();RJr=class extends Zut{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 owe({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 l=new PJr({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert(),p=this.transformToValidPath(l??this.channelPath),d=this.resolveServerName(this.channel.servers?.[0])??this.resolveServerName(Object.keys(this.context.spec.servers??{})[0]),f=nb(p),m=ri(this.channelPath),g=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[],A=this.hasServerSecurity()||this.context.authOverrides?.auth!=null,y=new swe({context:this.context,breadcrumbs:this.breadcrumbs,node:this.context.spec}).convert(),x=new swe({context:this.context,breadcrumbs:this.breadcrumbs,node:this.channel}).convert()??y;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:x},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=$Me(ri(`${this.channelPath}_${o}`)).replace(/ /g,"");if("oneOf"in r.message){let l=new Um.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:s,schemaOrReference:r.message,schemaIdOverride:c}).convert();l!=null&&l.schema!=null&&(i=l.schema,this.inlinedTypes={...this.inlinedTypes,...l.inlinedTypes})}else if(t.isMessageWithPayload(r.message)){let u=t.resolveMaybeReference({schemaOrReference:r.message.payload,breadcrumbs:s});if(u!=null){let p=new Um.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:s,schemaOrReference:u,schemaIdOverride:c}).convert();p!=null&&p.schema!=null&&(i=p.schema,this.inlinedTypes={...this.inlinedTypes,...p.inlinedTypes})}}if(i!=null){let u=i,l=$r.named({fernFilepath:t.createFernFilepath(),name:u.typeDeclaration.name.name,typeId:u.typeDeclaration.name.typeId,displayName:void 0,default:void 0,inline:!1}),p=uB.reference({bodyType:l,docs:r.description}),d=n==="server"?"subscribe":"publish",m=new owe({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 iwe({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 iwe({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 CJ.getServerName(t,n)}return t}getOperationMethodName(t){return new BJr({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 iwe({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 DJr,bUu=h(()=>{"use strict";_9t();DJr=class extends CJ{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 P8o,EUu,B8o,kJr,IUu=h(()=>{"use strict";Hn();fc();Dt();S8o();_9t();w8o();T8o();O8o();P8o="$message.",EUu="#/channels/",B8o="#/servers/",kJr=class extends Zut{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 owe({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,[y,I])=>{try{this.getChannelPathFromOperation(I)===this.channelPath&&(A[y]=I)}catch{}return A},{}),a=[];for(let[A,y]of Object.entries(s)){let x=new owe({breadcrumbs:[...this.breadcrumbs,A],node:y,context:this.context}).convert()??A;for(let v of y.messages){let S=this.context.convertReferenceToTypeReference({reference:v});if(S.ok){let B=this.resolveMessageDocs(v)??y.description,R=uB.reference({bodyType:S.reference,docs:B});a.push({type:A,displayName:x,origin:y.action==="send"?"client":"server",body:R,availability:this.context.getAvailability({node:y,breadcrumbs:this.breadcrumbs}),docs:B,methodName:void 0})}}}let c=this.resolveChannelServersFromReference(this.channel.servers??[])??this.resolveFirstServerName(),u=this.transformToValidPath(this.channel.address??this.channelPath),l=nb(u),p=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[],d=this.hasServerSecurity()||this.context.authOverrides?.auth!=null,f=new swe({context:this.context,breadcrumbs:this.breadcrumbs,node:this.context.spec}).convert(),g=new swe({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:l,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:u,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(B8o,""),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:u}=a,p=new iwe({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...s,name:u,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(P8o)){this.context.errorCollector.collect({message:`Invalid location format: ${t}; expected ${P8o} prefix`,path:this.breadcrumbs});return}let i=r.substring(P8o.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(B8o)){this.context.errorCollector.collect({message:`Failed to resolve server name from server ref ${r.$ref}`,path:this.breadcrumbs});return}let n=r.$ref.substring(B8o.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 CJ.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 CJ.getServerName(r,n)}getChannelPathFromOperation(t){if(!t.channel.$ref.startsWith(EUu))throw new T({message:`Failed to resolve channel path from operation ${t.channel.$ref}`,code:T.Code.ReferenceError});return t.channel.$ref.substring(EUu.length)}}});var FJr,vUu=h(()=>{"use strict";_9t();FJr=class extends CJ{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 U9t,CUu=h(()=>{"use strict";Hn();fc();Xo();yUu();bUu();IUu();vUu();U9t=class extends vJ{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 u=`${r}_${i}`;this.convertSchema({id:u,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 Um.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 FJr({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}else{let r=this.context.spec.servers;t=new DJr({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}this.addEnvironmentsToIr({environmentConfig:t})}convertSecuritySchemes(){if(this.context.authOverrides){let r=OGt({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 _p.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 _p.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 _p.header({key:r,name:{name:this.context.casingsGenerator.generateName("apiKey"),wireValue:t.name},valueType:io.OPTIONAL_STRING,prefix:void 0,headerEnvVar:void 0,headerPlaceholder:void 0,docs:t.description,playgroundDocs:void 0});break}case"oauth2":return _p.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 _C.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 kJr({context:this.context,breadcrumbs:["channels",t],websocketGroup:i,channel:r,channelPath:t,operations:a}).convert()}else o=new RJr({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 V9t,xUu=h(()=>{"use strict";Hn();Xo();V9t=class extends E0{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 u=a[1],l=a[2];return o=`${u}_${l}`,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:$r.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:$r.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:$r.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}}});var SUu=h(()=>{"use strict";CUu();xUu()});function rPm(e){let t=new Set,r,n=new RegExp(tPm.source,"g");for(;(r=n.exec(e))!=null;)r[1]!=null&&t.add(r[1]);return t}var tPm,NJr,wUu=h(()=>{"use strict";Xo();tPm=/\{([^}]+)\}/g,NJr=class extends es{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=rPm(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 u=o[c];if(u==null){s.push({name:c,type:"string",default:void 0,docs:void 0});continue}if(typeof u!="object"||Array.isArray(u)){this.context.errorCollector.collect({message:`Parameter '${c}' must be an object`,path:[...this.breadcrumbs,"parameters",c]});return}let l=u,p=typeof l.type=="string"?l.type:"string",d=typeof l.docs=="string"?l.docs:void 0;s.push({name:c,type:p,default:l.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 jJr,TUu=h(()=>{"use strict";Xo();jJr=class extends es{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 zJr,OUu=h(()=>{"use strict";Xo();zJr=class extends es{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 nPm(e){let r=e["x-fern-default"]??e.default;if(typeof r=="string"||typeof r=="boolean"||typeof r=="number")return r}var QJr,PUu=h(()=>{"use strict";Xo();QJr=class extends es{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:nPm(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 iPm(e){if(e!=null){if(typeof e=="string")return Xt.Literal.string(e);if(typeof e=="boolean")return Xt.Literal.boolean(e)}}function BUu({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:io.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:io.STRING,env:i.env,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}},availability:void 0,docs:i.docs,clientDefault:iPm(i.default),defaultValue:i.default})}return r}var RUu=h(()=>{"use strict";Hn();Xo()});function oPm(e){if(e!=null){if(typeof e=="string")return Xt.Literal.string(e);if(typeof e=="boolean")return Xt.Literal.boolean(e)}}function DUu({globalHeaders:e,context:t}){return e.map(r=>({name:t.casingsGenerator.generateNameAndWireValue({name:r.name??"",wireValue:r.header}),valueType:r.optional?io.OPTIONAL_STRING:io.STRING,env:r.env,v2Examples:r.optional?void 0:sPm({header:r,context:t}),availability:void 0,docs:void 0,clientDefault:oPm(r["x-fern-default"]),defaultValue:void 0}))}function sPm({header:e,context:t}){let r=new Jw({breadcrumbs:[],context:t,schema:{type:"string"},example:e.header}),{validExample:n}=r.convert();return{userSpecifiedExamples:{},autogeneratedExamples:{globalHeaderExample:n}}}var kUu=h(()=>{"use strict";Hn();Xo()});function aPm(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 Xt.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 Xt.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 Xt.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 cPm(e,t,r){switch(e){case void 0:case"body":return Xt.GlobalParameterLocation.Body;case"query":return Xt.GlobalParameterLocation.Query;case"header":return Xt.GlobalParameterLocation.Header;case"path":return Xt.GlobalParameterLocation.Path;default:return r.errorCollector.collect({message:`Invalid global parameter location '${e}'; expected one of: body, query, header, path`,path:t}),Xt.GlobalParameterLocation.Body}}function uPm(e,t,r){switch(e){case void 0:return;case"explicit":return Xt.GlobalParameterApplyMode.Explicit;case"auto":return Xt.GlobalParameterApplyMode.Auto;default:r.errorCollector.collect({message:`Invalid global parameter apply mode '${e}'; expected one of: explicit, auto`,path:t});return}}function lPm(e,t){let r=pPm(e);return t===!0?Xt.TypeReference.container(Xt.ContainerType.optional(r)):r}function pPm(e){switch(e){case"boolean":return Xt.TypeReference.primitive({v1:"BOOLEAN",v2:Xt.PrimitiveTypeV2.boolean({default:void 0})});case"integer":return Xt.TypeReference.primitive({v1:"INTEGER",v2:Xt.PrimitiveTypeV2.integer({default:void 0,validation:void 0})});case"double":case"number":return Xt.TypeReference.primitive({v1:"DOUBLE",v2:Xt.PrimitiveTypeV2.double({default:void 0,validation:void 0})});default:return io.STRING}}function fPm(e){return e.target!=null?e.target:e.name}function FUu({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=cPm(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:fPm(n),valueType:lPm(n.type,n.optional),env:n.env,clientDefault:aPm(n.default,n.type,o,t),optional:n.optional,apply:uPm(n.apply,[...o,"apply"],t),docs:n.docs}})}var NUu=h(()=>{"use strict";Hn();Xo()});var MJr,jUu=h(()=>{"use strict";ct();Xo();MJr=class extends Um.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 Um.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&&Zp.parse(t)?.isJSON())return r.schema}}}});function mPm({encoding:e}){if(e){if(e.explode)return"exploded";if(e.style==="form")return"form";if(e.contentType)return dPm[e.contentType]}}var LJr,dPm,zUu=h(()=>{"use strict";ct();Hn();fc();Xo();LJr=class extends Um.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:u,queryParameters:l}){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=u,this.queryParameters=l??[]}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(Zp.parse(this.contentType)?.isMultipart())return this.handleMultipartContent({contentType:this.contentType});if(this.isBinaryContentType())return this.handleBinaryContent({contentType:this.contentType})}isOrderedJsonOrFormContentType(){let t=Zp.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=Zp.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:Cd.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:Cd.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:Cd.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 u=this.context.resolveExampleWithValue(c),l=this.context.resolveExampleRecursively({example:c,breadcrumbs:this.breadcrumbs}),p=a;if(this.context.isExampleWithSummary(l)){let d=l.summary;s.has(d)||(p=d)}s.add(p),u!=null&&(i.userSpecifiedExamples[p]=u)}return{requestBody:Cd.reference({contentType:t,docs:this.description,requestBodyType:$r.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:Cd.fileUpload({contentType:t,docs:this.description,name:this.context.casingsGenerator.generateName(this.schemaId),properties:i.properties.map(o=>{let s=r.encoding?.[ar(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:Cd.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?Hx.file(sQ.fileArray({key:t.name,isOptional:o,contentType:r,docs:t.docs})):Hx.file(sQ.file({key:t.name,isOptional:o,contentType:r,docs:t.docs})):Hx.bodyProperty({...t,contentType:n?.contentType??r,style:mPm({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 u=c.schema?.typeDeclaration.shape;return u?.type==="object"?{requestBody:Cd.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:u.extendedProperties,extends:u.extends,properties:u.properties,extraProperties:u.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:a,exampleGenerationStrategy:"request"})}),inlinedTypes:c.inlinedTypes}:{requestBody:Cd.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=>ar(n.name).toLowerCase()));return t.some(n=>r.has(ar(n.name).toLowerCase()))}},dPm={"application/json":"json"}});function APm(e){return e?.header!=null}var hPm,gPm,$ut,R8o=h(()=>{"use strict";ct();Hn();fc();Xo();Gi();jUu();zUu();hPm=/{([^}]+)}/g,gPm=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]),$ut=class extends io{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 xm.Get;case"post":return xm.Post;case"put":return xm.Put;case"delete":return xm.Delete;case"patch":return xm.Patch;case"head":return xm.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 u=new MJr({context:this.context,breadcrumbs:t,parameter:a}).convert();if(u!=null)switch(this.inlinedTypes={...this.inlinedTypes,...u.inlinedTypes},u.type){case"path":r.push(u.parameter);break;case"query":n.push(u.parameter);break;case"header":{let l=Vr(u.parameter.name),p=ar(u.parameter.name),d=!1,f=this.context.authOverrides?.["auth-schemes"];if(f!=null){for(let g of Object.values(f))if(APm(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}}!gPm.has(l.toLowerCase())&&!d&&i.push(u.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(hPm)].map(i=>i[1]).filter(i=>!t.some(o=>Vr(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:io.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,u]of Object.entries(s.content)){let p=new LJr({context:this.context,breadcrumbs:t,contentType:c,mediaType:u,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 _C.SdkMethodNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.methodName,i=new _C.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?ri(this.operation.summary):ri(`${this.method}_${this.path.split("/").join("_")}`))}sanitizeMethodName(t){return t.includes(".")?ri(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=xH(t,n),o=xH(r,n);return Y0(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:ri(s.join("_"))}}generateStringParameterExample({example:t}){let r=new Um.ExampleConverter({breadcrumbs:this.breadcrumbs,context:this.context,schema:{type:"string"},example:t}),{validExample:n}=r.convert();return n}}});var elt,D8o=h(()=>{"use strict";Hn();R8o();elt=class extends $ut{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 u=c.type==="inlinedRequestBody"?a[0]?.inlinedPropertiesByAudience:void 0,l,p;if(c.type==="inlinedRequestBody")l=rT.inlinedPayload({name:c.name,extends:c.extends,properties:c.properties});else if(c.type==="reference")l=rT.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},l=rT.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:u,webhook:{id:`${r?.join(".")??""}.${n}`,name:this.context.casingsGenerator.generateName(n),displayName:this.operation.summary,method:t,headers:o,payload:l,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 QUu,MUu=h(()=>{"use strict";QUu=["get","post","put","delete","patch","head"]});var _Jr,LUu=h(()=>{"use strict";Xo();_Jr=class extends es{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 UJr,_Uu=h(()=>{"use strict";Xo();UJr=class extends es{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 yPm,bPm,EPm,IPm,k8o,UUu=h(()=>{"use strict";an();yPm=Fe.object({cursor:Fe.string(),next_cursor:Fe.string(),results:Fe.string()}),bPm=Fe.object({offset:Fe.string(),results:Fe.string(),step:Fe.string().optional(),"has-next-page":Fe.string().optional()}),EPm=Fe.object({next_uri:Fe.string(),results:Fe.string()}),IPm=Fe.object({next_path:Fe.string(),results:Fe.string()}),k8o=Fe.union([Fe.boolean(),yPm,bPm,EPm,IPm])});var F8o,awe,VJr,VUu=h(()=>{"use strict";Xo();UUu();F8o="$request.",awe="$response.",VJr=class extends es{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=k8o.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=k8o.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:E0.maybeTrimPrefix(r.cursor,F8o),nextCursor:E0.maybeTrimPrefix(r.next_cursor,awe),results:E0.maybeTrimPrefix(r.results,awe)};let n=t;if("next_uri"in n)return{type:"uri",nextUri:E0.maybeTrimPrefix(n.next_uri,awe),results:E0.maybeTrimPrefix(n.results,awe)};let i=t;if("next_path"in i)return{type:"path",nextPath:E0.maybeTrimPrefix(i.next_path,awe),results:E0.maybeTrimPrefix(i.results,awe)};let o=t;return{type:"offset",offset:E0.maybeTrimPrefix(o.offset,F8o),results:E0.maybeTrimPrefix(o.results,awe),step:o.step!=null?E0.maybeTrimPrefix(o.step,F8o):void 0,hasNextPage:o["has-next-page"]!=null?E0.maybeTrimPrefix(o["has-next-page"],awe):void 0}}}});function N8o(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 vPm,CPm,xPm,GJr,GUu=h(()=>{"use strict";Xo();an();vPm="$request.",CPm=Fe.object({"stream-condition":Fe.string().optional(),format:Fe.enum(["sse","json"]).optional(),"stream-description":Fe.string().optional(),"stream-request-name":Fe.string().optional(),"response-stream":Fe.any(),response:Fe.any(),terminator:Fe.string().optional(),resumable:Fe.boolean().optional()}),xPm=Fe.union([Fe.boolean(),CPm]),GJr=class extends es{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=xPm.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??N8o(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:E0.maybeTrimPrefix(r.data["stream-condition"],vPm),streamRequestName:r.data["stream-request-name"],responseStream:r.data["response-stream"],response:r.data.response,resumable:n}}}});var qJr,qUu=h(()=>{"use strict";Xo();qJr=class extends es{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 WJr,WUu=h(()=>{"use strict";Xo();WJr=class extends es{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 SPm(e){return Fi(e)&&typeof e.$ref=="string"}function wPm(e,t){if(e!=null){if(typeof e=="string")return e;if(SPm(e)){let r=(0,HUu.resolve)(t??process.cwd(),e.$ref);if((0,KJr.existsSync)(r))try{return(0,KJr.readFileSync)(r,"utf-8")}catch{return}}}}var KJr,HUu,HJr,KUu=h(()=>{"use strict";ct();Xo();KJr=require("fs"),HUu=require("path");HJr=class extends es{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=Fi(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(!Fi(c))continue;let u=c,l=u.lang,p=u.label,d=u.source;if(typeof l!="string")continue;let f=wPm(d,this.baseDir);f!=null&&a.push({name:typeof p=="string"?p:l,language:l,code:f,install:void 0,docs:void 0})}if(a.length!==0)return[{"code-samples":a}]}}});function TPm(e){return Fi(e)&&typeof e.$ref=="string"}function OPm(e,t){if(e!=null){if(typeof e=="string")return e;if(TPm(e)){let r=(0,JUu.resolve)(t??process.cwd(),e.$ref);if((0,YJr.existsSync)(r))try{return(0,YJr.readFileSync)(r,"utf-8")}catch{return}}}}function PPm(e,t){if(!Array.isArray(e))return[];let r=[];for(let n of e){if(!Fi(n))continue;let o=OPm(n.code,t);o!=null&&r.push({...n,code:o})}return r}var YJr,JUu,JJr,YUu=h(()=>{"use strict";ct();Ao();Xo();YJr=require("fs"),JUu=require("path");JJr=class extends es{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(!Fi(o))return o;let a=o["code-samples"];if(a!=null){let c=PPm(a,this.baseDir);return{...o,"code-samples":c}}return o}).filter(o=>{let s=$d.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 G9t,XUu=h(()=>{"use strict";Xo();G9t=class extends es{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 q9t,ZUu=h(()=>{"use strict";ct();Hn();Xo();q9t=class extends Um.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:Qu.json(fI.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:r.schema?.typeDeclaration.v2Examples})),streamResponseBody:Qu.streaming(Av.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:Qu.streaming(Av.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:Qu.streaming(Av.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:Qu.json(fI.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:Qu.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:Qu.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:Qu.text({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"}),contentType:Zp.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 Zp.parse(t)?.isText()??!1}convertResponseHeaders(){return this.convertedResponseHeaders??=Yut({context:this.context,breadcrumbs:this.breadcrumbs,headers:this.responseBody.headers}),this.convertedResponseHeaders}}});var XJr,$Uu=h(()=>{"use strict";ct();Hn();Xo();XJr=class extends Um.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:$r.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:CH(`${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}),u=this.getIdForErrorExample({key:o,example:c,usedExampleNames:n});n.add(u),a!=null&&(i[u]=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 TJr[t]}getErrorIdFromErrorName(t){return this.context.enableUniqueErrorsPerEndpoint?CH(`${this.methodName}Request${t}`):t}convertResponseHeaders(){return this.convertedResponseHeaders??=Yut({context:this.context,breadcrumbs:this.breadcrumbs,headers:this.responseError.headers}),this.convertedResponseHeaders}}});var ZJr,eVu=h(()=>{"use strict";Ao();Hn();fc();E5();Xo();Gi();KUu();YUu();XUu();ZUu();$Uu();R8o();ZJr=class e extends $ut{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:u,idToAuthScheme:l,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=u,this.idToAuthScheme=l,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"]}),u=this.collectQueryParameterAudiences({breadcrumbs:[...this.breadcrumbs,"parameters"]}),l=this.convertRequestBody({breadcrumbs:[...this.breadcrumbs,"requestBody"],group:r,method:n,streamingExtension:this.streamingExtension,queryParameters:c}),p=l?.[0]?.requestBody,d=l?.[0]?.streamRequestBody,f=l?.[0]?.inlinedPropertiesByAudience,m={requestBodies:l?.map(ue=>ue.requestBody)},g=this.convertResponseBody({breadcrumbs:[...this.breadcrumbs,"responses"],group:r,method:n,streamingExtension:this.streamingExtension}),A=g?.response,y=g?.streamResponse,I=g!=null?g.errors:[],x={},v=I.map(ue=>ue.error),S=nb(this.path),B=this.context.perSpecBasePath,R=this.getEndpointBaseUrl(),D=this.getEndpointBaseUrls(),O=this.convertExamples({httpPath:S,httpMethod:t,baseUrl:R});if(Object.keys(O.examples).length===0&&Object.keys(O.streamExamples).length===0){let ue=this.synthesizeEndpointExamplesFromNativeRequestBody({httpPath:S,httpMethod:t,baseUrl:R});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&&l!=null&&l.length>1){let ue=this.synthesizeEndpointExamplesFromPerContentTypeRequestBodies({convertedRequestBodies:l,httpPath:S,httpMethod:t,baseUrl:R});if(ue!=null)for(let[Pe,Ie]of Object.entries(ue))O.examples[Pe]=Ie}let z=new Set(this.operation.security?.flatMap(ue=>Object.keys(ue))??[]),Y=this.authSchemeToHeaders(Array.from(z));Y.length>0&&s.push(...Y);for(let ue of I){let Pe=ue.error,Ie=ue.errorType,Be=Pe.error.errorId,_e=ue.examples;x[Be]={name:Pe.error,displayName:ue.displayName,discriminantValue:{name:Pe.error.name,wireValue:Be},type:Ie,statusCode:ue.statusCode,isWildcardStatusCode:ue.isWildcardStatusCode,docs:Pe.docs,examples:[],v2Examples:{userSpecifiedExamples:_e??{},autogeneratedExamples:{}},headers:ue.headers}}let $=this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],ae=new G9t({context:this.context,breadcrumbs:this.breadcrumbs,document:this.context.spec}).convert(),me=new G9t({context:this.context,breadcrumbs:this.breadcrumbs,document:this.operation}).convert()??ae,Se={displayName:this.operation.summary,subtitle:this.subtitle,method:t,baseUrl:R,v2BaseUrls:D,path:S,pathParameters:a,queryParameters:c,headers:s.filter((ue,Pe,Ie)=>Pe===Ie.findIndex(Be=>ar(Be.name)===ar(ue.name))),responseHeaders:g?.responseHeaders,sdkRequest:void 0,errors:v,auth:this.computeEndpointAuth(),security:this.computeEndpointSecurity(),availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),userSpecifiedExamples:[],autogeneratedExamples:[],idempotent:this.idempotent??!1,basePath:B!=null?nb(B):void 0,fullPath:B!=null?nb(`${B}${this.path}`):S,allPathParameters:a,pagination:void 0,transport:void 0,source:dD.openapi(),audiences:$,retries:void 0,globalParameters:this.globalParameterIds,apiPlayground:me},Re=this.context.namespace!=null?[this.context.namespace]:[],ce=r?.map(ue=>ri(ue));return Re.push(...ce??[]),{audiences:$,group:r,groupDisplayName:i,groupDescription:o,errors:x,endpoint:{...Se,id:`endpoint_${Re.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:y!=null&&y.body!=null?{...Se,id:`endpoint_${Re.join("/")}.${n}_stream`,name:this.context.casingsGenerator.generateName(`${n}_stream`),requestBody:d,v2RequestBodies:void 0,response:y,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:y.body,docs:y.docs}]}}:void 0,inlinedTypes:this.inlinedTypes,servers:this.filterOutTopLevelServers(this.operation.servers??this.pathLevelServers??[]),inlinedRequestPropertiesByAudience:f,queryParametersByAudience:u}}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,u]of Object.entries(this.operation.responses)){let l=/^[45]XX$/i.test(c),p,d=!1;if(l)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:u,breadcrumbs:[...t,c]});if(f==null)continue;let g=new q9t({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:l?!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:l?!0:void 0,body:g.responseBody,docs:f.description},o.streamResponse={statusCode:p,isWildcardStatusCode:l?!0:void 0,body:g.streamResponseBody,docs:f.description},g.headers!=null&&(o.responseHeaders=g.headers)),o.v2Responses=[...o.v2Responses??[],{statusCode:p,isWildcardStatusCode:l?!0:void 0,body:g.responseBody,docs:f.description}])}if(d){let f=this.context.resolveMaybeReference({schemaOrReference:u,breadcrumbs:[...t,c]});if(f==null)continue;let g=new XJr({context:this.context,breadcrumbs:[...t,c],responseError:f,group:r??[],method:n,methodName:this.evaluateMethodNameFromOperation(),statusCode:p,isWildcardStatusCode:l?!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 u=new q9t({context:this.context,breadcrumbs:[...t,"stream"],responseBody:{description:""},group:r??[],method:n,statusCode:"stream",streamingExtension:i}).convert();u!=null&&(this.inlinedTypes={...this.inlinedTypes,...u.inlinedTypes},o.response={statusCode:200,isWildcardStatusCode:void 0,body:u.responseBody,docs:void 0},o.streamResponse={statusCode:200,isWildcardStatusCode:void 0,body:u.streamResponseBody,docs:void 0},o.v2Responses=[{statusCode:200,isWildcardStatusCode:void 0,body:u.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 u=c.value.responseBodyType;(u.type!=="container"||u.container.type!=="optional")&&(o.response={...o.response,body:Qu.json(fI.response({...c.value,responseBodyType:$r.container(Cs.optional(u))}))})}}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():x8o(this.operation.security??this.context.spec.security)}usesEndpointSecurity(){let t=this.context.authOverrides?.auth;return t!=null&&Btt(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:io.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 JJr({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],a=new HJr({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],u=o.some(l=>Array.isArray(l["code-samples"])&&l["code-samples"].length>0)?o:[...o,...a];return u.length===0?{examples:{},streamExamples:{}}:this.streamingExtension?.type==="streamCondition"?this.convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:u}):{examples:this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:u}),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[u,l]of c){let p=this.context.resolveExampleWithValue(l);p!=null&&(s[u]={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:Xt.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,u=c.contentType,l=c.v2Examples;if(l==null)continue;let p=l.userSpecifiedExamples;if(Object.keys(p).length===0)continue;let d=u!=null?s.get(u):void 0;for(let[f,m]of Object.entries(p)){let g=t.length>1&&u!=null?`${f} (${u})`:f;o[g]={displayName:t.length>1?g:void 0,contentType:u??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[,u]of c){let l=this.context.resolveExampleWithValue(u);if(l!=null){t.set(s,{docs:void 0,statusCode:i,body:Xt.V2HttpEndpointResponseBody.json(l)});break}}}}return t}convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:i}){let o=i.filter(u=>!(u.response!=null&&"stream"in u.response)),s=i.filter(u=>u.response!=null&&"stream"in u.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 Xt.V2HttpEndpointResponseBody.stream(t.response.stream);if("body"in t.response)return Xt.V2HttpEndpointResponseBody.json(t.response.body)}}getEndpointBaseUrl(){let r=new _C.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 "${mn.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 P4.getServerName({server:o,context:this.context})}getEndpointBaseUrls(){if(new _C.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 P4.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)&&ri(r)===ri(n))return i}getGroupDescription(t){let r=this.operation.tags?.[0],n=t?.[t.length-1];if(!(r==null||n==null)&&ri(r)===ri(n))return this.context.getDescriptionForTag(r)}}});var j8o,$Jr,tVu=h(()=>{"use strict";Xo();j8o=Ae(A4t(),1);MUu();LUu();_Uu();VUu();GUu();qUu();WUu();eVu();D8o();$Jr=class extends io{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 QUu){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 u=new GJr({breadcrumbs:s,document:this.context.spec,operation:o,context:this.context}).convert();u==null&&this.operationHasTextEventStreamResponse(o)&&(u={type:"stream",format:"sse",terminator:void 0,resumable:N8o(this.context.spec)??!1});let l=this.tryParseAsHttpEndpoint({operationBreadcrumbs:s,operation:o,method:i,streamingExtension:u});l!=null&&(t.push(l),Object.assign(n,l.inlinedTypes))}return{endpoints:t,webhooks:r,inlinedTypes:n}}tryParseAsWebhook({operation:t,method:r,operationBreadcrumbs:n,context:i}){return new WJr({breadcrumbs:n,operation:t,context:i}).convert()?new elt({context:this.context,breadcrumbs:n,operation:t,method:j8o.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 VJr({breadcrumbs:n,operation:t,document:this.context.spec,context:this.context}).convert()!=null;let c=new UJr({breadcrumbs:n,operation:t,context:this.context}).convert(),l=new qJr({breadcrumbs:n,operation:t,context:this.context}).convert(),d=new _Jr({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 ZJr({context:this.context,breadcrumbs:n,operation:t,method:j8o.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path,pathItemParameters:this.pathItem.parameters,idempotent:c,subtitle:l,globalParameterIds:d,idToAuthScheme:this.idToAuthScheme,topLevelServers:this.topLevelServers,pathLevelServers:this.pathItem.servers,streamingExtension:i}).convert()}}});var eYr,rVu=h(()=>{"use strict";Hn();Xo();eYr=class extends io{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 _p.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 _p.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 _p.header({key:this.schemeId,name:{name:this.context.casingsGenerator.generateName(n),wireValue:this.securityScheme.name},valueType:io.OPTIONAL_STRING,prefix:o,headerEnvVar:i,headerPlaceholder:s,docs:this.securityScheme.description,playgroundDocs:t})}break}case"oauth2":return _p.bearer({key:this.schemeId,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,tokenPlaceholder:void 0,docs:this.securityScheme.description,playgroundDocs:t})}}}});function BPm(e){if(e!=null){if(typeof e=="string")return rE.string(e);if(typeof e=="boolean")return rE.boolean(e)}}var nVu,W9t,iVu=h(()=>{"use strict";ct();Ao();Hn();fc();E5();Xo();nVu=Ae(A4t(),1);wUu();TUu();OUu();PUu();RUu();kUu();NUu();D8o();tVu();rVu();W9t=class extends vJ{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=y4t({document:this.context.spec,options:this.context.settings,logger:this.context.logger}),C8o({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=BUu({globalHeaderOverrides:this.context.globalHeaderOverrides,context:this.context});this.addGlobalHeadersToIr(n),this.context.setGlobalHeaders(n);return}let r=new zJr({breadcrumbs:["x-fern-global-headers"],document:this.context.spec,context:this.context}).convert();if(r!=null){let n=DUu({globalHeaders:r,context:this.context});this.addGlobalHeadersToIr(n),this.context.setGlobalHeaders(n)}}convertGlobalParameters(){let r=new QJr({breadcrumbs:["x-fern-global-parameters"],document:this.context.spec,context:this.context}).convert();if(r!=null){let n=FUu({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 NJr({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=Gy(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=nb(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:io.STRING,docs:n.docs,location:Xt.PathParameterLocation.Root,variable:void 0,clientDefault:BPm(n.default),v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}},explode:void 0});if(r.pathsIncludeBasePath){let n=g4t({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=OGt({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 eYr({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 jJr({breadcrumbs:["x-fern-base-url-env"],document:this.context.spec,context:this.context}).convert();if(this.context.environmentOverrides){let s=PGt({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 P4({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 Um.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 elt({context:this.context,breadcrumbs:["webhooks",n],operation:i,method:nVu.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 $Jr({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 u of c.servers)this.shouldAddServerToCollectedServers({server:u,currentServers:t})&&t.push(u);if(c.errors)for(let[u,l]of Object.entries(c.errors))r[u]=l}for(let c of a.webhooks){let u=this.context.getGroup({groupParts:c.group,namespace:this.context.namespace});this.addWebhookToIr({webhook:c.webhook,operationId:u.join("."),group:u,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&&Btt(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 tYr,oVu=h(()=>{"use strict";Xo();tYr=class extends es{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 uVe,sVu=h(()=>{"use strict";Hn();fc();Xo();oVu();uVe=class extends E0{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 u;if(o.includes("/")){let p=new Um.SchemaConverters.SchemaConverter({context:this,breadcrumbs:r??[],schema:a.value,id:o}).convert();p!=null&&(u={[o]:p.convertedSchema})}return{ok:!0,reference:$r.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(s),typeId:o,default:void 0,inline:!1,displayName:c}),inlinedTypes:u}}setGlobalHeaders(t){this.globalHeaderNames=t.map(r=>ar(r.name))}getDisplayNameForTag(t){if(Object.keys(this.tagToDisplayName).length===0)for(let r of this.spec.tags??[]){let i=new tYr({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 Q8o({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=Lfe(o,{header:()=>{},basic:()=>{},tokenBearer:()=>{},inferredBearer:()=>{},oauth:a=>DPm({ir:e,key:i.key,oauthScheme:a})});n.push(s??i)}return{...e,auth:{...e.auth,schemes:n}}}function DPm({ir:e,key:t,oauthScheme:r}){if(r.type!=="client-credentials")return;let n=r["get-token"];if(n==null)return;let i=aVu({ir:e,endpointRef:n.endpoint});if(i==null)return;let{endpoint:o,serviceId:s,subpackageId:a}=i,c=n["request-properties"],u=n["response-properties"],l=z8o({ir:e,endpoint:o,wireValue:xJ(c?.["client-id"],"client_id")}),p=z8o({ir:e,endpoint:o,wireValue:xJ(c?.["client-secret"],"client_secret")}),d=tlt({ir:e,endpoint:o,wireValue:xJ(u?.["access-token"],"access_token")});if(!(l==null||p==null||d==null))return _p.oauth({key:t,docs:r.docs,playgroundDocs:r["playground-docs"],configuration:pD.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:l,clientSecret:p,scopes:void 0,customProperties:NPm({ir:e,endpoint:o,excludeWireValues:[xJ(c?.["client-id"],"client_id"),xJ(c?.["client-secret"],"client_secret")]})},responseProperties:{accessToken:d,expiresIn:tlt({ir:e,endpoint:o,wireValue:xJ(u?.["expires-in"],"expires_in")}),refreshToken:tlt({ir:e,endpoint:o,wireValue:xJ(u?.["refresh-token"],"refresh_token")})}},refreshEndpoint:r["refresh-token"]!=null?kPm({ir:e,refreshTokenConfig:r["refresh-token"]}):void 0})})}function kPm({ir:e,refreshTokenConfig:t}){let r=aVu({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=z8o({ir:e,endpoint:n,wireValue:xJ(s?.["refresh-token"],"refresh_token")}),u=tlt({ir:e,endpoint:n,wireValue:xJ(a?.["access-token"],"access_token")});if(!(c==null||u==null))return{endpointReference:{endpointId:n.id,serviceId:i,subpackageId:o},requestProperties:{refreshToken:c},responseProperties:{accessToken:u,expiresIn:tlt({ir:e,endpoint:n,wireValue:xJ(a?.["expires-in"],"expires_in")}),refreshToken:tlt({ir:e,endpoint:n,wireValue:xJ(a?.["refresh-token"],"refresh_token")})}}}function aVu({ir:e,endpointRef:t}){let r=t.trim().split(/\s+/);if(r.length!==2)return;let n=RPm[r[0]?.toUpperCase()??""],i=Gy(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(FPm(a.fullPath)===i){let u=Object.entries(e.subpackages).find(([,l])=>l.service===o)?.[0];return{endpoint:a,serviceId:o,subpackageId:u}}}}function FPm(e){let t=e.head;for(let r of e.parts)t+=`{${r.pathParameter}}${r.tail}`;return Gy(t)}function xJ(e,t){return e==null?t:e.match(/^\$(?:request|response)\.(.+)$/)?.[1]??e}function cVu(e,t){return e.find(r=>ar(r.name)===t)}function M8o(e,t){let r=e.types[t];if(r?.shape.type==="object")return r.shape.properties}function z8o({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=M8o(e,t.requestBody.requestBodyType.typeId));let i=n!=null?cVu(n,r):void 0;if(i!=null)return{propertyPath:void 0,property:aB.body({...i})}}function NPm({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=M8o(e,t.requestBody.requestBodyType.typeId)),n==null)return;let i=new Set(r),o=n.filter(s=>!i.has(ar(s.name))).map(s=>({propertyPath:void 0,property:aB.body({...s})}));return o.length>0?o:void 0}function tlt({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=M8o(e,n.typeId),o=i!=null?cVu(i,r):void 0;if(o!=null)return{propertyPath:void 0,property:o}}var RPm,uVu=h(()=>{"use strict";ct();Ao();Hn();fc();RPm={GET:xm.Get,POST:xm.Post,PUT:xm.Put,PATCH:xm.Patch,DELETE:xm.Delete}});var L8o=h(()=>{"use strict";iVu();sVu();uVu()});var jPm,zPm,QPm,rYr,lVu=h(()=>{"use strict";ct();Xo();an();jPm=Fe.object({description:Fe.string().optional(),required:Fe.boolean().optional(),deprecated:Fe.boolean().optional(),allowEmptyValue:Fe.boolean().optional(),style:Fe.string().optional(),explode:Fe.boolean().optional(),allowReserved:Fe.boolean().optional(),schema:Fe.any().optional(),example:Fe.any().optional(),examples:Fe.record(Fe.string(),Fe.any()).optional(),content:Fe.record(Fe.string(),Fe.any()).optional()}),zPm=jPm.extend({name:Fe.string(),in:Fe.string()}),QPm=Fe.array(zPm),rYr=class extends es{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 QPm.parse(t)}catch(r){this.context.errorCollector.collect({message:`Failed to parse x-fern-parameters extension: ${Sn(r)}`,path:this.breadcrumbs});return}}}});var nYr,pVu=h(()=>{"use strict";Hn();fc();Xo();nYr=class extends io{method;pathParameters;queryParameters;headers;topLevelServers;constructor({context:t,breadcrumbs:r,method:n,pathParameters:i=[],queryParameters:o=[],headers:s=[],topLevelServers:a=[]}){super({context:t,breadcrumbs:r}),this.method=n,this.pathParameters=i,this.queryParameters=o,this.headers=s,this.topLevelServers=a}convert(){let t={},r="";for(let u of this.pathParameters)r+=`/{${Vr(u.name)}}`;let n=nb(r),i=[];for(let[u,l]of this.method.params.entries()){let p;if(this.context.isReferenceObject(l)){let g=this.context.resolveReference({reference:l});if(g.resolved)p=g.value;else continue}else p=l;let d=[this.method.name,"Param",p.name].join("_"),m=new Um.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:l,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 u=this.context.resolveMaybeReference({schemaOrReference:this.method.result,breadcrumbs:[...this.breadcrumbs,"result"]});if(u!=null){let l=new Um.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"result"],context:this.context,schemaOrReference:u.schema}),p=[this.method.name,"Result"].join("_"),d=l.convert();d!=null&&(o={docs:u.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?Cd.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:Qu.json(fI.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:dD.openrpc(),audiences:a,retries:void 0,globalParameters:void 0,apiPlayground:void 0,responseHeaders:[]},audiences:a,inlinedTypes:t,servers:this.filterOutTopLevelServers(this.method.servers??[])}}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 P4.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[Vr(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 l=this.context.resolveReference({reference:o});if(l.resolved)s=l.value;else continue}else s=o;let a;if(s.result)if(this.context.isReferenceObject(s.result)){let l=this.context.resolveReference({reference:s.result});l.resolved&&(a=l.value)}else a=s.result;let c=s.name??`Example ${i+1}`,u=[];if(s.params&&Array.isArray(s.params)){u=[];for(let l of s.params)if(this.context.isReferenceObject(l)){let p=this.context.resolveReference({reference:l});if(p.resolved)u.push(p.value);else continue}else u.push(l)}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:u.map(l=>l.value)??void 0},response:{docs:void 0,statusCode:void 0,body:a?.value?Xt.V2HttpEndpointResponseBody.json({jsonrpc:"2.0",id:s.examplePairedRequest?.id||"1",result:a.value}):void 0},codeSamples:[]}}++i}return r}}});var iYr,fVu=h(()=>{"use strict";Xo();iYr=class extends Um.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 Um.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 H9t,dVu=h(()=>{"use strict";Xo();lVu();pVu();fVu();H9t=class extends vJ{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 P4({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 Um.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 rYr({context:this.context,breadcrumbs:["methods"],operation:this.context.spec}).convert(),i=[],o=[],s=[];if(n&&n.length>0)for(let[c,u]of n.entries()){let p=new iYr({context:this.context,breadcrumbs:[...this.breadcrumbs,`x-fern-parameters[${c}]`],parameter:u}).convert();if(p!=null)switch(p.type){case"path":{i.push(p.parameter);break}case"query":{o.push(p.parameter);break}case"header":{s.push(p.parameter);break}}}let a=this.context.getGroup({groupParts:[],namespace:this.context.namespace});for(let c of this.context.spec.methods??[]){let u=this.context.resolveMaybeReference({schemaOrReference:c,breadcrumbs:["methods"]});if(u==null)continue;let p=new nYr({context:this.context,breadcrumbs:["methods"],method:u,pathParameters:i,queryParameters:o,headers:s,topLevelServers:this.context.spec.servers}).convert();if(p!=null&&(this.addEndpointToIr({endpoint:p.endpoint,audiences:p.audiences,endpointGroup:a,serviceName:"service_root"}),this.addTypesToIr(p.inlinedTypes),p.servers))for(let d of p.servers)this.shouldAddServerToCollectedServers({server:d,currentServers:t,specType:"openrpc"})&&t.push(this.maybeDeduplicateServerName(d))}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 K9t,mVu=h(()=>{"use strict";Hn();Xo();K9t=class extends E0{isReferenceObject(t){return t!=null&&"$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:$r.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}}});var hVu=h(()=>{"use strict";dVu();mVu()});var gVu,AVu=h(()=>{"use strict";gVu=/^(?:[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 MPm(e){return typeof e=="string"&&gVu.test(e)}var _8o,yVu=h(()=>{"use strict";AVu();_8o=MPm});function bVu(e,t=0){return(HB[e[t+0]]+HB[e[t+1]]+HB[e[t+2]]+HB[e[t+3]]+"-"+HB[e[t+4]]+HB[e[t+5]]+"-"+HB[e[t+6]]+HB[e[t+7]]+"-"+HB[e[t+8]]+HB[e[t+9]]+"-"+HB[e[t+10]]+HB[e[t+11]]+HB[e[t+12]]+HB[e[t+13]]+HB[e[t+14]]+HB[e[t+15]]).toLowerCase()}var HB,EVu=h(()=>{"use strict";HB=[];for(let e=0;e<256;++e)HB.push((e+256).toString(16).slice(1))});function U8o(){return crypto.getRandomValues(LPm)}var LPm,IVu=h(()=>{"use strict";LPm=new Uint8Array(16)});function _Pm(e,t,r){return!t&&!e&&crypto.randomUUID?crypto.randomUUID():UPm(e,t,r)}function UPm(e,t,r){e=e||{};let n=e.random??e.rng?.()??U8o();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 bVu(n)}var Yw,vVu=h(()=>{"use strict";IVu();EVu();Yw=_Pm});var lVe=h(()=>{"use strict";vVu();yVu()});async function rlt({absoluteFilePathToOverrides:e,data:t,context:r,allowNullKeys:n}){let i=null;try{let o=(await(0,CVu.readFile)(e,"utf8")).toString();try{i=JSON.parse(o)}catch{i=vr.load(o,{json:!0})}}catch{return r.failAndThrow(`Failed to read overrides from file ${e}`,void 0,{code:T.Code.ParseError})}return KZ({data:t,overrides:i,allowNullKeys:n})}var CVu,oYr=h(()=>{"use strict";ct();Dt();CVu=require("fs/promises");is()});async function V8o({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let n=(await(0,xVu.readFile)(t)).toString(),i;try{i=JSON.parse(n)}catch{i=vr.load(n)}let o=[];r!=null&&(Array.isArray(r)?o=r:o=[r]);let s=i;for(let a of o)s=await rlt({absoluteFilePathToOverrides:a,context:e,data:s});return s}var xVu,SVu=h(()=>{"use strict";xVu=require("fs/promises");is();oYr()});async function G8o({document:e,settings:t}){let r=t?.errorResponses;if(r==null)return{document:e,errorResponses:void 0};let n=typeof r.schema=="string"?await VPm(Zt.of(r.schema)):r.schema;return{document:fxo({document:e,errorResponses:r,schema:n}),errorResponses:{...r,schema:n}}}async function VPm(e){let t=(await(0,wVu.readFile)(e)).toString(),r=vr.load(t);if(!jr(r))throw new T({message:`Expected ${e} to contain an OpenAPI schema object.`,code:T.Code.ConfigError});return r}var wVu,TVu=h(()=>{"use strict";Dc();ct();tr();Dt();wVu=require("fs/promises");is()});var PVu=E((dxv,OVu)=>{"use strict";function GPm(){return typeof process=="object"&&typeof process.nextTick=="function"?process.nextTick:typeof setImmediate=="function"?setImmediate:function(t){setTimeout(t,0)}}OVu.exports=GPm()});var DVu=E((mxv,RVu)=>{"use strict";var BVu=PVu();RVu.exports=function(t,r){if(t){r.then(function(n){BVu(function(){t(null,n)})},function(n){BVu(function(){t(n)})});return}else return r}});var W8o=E((hxv,FVu)=>{"use strict";var q8o=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))}},sYr=class extends TypeError{constructor(t,r,n){let i=t.includes(".")?"property":"argument",o=`The "${t}" ${i} ${determiner} ${r}`}};function kVu(e,t,r="Object"){if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e))){let n=new sYr(t,r,e);throw Error.captureStackTrace(n,kVu),n}}FVu.exports={ERR_INVALID_ARG_TYPE:sYr,assertIsObject:kVu,DebounceTimers:q8o}});var zVu=E((gxv,jVu)=>{"use strict";var{assertIsObject:NVu}=W8o();function qPm(e){return NVu(e,"options"),e=Object.assign({},e),e.allowHalfOpen=!0,e.rejectUnauthorized=!1,NVu(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 WPm(e,t){e=qPm.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}jVu.exports={initializeTLSOptions:WPm}});var lYr=E((yxv,_Vu)=>{"use strict";var{URL:aYr}=require("url"),{EventEmitter:MVu}=require("events"),cYr=require("util")._extend,{DebounceTimers:HPm,assertIsObject:QVu,ERR_INVALID_ARG_TYPE:Axv}=W8o(),{initializeTLSOptions:KPm}=zVu(),J9t=require("http"),H8o=require("https"),{Stream:JPm}=require("stream");function uYr(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 mhe=[];uYr(mhe,J9t.ClientRequest);uYr(mhe,J9t.OutgoingMessage);uYr(mhe,MVu);uYr(mhe,JPm);var YPm=["httpVersionMajor","httpVersionMinor","httpVersion"],XPm=["host","connection"],cwe=Symbol("stubs");function Y9t(){this.http2Mimic=!0,this[cwe]=[];for(var e=0;e<mhe.length;e++){let u=mhe[e];Y9t.prototype[u]||(this[u]=function(){return this.genericStubber(u,arguments)}.bind(this))}var t,r,n,i;let o=arguments[0]instanceof X9t;var s,a;if(o){let u=arguments[0];u.method&&(s=u.method),u.protocol&&(a=u.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=K8o(new aYr(t)),!t.hostname)throw new Error("Unable to determine the domain name")}else n?t=cYr(K8o(new aYr(n)),t):t=cYr({},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)}Y9t.prototype={getGlobalManager(e){return e.agent?e.agent.protocol=="https:"?lwe.globalManager:pwe.globalManager:uwe.globalManager},genericStubber(e,t){return this[cwe]?(this[cwe].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[cwe])this[cwe].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<mhe.length;t++){let n=mhe[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[cwe].length;n++){var r=this[cwe][n];e[r[0]](...r[1])}this[cwe]=null},proxyProps(e){function t(){return e[this]}function r(c){e[this]=c}let n=["on","_on","_once","once","http2Mimic"].concat(mhe),i=Object.keys(this),o=[].concat(YPm);i.forEach(function(u){n.indexOf(u)==-1&&o.indexOf(u)==-1&&o.push(u)});let s=Object.getOwnPropertyDescriptors(e);for(var a=0;a<o.length;a++){let c=o[a],u=s[c],l;u||(l=!0),u&&(u.writable||u)&&(l=!0),l&&(e[c]=this[c]),Object.defineProperty(this,c,{get:t.bind(c),set:r.bind(c)})}}};var uwe=class e extends MVu{constructor(t){super(),this.httpsAgent=H8o.globalAgent,this.httpAgent=J9t.globalAgent,this.init(t)}log(){}init(t){t=t||{},this.http2Clients={},this.cachedHTTP1Result={},this.setModules(),this.http2Debouncer=new HPm(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 X9t(arguments);return this.enforceProtocol&&(i.protocol=this.enforceProtocol),new Y9t(i)}get(){var t=new X9t(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 u={createConnection(){return o}};if(c=="h2"&&this.http2Support){var l=this.http2.connect(r,u);this.setHttp2Client(t,l)}else this.cachedHTTP1Result[t]=Date.now();n(null,u),this.emit(i,u)}.bind(this))}}makeHttpRequest(t,r,n,i,o){n instanceof aYr&&(n=K8o(n));let s=cYr({},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(l){this.emit("http1.response",l)})}makeHttp2Request(t,r,n,i,o){var s=this.http2Debouncer;s.pause(t);var a=cYr({},i.headers||{});i.method&&(a[":method"]=i.method),i.path&&(a[":path"]=i.path),Object.keys(a).forEach(d=>{XPm.indexOf((d+"").toLowerCase())!=-1&&delete a[d]}),i.headers=a;var c=n.request(a);r.emit("socket",i.createConnection());let u,l=0;c.on("data",function(f){l+=f.length,l>=u&&s.unpauseAndTime(t)}),r.take(c);function p(d){u=parseInt(d["content-length"]),u<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),QVu(r,"options"),r=Object.assign({},r),typeof t=="string"&&(t=new aYr(t)),QVu(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,KPm.call(this,r,s),n);break;default:throw new Error("Not supprted"+i)}return a}};function K8o(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 X9t=class e{constructor(t){if(t[0]instanceof e)return t[0];this.args=t,this.method=null,this.protocol=null}},lwe=class extends uwe{constructor(){super(...arguments),this.Agent=H8o.Agent,this.globalAgent=H8o.globalAgent,this.enforceProtocol="https:"}},ZPm=new lwe;lwe.globalManager=ZPm;lwe.Manager=lwe;var pwe=class extends uwe{constructor(){super(...arguments),this.Agent=J9t.Agent,this.globalAgent=J9t.globalAgent,this.enforceProtocol="http:"}},$Pm=new pwe;pwe.globalManager=$Pm;pwe.Manager=pwe;var LVu=new uwe;LVu.enforceProtocol="detect";uwe.globalManager=LVu;_Vu.exports={HttpRequest:pwe,HttpsRequest:lwe,HTTP2OutgoingMessage:Y9t,ClientRequest:Y9t,HttpRequestManager:uwe}});var VVu=E((bxv,UVu)=>{"use strict";var{HttpRequest:eBm,ClientRequest:tBm}=lYr(),Z9t=eBm.globalManager,rBm=Z9t.request.bind(Z9t),nBm=Z9t.get.bind(Z9t),iBm=Object.assign({},require("http"));UVu.exports=Object.assign(iBm,{ClientRequest:tBm,globalManager:Z9t,request:rBm,get:nBm})});var qVu=E((Exv,GVu)=>{"use strict";var{HttpsRequest:oBm,ClientRequest:sBm}=lYr(),$9t=oBm.globalManager,aBm=$9t.request.bind($9t),cBm=$9t.get.bind($9t),uBm=Object.assign({},require("https"));GVu.exports=Object.assign(uBm,{ClientRequest:sBm,globalManager:$9t,request:aBm,get:cBm})});var HVu=E((Ixv,WVu)=>{"use strict";var{HttpRequestManager:J8o,HTTP2OutgoingMessage:lBm,ClientRequest:pBm}=lYr(),fBm=VVu(),dBm=qVu(),eWt=new J8o;J8o.globalManager=eWt;var mBm=eWt.request.bind(eWt),hBm=eWt.get.bind(eWt);WVu.exports={HTTP2OutgoingMessage:lBm,ClientRequest:pBm,globalManager:J8o.globalManager,request:mBm,get:hBm,http:fBm,https:dBm}});var iGo={};te(iGo,{FetchError:()=>ZD,Headers:()=>w8,Request:()=>dwe,Response:()=>Xre,default:()=>wBm});function ZD(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 $T(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:$Vu(e)?e=Buffer.from(e.toString()):e instanceof dVe?e=e[fVe]: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 SJ.default||(e=Buffer.from(String(e)))),this[ghe]={body:e,disturbed:!1,error:null},this.size=i,this.timeout=s,e instanceof SJ.default&&e.on("error",function(a){let c=a.name==="AbortError"?a:new ZD(`Invalid response body while trying to fetch ${t.url}: ${a.message}`,"system",a);t[ghe].error=c})}function nlt(){var e=this;if(this[ghe].disturbed)return $T.Promise.reject(new TypeError(`body used already for: ${this.url}`));if(this[ghe].disturbed=!0,this[ghe].error)return $T.Promise.reject(this[ghe].error);if(this.body===null)return $T.Promise.resolve(Buffer.alloc(0));if(Buffer.isBuffer(this.body))return $T.Promise.resolve(this.body);if(!(this.body instanceof SJ.default))return $T.Promise.resolve(Buffer.alloc(0));let t=[],r=0,n=!1;return new $T.Promise(function(i,o){let s;e.timeout&&(s=setTimeout(function(){n=!0,o(new ZD(`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 ZD(`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 ZD(`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 ZD(`Could not create Buffer from response body for ${e.url}: ${a.message}`,"system",a))}}})})}function gBm(e,t){if(typeof $8o!="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")),$8o(e,"UTF-8",n).toString()}function $Vu(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 e5u(e){let t,r,n=e.body;if(e.bodyUsed)throw new Error("cannot clone body after it is used");return n instanceof SJ.default&&typeof n.getBoundary!="function"&&(t=new KVu,r=new KVu,n.pipe(t),n.pipe(r),e[ghe].body=t,n=r),n}function t5u(e){return e===null?null:typeof e=="string"?"text/plain;charset=UTF-8":$Vu(e)?"application/x-www-form-urlencoded;charset=UTF-8":e instanceof dVe?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 SJ.default?null:"text/plain;charset=UTF-8"}function r5u(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 ABm(e,t){let r=t.body;r===null?e.end():Buffer.isBuffer(r)?(e.write(r),e.end()):r.pipe(e)}function tWt(e){if(e=`${e}`,n5u.test(e))throw new TypeError(`${e} is not a legal HTTP header name`)}function JVu(e){if(e=`${e}`,eGo.test(e))throw new TypeError(`${e} is not a legal HTTP header value`)}function olt(e,t){t=t.toLowerCase();for(let r in e)if(r.toLowerCase()===t)return r}function tGo(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"key+value";return Object.keys(e[UC]).sort().map(t==="key"?function(n){return n.toLowerCase()}:t==="value"?function(n){return e[UC][n].join(", ")}:function(n){return[n.toLowerCase(),e[UC][n].join(", ")]})}function X8o(e,t){let r=Object.create(nGo);return r[rGo]={target:e,kind:t,index:0},r}function yBm(e){let t=Object.assign({__proto__:null},e[UC]),r=olt(e[UC],"Host");return r!==void 0&&(t[r]=t[r][0]),t}function bBm(e){let t=new w8;for(let r of Object.keys(e))if(!n5u.test(r))if(Array.isArray(e[r]))for(let n of e[r])eGo.test(n)||(t[UC][r]===void 0?t[UC][r]=[n]:t[UC][r].push(n));else eGo.test(e[r])||(t[UC][r]=[e[r]]);return t}function pYr(e){return typeof e=="object"&&typeof e[hhe]=="object"}function CBm(e){let t=e&&typeof e=="object"&&Object.getPrototypeOf(e);return!!(t&&t.constructor.name==="AbortSignal")}function xBm(e){let t=e[hhe].parsedURL,r=new w8(e[hhe].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 SJ.default.Readable&&!vBm)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=r5u(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:yBm(r),agent:e.agent})}function rWt(e){Error.call(this,e),this.type="aborted",this.message=e,Error.captureStackTrace(this,this.constructor)}function fwe(e,t){if(!fwe.Promise)throw new Error("native promise missing, set fetch.Promise to your favorite alternative");return $T.Promise=fwe.Promise,new fwe.Promise(function(r,n){let i=new dwe(e,t),o=xBm(i),s=ZVu.default.request,a=i.signal,c=null,u=function(){let g=new rWt("The user aborted a request.");n(g),i.body&&i.body instanceof SJ.default.Readable&&i.body.destroy(g),!(!c||!c.body)&&c.body.emit("error",g)};if(a&&a.aborted){u();return}let l=function(){u(),f()},p=s(o),d;a&&a.addEventListener("abort",l);function f(){p.abort(),a&&a.removeEventListener("abort",l),clearTimeout(d)}i.timeout&&p.once("socket",function(m){d=setTimeout(function(){n(new ZD(`network timeout at: ${i.url}`,"request-timeout")),f()},i.timeout)}),p.on("error",function(m){n(new ZD(`request to ${i.url} failed, reason: ${m.message}`,"system",m)),f()}),p.on("response",function(m){clearTimeout(d);let g=bBm(m.headers);if(fwe.isRedirect(m.statusCode)){let v=g.get("Location"),S=v===null?null:SBm(i.url,v);switch(i.redirect){case"error":n(new ZD(`redirect mode is set to error: ${i.url}`,"no-redirect")),f();return;case"manual":if(S!==null)try{g.set("Location",S)}catch(R){n(R)}break;case"follow":if(S===null)break;if(i.counter>=i.follow){n(new ZD(`maximum redirect reached at: ${i.url}`,"max-redirect")),f();return}let B={headers:new w8(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&&r5u(i)===null){n(new ZD("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")&&(B.method="GET",B.body=void 0,B.headers.delete("content-length")),r(fwe(new dwe(S,B))),f();return}}m.once("end",function(){a&&a.removeEventListener("abort",l)});let A=m.pipe(new YVu),y={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 Xre(A,y),r(c);return}let x={flush:ilt.default.Z_SYNC_FLUSH,finishFlush:ilt.default.Z_SYNC_FLUSH};if(I=="gzip"||I=="x-gzip"){A=A.pipe(ilt.default.createGunzip(x)),c=new Xre(A,y),r(c);return}if(I=="deflate"||I=="x-deflate"){m.pipe(new YVu).once("data",function(S){(S[0]&15)===8?A=A.pipe(ilt.default.createInflate()):A=A.pipe(ilt.default.createInflateRaw()),c=new Xre(A,y),r(c)});return}c=new Xre(A,y),r(c)}),ABm(p,i)})}var SJ,XVu,fYr,ZVu,ilt,fVe,Y8o,dVe,$8o,ghe,KVu,n5u,eGo,UC,w8,rGo,nGo,pVe,EBm,Xre,hhe,Z8o,IBm,vBm,dwe,YVu,SBm,wBm,oGo=h(()=>{"use strict";SJ=Ae(require("stream"),1),XVu=Ae(require("http"),1),fYr=Ae(require("url"),1),ZVu=Ae(HVu(),1),ilt=Ae(require("zlib"),1),fVe=Symbol("buffer"),Y8o=Symbol("type"),dVe=class e{constructor(){this[Y8o]="";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],u;c instanceof Buffer?u=c:ArrayBuffer.isView(c)?u=Buffer.from(c.buffer,c.byteOffset,c.byteLength):c instanceof ArrayBuffer?u=Buffer.from(c):c instanceof e?u=c[fVe]:u=Buffer.from(typeof c=="string"?c:String(c)),n.push(u)}}this[fVe]=Buffer.concat(n);let i=r&&r.type!==void 0&&String(r.type).toLowerCase();i&&!/[^\u0020-\u007E]/.test(i)&&(this[Y8o]=i)}get size(){return this[fVe].length}get type(){return this[Y8o]}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[fVe].slice(i,i+s),u=new e([],{type:arguments[2]});return u[fVe]=c,u}};Object.defineProperties(dVe.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});Object.defineProperty(dVe.prototype,Symbol.toStringTag,{value:"Blob",writable:!1,enumerable:!1,configurable:!0});ZD.prototype=Object.create(Error.prototype);ZD.prototype.constructor=ZD;ZD.prototype.name="FetchError";try{$8o=require("encoding").convert}catch{}ghe=Symbol("Body internals"),KVu=SJ.default.PassThrough;$T.prototype={get body(){return this[ghe].body},get bodyUsed(){return this[ghe].disturbed},arrayBuffer(){return nlt.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 nlt.call(this).then(function(t){return Object.assign(new dVe([],{type:e.toLowerCase()}),{[fVe]:t})})},json(){var e=this;return nlt.call(this).then(function(t){try{return JSON.parse(t.toString())}catch(r){return $T.Promise.reject(new ZD(`invalid json response body at ${e.url} reason: ${r.message}`,"invalid-json"))}})},text(){return nlt.call(this).then(function(e){return e.toString()})},buffer(){return nlt.call(this)},textConverted(){var e=this;return nlt.call(this).then(function(t){return gBm(t,e.headers)})}};Object.defineProperties($T.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0}});$T.mixIn=function(e){for(let t of Object.getOwnPropertyNames($T.prototype))if(!(t in e)){let r=Object.getOwnPropertyDescriptor($T.prototype,t);Object.defineProperty(e,t,r)}};$T.Promise=global.Promise;n5u=/[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/,eGo=/[^\t\x20-\x7e\x80-\xff]/;UC=Symbol("map"),w8=class e{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:void 0;if(this[UC]=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}`,tWt(t);let r=olt(this[UC],t);return r===void 0?null:this[UC][r].join(", ")}forEach(t){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:void 0,n=tGo(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=tGo(this),i++}}set(t,r){t=`${t}`,r=`${r}`,tWt(t),JVu(r);let n=olt(this[UC],t);this[UC][n!==void 0?n:t]=[r]}append(t,r){t=`${t}`,r=`${r}`,tWt(t),JVu(r);let n=olt(this[UC],t);n!==void 0?this[UC][n].push(r):this[UC][t]=[r]}has(t){return t=`${t}`,tWt(t),olt(this[UC],t)!==void 0}delete(t){t=`${t}`,tWt(t);let r=olt(this[UC],t);r!==void 0&&delete this[UC][r]}raw(){return this[UC]}keys(){return X8o(this,"key")}values(){return X8o(this,"value")}[Symbol.iterator](){return X8o(this,"key+value")}};w8.prototype.entries=w8.prototype[Symbol.iterator];Object.defineProperty(w8.prototype,Symbol.toStringTag,{value:"Headers",writable:!1,enumerable:!1,configurable:!0});Object.defineProperties(w8.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}});rGo=Symbol("internal");nGo=Object.setPrototypeOf({next(){if(!this||Object.getPrototypeOf(this)!==nGo)throw new TypeError("Value of `this` is not a HeadersIterator");var e=this[rGo];let t=e.target,r=e.kind,n=e.index,i=tGo(t,r),o=i.length;return n>=o?{value:void 0,done:!0}:(this[rGo].index=n+1,{value:i[n],done:!1})}},Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));Object.defineProperty(nGo,Symbol.toStringTag,{value:"HeadersIterator",writable:!1,enumerable:!1,configurable:!0});pVe=Symbol("Response internals"),EBm=XVu.default.STATUS_CODES,Xre=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]:{};$T.call(this,t,r);let n=r.status||200,i=new w8(r.headers);if(t!=null&&!i.has("Content-Type")){let o=t5u(t);o&&i.append("Content-Type",o)}this[pVe]={url:r.url,status:n,statusText:r.statusText||EBm[n],headers:i}}get url(){return this[pVe].url}get status(){return this[pVe].status}get ok(){return this[pVe].status>=200&&this[pVe].status<300}get statusText(){return this[pVe].statusText}get headers(){return this[pVe].headers}clone(){return new e(e5u(this),{url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok})}};$T.mixIn(Xre.prototype);Object.defineProperties(Xre.prototype,{url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});Object.defineProperty(Xre.prototype,Symbol.toStringTag,{value:"Response",writable:!1,enumerable:!1,configurable:!0});hhe=Symbol("Request internals"),Z8o=fYr.default.parse,IBm=fYr.default.format,vBm="destroy"in SJ.default.Readable.prototype;dwe=class e{constructor(t){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n;pYr(t)?n=Z8o(t.url):(t&&t.href?n=Z8o(t.href):n=Z8o(`${t}`),t={});let i=r.method||t.method||"GET";if(i=i.toUpperCase(),(r.body!=null||pYr(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:pYr(t)&&t.body!==null?e5u(t):null;$T.call(this,o,{timeout:r.timeout||t.timeout||0,size:r.size||t.size||0});let s=new w8(r.headers||t.headers||{});if(o!=null&&!s.has("Content-Type")){let c=t5u(o);c&&s.append("Content-Type",c)}let a=pYr(t)?t.signal:null;if("signal"in r&&(a=r.signal),a!=null&&!CBm(a))throw new TypeError("Expected signal to be an instanceof AbortSignal");this[hhe]={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[hhe].method}get url(){return IBm(this[hhe].parsedURL)}get headers(){return this[hhe].headers}get redirect(){return this[hhe].redirect}get signal(){return this[hhe].signal}clone(){return new e(this)}};$T.mixIn(dwe.prototype);Object.defineProperty(dwe.prototype,Symbol.toStringTag,{value:"Request",writable:!1,enumerable:!1,configurable:!0});Object.defineProperties(dwe.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0}});rWt.prototype=Object.create(Error.prototype);rWt.prototype.constructor=rWt;rWt.prototype.name="AbortError";YVu=SJ.default.PassThrough,SBm=fYr.default.resolve;fwe.isRedirect=function(e){return e===301||e===302||e===303||e===307||e===308};fwe.Promise=global.Promise;wBm=fwe});var hVe=E(AM=>{"use strict";var Ahe={ANCHOR:"&",COMMENT:"#",TAG:"!",DIRECTIVES_END:"-",DOCUMENT_END:"."},nWt={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"},TBm="tag:yaml.org,2002:",OBm={MAP:"tag:yaml.org,2002:map",SEQ:"tag:yaml.org,2002:seq",STR:"tag:yaml.org,2002:str"};function i5u(e){let t=[0],r=e.indexOf(`
|
|
540
540
|
`);for(;r!==-1;)r+=1,t.push(r),r=e.indexOf(`
|
|
541
541
|
`,r);return t}function o5u(e){let t,r;return typeof e=="string"?(t=i5u(e),r=e):(Array.isArray(e)&&(e=e[0]),e&&e.context&&(e.lineStarts||(e.lineStarts=i5u(e.context.src)),t=e.lineStarts,r=e.context.src)),{lineStarts:t,src:r}}function sGo(e,t){if(typeof e!="number"||e<0)return null;let{lineStarts:r,src:n}=o5u(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 PBm(e,t){let{lineStarts:r,src:n}=o5u(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]===`
|
|
542
542
|
`;)--o;return n.slice(i,o)}function BBm({start:e,end:t},r,n=80){let i=PBm(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 l=Math.round(n/2);i.length>o+l&&(i=i.substr(0,o+l-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):"",u="^".repeat(s);return`${i}
|
|
@@ -3465,7 +3465,7 @@ ${Unl.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&JJo(th
|
|
|
3465
3465
|
`).length),this}updateBottomBar(t){return DHt(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+`
|
|
3466
3466
|
`}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&&znn(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var um=Ae(V4(),1),aol=Ae(uHt(),1);var gin=Ae(V4(),1),ool=Ae(uHt(),1),Ain=function(e,t,r){return typeof e[t]!="function"?(0,gin.of)(e):(0,gin.from)((0,ool.default)(e[t])(r).then(n=>(e[t]=n,e)))};var sol={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}},Sft=class extends b5e{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,um.from)(t):(0,um.isObservable)(t)?n=t:Object.values(t).every(i=>typeof i=="object"&&!Array.isArray(i)&&i!=null)?n=(0,um.from)(Object.entries(t).map(([i,o])=>({name:i,...o}))):n=(0,um.from)([t]),this.process=n.pipe((0,um.concatMap)(this.processQuestion.bind(this)),(0,um.publish)()),this.process.connect(),this.process.pipe((0,um.reduce)((i,o)=>(sol.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,um.defer)(()=>(0,um.of)(t).pipe((0,um.concatMap)(this.setDefaultType.bind(this)),(0,um.concatMap)(this.filterIfRunnable.bind(this)),(0,um.concatMap)(()=>Ain(t,"message",this.answers)),(0,um.concatMap)(()=>Ain(t,"default",this.answers)),(0,um.concatMap)(()=>Ain(t,"choices",this.answers)),(0,um.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,um.defer)(()=>(0,um.from)(this.activePrompt.run().then(n=>({name:t.name,answer:n}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,um.defer)(()=>(0,um.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&sol.get(this.answers,t.name)!==void 0)return um.EMPTY;if(t.when===!1)return um.EMPTY;if(typeof t.when!="function")return(0,um.of)(t);let{answers:r}=this;return(0,um.defer)(()=>(0,um.from)((0,aol.default)(t.when)(r).then(n=>{if(n)return t})).pipe((0,um.filter)(n=>n!=null)))}};function col(e){let t=function(r,n){let i;try{i=new Sft(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",FHt),this.registerPrompt("input",m5e),this.registerPrompt("number",NHt),this.registerPrompt("confirm",jHt),this.registerPrompt("rawlist",zHt),this.registerPrompt("expand",QHt),this.registerPrompt("checkbox",MHt),this.registerPrompt("password",LHt),this.registerPrompt("editor",KHt)},t.restoreDefaultPrompts(),t}var AXo=col();function Ysh(e,t){AXo.registerPrompt(e,t)}function Xsh(){AXo.restoreDefaultPrompts()}var Zsh={prompt:AXo,ui:{BottomBar:JHt,Prompt:Sft},createPromptModule:col,registerPrompt:Ysh,restoreDefaultPrompts:Xsh,Separator:PM},Ru=Zsh;var $sh=["prod","pre-prod","beta","dev","local"];function eah(e){return $sh.some(t=>t===e)}function VJ(e="prod"){let t=e?.trim();return t!=null&&eah(t)?t:"local"}function yin(){let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";return e==null||e.trim().length===0?!1:process.env.FERN_DISABLE_TELEMETRY!=="true"}var wft=require("path");function lol(){let e=tah();return async t=>{for(let r of t)r.module=e(r.filename);return t}}function tah(e=process.argv[1]?(0,wft.dirname)(process.argv[1]):process.cwd(),t=wft.sep==="\\"){let r=t?uol(e):e;return n=>{if(!n)return;let i=t?uol(n):n,{dir:o,base:s,ext:a}=wft.posix.parse(i);(a===".js"||a===".mjs"||a===".cjs")&&(s=s.slice(0,-1*a.length));let c=decodeURIComponent(s);o||(o=".");let u=o.lastIndexOf("/node_modules");if(u>-1)return`${o.slice(u+14).replace(/\//g,".")}:${c}`;if(o.startsWith(r)){let l=o.slice(r.length+1).replace(/\//g,".");return l?`${l}:${c}`:c}return c}}function uol(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var sO={};te(sO,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>jin,DOMExceptionCoercer:()=>FXo,EXCEPTION_STEP_INTERNAL_FIELDS:()=>oKt,ErrorCoercer:()=>tKt,ErrorEventCoercer:()=>NXo,ErrorPropertiesBuilder:()=>eKt,EventCoercer:()=>jXo,ExceptionStepsBuffer:()=>LXo,ObjectCoercer:()=>nKt,PrimitiveCoercer:()=>iKt,PromiseRejectionEventCoercer:()=>zXo,ReduceableCache:()=>QXo,StringCoercer:()=>rKt,chromeStackLineParser:()=>BXo,createDefaultStackParser:()=>kXo,createStackParser:()=>Zol,geckoStackLineParser:()=>RXo,getInjectedReleaseId:()=>hch,getUtf8ByteLength:()=>esl,nodeStackLineParser:()=>Wol,opera10StackLineParser:()=>Vol,opera11StackLineParser:()=>Gol,resolveExceptionStepsConfig:()=>MXo,reverseAndStripFrames:()=>Xol,stripReservedExceptionStepFields:()=>fch,winjsStackLineParser:()=>Uol});var RM=(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 g1e(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 rah=Array.isArray,fol=Object.prototype,a9v=fol.hasOwnProperty,bin=fol.toString,q4=rah||function(e){return bin.call(e)==="[object Array]"};var YHt=e=>e===Object(e)&&!q4(e);var Hhe=e=>e===void 0,ak=e=>bin.call(e)=="[object String]",yXo=e=>ak(e)&&e.trim().length===0,bXo=e=>e===null,GJ=e=>Hhe(e)||bXo(e),Tft=e=>bin.call(e)=="[object Number]"&&e===e;var dol=e=>bin.call(e)==="[object Boolean]";function Ein(e){return e===null||typeof e!="object"}function E5e(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function A1e(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 gol(e,Error)}}function mol(e){return E5e(e,"ErrorEvent")}function Oft(e){return"u">typeof Event&&gol(e,Event)}function hol(e){return E5e(e,"Object")}function gol(e,t){try{return e instanceof t}catch{return!1}}var nah=["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"],Iin=new Map,iah=256;function oah(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 Aol=function(e,t=[]){if(!e)return!1;let r=oah(e,t),n=Iin.get(r);if(n!==void 0)return n;let i=e.toLowerCase(),o=nah.concat(t).some(s=>i.indexOf(s.toLowerCase())!==-1);return Iin.size>=iah&&Iin.clear(),Iin.set(r,o),o};function XHt(e,t,r,n,i){return t>r&&(n.warn("min cannot be greater than max."),t=r),Tft(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),XHt(i??r,t,r,n))}var sah=864e5,aah=1,cah=10;function yol(e={}){return{refillRate:e.exceptionRateLimiterRefillRate??e.__exceptionRateLimiterRefillRate??aah,bucketSize:e.exceptionRateLimiterBucketSize??e.__exceptionRateLimiterBucketSize??cah}}var vin=class{constructor(t){this._buckets={},this._onBucketRateLimited=t._onBucketRateLimited,this._bucketSize=XHt(t.bucketSize,0,100,t._logger),this._refillRate=XHt(t.refillRate,0,this._bucketSize,t._logger),this._refillInterval=XHt(t.refillInterval,0,sah,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 Cin="0123456789abcdef",xin=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+=Cin.charAt(this.bytes[r]>>>4),t+=Cin.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+=Cin.charAt(this.bytes[r]>>>4),t+=Cin.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}},EXo=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??uah()}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 xin.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,xin.ofInner(t)}},uah=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),bol,MN=()=>lah().toString(),lah=()=>(bol||(bol=new EXo)).generate();var Sin=class{add(t){let r=MN(),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 pah(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var Eol=(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=>Eol(`${e} ${o}`,t,r)}},fah=e=>e();function Iol(e,t=fah){return Eol(e,t,pah())}var Bft="Mobile",Tin="iOS",Pft="Android",wol="Tablet",v9v=Pft+" "+wol;var mah="Apple",C9v=mah+" Watch",Tol="Safari",Oin="BlackBerry",Ool="Samsung",hah=Ool+"Browser",gah=Ool+" Internet",Pin="Chrome",Aah=Pin+" OS",yah=Pin+" "+Tin,Pol="Internet Explorer",bah=Pol+" "+Bft,CXo="Opera",x9v=CXo+" Mini",Bol="Edge",Eah="Microsoft "+Bol,xXo="Firefox",Iah=xXo+" "+Tin,SXo="Nintendo",wXo="PlayStation",win="Xbox",vah=Pft+" "+Bft,Cah=Bft+" "+Tol,ZHt="Windows",xah=ZHt+" Phone";var Rol="Generic",S9v=Rol+" "+Bft.toLowerCase(),w9v=Rol+" "+wol.toLowerCase(),Sah="Konqueror",wah="Oculus Browser",vol="Vivaldi",Tah="Yandex",Col="Whale",Oah="DuckDuckGo",Pah="Pale Moon",xol="Waterfox",Sol="Brave",Dol="Claude",kol="Codex",Fol="ChatGPT",Bah="Google Search App",C0="(\\d+(\\.\\d+)?)",IXo=new RegExp("Version/"+C0),vXo=new RegExp("("+Dol+"|"+kol+"|"+Fol+")\\/"+C0);var T9v=new RegExp(win,"i"),O9v=new RegExp(wXo+" \\w+","i"),P9v=new RegExp(SXo+" \\w+","i"),Rah=new RegExp(Oin+"|PlayBook|BB10","i"),Dah={"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 B9v={[bah]:[new RegExp("rv:"+C0)],[Eah]:[new RegExp(Bol+"?\\/"+C0)],[Pin]:[new RegExp("("+Pin+"|CrMo)\\/"+C0)],[yah]:[new RegExp("CriOS\\/"+C0)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+C0)],[Tol]:[IXo],[Cah]:[IXo],[CXo]:[new RegExp("("+CXo+"|OPR)\\/"+C0)],[xXo]:[new RegExp(xXo+"\\/"+C0)],[Iah]:[new RegExp("FxiOS\\/"+C0)],[Sah]:[new RegExp("Konqueror[:/]?"+C0,"i")],[Oin]:[new RegExp(Oin+" "+C0),IXo],[vah]:[new RegExp("android\\s"+C0,"i")],[gah]:[new RegExp(hah+"\\/"+C0)],[wah]:[new RegExp("OculusBrowser\\/"+C0)],[vol]:[new RegExp(vol+"\\/"+C0)],[Tah]:[new RegExp("YaBrowser\\/"+C0)],[Col]:[new RegExp(Col+"\\/"+C0)],[Sol]:[new RegExp(Sol+"\\/"+C0)],[Dol]:[vXo],[kol]:[vXo],[Fol]:[vXo],[Oah]:[new RegExp("(DuckDuckGo|Ddg)\\/"+C0)],[Pah]:[new RegExp("PaleMoon\\/"+C0)],[xol]:[new RegExp(xol+"\\/"+C0)],[Bah]:[new RegExp("GSA\\/"+C0)],[Pol]:[new RegExp("(rv:|MSIE )"+C0)],Mozilla:[new RegExp("rv:"+C0)]};var R9v=[[new RegExp(win+"; "+win+" (.*?)[);]","i"),e=>[win,e&&e[1]||""]],[new RegExp(SXo,"i"),[SXo,""]],[new RegExp(wXo,"i"),[wXo,""]],[Rah,[Oin,""]],[new RegExp(ZHt,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[xah,""];if(new RegExp(Bft).test(t)&&!/IEMobile\b/.test(t))return[ZHt+" "+Bft,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let n=r[1],i=Dah[n]||"";return/arm/i.test(t)&&(i="RT"),[ZHt,i]}return[ZHt,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[Tin,t.join(".")]}return[Tin,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=Hhe(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+Pft+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Pft+")","i"),e=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[Pft,t.join(".")]}return[Pft,""]}],[/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/,[Aah,""]],[/Linux|debian/i,["Linux",""]]];var Bin="[Circular]",Rin="[Truncated]",K8="[Unserializable]",Nol="[Function]",F9v=Date.prototype.getTime,N9v=Date.prototype.toISOString;function bne(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 Khe(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=K8}Object.defineProperty(e,n,{value:i,enumerable:!0,writable:!0,configurable:!0})}return e}function TXo(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 I5e=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 jol="utf8",kah=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Fah(e){return typeof e=="string"&&kah.test(e)}function v5e(e,t){return Fah(e)?e:t()}function Rft(e,t){let r=new Error(t);try{Object.defineProperty(r,"name",{value:e,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function zol(e){return e?.replace(/\/+$/,"")}async function Qol(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 OXo(){return new Date().toISOString()}function LN(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}async function y1e(e,t,r){let n;try{return await Promise.race([e,new Promise((i,o)=>{n=LN(()=>{try{r?.(),i()}catch(s){o(s)}},t)})])}finally{clearTimeout(n)}}var Mol=e=>e&&typeof e.then=="function";function $Ht(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var Din,Lol,kin;function _ol(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);return kin&&r.length===Lol||(Lol=r.length,kin=r.reduce((n,i)=>{Din||(Din={});let o=Din[i];if(o)n[o[0]]=o[1];else{let s=e(i);for(let a=s.length-1;a>=0;a--){let u=s[a]?.filename,l=t[i];if(u&&l){n[u]=l,Din[i]=[u,l];break}}}return n},{})),kin}var PXo=50,Nah=1e3,jah=100,zah=4,eKt=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&&q4(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,u=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},l={type:o.type,value:o.value,mechanism:u};o.stack&&(l.stacktrace={type:"raw",frames:o.stack}),n.push(l),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:_ol(this.stackParser),skipFirstLines:t.skipFirstLines??1}}getAggregateErrors(t){try{if(A1e(t)){let r=Object.getPrototypeOf(t);for(let n=0;r&&n<jah;n++){let i=Object.getOwnPropertyDescriptor(r,"constructor")?.value;if(typeof i=="function"&&i.name==="AggregateError"){let o=t.errors;return q4(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=[],u={},l=(f,m,g=0)=>{let A=p(m,g),y=A.apply;if(A.apply=R=>{c.push(f);try{return y(R)}finally{c.pop()}},g>zah||g>0&&c.indexOf(f)!==-1)return this.coerceFallback(A);let I=typeof f=="object"&&f!==null||typeof f=="function";if(g===0&&i>=PXo||I&&a.has(f))return;I&&a.add(f),g===0&&i++;let x=this.getAggregateErrors(f);s||=!!x;let v;try{if(v=this.applyCoercers(f,A),!v)throw u}catch(R){if(R===u){g===0&&i--;return}if(!s)throw R;v=this.coerceFallback(A)}if(!x||i>=PXo)return v;let S;try{S=x.length}catch{return v}if(!Number.isInteger(S)||S<0||S>4294967295)return v;let B=[];for(let R=0;i<PXo&&o<Nah&&R<S;R++){o++;let D;try{D=A.next(x[R])}catch{i++,D=this.coerceFallback(p(m+1))}D&&B.push(D)}return{...v,errors:B}},p=(f,m=0)=>({...r,syntheticException:f==0?r.syntheticException:void 0,mechanism:f==0?t:{},apply:g=>{let A=l(g,f,m+1);if(!A)throw u;return A},next:g=>l(g,f+1)}),d=p(n);return{...d,apply:f=>l(f,n)??this.coerceFallback(d)}}};var iR="?",Qah="<anonymous>",Mah=/^([a-z][a-z0-9.+-]+):/i,Lah=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function _ah(e){if(!e||e===Qah)return!1;let t=Mah.exec(e);return!t||Lah.includes(t[1].toLowerCase())}function Ene(e,t,r,n,i){let o={platform:e,filename:t,function:r==="<anonymous>"?iR:r,in_app:_ah(t)};return Hhe(n)||(o.lineno=n),Hhe(i)||(o.colno=i),o}var Fin=(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]:iR,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var Uah=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Vah=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Gah=/\((\S*)(?::(\d+))(?::(\d+))\)/,BXo=(e,t)=>{let r=Uah.exec(e);if(r){let[,i,o,s]=r;return Ene(t,i,iR,+o,+s)}let n=Vah.exec(e);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=Gah.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}let[o,s]=Fin(n[1]||iR,n[2]);return Ene(t,s,o,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var qah=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Wah=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,RXo=(e,t)=>{let r=qah.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let s=Wah.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]||iR;return[o,i]=Fin(o,i),Ene(t,i,o,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var Hah=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,Uol=(e,t)=>{let r=Hah.exec(e);return r?Ene(t,r[2],r[1]||iR,+r[3],r[4]?+r[4]:void 0):void 0};var Kah=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,Vol=(e,t)=>{let r=Kah.exec(e);return r?Ene(t,r[2],r[3]||iR,+r[1]):void 0},Jah=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,Gol=(e,t)=>{let r=Jah.exec(e);return r?Ene(t,r[5],r[3]||r[4]||iR,+r[1],+r[2]):void 0};var Yah=/^\s*[-]{4,}$/,Xah=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,Zah=/^Promise\.(?:all|any)$/,$ah=/^index \d+$/,ech="node:internal/promise",Wol=(e,t)=>{let r=e.match(Xah);if(r){let n,i,o,s,a;if(r[1]){o=r[1];let l=o.lastIndexOf(".");if(o[l-1]==="."&&l--,l>0){n=o.slice(0,l),i=o.slice(l+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||iR,o=s?`${s}.${a}`:a);let c=r[2]?.startsWith("file://")?r[2].slice(7):r[2],u=r[5]==="native";return c?.match(/\/[A-Z]:/)&&(c=c.slice(1)),!c&&r[5]&&!u&&(c=r[5]),Zah.test(o)&&$ah.test(c||"")&&(c=ech),{filename:c?decodeURI(c):void 0,module:void 0,function:o,lineno:qol(r[3]),colno:qol(r[4]),in_app:tch(c||"",u),platform:t}}if(e.match(Yah))return{filename:e,platform:t}};function tch(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 qol(e){return parseInt(e||"",10)||void 0}var Hol=/\(error: (.*)\)/,Kol=50,rch=10,nch=1e3;function DXo(e,t){return e.filename===t.filename&&e.function===t.function&&e.module===t.module&&e.lineno===t.lineno&&e.colno===t.colno}function ich(e){for(let t=1;t<=rch;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(!DXo(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 och(e,t){let r=t.start+t.length,n=Yol(e,t);n&&e.splice(r+n===e.length?r:t.start,n)}function Jol(e,t){let r=t.start;for(;r>0&&DXo(e[r-1],e[r-1+t.length]);)r--;return t.start-r}function Yol(e,t){let r=t.start+t.length,n=r;for(;n<e.length&&DXo(e[n],e[n-t.length]);)n++;return n-r}function sch(e,t){let r=t[0],n=e.length-(r?Jol(e,r):0);for(let i of t)n-=Yol(e,i);return n}function ach(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++)cch(t,n,r)&&(r=n);e.push(...e.splice(0,r))}function cch(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 Xol(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,Kol).map(r=>({...r,filename:r.filename||uch(t).filename,function:r.function||iR}))}function uch(e){return e[e.length-1]||{}}function kXo(){return Zol("web:javascript",BXo,RXo)}function Zol(e,...t){return(r,n=0)=>{let i=[],o=r.split(`
|
|
3467
3467
|
`),s=Math.min(o.length,n+nch),a=[];for(let l=n;l<s;l++){let p=o[l];if(p.length>1024)continue;let d=Hol.test(p)?p.replace(Hol,"$1"):p;if(!d.match(/\S*Error: /)){for(let f of t){let m=f(d,e);if(m){i.push(m);let g=ich(i);if(g){for(let A=a.length-1;A>=0;A--){let y=a[A];if(y.start+y.length<=g.start)break;a.pop()}a.push(g)}break}}if(sch(i,a)>=Kol)break}}let c=[...a].sort((l,p)=>p.start-l.start),u=c[c.length-1];if(u){let l=Jol(i,u);i.splice(u.start-l,l);for(let p of c)p.start-=l}for(let l of c)och(i,l);return a.some(l=>l.start===0&&i.length===l.length)&&ach(i),Xol(i)}}var FXo=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let n=ak(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 E5e(t,"DOMException")}isDOMError(t){return E5e(t,"DOMError")}};var tKt=class{match(t){return A1e(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 NXo=class{match(t){if(!mol(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 ak(t.message)&&t.message.length>0}_buildLocationStack(t){let r=t,n=r.lineno??0,i=r.colno??0;if(!(!ak(r.filename)||r.filename.length===0)&&n!==0)return`Error
|
|
3468
|
-
at ${r.filename}:${n}:${i}`}};var lch=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,rKt=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(lch);return i&&(r=i[1],n=i[2]),[r,n]}};var $ol=["fatal","error","warning","log","info","debug"];function Nin(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 nKt=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(Oft(t))return t.constructor.name;let r="name"in t?t.name:void 0;return ak(r)&&!yXo(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=Nin(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(t){return ak(t)&&!yXo(t)&&$ol.indexOf(t)>=0}getStack(t){try{return ak(t.stacktrace)&&t.stacktrace.length>0?t.stacktrace:ak(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(A1e(n))return n}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var jXo=class{match(t){return Oft(t)}coerce(t,r){let n=t.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${Nin(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var iKt=class{match(t){return Ein(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var zXo=class{match(t){return E5e(t,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(t)}isCustomEventWrappingRejection(t){if(!Oft(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 Ein(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 QXo=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 oKt={MESSAGE:"$message",TIMESTAMP:"$timestamp"},pch=new Set([oKt.MESSAGE,oKt.TIMESTAMP]),jin={enabled:!0,max_bytes:32768};function MXo(e){return e?{enabled:e.enabled??jin.enabled,max_bytes:dch(e.max_bytes,jin.max_bytes)}:{...jin}}function fch(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((n,i)=>pch.has(i)?(t.push(i),n):(n[i]=e[i],n),{}),droppedKeys:t}}var LXo=class{constructor(t){this._entries=[],this._totalBytes=0,this._config=MXo(t)}setConfig(t){this._config=MXo(t),this._trimToMaxBytes()}add(t){let r=mch(t);if(!r)return;let n=esl(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 dch(e,t){if(!Tft(e)||e===1/0||e===-1/0)return t;let r=Math.floor(e);return r<0?t:r}function mch(e){let t;try{t=g1e(e)}catch{return}try{let r=JSON.parse(t);if(!YHt(r))return;let n=r,i=n[oKt.MESSAGE],o=n[oKt.TIMESTAMP];return!ak(i)||i.trim().length===0||!ak(o)&&!Tft(o)?void 0:{step:n,json:t}}catch{return}}function esl(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 hch(){let e=globalThis._posthogReleaseId;return typeof e=="string"&&e.length>0?e:void 0}var _Xo=e=>{if("flags"in e){let t=tsl(e.flags),r=rsl(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([i,o])=>[i,Dft(o)])),n=Object.fromEntries(Object.entries(t).map(([i,o])=>[i,gch(i,o,r[i])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:n}}};function gch(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 tsl=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,sKt(r)]).filter(([,t])=>t!==void 0)),rsl=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?Dft(n):void 0]}))},sKt=e=>e===void 0?void 0:e.variant??e.enabled,Dft=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var nsl=["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"],Ach=["$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",...nsl,"$session_id","$window_id","$lib","$lib_version","$device_id","$is_server","$react_native_version"],aKt=(e,t=[])=>{let r={},n=i=>{e[i]!==void 0&&(r[i]=e[i])};return Ach.forEach(n),t.forEach(n),r};var zin=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 UXo(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var bch="NativeGzipValidationError",Ech=31,Ich=139,vch=8,Cch=e=>e.length>=2&&e[0]===Ech&&e[1]===Ich;var cKt,xch=()=>{if(cKt)return cKt;cKt=[];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;cKt[e]=t>>>0}return cKt},Sch=e=>{let t=xch(),r=4294967295;for(let n=0;n<e.length;n++)r=t[(r^e[n])&255]^r>>>8;return(4294967295^r)>>>0},Qin=e=>{throw Rft(bch,`Native gzip produced invalid output: ${e}`)},wch=async(e,t)=>{e.size<18&&Qin("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());(!Cch(r)||r[2]!==vch)&&Qin("invalid-header");let n=new DataView(await e.slice(e.size-8).arrayBuffer());n.getUint32(0,!0)!==Sch(t)&&Qin("invalid-crc");let i=t.length>>>0;n.getUint32(4,!0)!==i&&Qin("invalid-size")};async function uKt(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 u=>{try{await o.abort(u)}catch{}throw u}),a=new Response(i.readable).blob(),[c]=await Promise.all([a,s]);return await wch(c,n),c}catch(n){if(r?.rethrow)throw n;return t&&console.error("Failed to gzip compress data",n),null}}var J8=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 TXo(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=Rft("AbortError","Response body read timed out");this.cancelResponseBody(t),this.responseBodyTextPromise=Promise.reject(t)}else{let t=new Promise((n,i)=>{this.responseBodyTimer=LN(()=>{this._bodyReadTimedOut=!0;let o=Rft("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{}})()}},Jhe=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};var csl=(e,t)=>{for(let r of Object.keys(t))(r.startsWith("$feature/")||r==="$active_feature_flags")&&(e[r]=t[r])};async function isl(e){if(e instanceof J8){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 Tch(e){return typeof e=="object"&&(e instanceof J8||usl(e))}function usl(e){return e instanceof Jhe}function Och(e){if(e instanceof J8)return e.status===502||e.status===504;if(!(e instanceof Jhe))return!1;let t=e.error;return(t?.code??t?.cause?.code)!=="ECONNREFUSED"}var osl=10485760;function ssl(e){try{return typeof e!="string"?e instanceof Uint8Array?e.byteLength:e.size:"u">typeof Buffer?Buffer.byteLength(e,jol):new TextEncoder().encode(e).length}catch{return 0}}function kft(e){return typeof e=="object"&&e instanceof J8&&e.status===413}function Min(e){return e instanceof J8?e.status===408||e.status===429||e.status>=500:usl(e)}function asl(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var VXo="default",lKt=class{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new eKt([new tKt,new nKt,new rKt,new iKt],kXo())}getEvaluationRuntime(){}constructor(t,r={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new Sin,this._events=new zin,this._isInitialized=!1;let n=typeof t=="string"?t.trim():"",i=typeof r.host=="string"?r.host.trim():"",o=!n;this._logger=Iol("[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=zol(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:Min},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=!UXo()||(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(RM.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(RM.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(RM.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 csl(n,r),t.event==="$feature_flag_called"&&n.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled()&&(n=aKt(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}`,u={token:this.apiKey,distinct_id:t,groups:r,person_properties:n,group_properties:i,...o};n.$device_id&&(u.$device_id=n.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(u.evaluation_contexts=this.evaluationContexts);let l=this.getEvaluationRuntime();l&&(u.evaluation_runtime=l);let p={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(u)};return this._logger.info("Flags URL",c),this.fetchWithRetry(c,p,{type:"required",consume:d=>d.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:Och},this.featureFlagsRequestTimeoutMs).then(d=>({success:!0,response:_Xo(d)})).catch(d=>(this._events.emit("error",d),{success:!1,error:this.categorizeRequestError(d)}))}categorizeRequestError(t){if(t instanceof J8)return{type:"api_error",statusCode:t.status};if(t instanceof Jhe){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=sKt(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 u=c.response;return u.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"),u.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:u?.requestId,quotaLimited:u.quotaLimited}):u}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(RM.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(RM.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(RM.Props,this.props)})}processBeforeEnqueue(t){return t}async flushStorage(){}getQueueRouteKey(t){return VXo}persistedQueueKeyForRoute(t){return RM.Queue}getActiveQueueRoutes(){return[VXo]}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=LN(()=>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=asl(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=v5e(o.uuid,MN),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:OXo(),uuid:v5e(r?.uuid,MN)};return(r?.disableGeoip??this.disableGeoip)&&(asl(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 isl(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(()=>$Ht([r])).then(()=>(this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=i,this.flushPromise=i,this.flushPromises.add(i),this.addPendingPromise(i),$Ht([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 uKt(t,this.isDebug)}getBatchEndpointPath(t){return"/batch/"}async sendBatch(t,r,n=VXo){let i={api_key:this.apiKey,batch:t.map(u=>{if(!u)return u;let l=this.normalizeTimestampForWire(u.timestamp);return l===u.timestamp?u:{...u,timestamp:l}}),sent_at:OXo()};this.historicalMigration&&(i.historical_migration=!0);let o=g1e(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)),u=async()=>{let p=this.getPersistedProperty(n)||[],d=[...a],f=p.filter(m=>{let g=m.message?.uuid,A=d.findIndex(y=>y===m||typeof g=="string"&&g.length>0&&y.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()},l={retryCheck:p=>kft(p)?!1:Min(p)};try{await this.sendBatch(c,l,t)}catch(p){if(kft(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 Jhe||await u(),this._events.emit("error",p),p}await u(),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(l){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${t} batch; reporting it as too large`,l)),{kind:"too-large",measuredLocally:!0}}let o=ssl(i);if(o>osl)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${t} batch of ${o} bytes: the endpoint accepts at most ${osl}`)),{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,u={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,u,{type:"successful-write"},{retryCheck:l=>kft(l)||l instanceof J8&&l.retryAfterMs!==void 0?!1:Min(l)}),{kind:"ok"}}catch(l){if(kft(l))return{kind:"too-large"};if(Min(l)){let p=l instanceof J8?l.retryAfterMs:void 0;return{kind:"retry-later",error:l,...p!==void 0&&{retryAfterMs:p}}}return{kind:"fatal",error:l}}}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=ssl(s),c={...this._retryOptions,...i},u=0;return await Qol(async()=>{u++;let l=new AbortController,p=o??this.requestTimeout,d=Date.now()+p,f,m=new Promise((x,v)=>{f=LN(()=>{let S=Rft("AbortError",`Request timed out after ${p}ms`);v(S),l.abort(S)},p)}),g,A=!1,y,I=()=>y??=(async()=>{try{await g?.body?.cancel()}catch{}})();try{let x;try{x=this.fetch(t,{signal:l.signal,...r})}catch(B){throw new Jhe(B)}x.then(B=>{l.signal.aborted&&!A&&Promise.resolve(B.body?.cancel()).catch(()=>{})}).catch(()=>{});try{g=await Promise.race([x,m]),A=!0}catch(B){throw new Jhe(B)}let v=r.mode==="no-cors",S=n.type==="successful-write"?300:400;if(!v&&(g.status<200||g.status>=S))throw new J8(g,a,d,l);if(n.type==="successful-write"){try{await Promise.race([I(),m])}catch{}return}try{return await Promise.race([n.consume(g),m])}catch(B){throw l.signal.aborted?new Jhe(B):B}}finally{clearTimeout(f),l.signal.aborted&&g&&I()}},{...c,retryCheck:l=>{let p=c.retryCheck(l);return p&&u<=c.retryCount&&l instanceof J8&&l.cancelResponseBody(),p}})}async _shutdown(t=3e4){await this._initPromise;let r=!1;return this.clearFlushTimer(),this.disabled?void 0:y1e((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(!Tch(i))throw i;await isl(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 kch=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi;var _7v=new RegExp(kch.source,"i"),lsl=/[a-z][a-z0-9+.-]{0,63}:\/\//i,U7v=new RegExp(`^${lsl.source}`,"i"),V7v=new RegExp(lsl.source,"gi");var Fch=["is_not","is_set"],Nch=1152921504606847e3,el=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,e.prototype)}};function GXo(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(!GXo(t in e?e[t]:null))return!1;return!0}function qXo(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(!qXo(t in e?e[t]:null))return!1;return!0}function pKt(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 el("Cannot stringify an unpaired surrogate like the flags service");t++}else if(r>=56320&&r<=57343)throw new el("Cannot stringify an unpaired surrogate like the flags service")}}function _in(e,t=new Set){if(!(e===null||typeof e=="boolean")){if(typeof e=="string")return void pKt(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new el(`Cannot represent non-finite number ${e} like the flags service`);return}if(Array.isArray(e)){if(t.has(e))throw new el("Cannot represent a circular array during local evaluation");t.add(e);try{for(let r=0;r<e.length;r++)r in e&&_in(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 el("Cannot represent a non-JSON object like the flags service");if(t.has(e))throw new el("Cannot represent a circular object during local evaluation");t.add(e);try{for(let n of Object.keys(e))pKt(n),_in(e[n],t)}finally{t.delete(e)}return}throw new el(`Cannot represent ${typeof e} like the flags service`)}}function jch(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,u=a?t.charCodeAt(n+1):0,l=s?(i-55296)*1024+c-56320+65536:i,p=a?(o-55296)*1024+u-56320+65536:o;if(l!==p)return l-p;r+=s?2:1,n+=a?2:1}return e.length-t.length}function WXo(e,t=new Set){if(e===null)return"null";if(typeof e=="string")return pKt(e),JSON.stringify(e);if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"){if(!Number.isFinite(e))throw new el(`Cannot stringify non-finite number ${e} like the flags service`);if(Number.isInteger(e))throw new el(`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 el("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?WXo(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 el("Cannot stringify a non-JSON object like the flags service");if(t.has(e))throw new el("Cannot stringify a circular object during local evaluation");t.add(e);try{let n=Object.keys(e);return n.forEach(pKt),`{${n.sort(jch).map(i=>`${JSON.stringify(i)}:${WXo(e[i],t)}`).join(",")}}`}finally{t.delete(e)}}throw new el(`Cannot stringify ${typeof e} like the flags service`)}function Lin(e){return typeof e=="string"?(pKt(e),e):WXo(e)}function psl(e){try{return new RegExp(e),!0}catch{return!1}}function Y8(e){return String(e).replace(/[A-Z]/g,t=>t.toLowerCase())}function dsl(e,t,r){if(!/^\d+$/.test(e)||r==="strict"&&e.length>1&&e[0]==="0")throw new el(`Invalid semver: ${t}`);return parseInt(e,10)}function t1(e,t="strict"){let n=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!n||n.startsWith("."))throw new el(`Invalid semver: ${e}`);let i=n.split("."),o=s=>s===void 0||s===""?0:dsl(s,e,t);return[o(i[0]),o(i[1]),o(i[2])]}function X8(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 zch(e,t){let r=t1(e,t);return{lower:[r[0],r[1],r[2]],upper:[r[0],r[1]+1,0]}}function Qch(e,t){let[r,n,i]=t1(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 Mch(e,t){let n=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!n)throw new el(`Invalid wildcard semver: ${e}`);let i=n.split("."),o=c=>{if(t==="legacy-permissive"){let u=parseInt(c,10);if(!isNaN(u))return u}else try{return dsl(c,e,t)}catch{}throw new el(`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 fsl(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 el(`${e} is in an invalid date format`)}throw new el(`The date provided ${e} must be a string, number, or date object`)}function HXo(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 KXo(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 el(`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&&!Fch.includes(o)&&o!=="exact"&&o!=="is_not")return r.warnFunction?.(`Property ${n} cannot have a value of null with the ${o} operator`),!1;let u=(p,d)=>{if(r.propertyMatchingVersion!==2&&GXo(p)||Array.isArray(p)&&p.length===0)return _in(d),qXo(p)===qXo(d);if(r.propertyMatchingVersion===2&&typeof d=="number"&&GXo(p))return _in(d),!1;if(Array.isArray(p)){let f=Lin(d).toLowerCase();return p.some(m=>Lin(m).toLowerCase()===f)}return Lin(p).toLowerCase()===Lin(d).toLowerCase()},l=(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 u(i,c);case"is_not":return!u(i,c);case"is_set":return!0;case"icontains":return Y8(c).includes(Y8(i));case"not_icontains":return!Y8(c).includes(Y8(i));case"starts_with":return Y8(c).startsWith(Y8(i));case"not_starts_with":return!Y8(c).startsWith(Y8(i));case"ends_with":return Y8(c).endsWith(Y8(i));case"not_ends_with":return!Y8(c).endsWith(Y8(i));case"regex":return psl(String(i))&&String(c).match(String(i))!==null;case"not_regex":return psl(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)?l(d,p,o):l(String(c),String(i),o)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new el("Date operations cannot be performed on boolean values");let p=HXo(String(i));p==null&&(p=fsl(i));let d=fsl(c);return o==="is_date_before"?d<p:d>p}case"semver_eq":return X8(t1(String(c),s),t1(String(i),s))===0;case"semver_neq":return X8(t1(String(c),s),t1(String(i),s))!==0;case"semver_gt":return X8(t1(String(c),s),t1(String(i),s))>0;case"semver_gte":return X8(t1(String(c),s),t1(String(i),s))>=0;case"semver_lt":return X8(t1(String(c),s),t1(String(i),s))<0;case"semver_lte":return X8(t1(String(c),s),t1(String(i),s))<=0;case"semver_tilde":{let p=t1(String(c),s),{lower:d,upper:f}=zch(String(i),s);return X8(p,d)>=0&&X8(p,f)<0}case"semver_caret":{let p=t1(String(c),s),{lower:d,upper:f}=Qch(String(i),s);return X8(p,d)>=0&&X8(p,f)<0}case"semver_wildcard":{let p=t1(String(c),s),{lower:d,upper:f}=Mch(String(i),s);return X8(p,d)>=0&&X8(p,f)<0}default:throw new el(`Unknown operator: ${o}`)}}async function msl(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 fKt(e,t,r="",n="."){let i=await msl(`${e}${n}${t}${r}`);return parseInt(i.slice(0,15),16)/Nch}async function JXo(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 fKt("holdout",t,"","-")>n/100))return`holdout-${e.id}`}function Uin(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 YXo(e,t,r){let n=await fKt(e,t,"variant");return Uin(r).find(i=>n>=i.valueMin&&n<i.valueMax)?.key}function XXo(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:Dft(n)}var hsl=9223372036854776e3,Lch="9223372036854775808",_ch=Object.prototype.propertyIsEnumerable;function Uch(){return{ancestors:new WeakSet,remainingNodes:1e4}}function Ine(e,t){try{return gsl(e,t,Uch(),0)}catch{return[]}}function Vch(e,t){let r=e.toString(),n=BigInt(Lch);return e>=n||e<-n?(t?.debug(`Attribute ${r} is outside the int64 range; encoding it as a string`),{stringValue:r}):{intValue:r}}function eZo(e,t,r,n){if(r.remainingNodes<=0)return{stringValue:Rin};if(r.remainingNodes--,dol(e))return{boolValue:e};if(typeof e=="bigint")return Vch(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>=hsl||e<-hsl?(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:bne(e)};if(typeof e=="function")return{stringValue:Nol};if(typeof e=="symbol")return{stringValue:String(e)};if(typeof e=="object"&&e!==null){if(r.ancestors.has(e))return{stringValue:Bin};if(n>=20)return{stringValue:Rin};if(e instanceof Date){let i=e.getTime(),o=Number.isFinite(i)?e.toISOString():String(e);return{stringValue:typeof o=="string"?bne(o):String(o)}}r.ancestors.add(e);try{try{let i=e.toJSON;if(typeof i=="function")return eZo(i.call(e),t,r,n+1)}catch{}return q4(e)?{arrayValue:{values:Gch(e,t,r,n+1)}}:{kvlistValue:{values:gsl(e,t,r,n+1)}}}finally{r.ancestors.delete(e)}}return{stringValue:bne(String(e))}}function Gch(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(GJ(a))continue;i.push(eZo(a,t,r,n))}catch{i.push({stringValue:K8})}return e.length>s&&i.push({stringValue:Rin}),i}function gsl(e,t,r,n){let i=[];for(let o in e)if(_ch.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(bXo(s)||Hhe(s))continue;i.push({key:bne(o),value:eZo(s,t,r,n)})}catch{i.push({key:bne(o),value:{stringValue:K8}})}}return i}function mKt(e,t,r){return{...Khe({},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 qch=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function hKt(e,t){let r=Khe({},e),n={};for(let i of qch)Object.prototype.hasOwnProperty.call(r,i)&&(n[i]=r[i],delete r[i]);return[...Ine(r,t),...Ine(n,t)]}var Asl={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 Wch(e){if(e)return Object.prototype.hasOwnProperty.call(Asl,e)?Asl[e]:e}function tZo(e,t){let r=Wch(e);return{...r?{"os.name":r}:{},...t?{"os.version":t}:{}}}var Hch={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}},oHv=Hch.info;var C5e=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=LN(()=>{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 gKt(){return 1-.25+Math.random()*.25*2}var Z8=1;function AKt(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 yKt=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function rZo(e){return String(e)+"000000"}function nZo(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 ysl(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}function iZo(e,t,r){return mKt(e,t,r)}function oZo(e,t,r,n){return{resourceMetrics:[{resource:{attributes:hKt(t)},scopeMetrics:[{scope:{name:r,version:n},metrics:e}]}]}}function Gin(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 bsl=1,bKt=class{constructor(t,r,n){this._instance=t,this._config=r,this._logger=n,this._series=new Map,this._flushTimer=new C5e(()=>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 I5e,this._consecutiveFlushFailures=0,this._flushJitter=Z8,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=Z8,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=nZo(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(yKt.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[ysl(r,yKt)]+=1;break}}}_runBeforeSend(t){let r=this._config.beforeSend;if(!r)return t;let n=q4(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(AKt(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=gKt()):(this._consecutiveFlushFailures=0,this._flushJitter=Z8),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 oZo(this._buildMetrics(t),iZo(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(t){let r=rZo(Date.now()),n=new Map;for(let i of t.values()){let o=nZo(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:bsl,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?s.gauge={dataPoints:[]}:s.histogram={aggregationTemporality:bsl,dataPoints:[]},n.set(o,s));let a=Ine(i.attributes??{},this._logger),c=rZo(i.windowStartMs);if(i.type==="count"){let u={attributes:a,startTimeUnixNano:c,timeUnixNano:r,asDouble:i.total??0};s.sum.dataPoints.push(u)}else if(i.type==="gauge"){let u={attributes:a,timeUnixNano:r,asDouble:i.last??0};s.gauge.dataPoints.push(u)}else if(i.hist){let u={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:yKt};s.histogram.dataPoints.push(u)}}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 Xch="0".repeat(32),Zch="0".repeat(16),$ch=/^[0-9a-f]+$/;function euh(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 tuh(e){let t="";for(let r=0;r<e.length;r++)t+=e[r].toString(16).padStart(2,"0");return t}function Esl(e){let t=tuh(euh(e));return/[^0]/.test(t)?t:t.slice(0,-1)+"1"}function Isl(){return Esl(16)}function vsl(){return Esl(8)}function Csl(e,t,r){return typeof e=="string"&&e.length===t&&e!==r&&$ch.test(e)}function xsl(e){return Csl(e,32,Xch)}function Ssl(e){return Csl(e,16,Zch)}var ruh=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function wsl(e){let t=Tsl(e);return t&&{traceId:t.traceId,spanId:t.spanId,flags:nuh(t.flags)}}function nuh(e){return 1&parseInt(e,16)?Win:iuh}function Tsl(e){if(typeof e!="string")return;let t=ruh.exec(e.trim());if(!t)return;let[,r,n,i,o,s]=t;if(r!=="ff"&&!(r==="00"&&s)&&!(!xsl(n)||!Ssl(i)))return{version:r,traceId:n,spanId:i,flags:o}}function Osl(e){return Tsl(e)&&e.trim()}function qin(e){return Array.isArray(e)&&e.length===1?e[0]:e}var Win="01",iuh="00";function Psl(e,t,r=Win){return`00-${e}-${t}-${r}`}var ouh=32,sZo=512;function Hin(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>ouh)){for(let n of r)if(n.trim()&&!n.includes("="))return;return t.length<=sZo?t:auh(r)}}var suh=128;function auh(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()>sZo;n--)t[n].length>suh&&t.splice(n,1);for(;t.length&&r()>sZo;)t.pop();return t.length?t.join(","):void 0}var Bsl="unknown";function x5e(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 "${Bsl}"`),Bsl)}function Fft(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 Rsl(e,t,r){let n=Fft(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 Kin(e,t){return e<t?t:e}function EKt(e,t,r,n){let i=Fft(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 Yin(){let e=globalThis.performance;return typeof e?.now=="function"?e.now():void 0}var Nft=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??Win,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:Yin(),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=Yin();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(GJ(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]=Zin(r,this._maxAttributeValueLength)}setAttribute(t,r){return this._mutable("setAttribute")&&this._writeAttribute(t,r),this}setAttributes(t){if(this._mutable("setAttributes")){let r=Khe({},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&&Nsl(r,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:x5e(t,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:EKt(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:aZo(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}=cZo(t);return this.addEvent(cuh,{"exception.type":r,"exception.message":n,...i&&{"exception.stacktrace":i}}),this.setStatus("error",n)}updateName(t){return this._mutable("updateName")&&(this._name=x5e(t,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return Psl(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=EKt(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:Kin(n,this._startTime),...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}},cuh="exception",uuh=4294967295;function luh(e){try{return typeof e=="string"?e:String(e)}catch{return K8}}function S5e(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?0:Math.min(Math.floor(e),uuh)}function puh(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 ksl(e,t,r,n,i,o,s=[]){let a=0,c=0,u={};for(let f of puh(e.attributes,s)){let m=e.attributes[f];if(!GJ(m)){if(!t.has(f)){if(a>=r){c++;continue}a++}Object.defineProperty(u,f,{value:Zin(m,o),enumerable:!0,writable:!0,configurable:!0})}}e.attributes=u,c&&(e.droppedAttributesCount=S5e(e.droppedAttributesCount)+c);let l=0,p=0,d=[];for(let f of e.events){if(l>=n){p++;continue}if(l++,f.attributes){let m=Nsl(f.attributes,i,o);f.attributes=m.attributes,m.dropped&&(f.droppedAttributesCount=S5e(f.droppedAttributesCount)+m.dropped)}d.push(f)}e.events=d,p&&(e.droppedEventsCount=S5e(e.droppedEventsCount)+p),e.status?.message&&(e.status={...e.status,message:aZo(luh(e.status.message),o)})}var Xin=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(){}},Fsl=new Xin,IKt=class extends Xin{constructor(t,r){super(),this._traceparent=t,this._tracestate=r}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}};function fuh(e){try{let t=e.stack;return typeof t=="string"&&t?{stack:t}:{}}catch{return{}}}function b1e(e,t){let r=qin(e?.parent)??t,n=typeof r=="string"||r==null?r:Dsl(r,"traceparent"),i=Osl(n);if(!i)return Fsl;let o=typeof r=="string"||r==null?e?.tracestate:Dsl(r,"tracestate");return new IKt(i,Hin(o))}function Dsl(e,t){try{let r=e[t];return typeof r=="function"?r.call(e):void 0}catch{return}}function aZo(e,t){return e.length>t?e.slice(0,t):e}function Zin(e,t){return Jin(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}function Jin(e,t,r,n){if(e===null||typeof e!="object")return GJ(e)||r.remainingNodes<=0?e:(r.remainingNodes--,typeof e=="string"?aZo(e,t):e);if(r.ancestors.has(e))return Bin;if(r.remainingNodes<=0||n>=20)return e;r.remainingNodes--,r.ancestors.add(e);try{if(e instanceof Date)return e;let i=duh(e);if(i.selfDescribed)return GJ(i.value)?String(i.value):Jin(i.value,t,r,n+1);if(q4(e)){let a=Math.min(e.length,1e3),c=[];for(let u=0;u<a;u++)try{c.push(Jin(e[u],t,r,n+1))}catch{c.push(K8)}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=Jin(e[a],t,r,n+1)}catch{c=K8}a&&!GJ(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 duh(e){try{let t=e.toJSON;if(typeof t=="function")return{selfDescribed:!0,value:t.call(e)}}catch{}return{selfDescribed:!1}}function Nsl(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=Zin(e[a],r)}catch{c=K8}GJ(c)||(o++,Object.defineProperty(i,a,{value:c,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:i,dropped:s}}function jsl(e,t){for(let r of Object.keys(e))e[r]=Zin(e[r],t);return e}function vKt(e,t,r){return t===Fsl?r(t):e.with(t,()=>r(t))}function cZo(e){try{let t=fuh(e);if(A1e(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 uZo={internal:1,server:2,client:3,producer:4,consumer:5},muh={ok:1,error:2},huh=1,guh=256,Auh=512;function yuh(e){let t=parseInt(e.traceFlags,16);return(Number.isFinite(t)?255&t:huh)|guh|(e.parentIsRemote?Auh:0)}function $in(e){if(typeof e=="string")return bne(e);try{return bne(String(e))}catch{return K8}}function buh(e){return e&&Object.prototype.hasOwnProperty.call(uZo,e)?uZo[e]:uZo.internal}function lZo(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 Euh(e,t){let r={name:$in(e.name),timeUnixNano:lZo(e.timestamp)};if(e.attributes){let i=Ine(e.attributes,t);i.length&&(r.attributes=i)}let n=S5e(e.droppedAttributesCount);return n&&(r.droppedAttributesCount=n),r}function zsl(e,t){let r={traceId:e.traceId,spanId:e.spanId,name:$in(e.name),kind:buh(e.kind),startTimeUnixNano:lZo(e.startTime),endTimeUnixNano:lZo(e.endTime),flags:yuh(e)};e.parentSpanId&&(r.parentSpanId=e.parentSpanId),e.traceState&&(r.traceState=$in(e.traceState));let n=Ine(e.attributes,t);n.length&&(r.attributes=n),e.events.length&&(r.events=e.events.map(s=>Euh(s,t)));let i=S5e(e.droppedAttributesCount);i&&(r.droppedAttributesCount=i);let o=S5e(e.droppedEventsCount);return o&&(r.droppedEventsCount=o),e.status&&(r.status={code:muh[e.status.code],...e.status.message&&{message:$in(e.status.message)}}),r}function Qsl(e,t,r){return mKt(e,t,r)}function Msl(e,t,r,n,i){return{resourceSpans:[{resource:{attributes:hKt(t,i)},scopeSpans:[{scope:{name:r,version:n},spans:e}]}]}}var Lsl=8;function eon(){return Yin()??Date.now()}function pZo(e){try{return e instanceof Nft}catch{return!1}}function _sl(e,t){let r=wsl(e);if(r)return{traceId:r.traceId,parentSpanId:r.spanId,traceState:Hin(t),traceFlags:r.flags,isRemote:!0}}function Iuh(e){try{return typeof e.traceparent=="function"}catch{return!1}}function vuh(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 ton(e,t,r){e[t]!==r&&(e[t]=r)}function Cuh(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 CKt=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 C5e(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=Z8,this._retryAfter=new I5e,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 b1e(r,this._contextManager.active());let n=qin(r?.parent);if(n&&typeof n!="string"&&!pZo(n)){if(Iuh(n))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),b1e(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`),b1e(r,this._contextManager.active());let o=Date.now(),s=Rsl(r?.startTime,o,this._logger),a=vsl();this._liveSpans.set(a,eon());let c=this._autoContextAttributes();return new Nft({traceId:i?.traceId??Isl(),spanId:a,parentSpanId:i?.parentSpanId,traceState:i?.traceState,traceFlags:i?.traceFlags,parentIsRemote:i?.isRemote,name:x5e(t,"Span name",this._config.maxAttributeValueLength,this._logger),kind:r?.kind??"internal",attributes:Khe({...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:Fft(r?.startTime)===void 0?i?.clockAnchor:void 0},(u,l)=>this._onSpanEnd(u,l),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=vKt(this._contextManager,s,o);return Mol(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=Z8,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(t,r){if(typeof t=="string"){let i=_sl(t,r?.tracestate);return i||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),i}if(pZo(t))return t.childContext();let n=this._contextManager.active();if(pZo(n))return n.childContext();if(n instanceof IKt)return _sl(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 Nft))return;let{type:n,message:i,stack:o}=cZo(r);t.addEvent("exception",{"exception.type":n,"exception.message":i,...o&&{"exception.stacktrace":o}}),t.statusIsExplicitlyOk||t.setStatus("error",i)}_evictAgedSpans(){let t=eon()-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},u=t,l=t;try{for(let f of this._config.beforeSpanSend){let m=f(u);if(!m)return this._recordDrop(1,"beforeSpanSend dropped it"),null;u=this._keepSpanIdentity(m,n)}if(l={traceId:n.traceId,spanId:n.spanId,parentSpanId:n.parentSpanId,traceState:n.traceState,name:u.name,kind:u.kind,status:u.status,attributes:u.attributes,events:u.events,startTime:u.startTime,endTime:u.endTime,traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote,droppedAttributesCount:o.attributes,droppedEventsCount:o.events},!vuh(l))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;l.name=x5e(l.name,"Span name",this._config.maxAttributeValueLength,this._logger),l.status&&l.status.code!=="ok"&&l.status.code!=="error"&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),l.status=c),l.startTime=Fft(l.startTime)??i.startTime,l.endTime=Kin(Fft(l.endTime)??i.endTime,l.startTime);let d=[];for(let f of l.events)try{d.push({...f,name:x5e(f.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:EKt(f.timestamp,l.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return l.events=d,ksl(l,r,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,s),l}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{ton(t,"traceId",r.traceId),ton(t,"spanId",r.spanId),ton(t,"parentSpanId",r.parentSpanId),ton(t,"traceState",r.traceState)}catch{return Cuh(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(zsl(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=jsl(Qsl(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 u=this._discardQueueIfConsentWithdrawn();if(u)return s+u;let l=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,p=Math.max(1,Math.min(l,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=eon()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),g=await this._instance._sendTracesBatch(Msl(f,r,n,i,this._logger));if(c!==this._generation)break;if(this._retryAfter.record(g),g.kind==="ok"){this._consecutiveFlushFailures=0,this._flushJitter=Z8,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=Z8,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=gKt(),this._headBatchSize=p,m&&(this._headBatchFailures++,this._headBatchChargeableAt=eon()+this._nextFlushDelay()),this._headBatchFailures<Lsl)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=Z8,this._resetHeadBatchBudget(),this._recordDrop(p,`the ingestion endpoint failed ${Lsl} 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=Z8,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(AKt(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}};var xKt=class{active(){return this._active}with(t,r){let n=this._active;this._active=t;try{return r()}finally{this._active=n}}};var xuh=5e3,Suh=512,wuh=2048,Tuh=128,Ouh=128,Puh=128,Buh=8192,Ruh=1e4,Duh=36e5;function E1e(e,t){return typeof e=="number"&&Number.isInteger(e)&&e>=1?e:t}var Usl=["service.name","service.version","deployment.environment"];function kuh(e){if(!(!e||typeof e!="object"||Array.isArray(e)))try{if(Usl.every(r=>!(r in e)||typeof e[r]=="string"))return e;let t={...e};for(let r of Usl)r in t&&typeof t[r]!="string"&&delete t[r];return t}catch{return}}function Fuh(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 fZo(e,t,r){let n=Khe({...t},kuh(e?.resourceAttributes)),i=E1e(e?.maxExportBatchSize,Suh);return{serviceName:n?.["service.name"]??e?.serviceName,serviceVersion:n?.["service.version"]??e?.serviceVersion,environment:n?.["deployment.environment"]??e?.environment,resourceAttributes:n,beforeSpanSend:Fuh(e?.beforeSpanSend,r),maxAttributesPerSpan:E1e(e?.maxAttributesPerSpan,Tuh),maxEventsPerSpan:E1e(e?.maxEventsPerSpan,Ouh),maxAttributesPerEvent:Puh,maxAttributeValueLength:E1e(e?.maxAttributeValueLength,Buh),flushIntervalMs:E1e(e?.flushIntervalMs,xuh),maxExportBatchSize:i,maxQueueSize:Math.max(E1e(e?.maxQueueSize,wuh),i),maxLiveSpans:E1e(e?.maxLiveSpans,Ruh),maxSpanAgeMs:E1e(e?.maxSpanAgeMs,Duh)}}var dZo=require("fs"),qsl=require("fs/promises"),hZo=require("path"),Wsl=require("readline"),ron=new sO.ReduceableCache(25),SKt=new sO.ReduceableCache(20),gZo=7,Nuh=1e3,juh=1e4,mZo=10485760;async function Hsl(e,t=qsl.open,r){let n={},i;try{i=process.cwd()}catch{}for(let a=e.length-1;a>=0;a--){let c=e[a],u=c?.filename;if(!c||typeof u!="string"||typeof c.lineno!="number"||_uh(u)||Uuh(c)||!(0,hZo.isAbsolute)(u)&&i===void 0)continue;n[u]||(n[u]=[]),n[u].push(c.lineno)}let o=Object.keys(n);if(o.length==0)return e;let s=[];for(let a of o){let c=Ksl(a,i);if(c===void 0||SKt.get(c))continue;let u=n[a];if(!u)continue;u.sort((d,f)=>d-f);let l=Guh(u);if(l.every(d=>Vuh(c,d)))continue;let p=quh(ron,c,{});s.push(Quh(a,l,p,c,t,r))}return await Promise.all(s).catch(()=>{}),e&&e.length>0&&Muh(e,ron,i),ron.reduce(),e}async function zuh(e,t,r){let n,i=!1;try{n=await t(e,dZo.constants.O_RDONLY|dZo.constants.O_NONBLOCK);let o=await n.stat();return o.isFile()?o.size>mZo?void r?.debug(`Skipping source context for oversized file ${e}: ${o.size} bytes exceeds ${mZo}`):(i=!0,n):void 0}catch{return}finally{n&&!i&&await n.close().catch(()=>{})}}async function Quh(e,t,r,n,i,o){let s=await zuh(e,i,o);if(s===void 0)return void SKt.set(n,1);let a=s;return new Promise(c=>{let u=!1;function l(x){u||(u=!0,x?.destroy(),a.close().then(c,c))}let p;try{p=a.createReadStream({autoClose:!1,start:0,end:mZo-1})}catch{SKt.set(n,1),l();return}let d;try{d=(0,Wsl.createInterface)({input:p})}catch{SKt.set(n,1),l(p);return}let f=0,m=0,g=t[m];if(g===void 0)return void l(p);let A=g[0],y=g[1];function I(){SKt.set(n,1),d.close(),d.removeAllListeners(),l(p)}p.on("error",I),d.on("error",I),d.on("close",()=>l(p)),d.on("line",x=>{if(f++,!(f<A)&&(r[f]=Wuh(x,0),f>=y)){if(m===t.length-1){d.close(),d.removeAllListeners();return}m++;let v=t[m];if(v===void 0){d.close(),d.removeAllListeners();return}A=v[0],y=v[1]}})})}function Muh(e,t,r){for(let n of e)if(n.filename&&n.context_line===void 0&&typeof n.lineno=="number"){let i=Ksl(n.filename,r),o=i===void 0?void 0:t.get(i);if(o===void 0)continue;Luh(n.lineno,n,o)}}function Luh(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=Jsl(e);i<e;i++){let o=r[i];if(o===void 0)return void Vsl(t);t.pre_context.push(o)}if(r[e]===void 0)return void Vsl(t);t.context_line=r[e];let n=Ysl(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 Vsl(e){delete e.pre_context,delete e.context_line,delete e.post_context}function _uh(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function Uuh(e){return e.lineno!==void 0&&e.lineno>juh||e.colno!==void 0&&e.colno>Nuh}function Ksl(e,t){return(0,hZo.isAbsolute)(e)?JSON.stringify([null,e]):t===void 0?void 0:JSON.stringify([t,e])}function Vuh(e,t){let r=ron.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 Guh(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=Gsl(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+gZo:(i.push(n),n=Gsl(o)),t++}return i}function Gsl(e){return[Jsl(e),Ysl(e)]}function Jsl(e){return Math.max(1,e-gZo)}function Ysl(e){return e+gZo}function quh(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function Wuh(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 jft=require("path");function Xsl(e=process.cwd()){let t=jft.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,jft.isAbsolute)(o.filename)&&(o.filename=r((0,jft.relative)(n,r(o.filename))));return i}}var Zsl="5.55.0";var Yhe={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var I1e=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(Yhe.ERRORS_WHILE_COMPUTING),this._quotaLimited&&o.push(Yhe.QUOTA_LIMITED),r===void 0&&o.push(Yhe.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 Huh=6e4;function $sl(e){return e==="client"||e==="server"?e:"all"}function Kuh(e,t){return e===t||e==="all"||t==="all"}var zft=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}};function Juh(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}var vne=class e extends Error{constructor(t){super(t),Juh(this,e)}},non=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(u){u instanceof vne||u instanceof el?this.logMsgIfDebug(()=>console.debug(`${u.name} when computing flag locally: ${t}: ${u.message}`)):u instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${u}`))}}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:u,payload:l}=await this.computeFlagAndPayloadLocally(c,a,{skipLoadCheck:!0});n[c.key]=u,l&&(i[c.key]=l)}catch(u){u instanceof vne||u instanceof el?this.logMsgIfDebug(()=>console.debug(`${u.name} when computing flag locally: ${c.key}: ${u.message}`)):u instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${c.key}: ${u}`)),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=XXo(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 el("Flag has experience continuity enabled");let c=(t.filters||{}).aggregation_group_type_index;if(c!=null){let u=r.definitions.groupTypeMapping[String(c)];if(!u)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new el("Flag has unknown group type index");if(!(u 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 l=s[u];return await this.matchFeatureFlagProperties(t,i[u],l,r)}{let u=this.getBucketingValueForFlag(t,n,o);if(u===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 el(`Can't compute feature flag: ${t.key} without $device_id`);return await this.matchFeatureFlagProperties(t,u,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 el("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new el(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let s=t.dependency_chain;if(!Array.isArray(s))throw new el(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new el(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let c of s){if(!(c in i)){let l=n.definitions.featureFlagsByKey[c];if(l)if(l.active)try{let p=await this.computeFlagValueLocally(l,n);i[c]=p}catch(p){throw new el(`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 el(`Missing flag dependency '${c}' for flag '${o}'`)}if(i[c]==null)throw new el(`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 JXo(o.holdout,r);if(s!==void 0)return s;let a=o.groups||[],c=o.aggregation_group_type_index,u=o.early_exit??!1,{groups:l,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,y=r;if(g!==c&&g!=null){let x=i.definitions.groupTypeMapping[String(g)];if(!x||!(x in l)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${t.key}': group type index ${g} not available`));continue}if(!(x in p)){d=!0;continue}A=p[x],y=l[x]}let I=await this.isConditionMatch(t,y,m,A,i);if(I==="match"){let x=m.variant,v=o.multivariate?.variants||[];f=x&&v.some(S=>S.key===x)?x:await this.getMatchingVariant(t,y)||!0;break}if(u&&I==="out_of_rollout_bound"){if(d)break;return!1}}catch(g){if(g instanceof vne)throw g;if(g instanceof el)d=!0;else throw g}if(f!==void 0)return f;if(d)throw new el("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=u=>{this.logMsgIfDebug(()=>console.warn(u))};if((n.properties||[]).length>0){for(let u of n.properties){let l=u.type,p=!1;if(l==="cohort"){let d=await tal(u,i,s.cohorts,this.debugMode,f=>this.evaluateFlagDependency(f,i,o),s.propertyMatchingVersion);p=u.operator==="not_in"?!d:d}else p=l==="flag"?await this.evaluateFlagDependency(u,i,o):eal(u,i,c,s.propertyMatchingVersion);if(!p)return"no_match"}if(a==null)return"match"}return a!=null&&await fKt(t.key,r)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(t,r){return YXo(t.key,r,t.filters?.multivariate?.variants||[])}variantLookupTable(t){return Uin(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?$sl(r.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(t){return this.featureFlags.filter(r=>Kuh($sl(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(Huh,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 zft(`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 zft(`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 zft(`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 zft&&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=LN(()=>{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 y1e(r,t,()=>{throw new Error(`Cache shutdown timeout after ${t}ms`)})}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};function eal(e,t,r,n){return KXo(e,t,{warnFunction:r,propertyMatchingVersion:n})}function Yuh(e,t){if(!(e in t))throw new vne(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function tal(e,t,r,n=!1,i,o){let s=String(e.value);Yuh(s,r);let a=r[s];return ral(a,t,r,n,i,o)}async function ral(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 u of a)try{let l=await ral(u,t,r,n,i,o);if(s==="AND"){if(!l)return!1}else if(l)return!0}catch(l){if(l instanceof vne)throw l;if(l instanceof el)n&&console.debug(`Failed to compute property ${u} locally: ${l}`),c=!0;else throw l}if(c)throw new el("Can't match cohort without a given cohort property value");return s==="AND"}for(let u of a)try{let l;if(u.type==="cohort")l=await tal(u,t,r,n,i,o);else if(u.type==="flag"){if(!i)throw new el(`Flag dependency '${u.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);l=await i(u)}else l=eal(u,t,void 0,o);let p=u.negation||!1;if(s==="AND"){if(!l&&!p||l&&p)return!1}else if(l&&!p||!l&&p)return!0}catch(l){if(l instanceof vne)throw l;if(l instanceof el)n&&console.debug(`Failed to compute property ${u} locally: ${l}`),c=!0;else throw l}if(c)throw new el("can't match cohort without a given cohort property value");return s==="AND"}var Xuh=["--unhandled-rejections","--unhandled_rejections"],Zuh=new Set(["throw","strict","warn","warn-with-error-code","none"]),$uh=[...globalThis.process?.execArgv??[]],elh=globalThis.process?.env?.NODE_OPTIONS;function tlh(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 nal(e){let t;for(let r=0;r<e.length;r++){let n=e[r],i=Xuh.find(s=>n===s||n.startsWith(`${s}=`));if(!i)continue;let o=n===i?e[++r]:n.slice(i.length+1);Zuh.has(o)&&(t=o)}return t}function rlh(e=$uh,t=elh){return nal(e)??nal(tlh(t??""))??"throw"}var ial=rlh();function oal(e,t,r){e(t,{mechanism:{type:r==="unhandledRejection"?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function nlh(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;oal(e,n,i),!r&&o===0&&(r=!0,t(n))},{_posthogErrorHandler:!0})}function sal(e,t,r=ial){let n=globalThis.process;if(n){if(r==="strict")return void n.on("uncaughtExceptionMonitor",(i,o)=>oal(e,i,o));n.on("uncaughtException",nlh(e,t))}}function aal(e,t=ial){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 ilh=2e3,AZo=class e{constructor(t,r,n){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new vin({...yol(r),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return YHt(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=sO.getInjectedReleaseId();return c&&(s.$release_id=c),{event:"$exception",distinctId:i,properties:{...a,...s},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(sal(this.onException.bind(this),this.onFatalError.bind(this)),aal(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(ilh),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}},w5e=AZo;var ion=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};function olh(e){return e==="v0"||e==="v1"}function cal(){let e="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return olh(e)?e:"v0"}var slh="$ai_",wKt="analytics";function ual(e){return typeof e.event=="string"&&e.event.startsWith(slh)}var Qft=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 yZo(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 alh(e){return typeof e=="string"?e:void 0}var clh=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:yZo},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:yZo},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:yZo},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:alh}],ulh=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function llh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function plh(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 lal(e,t,r){r!==void 0&&!(t in e)&&(e[t]=r)}function flh(e){let r={...llh(e.properties)?e.properties:{}},n={};for(let{property:o,optionKey:s,coerce:a}of clh)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 ulh)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,lal(r,"$set",e.$set),lal(r,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:plh(e.timestamp),...i,options:n,properties:r}}function pal(e,{createdAt:t,historicalMigration:r}){let n={created_at:t,batch:e.map(flh)};return r&&(n.historical_migration=!0),n}var dlh="/i/v1/analytics/events",mlh=3e4,hlh=new Set([408,500,502,503,504]),oon=class{constructor(t,r){this.config=t,this.maxBackoffMs=t.maxBackoffMs??mlh,this.fetchFn=r.fetch,this.onError=r.onError,this.now=r.now??Date.now,this.sleep=r.sleep??(n=>new Promise(i=>LN(i,n))),this.generateRequestId=r.generateRequestId??MN,this.compress=r.compress??uKt}async sendV1Batch(t){if(t.length===0)return;let r=this.generateRequestId(),n=new Date(this.now()).toISOString(),{batch:i}=pal(t,{createdAt:n,historicalMigration:this.config.historicalMigration}),o=`${this.config.host}${dlh}`,s=[],a=i,c=Math.max(1,this.config.maxAttempts);for(let u=1;u<=c;u++){let l=u===c,p=g1e({created_at:n,...this.config.historicalMigration?{historical_migration:!0}:{},batch:a}),d,f;try{d=await this.sendOnce(o,p,u,r);let{response:m,signal:g}=d,{status:A}=m;if(A<200||A>=300)if(!l&&hlh.has(A)){let y=this.parseRetryAfter(m);await d.waitFor(d.cancelBody()).catch(()=>{}),f=this.backoffDelay(u,y)}else{let y=await this.buildHttpError(m,A,d.waitFor);return this.surfaceBatchFailure(r,s,a,y)}else{let y;try{y=await d.waitFor(this.parseResponse(m))}catch(v){if(g.aborted)throw v;return this.surfaceBatchFailure(r,s,a,new Error(`Capture V1 returned an unparseable ${A} response body`))}let I=this.classify(a,y,s);if(I.length===0)return this.surfacePartialDrops(r,s);if(l)return void this.onError(new Qft({requestId:r,drops:s,retryExhausted:I.map(v=>v.uuid)}));a=I;let x=this.parseRetryAfter(m);f=this.backoffDelay(u,x)}}catch(m){if(d&&!d.signal.aborted)throw m;if(l)return this.surfaceBatchFailure(r,s,a,m);f=this.backoffDelay(u)}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",u,l=new Promise((p,d)=>{u=LN(()=>{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(y=>{a.signal.aborted&&!d&&this.cancelBody(y)}).catch(()=>{});let f=await Promise.race([p,l]);d=!0,c="while reading the response body";let m=!1,g,A=()=>g??=this.cancelBody(f);return{response:f,signal:a.signal,waitFor:y=>Promise.race([y,l]),cancelBody:A,cleanup:()=>{m||(m=!0,clearTimeout(u),a.signal.aborted&&A())}}}catch(p){throw clearTimeout(u),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 Qft({requestId:t,drops:r,retryExhausted:n.map(o=>o.uuid),cause:i}))}surfacePartialDrops(t,r){r.length>0&&this.onError(new Qft({requestId:t,drops:r,retryExhausted:[]}))}async cancelBody(t){try{await t.body?.cancel()}catch{}}};var T5e="ai-capture",son="/i/v0/ai/batch/";var Alh=new TextEncoder;function EZo(e){return Alh.encode(g1e(e)).length}function fal(e,t=8388608,r=5242880){let n=[],i=[],o=[],s=0;for(let a of e){if(a===void 0)continue;let c=EZo(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 ylh=100,dal=3e4,blh=5e4,Elh=50,Ilh=500,vlh="https://us.i.posthog.com",mal=new Set;function con(e,t){mal.has(e)||(mal.add(e),console.warn(`[PostHog] ${t}`))}function Clh(e){return typeof e=="string"?e.trim():""}function xlh(e){return(typeof e=="string"?e.trim():"")||void 0}function Slh(e){return(typeof e=="string"?e.trim():"")||vlh}function wlh(e){return(Array.isArray(e)?e:[e]).filter(r=>typeof r=="string"&&r.trim().length>0)}function Tlh(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 uon=class extends lKt{constructor(t,r={}){let n=Clh(t),i={...r,maxQueueSize:r.maxQueueSize??1e4,flushInterval:r.flushInterval??5e3,host:Slh(r.host),personalApiKey:xlh(r.secretKey??r.personalApiKey)};if(super(n,i),this._memoryStorage=new ion,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=i,this.captureMode=cal(),this.enableFullAiCapture=i.enableFullAiCapture===!0,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof i.featureFlagsPollingInterval=="number"?Math.max(i.featureFlagsPollingInterval,ylh):i.featureFlagsPollingInterval===null?null:dal,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 non({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 w5e(this,i,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=i.maxCacheSize||blh}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:$Ht([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??Ilh,i=r>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),i)return void this.resolveWaitUntilFlush();let o=this.options.waitUntilDebounceMs??Elh;this._waitUntilCycle.timer=LN(()=>{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"&&ual(t)?"ai":wKt}persistedQueueKeyForRoute(t){return t===T5e?RM.AiCaptureQueue:t==="ai"?RM.AiQueue:RM.Queue}getActiveQueueRoutes(){let t=this.captureMode==="v1"?[wKt,"ai"]:[wKt];return this._aiCaptureRouteActive&&t.push(T5e),t}getBatchEndpointPath(t){return t===T5e?son:super.getBatchEndpointPath(t)}async sendBatch(t,r,n=wKt){if(n===T5e)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}=fal(t);for(let{event:o,bytes:s}of i){let a=`Event ${o} (${s} bytes) exceeds the ${8388608/1048576}MiB limit for ${son}, 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,T5e)}catch(n){if(!kft(n))throw n;if(t.length===1){let[o]=t,a=`Event ${typeof o.event=="string"?o.event:"unknown"} (${EZo(o)} bytes) was rejected with 413 by ${son} 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 oon({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 Zsl}get metrics(){return this._metrics||(this._metrics=new bKt(this,Gin(this.options.metrics),this._logger)),this._metrics}initializeSpanContextManager(){return new xKt}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 CKt(this,fZo(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)??b1e(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):vKt(this._spanContextManager,b1e(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:u})=>{let l={timestamp:u.timestamp,disableGeoip:u.disableGeoip,uuid:u.uuid},p={distinctId:s,event:a,properties:{...c,...this.getCommonEventProperties()}};return n?this.sendImmediate(t,p,l,o):this.enqueue(t,p,l,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=v5e(t.uuid,MN);return this._sendPreparedAiEvent({...t,uuid:r},!1),r}async captureAiImmediate(t){if(this.disabled)return;let r=v5e(t.uuid,MN);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,T5e)}identify({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,l={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};this._sendPreparedEvent("identify",{distinctId:t,event:"$identify",properties:l,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,l={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};await this._sendPreparedEvent("identify",{distinctId:t,event:"$identify",properties:l,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=wlh(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=dal){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 R=this._flagOverrides[t];if(R===void 0)return;let D=this._payloadOverrides?.[t];return{key:t,enabled:R!==!1,variant:typeof R=="string"?R:void 0,payload:D}}let{groups:s,disableGeoip:a}=n,{onlyEvaluateLocally:c,personProperties:u,groupProperties:l}=n,p=this.addLocalPersonAndGroupProperties(r,s,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,s,this.personPropertiesForLocalEvaluation(r,u),l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f,m=!1,g,A,y,I,x,v,S;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let R=this.featureFlagsPoller?.featureFlagsByKey[t];if(R)try{let D=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(R,d,{matchValue:i});if(D){m=!0;let O=D.value;I=R.id,v="Evaluated locally",S=R.has_experiment,f={key:t,enabled:O!==!1,variant:typeof O=="string"?O:void 0,payload:D.payload??void 0,reason:v,reasonCode:R.active===!1?"flag_disabled":void 0}}}catch(D){if(D instanceof vne||D instanceof el)this._logger?.info(`${D.name} when computing flag locally: ${t}: ${D.message}`);else throw D}}if(!m&&!c){let R=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,u,l,a,[t]);if(R===void 0)y=Yhe.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=R.minimalFlagCalledEvents===!0,g=R.requestId,A=R.evaluatedAt;let D=[];R.errorsWhileComputingFlags&&D.push(Yhe.ERRORS_WHILE_COMPUTING),R.quotaLimited?.includes("feature_flags")&&D.push(Yhe.QUOTA_LIMITED);let O=R.flags[t];if(O===void 0)D.push(Yhe.FLAG_MISSING);else{I=O.metadata?.id,x=O.metadata?.version,v=O.reason?.description??O.reason?.code,S=O.metadata?.has_experiment;let z;if(O.metadata?.payload!==void 0)try{z=JSON.parse(O.metadata.payload)}catch{z=O.metadata.payload}f={key:t,enabled:O.enabled,variant:O.variant??void 0,payload:z,reason:v,reasonCode:O.reason?.code}}D.length>0&&(y=D.join(","))}}if(o){let R=f===void 0?void 0:f.enabled===!1?!1:f.variant??!0,D={$feature_flag:t,$feature_flag_response:R,$feature_flag_id:I,$feature_flag_version:x,$feature_flag_reason:v,locally_evaluated:m,[`$feature/${t}`]:R,$feature_flag_request_id:g,$feature_flag_evaluated_at:m?Date.now():A};if(S!==void 0&&(D.$feature_flag_has_experiment=S),m&&this.featureFlagsPoller){let O=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();O!==void 0&&(D.$feature_flag_definitions_loaded_at=O)}y&&(D.$feature_flag_error=y),this._captureFlagCalledEventIfNeeded({distinctId:r,key:t,response:R,groups:s,disableGeoip:a,properties:D})}return f!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(f={...f,payload:this._payloadOverrides[t]}),f}async getFeatureFlag(t,r,n){con("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(con("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){con("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:u,groupProperties:l}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,u),l);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 y=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,u,l,s,a);m={...m,...y.flags||{}},g={...g,...y.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 I1e({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new I1e({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,flags:{}});let{groups:o,disableGeoip:s}=i||{},a=i?.flagKeys??void 0;if(a?.length===0)return new I1e({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:{}});let{onlyEvaluateLocally:c,personProperties:u,groupProperties:l}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,u),l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=a?new Set(a):void 0,m={},g,A,y=!1,I=!1,x=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),v=new Set;if(x)for(let[R,D]of Object.entries(x.response)){let O=this.featureFlagsPoller?.featureFlagsByKey[R];m[R]={key:R,enabled:D!==!1,variant:typeof D=="string"?D:void 0,payload:x.payloads[R],id:O?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:O?.has_experiment},v.add(R)}let S=f!==void 0&&Array.from(f).some(R=>this.featureFlagsPoller?.featureFlagsByKey[R]===void 0);if((x?x.fallbackToFlags||S:!0)&&!c){let R=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,u,l,s,a);if(R){this._minimalFlagCalledEvents=R.minimalFlagCalledEvents===!0,g=R.requestId,A=R.evaluatedAt,y=!!R.errorsWhileComputingFlags,I=Array.isArray(R.quotaLimited)&&R.quotaLimited.includes("feature_flags");for(let[D,O]of Object.entries(R.flags)){if(v.has(D))continue;let z;if(O.metadata?.payload!==void 0)try{z=JSON.parse(O.metadata.payload)}catch{z=O.metadata.payload}m[D]={key:D,enabled:O.enabled,variant:O.variant,payload:z,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[R,D]of Object.entries(this._flagOverrides)){if(D===void 0){delete m[R];continue}let O=m[R];m[R]={key:R,enabled:D!==!1,variant:typeof D=="string"?D: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[R,D]of Object.entries(this._payloadOverrides)){let O=m[R];O&&(m[R]={...O,payload:D})}if(f!==void 0)for(let R of Object.keys(m))f.has(R)||delete m[R];return new I1e({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:m,requestId:g,evaluatedAt:A,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:y,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(([l],[p])=>l<p?-1:l>p?1:0))}`:"",u=`${n}_${i}${c}`;r in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[r].has(u)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),this.distinctIdHasSentFlagCalls[r]instanceof Set?this.distinctIdHasSentFlagCalls[r].add(u):this.distinctIdHasSentFlagCalls[r]=new Set([u]),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 y1e(this._metrics.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._metrics.reset()),this._traces&&(await y1e(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=LN(()=>{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(hol(s)&&r&&o in r){let a={};for(let[c,u]of Object.entries(s))a[String(c)]=String(u);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 u={};for(let[l,p]of Object.entries(r||{}))u[l]=String(p);return await this.getAllFlags(t,{groups:u,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let u={};for(let[l,p]of Object.entries(r||{}))u[l]=String(p);return await this.getAllFlags(t,{groups:u,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(!w5e.isPreviouslyCapturedError(t)){let s=new Error("PostHog syntheticException");this.addPendingPromise(w5e.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(!w5e.isPreviouslyCapturedError(t)){let o=new Error("PostHog syntheticException");return this.addPendingPromise(w5e.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:u,disableGeoip:l,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=MN(),g.$process_person_profile=!1),f&&d?.sessionId&&!g.$session_id&&(g.$session_id=d.sessionId);let A=this._shouldSendMinimalFlagCalledEvent(i,g)?aKt(g):g,y=this._runBeforeSend({distinctId:m,event:i,properties:A,groups:s,flags:a,sendFeatureFlags:c,timestamp:u,disableGeoip:l,uuid:p});if(!y)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){con("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 x=typeof c=="object"?c:void 0,v=await this.getFeatureFlagsForEvent(y.distinctId,s,l,x);return Tlh(v)}return{}}).catch(()=>({})).then(x=>{let v=y.groups||s;return{...x,...y.properties||{},...v!==void 0&&Object.keys(v).length>0?{$groups:v}:{}}});return y.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof I.$raw_user_agent=="string"&&Aol(I.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(y.event="$bot_pageview",I.$browser_type="bot"),{distinctId:y.distinctId,event:y.event,properties:I,options:{timestamp:y.timestamp,disableGeoip:y.disableGeoip,uuid:y.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 hal=require("async_hooks"),lon=class{constructor(){this.storage=new hal.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 gal=require("async_hooks"),pon=class{active(){return this._storage.getStore()}with(t,r){return this._storage.run(t,r)}constructor(){this._storage=new gal.AsyncLocalStorage}};var Aal=require("zlib"),yal=require("util"),Olh=(0,yal.promisify)(Aal.gzip);async function bal(e,t=!0){try{let r=await Olh(e);return new Uint8Array(r)}catch(r){return t&&console.error("Failed to gzip compress data",r),null}}var fon=require("os");function Eal(){let e,t;try{e=(0,fon.platform)(),t=(0,fon.release)()}catch{}return tZo(e,t)}var Ial="posthog-node";function Plh(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[IZo.POSTHOG_ID_TAG];if(c===void 0)return s;let u=e.options.host??"https://us.i.posthog.com",l=new URL(`/project/${e.apiKey}/person/${c}`,u).toString();s.tags["PostHog Person URL"]=l;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=sO.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 IZo=class{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(t,r,n,i,o){this.name=Ial,this.name=Ial,this.setupOnce=function(s,a){let c=a()?.getClient()?.getDsn()?.projectId;s(Plh(t,{organization:r,projectId:c,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o??!0}))}}};var Cne=class extends uon{getLibraryId(){return"posthog-node"}compressPayload(t){return bal(t,this.isDebug)}initializeContext(){return new lon}initializeSpanContextManager(){return new pon}hostResourceAttributes(){return Eal()}createErrorPropertiesBuilder(){return new sO.ErrorPropertiesBuilder([new sO.EventCoercer,new sO.ErrorCoercer,new sO.ObjectCoercer,new sO.StringCoercer,new sO.PrimitiveCoercer],sO.createStackParser("node:javascript",sO.nodeStackLineParser),[lol(),t=>Hsl(t,void 0,this._logger),Xsl()])}};function val(e){return e==null||!e.enabled?!1:e.variant==null||e.variant==="true"}var don=class{isEnabled(){return Promise.resolve(!1)}getCachedValue(){}flush(){return Promise.resolve()}},Blh="feature_flag_evaluated",Rlh=3e3,Dlh=3e3,mon=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 Cne(n??"",{featureFlagsRequestTimeoutMs:Rlh,isServer:!1})}isEnabled(t,r){let n=Cal(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(Cal(t,r))}async flush(){if(!this.sendFeatureFlagEvents)return;let t;try{await Promise.race([this.flushAfterPendingEvaluations(),new Promise(r=>{t=setTimeout(r,Dlh),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=Flh(r,this.environment),o;try{o=await this.evaluator.getFeatureFlagResult(t,vZo(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}),val(o)}captureFlagUsage({flag:t,org:r,result:n,properties:i}){let o=klh(n),s={...i,...n?.reason!=null?{$feature_flag_reason:n.reason}:{},version:"5.172.0"};this.tryCapture({distinctId:vZo(r),event:"$feature_flag_called",groups:{organization:r},properties:{...s,$feature_flag:t,$feature_flag_response:o,[`$feature/${t}`]:o}}),this.tryCapture({distinctId:vZo(r),event:Blh,groups:{organization:r},properties:{...s,flag:t,response:o,enabled:val(n)}})}tryCapture(t){try{this.evaluator.capture(t)}catch{}}};function klh(e){if(e!=null)return e.enabled?e.variant??!0:!1}function vZo(e){return`org:${e}`}function Flh({org:e,generator:t,language:r},n){return{org:e,environment:n,...t!=null?{generator:t}:{},...r!=null?{language:r}:{}}}function Cal(e,{org:t,generator:r,language:n}){return JSON.stringify([e,t,r??null,n??null])}var hon;function gon(){return hon==null&&(hon=Nlh()),hon}async function CZo(){await hon?.flush()}function Nlh(){let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";return e==null||e.trim().length===0?new don:new mon({posthogApiKey:e,environment:VJ(),sendFeatureFlagEvents:yin()})}var Aon=class{posthog;constructor({posthogApiKey:t}){this.posthog=new Cne(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.172.0",usingAccessToken:!0,cliReleaseEnvironment:VJ(),...Dpe()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:{...t.properties,cliReleaseEnvironment:VJ()}})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}};var TKt=class{async sendEvent(){}async sendAutomationEvent(){}async identify(){}async flush(){}};dd();tr();var Mft=require("fs/promises"),xal=require("os"),Sal=require("path");lVe();var jlh="id",zlh=".fern",OKt=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new Cne(r,{isServer:!1}),this.userId=t==null?void 0:mWo(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.172.0",...t,...t.properties,usingAccessToken:!1,cliReleaseEnvironment:VJ(),agent:yHr(),...r!=null?{userEmail:r}:{},...Dpe()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:{...t.properties,cliReleaseEnvironment:VJ()}})}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 Vp({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=Yw(),r=ke(Zt.of((0,xal.homedir)()),ye.of(zlh),ye.of(jlh));try{await Ut(r)?this.persistedDistinctId=(await(0,Mft.readFile)(r)).toString():(await(0,Mft.mkdir)((0,Sal.dirname)(r),{recursive:!0}),await(0,Mft.writeFile)(r,t),this.persistedDistinctId=t)}catch{this.persistedDistinctId=t}}return this.persistedDistinctId}};var xZo;async function PKt(){return xZo==null&&(xZo=await Qlh()),xZo}async function Qlh(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";if(e==null||!yin())return new TKt;let t=await Ylt();return t!=null?new OKt({token:t,posthogApiKey:e}):await CM()!=null?new Aon({posthogApiKey:e}):new OKt({token:void 0,posthogApiKey:e})}catch{return new TKt}}On();ct();Dt();C8();var BKt=Ae(require("process"),1);fZe();var Oal=Ae(q3o(),1),Pal=Ae(Tal(),1);function aO(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=yH(e),e.length===0))return 0;e=e.replace((0,Pal.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(Oal.default.eastAsianWidth(i)){case"F":case"W":n+=2;break;case"A":n+=r;break;default:n+=1}}return n}On();function yon(e){let t=0;for(let r of e.split(`
|
|
3468
|
+
at ${r.filename}:${n}:${i}`}};var lch=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,rKt=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(lch);return i&&(r=i[1],n=i[2]),[r,n]}};var $ol=["fatal","error","warning","log","info","debug"];function Nin(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 nKt=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(Oft(t))return t.constructor.name;let r="name"in t?t.name:void 0;return ak(r)&&!yXo(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=Nin(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(t){return ak(t)&&!yXo(t)&&$ol.indexOf(t)>=0}getStack(t){try{return ak(t.stacktrace)&&t.stacktrace.length>0?t.stacktrace:ak(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(A1e(n))return n}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var jXo=class{match(t){return Oft(t)}coerce(t,r){let n=t.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${Nin(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var iKt=class{match(t){return Ein(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var zXo=class{match(t){return E5e(t,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(t)}isCustomEventWrappingRejection(t){if(!Oft(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 Ein(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 QXo=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 oKt={MESSAGE:"$message",TIMESTAMP:"$timestamp"},pch=new Set([oKt.MESSAGE,oKt.TIMESTAMP]),jin={enabled:!0,max_bytes:32768};function MXo(e){return e?{enabled:e.enabled??jin.enabled,max_bytes:dch(e.max_bytes,jin.max_bytes)}:{...jin}}function fch(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((n,i)=>pch.has(i)?(t.push(i),n):(n[i]=e[i],n),{}),droppedKeys:t}}var LXo=class{constructor(t){this._entries=[],this._totalBytes=0,this._config=MXo(t)}setConfig(t){this._config=MXo(t),this._trimToMaxBytes()}add(t){let r=mch(t);if(!r)return;let n=esl(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 dch(e,t){if(!Tft(e)||e===1/0||e===-1/0)return t;let r=Math.floor(e);return r<0?t:r}function mch(e){let t;try{t=g1e(e)}catch{return}try{let r=JSON.parse(t);if(!YHt(r))return;let n=r,i=n[oKt.MESSAGE],o=n[oKt.TIMESTAMP];return!ak(i)||i.trim().length===0||!ak(o)&&!Tft(o)?void 0:{step:n,json:t}}catch{return}}function esl(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 hch(){let e=globalThis._posthogReleaseId;return typeof e=="string"&&e.length>0?e:void 0}var _Xo=e=>{if("flags"in e){let t=tsl(e.flags),r=rsl(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([i,o])=>[i,Dft(o)])),n=Object.fromEntries(Object.entries(t).map(([i,o])=>[i,gch(i,o,r[i])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:n}}};function gch(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 tsl=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,sKt(r)]).filter(([,t])=>t!==void 0)),rsl=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?Dft(n):void 0]}))},sKt=e=>e===void 0?void 0:e.variant??e.enabled,Dft=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var nsl=["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"],Ach=["$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",...nsl,"$session_id","$window_id","$lib","$lib_version","$device_id","$is_server","$react_native_version"],aKt=(e,t=[])=>{let r={},n=i=>{e[i]!==void 0&&(r[i]=e[i])};return Ach.forEach(n),t.forEach(n),r};var zin=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 UXo(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var bch="NativeGzipValidationError",Ech=31,Ich=139,vch=8,Cch=e=>e.length>=2&&e[0]===Ech&&e[1]===Ich;var cKt,xch=()=>{if(cKt)return cKt;cKt=[];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;cKt[e]=t>>>0}return cKt},Sch=e=>{let t=xch(),r=4294967295;for(let n=0;n<e.length;n++)r=t[(r^e[n])&255]^r>>>8;return(4294967295^r)>>>0},Qin=e=>{throw Rft(bch,`Native gzip produced invalid output: ${e}`)},wch=async(e,t)=>{e.size<18&&Qin("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());(!Cch(r)||r[2]!==vch)&&Qin("invalid-header");let n=new DataView(await e.slice(e.size-8).arrayBuffer());n.getUint32(0,!0)!==Sch(t)&&Qin("invalid-crc");let i=t.length>>>0;n.getUint32(4,!0)!==i&&Qin("invalid-size")};async function uKt(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 u=>{try{await o.abort(u)}catch{}throw u}),a=new Response(i.readable).blob(),[c]=await Promise.all([a,s]);return await wch(c,n),c}catch(n){if(r?.rethrow)throw n;return t&&console.error("Failed to gzip compress data",n),null}}var J8=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 TXo(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=Rft("AbortError","Response body read timed out");this.cancelResponseBody(t),this.responseBodyTextPromise=Promise.reject(t)}else{let t=new Promise((n,i)=>{this.responseBodyTimer=LN(()=>{this._bodyReadTimedOut=!0;let o=Rft("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{}})()}},Jhe=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};var csl=(e,t)=>{for(let r of Object.keys(t))(r.startsWith("$feature/")||r==="$active_feature_flags")&&(e[r]=t[r])};async function isl(e){if(e instanceof J8){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 Tch(e){return typeof e=="object"&&(e instanceof J8||usl(e))}function usl(e){return e instanceof Jhe}function Och(e){if(e instanceof J8)return e.status===502||e.status===504;if(!(e instanceof Jhe))return!1;let t=e.error;return(t?.code??t?.cause?.code)!=="ECONNREFUSED"}var osl=10485760;function ssl(e){try{return typeof e!="string"?e instanceof Uint8Array?e.byteLength:e.size:"u">typeof Buffer?Buffer.byteLength(e,jol):new TextEncoder().encode(e).length}catch{return 0}}function kft(e){return typeof e=="object"&&e instanceof J8&&e.status===413}function Min(e){return e instanceof J8?e.status===408||e.status===429||e.status>=500:usl(e)}function asl(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var VXo="default",lKt=class{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new eKt([new tKt,new nKt,new rKt,new iKt],kXo())}getEvaluationRuntime(){}constructor(t,r={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new Sin,this._events=new zin,this._isInitialized=!1;let n=typeof t=="string"?t.trim():"",i=typeof r.host=="string"?r.host.trim():"",o=!n;this._logger=Iol("[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=zol(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:Min},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=!UXo()||(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(RM.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(RM.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(RM.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 csl(n,r),t.event==="$feature_flag_called"&&n.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled()&&(n=aKt(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}`,u={token:this.apiKey,distinct_id:t,groups:r,person_properties:n,group_properties:i,...o};n.$device_id&&(u.$device_id=n.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(u.evaluation_contexts=this.evaluationContexts);let l=this.getEvaluationRuntime();l&&(u.evaluation_runtime=l);let p={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(u)};return this._logger.info("Flags URL",c),this.fetchWithRetry(c,p,{type:"required",consume:d=>d.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:Och},this.featureFlagsRequestTimeoutMs).then(d=>({success:!0,response:_Xo(d)})).catch(d=>(this._events.emit("error",d),{success:!1,error:this.categorizeRequestError(d)}))}categorizeRequestError(t){if(t instanceof J8)return{type:"api_error",statusCode:t.status};if(t instanceof Jhe){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=sKt(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 u=c.response;return u.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"),u.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:u?.requestId,quotaLimited:u.quotaLimited}):u}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(RM.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(RM.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(RM.Props,this.props)})}processBeforeEnqueue(t){return t}async flushStorage(){}getQueueRouteKey(t){return VXo}persistedQueueKeyForRoute(t){return RM.Queue}getActiveQueueRoutes(){return[VXo]}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=LN(()=>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=asl(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=v5e(o.uuid,MN),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:OXo(),uuid:v5e(r?.uuid,MN)};return(r?.disableGeoip??this.disableGeoip)&&(asl(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 isl(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(()=>$Ht([r])).then(()=>(this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=i,this.flushPromise=i,this.flushPromises.add(i),this.addPendingPromise(i),$Ht([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 uKt(t,this.isDebug)}getBatchEndpointPath(t){return"/batch/"}async sendBatch(t,r,n=VXo){let i={api_key:this.apiKey,batch:t.map(u=>{if(!u)return u;let l=this.normalizeTimestampForWire(u.timestamp);return l===u.timestamp?u:{...u,timestamp:l}}),sent_at:OXo()};this.historicalMigration&&(i.historical_migration=!0);let o=g1e(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)),u=async()=>{let p=this.getPersistedProperty(n)||[],d=[...a],f=p.filter(m=>{let g=m.message?.uuid,A=d.findIndex(y=>y===m||typeof g=="string"&&g.length>0&&y.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()},l={retryCheck:p=>kft(p)?!1:Min(p)};try{await this.sendBatch(c,l,t)}catch(p){if(kft(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 Jhe||await u(),this._events.emit("error",p),p}await u(),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(l){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${t} batch; reporting it as too large`,l)),{kind:"too-large",measuredLocally:!0}}let o=ssl(i);if(o>osl)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${t} batch of ${o} bytes: the endpoint accepts at most ${osl}`)),{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,u={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,u,{type:"successful-write"},{retryCheck:l=>kft(l)||l instanceof J8&&l.retryAfterMs!==void 0?!1:Min(l)}),{kind:"ok"}}catch(l){if(kft(l))return{kind:"too-large"};if(Min(l)){let p=l instanceof J8?l.retryAfterMs:void 0;return{kind:"retry-later",error:l,...p!==void 0&&{retryAfterMs:p}}}return{kind:"fatal",error:l}}}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=ssl(s),c={...this._retryOptions,...i},u=0;return await Qol(async()=>{u++;let l=new AbortController,p=o??this.requestTimeout,d=Date.now()+p,f,m=new Promise((x,v)=>{f=LN(()=>{let S=Rft("AbortError",`Request timed out after ${p}ms`);v(S),l.abort(S)},p)}),g,A=!1,y,I=()=>y??=(async()=>{try{await g?.body?.cancel()}catch{}})();try{let x;try{x=this.fetch(t,{signal:l.signal,...r})}catch(B){throw new Jhe(B)}x.then(B=>{l.signal.aborted&&!A&&Promise.resolve(B.body?.cancel()).catch(()=>{})}).catch(()=>{});try{g=await Promise.race([x,m]),A=!0}catch(B){throw new Jhe(B)}let v=r.mode==="no-cors",S=n.type==="successful-write"?300:400;if(!v&&(g.status<200||g.status>=S))throw new J8(g,a,d,l);if(n.type==="successful-write"){try{await Promise.race([I(),m])}catch{}return}try{return await Promise.race([n.consume(g),m])}catch(B){throw l.signal.aborted?new Jhe(B):B}}finally{clearTimeout(f),l.signal.aborted&&g&&I()}},{...c,retryCheck:l=>{let p=c.retryCheck(l);return p&&u<=c.retryCount&&l instanceof J8&&l.cancelResponseBody(),p}})}async _shutdown(t=3e4){await this._initPromise;let r=!1;return this.clearFlushTimer(),this.disabled?void 0:y1e((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(!Tch(i))throw i;await isl(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 kch=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi;var _7v=new RegExp(kch.source,"i"),lsl=/[a-z][a-z0-9+.-]{0,63}:\/\//i,U7v=new RegExp(`^${lsl.source}`,"i"),V7v=new RegExp(lsl.source,"gi");var Fch=["is_not","is_set"],Nch=1152921504606847e3,el=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,e.prototype)}};function GXo(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(!GXo(t in e?e[t]:null))return!1;return!0}function qXo(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(!qXo(t in e?e[t]:null))return!1;return!0}function pKt(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 el("Cannot stringify an unpaired surrogate like the flags service");t++}else if(r>=56320&&r<=57343)throw new el("Cannot stringify an unpaired surrogate like the flags service")}}function _in(e,t=new Set){if(!(e===null||typeof e=="boolean")){if(typeof e=="string")return void pKt(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new el(`Cannot represent non-finite number ${e} like the flags service`);return}if(Array.isArray(e)){if(t.has(e))throw new el("Cannot represent a circular array during local evaluation");t.add(e);try{for(let r=0;r<e.length;r++)r in e&&_in(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 el("Cannot represent a non-JSON object like the flags service");if(t.has(e))throw new el("Cannot represent a circular object during local evaluation");t.add(e);try{for(let n of Object.keys(e))pKt(n),_in(e[n],t)}finally{t.delete(e)}return}throw new el(`Cannot represent ${typeof e} like the flags service`)}}function jch(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,u=a?t.charCodeAt(n+1):0,l=s?(i-55296)*1024+c-56320+65536:i,p=a?(o-55296)*1024+u-56320+65536:o;if(l!==p)return l-p;r+=s?2:1,n+=a?2:1}return e.length-t.length}function WXo(e,t=new Set){if(e===null)return"null";if(typeof e=="string")return pKt(e),JSON.stringify(e);if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"){if(!Number.isFinite(e))throw new el(`Cannot stringify non-finite number ${e} like the flags service`);if(Number.isInteger(e))throw new el(`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 el("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?WXo(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 el("Cannot stringify a non-JSON object like the flags service");if(t.has(e))throw new el("Cannot stringify a circular object during local evaluation");t.add(e);try{let n=Object.keys(e);return n.forEach(pKt),`{${n.sort(jch).map(i=>`${JSON.stringify(i)}:${WXo(e[i],t)}`).join(",")}}`}finally{t.delete(e)}}throw new el(`Cannot stringify ${typeof e} like the flags service`)}function Lin(e){return typeof e=="string"?(pKt(e),e):WXo(e)}function psl(e){try{return new RegExp(e),!0}catch{return!1}}function Y8(e){return String(e).replace(/[A-Z]/g,t=>t.toLowerCase())}function dsl(e,t,r){if(!/^\d+$/.test(e)||r==="strict"&&e.length>1&&e[0]==="0")throw new el(`Invalid semver: ${t}`);return parseInt(e,10)}function t1(e,t="strict"){let n=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!n||n.startsWith("."))throw new el(`Invalid semver: ${e}`);let i=n.split("."),o=s=>s===void 0||s===""?0:dsl(s,e,t);return[o(i[0]),o(i[1]),o(i[2])]}function X8(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 zch(e,t){let r=t1(e,t);return{lower:[r[0],r[1],r[2]],upper:[r[0],r[1]+1,0]}}function Qch(e,t){let[r,n,i]=t1(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 Mch(e,t){let n=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!n)throw new el(`Invalid wildcard semver: ${e}`);let i=n.split("."),o=c=>{if(t==="legacy-permissive"){let u=parseInt(c,10);if(!isNaN(u))return u}else try{return dsl(c,e,t)}catch{}throw new el(`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 fsl(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 el(`${e} is in an invalid date format`)}throw new el(`The date provided ${e} must be a string, number, or date object`)}function HXo(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 KXo(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 el(`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&&!Fch.includes(o)&&o!=="exact"&&o!=="is_not")return r.warnFunction?.(`Property ${n} cannot have a value of null with the ${o} operator`),!1;let u=(p,d)=>{if(r.propertyMatchingVersion!==2&&GXo(p)||Array.isArray(p)&&p.length===0)return _in(d),qXo(p)===qXo(d);if(r.propertyMatchingVersion===2&&typeof d=="number"&&GXo(p))return _in(d),!1;if(Array.isArray(p)){let f=Lin(d).toLowerCase();return p.some(m=>Lin(m).toLowerCase()===f)}return Lin(p).toLowerCase()===Lin(d).toLowerCase()},l=(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 u(i,c);case"is_not":return!u(i,c);case"is_set":return!0;case"icontains":return Y8(c).includes(Y8(i));case"not_icontains":return!Y8(c).includes(Y8(i));case"starts_with":return Y8(c).startsWith(Y8(i));case"not_starts_with":return!Y8(c).startsWith(Y8(i));case"ends_with":return Y8(c).endsWith(Y8(i));case"not_ends_with":return!Y8(c).endsWith(Y8(i));case"regex":return psl(String(i))&&String(c).match(String(i))!==null;case"not_regex":return psl(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)?l(d,p,o):l(String(c),String(i),o)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new el("Date operations cannot be performed on boolean values");let p=HXo(String(i));p==null&&(p=fsl(i));let d=fsl(c);return o==="is_date_before"?d<p:d>p}case"semver_eq":return X8(t1(String(c),s),t1(String(i),s))===0;case"semver_neq":return X8(t1(String(c),s),t1(String(i),s))!==0;case"semver_gt":return X8(t1(String(c),s),t1(String(i),s))>0;case"semver_gte":return X8(t1(String(c),s),t1(String(i),s))>=0;case"semver_lt":return X8(t1(String(c),s),t1(String(i),s))<0;case"semver_lte":return X8(t1(String(c),s),t1(String(i),s))<=0;case"semver_tilde":{let p=t1(String(c),s),{lower:d,upper:f}=zch(String(i),s);return X8(p,d)>=0&&X8(p,f)<0}case"semver_caret":{let p=t1(String(c),s),{lower:d,upper:f}=Qch(String(i),s);return X8(p,d)>=0&&X8(p,f)<0}case"semver_wildcard":{let p=t1(String(c),s),{lower:d,upper:f}=Mch(String(i),s);return X8(p,d)>=0&&X8(p,f)<0}default:throw new el(`Unknown operator: ${o}`)}}async function msl(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 fKt(e,t,r="",n="."){let i=await msl(`${e}${n}${t}${r}`);return parseInt(i.slice(0,15),16)/Nch}async function JXo(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 fKt("holdout",t,"","-")>n/100))return`holdout-${e.id}`}function Uin(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 YXo(e,t,r){let n=await fKt(e,t,"variant");return Uin(r).find(i=>n>=i.valueMin&&n<i.valueMax)?.key}function XXo(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:Dft(n)}var hsl=9223372036854776e3,Lch="9223372036854775808",_ch=Object.prototype.propertyIsEnumerable;function Uch(){return{ancestors:new WeakSet,remainingNodes:1e4}}function Ine(e,t){try{return gsl(e,t,Uch(),0)}catch{return[]}}function Vch(e,t){let r=e.toString(),n=BigInt(Lch);return e>=n||e<-n?(t?.debug(`Attribute ${r} is outside the int64 range; encoding it as a string`),{stringValue:r}):{intValue:r}}function eZo(e,t,r,n){if(r.remainingNodes<=0)return{stringValue:Rin};if(r.remainingNodes--,dol(e))return{boolValue:e};if(typeof e=="bigint")return Vch(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>=hsl||e<-hsl?(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:bne(e)};if(typeof e=="function")return{stringValue:Nol};if(typeof e=="symbol")return{stringValue:String(e)};if(typeof e=="object"&&e!==null){if(r.ancestors.has(e))return{stringValue:Bin};if(n>=20)return{stringValue:Rin};if(e instanceof Date){let i=e.getTime(),o=Number.isFinite(i)?e.toISOString():String(e);return{stringValue:typeof o=="string"?bne(o):String(o)}}r.ancestors.add(e);try{try{let i=e.toJSON;if(typeof i=="function")return eZo(i.call(e),t,r,n+1)}catch{}return q4(e)?{arrayValue:{values:Gch(e,t,r,n+1)}}:{kvlistValue:{values:gsl(e,t,r,n+1)}}}finally{r.ancestors.delete(e)}}return{stringValue:bne(String(e))}}function Gch(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(GJ(a))continue;i.push(eZo(a,t,r,n))}catch{i.push({stringValue:K8})}return e.length>s&&i.push({stringValue:Rin}),i}function gsl(e,t,r,n){let i=[];for(let o in e)if(_ch.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(bXo(s)||Hhe(s))continue;i.push({key:bne(o),value:eZo(s,t,r,n)})}catch{i.push({key:bne(o),value:{stringValue:K8}})}}return i}function mKt(e,t,r){return{...Khe({},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 qch=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function hKt(e,t){let r=Khe({},e),n={};for(let i of qch)Object.prototype.hasOwnProperty.call(r,i)&&(n[i]=r[i],delete r[i]);return[...Ine(r,t),...Ine(n,t)]}var Asl={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 Wch(e){if(e)return Object.prototype.hasOwnProperty.call(Asl,e)?Asl[e]:e}function tZo(e,t){let r=Wch(e);return{...r?{"os.name":r}:{},...t?{"os.version":t}:{}}}var Hch={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}},oHv=Hch.info;var C5e=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=LN(()=>{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 gKt(){return 1-.25+Math.random()*.25*2}var Z8=1;function AKt(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 yKt=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function rZo(e){return String(e)+"000000"}function nZo(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 ysl(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}function iZo(e,t,r){return mKt(e,t,r)}function oZo(e,t,r,n){return{resourceMetrics:[{resource:{attributes:hKt(t)},scopeMetrics:[{scope:{name:r,version:n},metrics:e}]}]}}function Gin(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 bsl=1,bKt=class{constructor(t,r,n){this._instance=t,this._config=r,this._logger=n,this._series=new Map,this._flushTimer=new C5e(()=>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 I5e,this._consecutiveFlushFailures=0,this._flushJitter=Z8,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=Z8,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=nZo(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(yKt.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[ysl(r,yKt)]+=1;break}}}_runBeforeSend(t){let r=this._config.beforeSend;if(!r)return t;let n=q4(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(AKt(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=gKt()):(this._consecutiveFlushFailures=0,this._flushJitter=Z8),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 oZo(this._buildMetrics(t),iZo(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(t){let r=rZo(Date.now()),n=new Map;for(let i of t.values()){let o=nZo(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:bsl,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?s.gauge={dataPoints:[]}:s.histogram={aggregationTemporality:bsl,dataPoints:[]},n.set(o,s));let a=Ine(i.attributes??{},this._logger),c=rZo(i.windowStartMs);if(i.type==="count"){let u={attributes:a,startTimeUnixNano:c,timeUnixNano:r,asDouble:i.total??0};s.sum.dataPoints.push(u)}else if(i.type==="gauge"){let u={attributes:a,timeUnixNano:r,asDouble:i.last??0};s.gauge.dataPoints.push(u)}else if(i.hist){let u={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:yKt};s.histogram.dataPoints.push(u)}}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 Xch="0".repeat(32),Zch="0".repeat(16),$ch=/^[0-9a-f]+$/;function euh(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 tuh(e){let t="";for(let r=0;r<e.length;r++)t+=e[r].toString(16).padStart(2,"0");return t}function Esl(e){let t=tuh(euh(e));return/[^0]/.test(t)?t:t.slice(0,-1)+"1"}function Isl(){return Esl(16)}function vsl(){return Esl(8)}function Csl(e,t,r){return typeof e=="string"&&e.length===t&&e!==r&&$ch.test(e)}function xsl(e){return Csl(e,32,Xch)}function Ssl(e){return Csl(e,16,Zch)}var ruh=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function wsl(e){let t=Tsl(e);return t&&{traceId:t.traceId,spanId:t.spanId,flags:nuh(t.flags)}}function nuh(e){return 1&parseInt(e,16)?Win:iuh}function Tsl(e){if(typeof e!="string")return;let t=ruh.exec(e.trim());if(!t)return;let[,r,n,i,o,s]=t;if(r!=="ff"&&!(r==="00"&&s)&&!(!xsl(n)||!Ssl(i)))return{version:r,traceId:n,spanId:i,flags:o}}function Osl(e){return Tsl(e)&&e.trim()}function qin(e){return Array.isArray(e)&&e.length===1?e[0]:e}var Win="01",iuh="00";function Psl(e,t,r=Win){return`00-${e}-${t}-${r}`}var ouh=32,sZo=512;function Hin(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>ouh)){for(let n of r)if(n.trim()&&!n.includes("="))return;return t.length<=sZo?t:auh(r)}}var suh=128;function auh(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()>sZo;n--)t[n].length>suh&&t.splice(n,1);for(;t.length&&r()>sZo;)t.pop();return t.length?t.join(","):void 0}var Bsl="unknown";function x5e(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 "${Bsl}"`),Bsl)}function Fft(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 Rsl(e,t,r){let n=Fft(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 Kin(e,t){return e<t?t:e}function EKt(e,t,r,n){let i=Fft(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 Yin(){let e=globalThis.performance;return typeof e?.now=="function"?e.now():void 0}var Nft=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??Win,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:Yin(),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=Yin();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(GJ(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]=Zin(r,this._maxAttributeValueLength)}setAttribute(t,r){return this._mutable("setAttribute")&&this._writeAttribute(t,r),this}setAttributes(t){if(this._mutable("setAttributes")){let r=Khe({},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&&Nsl(r,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:x5e(t,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:EKt(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:aZo(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}=cZo(t);return this.addEvent(cuh,{"exception.type":r,"exception.message":n,...i&&{"exception.stacktrace":i}}),this.setStatus("error",n)}updateName(t){return this._mutable("updateName")&&(this._name=x5e(t,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return Psl(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=EKt(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:Kin(n,this._startTime),...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}},cuh="exception",uuh=4294967295;function luh(e){try{return typeof e=="string"?e:String(e)}catch{return K8}}function S5e(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?0:Math.min(Math.floor(e),uuh)}function puh(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 ksl(e,t,r,n,i,o,s=[]){let a=0,c=0,u={};for(let f of puh(e.attributes,s)){let m=e.attributes[f];if(!GJ(m)){if(!t.has(f)){if(a>=r){c++;continue}a++}Object.defineProperty(u,f,{value:Zin(m,o),enumerable:!0,writable:!0,configurable:!0})}}e.attributes=u,c&&(e.droppedAttributesCount=S5e(e.droppedAttributesCount)+c);let l=0,p=0,d=[];for(let f of e.events){if(l>=n){p++;continue}if(l++,f.attributes){let m=Nsl(f.attributes,i,o);f.attributes=m.attributes,m.dropped&&(f.droppedAttributesCount=S5e(f.droppedAttributesCount)+m.dropped)}d.push(f)}e.events=d,p&&(e.droppedEventsCount=S5e(e.droppedEventsCount)+p),e.status?.message&&(e.status={...e.status,message:aZo(luh(e.status.message),o)})}var Xin=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(){}},Fsl=new Xin,IKt=class extends Xin{constructor(t,r){super(),this._traceparent=t,this._tracestate=r}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}};function fuh(e){try{let t=e.stack;return typeof t=="string"&&t?{stack:t}:{}}catch{return{}}}function b1e(e,t){let r=qin(e?.parent)??t,n=typeof r=="string"||r==null?r:Dsl(r,"traceparent"),i=Osl(n);if(!i)return Fsl;let o=typeof r=="string"||r==null?e?.tracestate:Dsl(r,"tracestate");return new IKt(i,Hin(o))}function Dsl(e,t){try{let r=e[t];return typeof r=="function"?r.call(e):void 0}catch{return}}function aZo(e,t){return e.length>t?e.slice(0,t):e}function Zin(e,t){return Jin(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}function Jin(e,t,r,n){if(e===null||typeof e!="object")return GJ(e)||r.remainingNodes<=0?e:(r.remainingNodes--,typeof e=="string"?aZo(e,t):e);if(r.ancestors.has(e))return Bin;if(r.remainingNodes<=0||n>=20)return e;r.remainingNodes--,r.ancestors.add(e);try{if(e instanceof Date)return e;let i=duh(e);if(i.selfDescribed)return GJ(i.value)?String(i.value):Jin(i.value,t,r,n+1);if(q4(e)){let a=Math.min(e.length,1e3),c=[];for(let u=0;u<a;u++)try{c.push(Jin(e[u],t,r,n+1))}catch{c.push(K8)}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=Jin(e[a],t,r,n+1)}catch{c=K8}a&&!GJ(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 duh(e){try{let t=e.toJSON;if(typeof t=="function")return{selfDescribed:!0,value:t.call(e)}}catch{}return{selfDescribed:!1}}function Nsl(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=Zin(e[a],r)}catch{c=K8}GJ(c)||(o++,Object.defineProperty(i,a,{value:c,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:i,dropped:s}}function jsl(e,t){for(let r of Object.keys(e))e[r]=Zin(e[r],t);return e}function vKt(e,t,r){return t===Fsl?r(t):e.with(t,()=>r(t))}function cZo(e){try{let t=fuh(e);if(A1e(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 uZo={internal:1,server:2,client:3,producer:4,consumer:5},muh={ok:1,error:2},huh=1,guh=256,Auh=512;function yuh(e){let t=parseInt(e.traceFlags,16);return(Number.isFinite(t)?255&t:huh)|guh|(e.parentIsRemote?Auh:0)}function $in(e){if(typeof e=="string")return bne(e);try{return bne(String(e))}catch{return K8}}function buh(e){return e&&Object.prototype.hasOwnProperty.call(uZo,e)?uZo[e]:uZo.internal}function lZo(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 Euh(e,t){let r={name:$in(e.name),timeUnixNano:lZo(e.timestamp)};if(e.attributes){let i=Ine(e.attributes,t);i.length&&(r.attributes=i)}let n=S5e(e.droppedAttributesCount);return n&&(r.droppedAttributesCount=n),r}function zsl(e,t){let r={traceId:e.traceId,spanId:e.spanId,name:$in(e.name),kind:buh(e.kind),startTimeUnixNano:lZo(e.startTime),endTimeUnixNano:lZo(e.endTime),flags:yuh(e)};e.parentSpanId&&(r.parentSpanId=e.parentSpanId),e.traceState&&(r.traceState=$in(e.traceState));let n=Ine(e.attributes,t);n.length&&(r.attributes=n),e.events.length&&(r.events=e.events.map(s=>Euh(s,t)));let i=S5e(e.droppedAttributesCount);i&&(r.droppedAttributesCount=i);let o=S5e(e.droppedEventsCount);return o&&(r.droppedEventsCount=o),e.status&&(r.status={code:muh[e.status.code],...e.status.message&&{message:$in(e.status.message)}}),r}function Qsl(e,t,r){return mKt(e,t,r)}function Msl(e,t,r,n,i){return{resourceSpans:[{resource:{attributes:hKt(t,i)},scopeSpans:[{scope:{name:r,version:n},spans:e}]}]}}var Lsl=8;function eon(){return Yin()??Date.now()}function pZo(e){try{return e instanceof Nft}catch{return!1}}function _sl(e,t){let r=wsl(e);if(r)return{traceId:r.traceId,parentSpanId:r.spanId,traceState:Hin(t),traceFlags:r.flags,isRemote:!0}}function Iuh(e){try{return typeof e.traceparent=="function"}catch{return!1}}function vuh(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 ton(e,t,r){e[t]!==r&&(e[t]=r)}function Cuh(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 CKt=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 C5e(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=Z8,this._retryAfter=new I5e,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 b1e(r,this._contextManager.active());let n=qin(r?.parent);if(n&&typeof n!="string"&&!pZo(n)){if(Iuh(n))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),b1e(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`),b1e(r,this._contextManager.active());let o=Date.now(),s=Rsl(r?.startTime,o,this._logger),a=vsl();this._liveSpans.set(a,eon());let c=this._autoContextAttributes();return new Nft({traceId:i?.traceId??Isl(),spanId:a,parentSpanId:i?.parentSpanId,traceState:i?.traceState,traceFlags:i?.traceFlags,parentIsRemote:i?.isRemote,name:x5e(t,"Span name",this._config.maxAttributeValueLength,this._logger),kind:r?.kind??"internal",attributes:Khe({...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:Fft(r?.startTime)===void 0?i?.clockAnchor:void 0},(u,l)=>this._onSpanEnd(u,l),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=vKt(this._contextManager,s,o);return Mol(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=Z8,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(t,r){if(typeof t=="string"){let i=_sl(t,r?.tracestate);return i||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),i}if(pZo(t))return t.childContext();let n=this._contextManager.active();if(pZo(n))return n.childContext();if(n instanceof IKt)return _sl(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 Nft))return;let{type:n,message:i,stack:o}=cZo(r);t.addEvent("exception",{"exception.type":n,"exception.message":i,...o&&{"exception.stacktrace":o}}),t.statusIsExplicitlyOk||t.setStatus("error",i)}_evictAgedSpans(){let t=eon()-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},u=t,l=t;try{for(let f of this._config.beforeSpanSend){let m=f(u);if(!m)return this._recordDrop(1,"beforeSpanSend dropped it"),null;u=this._keepSpanIdentity(m,n)}if(l={traceId:n.traceId,spanId:n.spanId,parentSpanId:n.parentSpanId,traceState:n.traceState,name:u.name,kind:u.kind,status:u.status,attributes:u.attributes,events:u.events,startTime:u.startTime,endTime:u.endTime,traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote,droppedAttributesCount:o.attributes,droppedEventsCount:o.events},!vuh(l))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;l.name=x5e(l.name,"Span name",this._config.maxAttributeValueLength,this._logger),l.status&&l.status.code!=="ok"&&l.status.code!=="error"&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),l.status=c),l.startTime=Fft(l.startTime)??i.startTime,l.endTime=Kin(Fft(l.endTime)??i.endTime,l.startTime);let d=[];for(let f of l.events)try{d.push({...f,name:x5e(f.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:EKt(f.timestamp,l.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return l.events=d,ksl(l,r,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,s),l}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{ton(t,"traceId",r.traceId),ton(t,"spanId",r.spanId),ton(t,"parentSpanId",r.parentSpanId),ton(t,"traceState",r.traceState)}catch{return Cuh(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(zsl(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=jsl(Qsl(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 u=this._discardQueueIfConsentWithdrawn();if(u)return s+u;let l=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,p=Math.max(1,Math.min(l,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=eon()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),g=await this._instance._sendTracesBatch(Msl(f,r,n,i,this._logger));if(c!==this._generation)break;if(this._retryAfter.record(g),g.kind==="ok"){this._consecutiveFlushFailures=0,this._flushJitter=Z8,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=Z8,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=gKt(),this._headBatchSize=p,m&&(this._headBatchFailures++,this._headBatchChargeableAt=eon()+this._nextFlushDelay()),this._headBatchFailures<Lsl)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=Z8,this._resetHeadBatchBudget(),this._recordDrop(p,`the ingestion endpoint failed ${Lsl} 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=Z8,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(AKt(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}};var xKt=class{active(){return this._active}with(t,r){let n=this._active;this._active=t;try{return r()}finally{this._active=n}}};var xuh=5e3,Suh=512,wuh=2048,Tuh=128,Ouh=128,Puh=128,Buh=8192,Ruh=1e4,Duh=36e5;function E1e(e,t){return typeof e=="number"&&Number.isInteger(e)&&e>=1?e:t}var Usl=["service.name","service.version","deployment.environment"];function kuh(e){if(!(!e||typeof e!="object"||Array.isArray(e)))try{if(Usl.every(r=>!(r in e)||typeof e[r]=="string"))return e;let t={...e};for(let r of Usl)r in t&&typeof t[r]!="string"&&delete t[r];return t}catch{return}}function Fuh(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 fZo(e,t,r){let n=Khe({...t},kuh(e?.resourceAttributes)),i=E1e(e?.maxExportBatchSize,Suh);return{serviceName:n?.["service.name"]??e?.serviceName,serviceVersion:n?.["service.version"]??e?.serviceVersion,environment:n?.["deployment.environment"]??e?.environment,resourceAttributes:n,beforeSpanSend:Fuh(e?.beforeSpanSend,r),maxAttributesPerSpan:E1e(e?.maxAttributesPerSpan,Tuh),maxEventsPerSpan:E1e(e?.maxEventsPerSpan,Ouh),maxAttributesPerEvent:Puh,maxAttributeValueLength:E1e(e?.maxAttributeValueLength,Buh),flushIntervalMs:E1e(e?.flushIntervalMs,xuh),maxExportBatchSize:i,maxQueueSize:Math.max(E1e(e?.maxQueueSize,wuh),i),maxLiveSpans:E1e(e?.maxLiveSpans,Ruh),maxSpanAgeMs:E1e(e?.maxSpanAgeMs,Duh)}}var dZo=require("fs"),qsl=require("fs/promises"),hZo=require("path"),Wsl=require("readline"),ron=new sO.ReduceableCache(25),SKt=new sO.ReduceableCache(20),gZo=7,Nuh=1e3,juh=1e4,mZo=10485760;async function Hsl(e,t=qsl.open,r){let n={},i;try{i=process.cwd()}catch{}for(let a=e.length-1;a>=0;a--){let c=e[a],u=c?.filename;if(!c||typeof u!="string"||typeof c.lineno!="number"||_uh(u)||Uuh(c)||!(0,hZo.isAbsolute)(u)&&i===void 0)continue;n[u]||(n[u]=[]),n[u].push(c.lineno)}let o=Object.keys(n);if(o.length==0)return e;let s=[];for(let a of o){let c=Ksl(a,i);if(c===void 0||SKt.get(c))continue;let u=n[a];if(!u)continue;u.sort((d,f)=>d-f);let l=Guh(u);if(l.every(d=>Vuh(c,d)))continue;let p=quh(ron,c,{});s.push(Quh(a,l,p,c,t,r))}return await Promise.all(s).catch(()=>{}),e&&e.length>0&&Muh(e,ron,i),ron.reduce(),e}async function zuh(e,t,r){let n,i=!1;try{n=await t(e,dZo.constants.O_RDONLY|dZo.constants.O_NONBLOCK);let o=await n.stat();return o.isFile()?o.size>mZo?void r?.debug(`Skipping source context for oversized file ${e}: ${o.size} bytes exceeds ${mZo}`):(i=!0,n):void 0}catch{return}finally{n&&!i&&await n.close().catch(()=>{})}}async function Quh(e,t,r,n,i,o){let s=await zuh(e,i,o);if(s===void 0)return void SKt.set(n,1);let a=s;return new Promise(c=>{let u=!1;function l(x){u||(u=!0,x?.destroy(),a.close().then(c,c))}let p;try{p=a.createReadStream({autoClose:!1,start:0,end:mZo-1})}catch{SKt.set(n,1),l();return}let d;try{d=(0,Wsl.createInterface)({input:p})}catch{SKt.set(n,1),l(p);return}let f=0,m=0,g=t[m];if(g===void 0)return void l(p);let A=g[0],y=g[1];function I(){SKt.set(n,1),d.close(),d.removeAllListeners(),l(p)}p.on("error",I),d.on("error",I),d.on("close",()=>l(p)),d.on("line",x=>{if(f++,!(f<A)&&(r[f]=Wuh(x,0),f>=y)){if(m===t.length-1){d.close(),d.removeAllListeners();return}m++;let v=t[m];if(v===void 0){d.close(),d.removeAllListeners();return}A=v[0],y=v[1]}})})}function Muh(e,t,r){for(let n of e)if(n.filename&&n.context_line===void 0&&typeof n.lineno=="number"){let i=Ksl(n.filename,r),o=i===void 0?void 0:t.get(i);if(o===void 0)continue;Luh(n.lineno,n,o)}}function Luh(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=Jsl(e);i<e;i++){let o=r[i];if(o===void 0)return void Vsl(t);t.pre_context.push(o)}if(r[e]===void 0)return void Vsl(t);t.context_line=r[e];let n=Ysl(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 Vsl(e){delete e.pre_context,delete e.context_line,delete e.post_context}function _uh(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function Uuh(e){return e.lineno!==void 0&&e.lineno>juh||e.colno!==void 0&&e.colno>Nuh}function Ksl(e,t){return(0,hZo.isAbsolute)(e)?JSON.stringify([null,e]):t===void 0?void 0:JSON.stringify([t,e])}function Vuh(e,t){let r=ron.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 Guh(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=Gsl(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+gZo:(i.push(n),n=Gsl(o)),t++}return i}function Gsl(e){return[Jsl(e),Ysl(e)]}function Jsl(e){return Math.max(1,e-gZo)}function Ysl(e){return e+gZo}function quh(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function Wuh(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 jft=require("path");function Xsl(e=process.cwd()){let t=jft.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,jft.isAbsolute)(o.filename)&&(o.filename=r((0,jft.relative)(n,r(o.filename))));return i}}var Zsl="5.55.0";var Yhe={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var I1e=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(Yhe.ERRORS_WHILE_COMPUTING),this._quotaLimited&&o.push(Yhe.QUOTA_LIMITED),r===void 0&&o.push(Yhe.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 Huh=6e4;function $sl(e){return e==="client"||e==="server"?e:"all"}function Kuh(e,t){return e===t||e==="all"||t==="all"}var zft=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}};function Juh(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}var vne=class e extends Error{constructor(t){super(t),Juh(this,e)}},non=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(u){u instanceof vne||u instanceof el?this.logMsgIfDebug(()=>console.debug(`${u.name} when computing flag locally: ${t}: ${u.message}`)):u instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${u}`))}}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:u,payload:l}=await this.computeFlagAndPayloadLocally(c,a,{skipLoadCheck:!0});n[c.key]=u,l&&(i[c.key]=l)}catch(u){u instanceof vne||u instanceof el?this.logMsgIfDebug(()=>console.debug(`${u.name} when computing flag locally: ${c.key}: ${u.message}`)):u instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${c.key}: ${u}`)),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=XXo(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 el("Flag has experience continuity enabled");let c=(t.filters||{}).aggregation_group_type_index;if(c!=null){let u=r.definitions.groupTypeMapping[String(c)];if(!u)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new el("Flag has unknown group type index");if(!(u 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 l=s[u];return await this.matchFeatureFlagProperties(t,i[u],l,r)}{let u=this.getBucketingValueForFlag(t,n,o);if(u===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 el(`Can't compute feature flag: ${t.key} without $device_id`);return await this.matchFeatureFlagProperties(t,u,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 el("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new el(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let s=t.dependency_chain;if(!Array.isArray(s))throw new el(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new el(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let c of s){if(!(c in i)){let l=n.definitions.featureFlagsByKey[c];if(l)if(l.active)try{let p=await this.computeFlagValueLocally(l,n);i[c]=p}catch(p){throw new el(`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 el(`Missing flag dependency '${c}' for flag '${o}'`)}if(i[c]==null)throw new el(`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 JXo(o.holdout,r);if(s!==void 0)return s;let a=o.groups||[],c=o.aggregation_group_type_index,u=o.early_exit??!1,{groups:l,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,y=r;if(g!==c&&g!=null){let x=i.definitions.groupTypeMapping[String(g)];if(!x||!(x in l)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${t.key}': group type index ${g} not available`));continue}if(!(x in p)){d=!0;continue}A=p[x],y=l[x]}let I=await this.isConditionMatch(t,y,m,A,i);if(I==="match"){let x=m.variant,v=o.multivariate?.variants||[];f=x&&v.some(S=>S.key===x)?x:await this.getMatchingVariant(t,y)||!0;break}if(u&&I==="out_of_rollout_bound"){if(d)break;return!1}}catch(g){if(g instanceof vne)throw g;if(g instanceof el)d=!0;else throw g}if(f!==void 0)return f;if(d)throw new el("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=u=>{this.logMsgIfDebug(()=>console.warn(u))};if((n.properties||[]).length>0){for(let u of n.properties){let l=u.type,p=!1;if(l==="cohort"){let d=await tal(u,i,s.cohorts,this.debugMode,f=>this.evaluateFlagDependency(f,i,o),s.propertyMatchingVersion);p=u.operator==="not_in"?!d:d}else p=l==="flag"?await this.evaluateFlagDependency(u,i,o):eal(u,i,c,s.propertyMatchingVersion);if(!p)return"no_match"}if(a==null)return"match"}return a!=null&&await fKt(t.key,r)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(t,r){return YXo(t.key,r,t.filters?.multivariate?.variants||[])}variantLookupTable(t){return Uin(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?$sl(r.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(t){return this.featureFlags.filter(r=>Kuh($sl(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(Huh,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 zft(`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 zft(`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 zft(`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 zft&&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=LN(()=>{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 y1e(r,t,()=>{throw new Error(`Cache shutdown timeout after ${t}ms`)})}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};function eal(e,t,r,n){return KXo(e,t,{warnFunction:r,propertyMatchingVersion:n})}function Yuh(e,t){if(!(e in t))throw new vne(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function tal(e,t,r,n=!1,i,o){let s=String(e.value);Yuh(s,r);let a=r[s];return ral(a,t,r,n,i,o)}async function ral(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 u of a)try{let l=await ral(u,t,r,n,i,o);if(s==="AND"){if(!l)return!1}else if(l)return!0}catch(l){if(l instanceof vne)throw l;if(l instanceof el)n&&console.debug(`Failed to compute property ${u} locally: ${l}`),c=!0;else throw l}if(c)throw new el("Can't match cohort without a given cohort property value");return s==="AND"}for(let u of a)try{let l;if(u.type==="cohort")l=await tal(u,t,r,n,i,o);else if(u.type==="flag"){if(!i)throw new el(`Flag dependency '${u.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);l=await i(u)}else l=eal(u,t,void 0,o);let p=u.negation||!1;if(s==="AND"){if(!l&&!p||l&&p)return!1}else if(l&&!p||!l&&p)return!0}catch(l){if(l instanceof vne)throw l;if(l instanceof el)n&&console.debug(`Failed to compute property ${u} locally: ${l}`),c=!0;else throw l}if(c)throw new el("can't match cohort without a given cohort property value");return s==="AND"}var Xuh=["--unhandled-rejections","--unhandled_rejections"],Zuh=new Set(["throw","strict","warn","warn-with-error-code","none"]),$uh=[...globalThis.process?.execArgv??[]],elh=globalThis.process?.env?.NODE_OPTIONS;function tlh(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 nal(e){let t;for(let r=0;r<e.length;r++){let n=e[r],i=Xuh.find(s=>n===s||n.startsWith(`${s}=`));if(!i)continue;let o=n===i?e[++r]:n.slice(i.length+1);Zuh.has(o)&&(t=o)}return t}function rlh(e=$uh,t=elh){return nal(e)??nal(tlh(t??""))??"throw"}var ial=rlh();function oal(e,t,r){e(t,{mechanism:{type:r==="unhandledRejection"?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function nlh(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;oal(e,n,i),!r&&o===0&&(r=!0,t(n))},{_posthogErrorHandler:!0})}function sal(e,t,r=ial){let n=globalThis.process;if(n){if(r==="strict")return void n.on("uncaughtExceptionMonitor",(i,o)=>oal(e,i,o));n.on("uncaughtException",nlh(e,t))}}function aal(e,t=ial){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 ilh=2e3,AZo=class e{constructor(t,r,n){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new vin({...yol(r),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return YHt(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=sO.getInjectedReleaseId();return c&&(s.$release_id=c),{event:"$exception",distinctId:i,properties:{...a,...s},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(sal(this.onException.bind(this),this.onFatalError.bind(this)),aal(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(ilh),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}},w5e=AZo;var ion=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};function olh(e){return e==="v0"||e==="v1"}function cal(){let e="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return olh(e)?e:"v0"}var slh="$ai_",wKt="analytics";function ual(e){return typeof e.event=="string"&&e.event.startsWith(slh)}var Qft=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 yZo(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 alh(e){return typeof e=="string"?e:void 0}var clh=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:yZo},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:yZo},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:yZo},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:alh}],ulh=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function llh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function plh(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 lal(e,t,r){r!==void 0&&!(t in e)&&(e[t]=r)}function flh(e){let r={...llh(e.properties)?e.properties:{}},n={};for(let{property:o,optionKey:s,coerce:a}of clh)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 ulh)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,lal(r,"$set",e.$set),lal(r,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:plh(e.timestamp),...i,options:n,properties:r}}function pal(e,{createdAt:t,historicalMigration:r}){let n={created_at:t,batch:e.map(flh)};return r&&(n.historical_migration=!0),n}var dlh="/i/v1/analytics/events",mlh=3e4,hlh=new Set([408,500,502,503,504]),oon=class{constructor(t,r){this.config=t,this.maxBackoffMs=t.maxBackoffMs??mlh,this.fetchFn=r.fetch,this.onError=r.onError,this.now=r.now??Date.now,this.sleep=r.sleep??(n=>new Promise(i=>LN(i,n))),this.generateRequestId=r.generateRequestId??MN,this.compress=r.compress??uKt}async sendV1Batch(t){if(t.length===0)return;let r=this.generateRequestId(),n=new Date(this.now()).toISOString(),{batch:i}=pal(t,{createdAt:n,historicalMigration:this.config.historicalMigration}),o=`${this.config.host}${dlh}`,s=[],a=i,c=Math.max(1,this.config.maxAttempts);for(let u=1;u<=c;u++){let l=u===c,p=g1e({created_at:n,...this.config.historicalMigration?{historical_migration:!0}:{},batch:a}),d,f;try{d=await this.sendOnce(o,p,u,r);let{response:m,signal:g}=d,{status:A}=m;if(A<200||A>=300)if(!l&&hlh.has(A)){let y=this.parseRetryAfter(m);await d.waitFor(d.cancelBody()).catch(()=>{}),f=this.backoffDelay(u,y)}else{let y=await this.buildHttpError(m,A,d.waitFor);return this.surfaceBatchFailure(r,s,a,y)}else{let y;try{y=await d.waitFor(this.parseResponse(m))}catch(v){if(g.aborted)throw v;return this.surfaceBatchFailure(r,s,a,new Error(`Capture V1 returned an unparseable ${A} response body`))}let I=this.classify(a,y,s);if(I.length===0)return this.surfacePartialDrops(r,s);if(l)return void this.onError(new Qft({requestId:r,drops:s,retryExhausted:I.map(v=>v.uuid)}));a=I;let x=this.parseRetryAfter(m);f=this.backoffDelay(u,x)}}catch(m){if(d&&!d.signal.aborted)throw m;if(l)return this.surfaceBatchFailure(r,s,a,m);f=this.backoffDelay(u)}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",u,l=new Promise((p,d)=>{u=LN(()=>{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(y=>{a.signal.aborted&&!d&&this.cancelBody(y)}).catch(()=>{});let f=await Promise.race([p,l]);d=!0,c="while reading the response body";let m=!1,g,A=()=>g??=this.cancelBody(f);return{response:f,signal:a.signal,waitFor:y=>Promise.race([y,l]),cancelBody:A,cleanup:()=>{m||(m=!0,clearTimeout(u),a.signal.aborted&&A())}}}catch(p){throw clearTimeout(u),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 Qft({requestId:t,drops:r,retryExhausted:n.map(o=>o.uuid),cause:i}))}surfacePartialDrops(t,r){r.length>0&&this.onError(new Qft({requestId:t,drops:r,retryExhausted:[]}))}async cancelBody(t){try{await t.body?.cancel()}catch{}}};var T5e="ai-capture",son="/i/v0/ai/batch/";var Alh=new TextEncoder;function EZo(e){return Alh.encode(g1e(e)).length}function fal(e,t=8388608,r=5242880){let n=[],i=[],o=[],s=0;for(let a of e){if(a===void 0)continue;let c=EZo(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 ylh=100,dal=3e4,blh=5e4,Elh=50,Ilh=500,vlh="https://us.i.posthog.com",mal=new Set;function con(e,t){mal.has(e)||(mal.add(e),console.warn(`[PostHog] ${t}`))}function Clh(e){return typeof e=="string"?e.trim():""}function xlh(e){return(typeof e=="string"?e.trim():"")||void 0}function Slh(e){return(typeof e=="string"?e.trim():"")||vlh}function wlh(e){return(Array.isArray(e)?e:[e]).filter(r=>typeof r=="string"&&r.trim().length>0)}function Tlh(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 uon=class extends lKt{constructor(t,r={}){let n=Clh(t),i={...r,maxQueueSize:r.maxQueueSize??1e4,flushInterval:r.flushInterval??5e3,host:Slh(r.host),personalApiKey:xlh(r.secretKey??r.personalApiKey)};if(super(n,i),this._memoryStorage=new ion,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=i,this.captureMode=cal(),this.enableFullAiCapture=i.enableFullAiCapture===!0,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof i.featureFlagsPollingInterval=="number"?Math.max(i.featureFlagsPollingInterval,ylh):i.featureFlagsPollingInterval===null?null:dal,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 non({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 w5e(this,i,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=i.maxCacheSize||blh}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:$Ht([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??Ilh,i=r>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),i)return void this.resolveWaitUntilFlush();let o=this.options.waitUntilDebounceMs??Elh;this._waitUntilCycle.timer=LN(()=>{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"&&ual(t)?"ai":wKt}persistedQueueKeyForRoute(t){return t===T5e?RM.AiCaptureQueue:t==="ai"?RM.AiQueue:RM.Queue}getActiveQueueRoutes(){let t=this.captureMode==="v1"?[wKt,"ai"]:[wKt];return this._aiCaptureRouteActive&&t.push(T5e),t}getBatchEndpointPath(t){return t===T5e?son:super.getBatchEndpointPath(t)}async sendBatch(t,r,n=wKt){if(n===T5e)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}=fal(t);for(let{event:o,bytes:s}of i){let a=`Event ${o} (${s} bytes) exceeds the ${8388608/1048576}MiB limit for ${son}, 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,T5e)}catch(n){if(!kft(n))throw n;if(t.length===1){let[o]=t,a=`Event ${typeof o.event=="string"?o.event:"unknown"} (${EZo(o)} bytes) was rejected with 413 by ${son} 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 oon({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 Zsl}get metrics(){return this._metrics||(this._metrics=new bKt(this,Gin(this.options.metrics),this._logger)),this._metrics}initializeSpanContextManager(){return new xKt}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 CKt(this,fZo(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)??b1e(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):vKt(this._spanContextManager,b1e(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:u})=>{let l={timestamp:u.timestamp,disableGeoip:u.disableGeoip,uuid:u.uuid},p={distinctId:s,event:a,properties:{...c,...this.getCommonEventProperties()}};return n?this.sendImmediate(t,p,l,o):this.enqueue(t,p,l,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=v5e(t.uuid,MN);return this._sendPreparedAiEvent({...t,uuid:r},!1),r}async captureAiImmediate(t){if(this.disabled)return;let r=v5e(t.uuid,MN);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,T5e)}identify({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,l={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};this._sendPreparedEvent("identify",{distinctId:t,event:"$identify",properties:l,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,l={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};await this._sendPreparedEvent("identify",{distinctId:t,event:"$identify",properties:l,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=wlh(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=dal){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 R=this._flagOverrides[t];if(R===void 0)return;let D=this._payloadOverrides?.[t];return{key:t,enabled:R!==!1,variant:typeof R=="string"?R:void 0,payload:D}}let{groups:s,disableGeoip:a}=n,{onlyEvaluateLocally:c,personProperties:u,groupProperties:l}=n,p=this.addLocalPersonAndGroupProperties(r,s,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,s,this.personPropertiesForLocalEvaluation(r,u),l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f,m=!1,g,A,y,I,x,v,S;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let R=this.featureFlagsPoller?.featureFlagsByKey[t];if(R)try{let D=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(R,d,{matchValue:i});if(D){m=!0;let O=D.value;I=R.id,v="Evaluated locally",S=R.has_experiment,f={key:t,enabled:O!==!1,variant:typeof O=="string"?O:void 0,payload:D.payload??void 0,reason:v,reasonCode:R.active===!1?"flag_disabled":void 0}}}catch(D){if(D instanceof vne||D instanceof el)this._logger?.info(`${D.name} when computing flag locally: ${t}: ${D.message}`);else throw D}}if(!m&&!c){let R=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,u,l,a,[t]);if(R===void 0)y=Yhe.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=R.minimalFlagCalledEvents===!0,g=R.requestId,A=R.evaluatedAt;let D=[];R.errorsWhileComputingFlags&&D.push(Yhe.ERRORS_WHILE_COMPUTING),R.quotaLimited?.includes("feature_flags")&&D.push(Yhe.QUOTA_LIMITED);let O=R.flags[t];if(O===void 0)D.push(Yhe.FLAG_MISSING);else{I=O.metadata?.id,x=O.metadata?.version,v=O.reason?.description??O.reason?.code,S=O.metadata?.has_experiment;let z;if(O.metadata?.payload!==void 0)try{z=JSON.parse(O.metadata.payload)}catch{z=O.metadata.payload}f={key:t,enabled:O.enabled,variant:O.variant??void 0,payload:z,reason:v,reasonCode:O.reason?.code}}D.length>0&&(y=D.join(","))}}if(o){let R=f===void 0?void 0:f.enabled===!1?!1:f.variant??!0,D={$feature_flag:t,$feature_flag_response:R,$feature_flag_id:I,$feature_flag_version:x,$feature_flag_reason:v,locally_evaluated:m,[`$feature/${t}`]:R,$feature_flag_request_id:g,$feature_flag_evaluated_at:m?Date.now():A};if(S!==void 0&&(D.$feature_flag_has_experiment=S),m&&this.featureFlagsPoller){let O=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();O!==void 0&&(D.$feature_flag_definitions_loaded_at=O)}y&&(D.$feature_flag_error=y),this._captureFlagCalledEventIfNeeded({distinctId:r,key:t,response:R,groups:s,disableGeoip:a,properties:D})}return f!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(f={...f,payload:this._payloadOverrides[t]}),f}async getFeatureFlag(t,r,n){con("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(con("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){con("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:u,groupProperties:l}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,u),l);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 y=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,u,l,s,a);m={...m,...y.flags||{}},g={...g,...y.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 I1e({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new I1e({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,flags:{}});let{groups:o,disableGeoip:s}=i||{},a=i?.flagKeys??void 0;if(a?.length===0)return new I1e({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:{}});let{onlyEvaluateLocally:c,personProperties:u,groupProperties:l}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,u),l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=a?new Set(a):void 0,m={},g,A,y=!1,I=!1,x=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),v=new Set;if(x)for(let[R,D]of Object.entries(x.response)){let O=this.featureFlagsPoller?.featureFlagsByKey[R];m[R]={key:R,enabled:D!==!1,variant:typeof D=="string"?D:void 0,payload:x.payloads[R],id:O?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:O?.has_experiment},v.add(R)}let S=f!==void 0&&Array.from(f).some(R=>this.featureFlagsPoller?.featureFlagsByKey[R]===void 0);if((x?x.fallbackToFlags||S:!0)&&!c){let R=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,u,l,s,a);if(R){this._minimalFlagCalledEvents=R.minimalFlagCalledEvents===!0,g=R.requestId,A=R.evaluatedAt,y=!!R.errorsWhileComputingFlags,I=Array.isArray(R.quotaLimited)&&R.quotaLimited.includes("feature_flags");for(let[D,O]of Object.entries(R.flags)){if(v.has(D))continue;let z;if(O.metadata?.payload!==void 0)try{z=JSON.parse(O.metadata.payload)}catch{z=O.metadata.payload}m[D]={key:D,enabled:O.enabled,variant:O.variant,payload:z,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[R,D]of Object.entries(this._flagOverrides)){if(D===void 0){delete m[R];continue}let O=m[R];m[R]={key:R,enabled:D!==!1,variant:typeof D=="string"?D: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[R,D]of Object.entries(this._payloadOverrides)){let O=m[R];O&&(m[R]={...O,payload:D})}if(f!==void 0)for(let R of Object.keys(m))f.has(R)||delete m[R];return new I1e({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:m,requestId:g,evaluatedAt:A,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:y,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(([l],[p])=>l<p?-1:l>p?1:0))}`:"",u=`${n}_${i}${c}`;r in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[r].has(u)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),this.distinctIdHasSentFlagCalls[r]instanceof Set?this.distinctIdHasSentFlagCalls[r].add(u):this.distinctIdHasSentFlagCalls[r]=new Set([u]),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 y1e(this._metrics.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._metrics.reset()),this._traces&&(await y1e(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=LN(()=>{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(hol(s)&&r&&o in r){let a={};for(let[c,u]of Object.entries(s))a[String(c)]=String(u);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 u={};for(let[l,p]of Object.entries(r||{}))u[l]=String(p);return await this.getAllFlags(t,{groups:u,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let u={};for(let[l,p]of Object.entries(r||{}))u[l]=String(p);return await this.getAllFlags(t,{groups:u,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(!w5e.isPreviouslyCapturedError(t)){let s=new Error("PostHog syntheticException");this.addPendingPromise(w5e.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(!w5e.isPreviouslyCapturedError(t)){let o=new Error("PostHog syntheticException");return this.addPendingPromise(w5e.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:u,disableGeoip:l,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=MN(),g.$process_person_profile=!1),f&&d?.sessionId&&!g.$session_id&&(g.$session_id=d.sessionId);let A=this._shouldSendMinimalFlagCalledEvent(i,g)?aKt(g):g,y=this._runBeforeSend({distinctId:m,event:i,properties:A,groups:s,flags:a,sendFeatureFlags:c,timestamp:u,disableGeoip:l,uuid:p});if(!y)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){con("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 x=typeof c=="object"?c:void 0,v=await this.getFeatureFlagsForEvent(y.distinctId,s,l,x);return Tlh(v)}return{}}).catch(()=>({})).then(x=>{let v=y.groups||s;return{...x,...y.properties||{},...v!==void 0&&Object.keys(v).length>0?{$groups:v}:{}}});return y.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof I.$raw_user_agent=="string"&&Aol(I.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(y.event="$bot_pageview",I.$browser_type="bot"),{distinctId:y.distinctId,event:y.event,properties:I,options:{timestamp:y.timestamp,disableGeoip:y.disableGeoip,uuid:y.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 hal=require("async_hooks"),lon=class{constructor(){this.storage=new hal.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 gal=require("async_hooks"),pon=class{active(){return this._storage.getStore()}with(t,r){return this._storage.run(t,r)}constructor(){this._storage=new gal.AsyncLocalStorage}};var Aal=require("zlib"),yal=require("util"),Olh=(0,yal.promisify)(Aal.gzip);async function bal(e,t=!0){try{let r=await Olh(e);return new Uint8Array(r)}catch(r){return t&&console.error("Failed to gzip compress data",r),null}}var fon=require("os");function Eal(){let e,t;try{e=(0,fon.platform)(),t=(0,fon.release)()}catch{}return tZo(e,t)}var Ial="posthog-node";function Plh(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[IZo.POSTHOG_ID_TAG];if(c===void 0)return s;let u=e.options.host??"https://us.i.posthog.com",l=new URL(`/project/${e.apiKey}/person/${c}`,u).toString();s.tags["PostHog Person URL"]=l;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=sO.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 IZo=class{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(t,r,n,i,o){this.name=Ial,this.name=Ial,this.setupOnce=function(s,a){let c=a()?.getClient()?.getDsn()?.projectId;s(Plh(t,{organization:r,projectId:c,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o??!0}))}}};var Cne=class extends uon{getLibraryId(){return"posthog-node"}compressPayload(t){return bal(t,this.isDebug)}initializeContext(){return new lon}initializeSpanContextManager(){return new pon}hostResourceAttributes(){return Eal()}createErrorPropertiesBuilder(){return new sO.ErrorPropertiesBuilder([new sO.EventCoercer,new sO.ErrorCoercer,new sO.ObjectCoercer,new sO.StringCoercer,new sO.PrimitiveCoercer],sO.createStackParser("node:javascript",sO.nodeStackLineParser),[lol(),t=>Hsl(t,void 0,this._logger),Xsl()])}};function val(e){return e==null||!e.enabled?!1:e.variant==null||e.variant==="true"}var don=class{isEnabled(){return Promise.resolve(!1)}getCachedValue(){}flush(){return Promise.resolve()}},Blh="feature_flag_evaluated",Rlh=3e3,Dlh=3e3,mon=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 Cne(n??"",{featureFlagsRequestTimeoutMs:Rlh,isServer:!1})}isEnabled(t,r){let n=Cal(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(Cal(t,r))}async flush(){if(!this.sendFeatureFlagEvents)return;let t;try{await Promise.race([this.flushAfterPendingEvaluations(),new Promise(r=>{t=setTimeout(r,Dlh),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=Flh(r,this.environment),o;try{o=await this.evaluator.getFeatureFlagResult(t,vZo(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}),val(o)}captureFlagUsage({flag:t,org:r,result:n,properties:i}){let o=klh(n),s={...i,...n?.reason!=null?{$feature_flag_reason:n.reason}:{},version:"5.172.1"};this.tryCapture({distinctId:vZo(r),event:"$feature_flag_called",groups:{organization:r},properties:{...s,$feature_flag:t,$feature_flag_response:o,[`$feature/${t}`]:o}}),this.tryCapture({distinctId:vZo(r),event:Blh,groups:{organization:r},properties:{...s,flag:t,response:o,enabled:val(n)}})}tryCapture(t){try{this.evaluator.capture(t)}catch{}}};function klh(e){if(e!=null)return e.enabled?e.variant??!0:!1}function vZo(e){return`org:${e}`}function Flh({org:e,generator:t,language:r},n){return{org:e,environment:n,...t!=null?{generator:t}:{},...r!=null?{language:r}:{}}}function Cal(e,{org:t,generator:r,language:n}){return JSON.stringify([e,t,r??null,n??null])}var hon;function gon(){return hon==null&&(hon=Nlh()),hon}async function CZo(){await hon?.flush()}function Nlh(){let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";return e==null||e.trim().length===0?new don:new mon({posthogApiKey:e,environment:VJ(),sendFeatureFlagEvents:yin()})}var Aon=class{posthog;constructor({posthogApiKey:t}){this.posthog=new Cne(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.172.1",usingAccessToken:!0,cliReleaseEnvironment:VJ(),...Dpe()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:{...t.properties,cliReleaseEnvironment:VJ()}})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}};var TKt=class{async sendEvent(){}async sendAutomationEvent(){}async identify(){}async flush(){}};dd();tr();var Mft=require("fs/promises"),xal=require("os"),Sal=require("path");lVe();var jlh="id",zlh=".fern",OKt=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new Cne(r,{isServer:!1}),this.userId=t==null?void 0:mWo(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.172.1",...t,...t.properties,usingAccessToken:!1,cliReleaseEnvironment:VJ(),agent:yHr(),...r!=null?{userEmail:r}:{},...Dpe()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:{...t.properties,cliReleaseEnvironment:VJ()}})}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 Vp({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=Yw(),r=ke(Zt.of((0,xal.homedir)()),ye.of(zlh),ye.of(jlh));try{await Ut(r)?this.persistedDistinctId=(await(0,Mft.readFile)(r)).toString():(await(0,Mft.mkdir)((0,Sal.dirname)(r),{recursive:!0}),await(0,Mft.writeFile)(r,t),this.persistedDistinctId=t)}catch{this.persistedDistinctId=t}}return this.persistedDistinctId}};var xZo;async function PKt(){return xZo==null&&(xZo=await Qlh()),xZo}async function Qlh(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";if(e==null||!yin())return new TKt;let t=await Ylt();return t!=null?new OKt({token:t,posthogApiKey:e}):await CM()!=null?new Aon({posthogApiKey:e}):new OKt({token:void 0,posthogApiKey:e})}catch{return new TKt}}On();ct();Dt();C8();var BKt=Ae(require("process"),1);fZe();var Oal=Ae(q3o(),1),Pal=Ae(Tal(),1);function aO(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=yH(e),e.length===0))return 0;e=e.replace((0,Pal.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(Oal.default.eastAsianWidth(i)){case"F":case"W":n+=2;break;case"A":n+=r;break;default:n+=1}}return n}On();function yon(e){let t=0;for(let r of e.split(`
|
|
3469
3469
|
`))t=Math.max(t,aO(r));return t}var Jal=Ae(wZo(),1);var Llh=/[\p{Lu}]/u,_lh=/[\p{Ll}]/u,Dal=/^[\p{Lu}](?![\p{Lu}])/gu,Nal=/([\p{Alpha}\p{N}_]|$)/u,TZo=/[_.\- ]+/,Ulh=new RegExp("^"+TZo.source),kal=new RegExp(TZo.source+Nal.source,"gu"),Fal=new RegExp("\\d+"+Nal.source,"gu"),Vlh=(e,t,r,n)=>{let i=!1,o=!1,s=!1,a=!1;for(let c=0;c<e.length;c++){let u=e[c];a=c>2?e[c-3]==="-":!0,i&&Llh.test(u)?(e=e.slice(0,c)+"-"+e.slice(c),i=!1,s=o,o=!0,c++):o&&s&&_lh.test(u)&&(!a||n)?(e=e.slice(0,c-1)+"-"+e.slice(c-1),s=o,o=!1,i=!0):(i=t(u)===u&&r(u)!==u,s=o,o=r(u)===u&&t(u)!==u)}return e},Glh=(e,t)=>(Dal.lastIndex=0,e.replace(Dal,r=>t(r))),qlh=(e,t)=>(kal.lastIndex=0,Fal.lastIndex=0,e.replace(kal,(r,n)=>t(n)).replace(Fal,r=>t(r)));function OZo(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?TZo.test(e)?"":t.pascalCase?n(e):r(e):(e!==r(e)&&(e=Vlh(e,r,n,t.preserveConsecutiveUppercase)),e=e.replace(Ulh,""),e=t.preserveConsecutiveUppercase?Glh(e,r):r(e),t.pascalCase&&(e=n(e.charAt(0))+e.slice(1)),qlh(e,n))}var DZo=Ae(zal(),1);fZe();var Qal=(e=0)=>t=>`\x1B[${t+e}m`,Mal=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,Lal=(e=0)=>(t,r,n)=>`\x1B[${38+e};2;${t};${r};${n}m`,xE={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]}},YYv=Object.keys(xE.modifier),Jlh=Object.keys(xE.color),Ylh=Object.keys(xE.bgColor),XYv=[...Jlh,...Ylh];function Xlh(){let e=new Map;for(let[t,r]of Object.entries(xE)){for(let[n,i]of Object.entries(r))xE[n]={open:`\x1B[${i[0]}m`,close:`\x1B[${i[1]}m`},r[n]=xE[n],e.set(i[0],i[1]);Object.defineProperty(xE,t,{value:r,enumerable:!1})}return Object.defineProperty(xE,"codes",{value:e,enumerable:!1}),xE.color.close="\x1B[39m",xE.bgColor.close="\x1B[49m",xE.color.ansi=Qal(),xE.color.ansi256=Mal(),xE.color.ansi16m=Lal(),xE.bgColor.ansi=Qal(10),xE.bgColor.ansi256=Mal(10),xE.bgColor.ansi16m=Lal(10),Object.defineProperties(xE,{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=>xE.rgbToAnsi256(...xE.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)=>xE.ansi256ToAnsi(xE.rgbToAnsi256(t,r,n)),enumerable:!1},hexToAnsi:{value:t=>xE.ansi256ToAnsi(xE.hexToAnsi256(t)),enumerable:!1}}),xE}var Zlh=Xlh(),_al=Zlh;var bon=new Set(["\x1B","\x9B"]),$lh=39,BZo="\x07",Gal="[",eph="]",qal="m",RZo=`${eph}8;;`,Ual=e=>`${bon.values().next().value}${Gal}${e}${qal}`,Val=e=>`${bon.values().next().value}${RZo}${e}${BZo}`,tph=e=>e.split(" ").map(t=>aO(t)),PZo=(e,t,r)=>{let n=[...t],i=!1,o=!1,s=aO(yH(e[e.length-1]));for(let[a,c]of n.entries()){let u=aO(c);if(s+u<=r?e[e.length-1]+=c:(e.push(c),s=0),bon.has(c)&&(i=!0,o=n.slice(a+1).join("").startsWith(RZo)),i){o?c===BZo&&(i=!1,o=!1):c===qal&&(i=!1);continue}s+=u,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())},rph=e=>{let t=e.split(" "),r=t.length;for(;r>0&&!(aO(t[r-1])>0);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},nph=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let n="",i,o,s=tph(e),a=[""];for(let[u,l]of e.split(" ").entries()){r.trim!==!1&&(a[a.length-1]=a[a.length-1].trimStart());let p=aO(a[a.length-1]);if(u!==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[u]>t){let d=t-p,f=1+Math.floor((s[u]-d-1)/t);Math.floor((s[u]-1)/t)<f&&a.push(""),PZo(a,l,t);continue}if(p+s[u]>t&&p>0&&s[u]>0){if(r.wordWrap===!1&&p<t){PZo(a,l,t);continue}a.push("")}if(p+s[u]>t&&r.wordWrap===!1){PZo(a,l,t);continue}a[a.length-1]+=l}r.trim!==!1&&(a=a.map(u=>rph(u)));let c=[...a.join(`
|
|
3470
3470
|
`)];for(let[u,l]of c.entries()){if(n+=l,bon.has(l)){let{groups:d}=new RegExp(`(?:\\${Gal}(?<code>\\d+)m|\\${RZo}(?<uri>.*)${BZo})`).exec(c.slice(u).join(""))||{groups:{}};if(d.code!==void 0){let f=Number.parseFloat(d.code);i=f===$lh?void 0:f}else d.uri!==void 0&&(o=d.uri.length===0?void 0:d.uri)}let p=_al.codes.get(Number(i));c[u+1]===`
|
|
3471
3471
|
`?(o&&(n+=Val("")),i&&p&&(n+=Ual(p))):l===`
|
|
@@ -4126,7 +4126,7 @@ ${$e.stack}`),!1}};await D();let O=S.apiWorkspaces.flatMap(Be=>Be.getAbsoluteFil
|
|
|
4126
4126
|
`)},ue=[],Pe,Ie=!1;z.on("all",(Be,_e)=>{n.logger.info(de.dim(`[${Be}] ${_e}`)),!Ie&&(ue.push(Zt.of(_e)),Pe!=null&&clearTimeout(Pe),Pe=setTimeout(()=>{(async()=>{Ie=!0;try{let $e=R.getFilesToReload(ue);await D($e)&&await ce()}finally{ue.length=0,Ie=!1}})()},t8g))}),n.logger.info(`Docs preview server (Astro) ready on http://localhost:${i}${g}`),await me}async function s8g({bundlePath:e,forceDownload:t,cacheDir:r,context:n}){if(e!=null)return n.logger.info(`Using Astro bundle from path: ${e}`),await iIp(Zt.of(e));if(t){let a=i2e({astro:!0,cacheDir:r});await Ut(a)&&(n.logger.info("Force download requested. Deleting cached Astro bundle..."),await(0,jSi.rm)(a,{recursive:!0}))}let i="https://prod-local-preview-astro-bundle.s3.amazonaws.com/";if(i==null)throw new T({message:"Failed to connect to the docs preview server. Please contact support@buildwithfern.com",code:T.Code.InternalError});let o=$Ge({astro:!0,cacheDir:r});if((await Z$t({bucketUrl:i,logger:n.logger,preferCached:!0,astro:!0,tryTar:!0,cacheDir:r})).type==="failure")if(await Ut(o))n.logger.warn("Falling back to cached Astro bundle...");else throw new T({message:"Failed to download the Astro docs preview bundle. Please reach out to support@buildwithfern.com.",code:T.Code.NetworkError});return await iIp(o)}async function iIp(e){let t=ke(e,ye.of(n8g)),r=i8g;if(await Ut(t)){let i=JSON.parse(await(0,jSi.readFile)(t,"utf-8"));typeof i.entry=="string"&&(r=i.entry)}let n=ke(e,ye.of(r));if(!await Ut(n))throw new T({message:`${e} does not contain the Astro preview server (missing ${r}).`,code:T.Code.UserError});return{root:e,entry:n}}var a8g="_fern-files";function c8g({rendererPort:e,rendererHost:t,mirrorPort:r,basepath:n,reloadClients:i}){let o=`${n}/${a8g}/`;return hNs.default.createServer((s,a)=>{if(s.url===sIp){a.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-store",connection:"keep-alive"}),a.write(`: connected
|
|
4127
4127
|
|
|
4128
4128
|
`),i.add(a),s.on("close",()=>i.delete(a));return}let c=s.url!=null&&s.url.startsWith(o),u=hNs.default.request(c?{host:"127.0.0.1",port:r,method:s.method,path:`/files/${s.url?.slice(o.length)??""}`,headers:s.headers}:{host:"127.0.0.1",port:e,method:s.method,path:s.url,headers:{...s.headers,[oIp]:t}},l=>{let p={...l.headers};if(!((p["content-type"]??"").includes("text/html")&&p["content-encoding"]==null)){a.writeHead(l.statusCode??502,p),l.pipe(a);return}let f=[];l.on("data",m=>f.push(m)),l.on("end",()=>{let m=Buffer.concat(f).toString("utf-8"),g=m.lastIndexOf("</body>"),A=g>=0?`${m.slice(0,g)}${nIp}${m.slice(g)}`:`${m}${nIp}`,y=Buffer.from(A,"utf-8");delete p["transfer-encoding"],p["content-length"]=y.byteLength.toString(),a.writeHead(l.statusCode??502,p),a.end(y)}),l.on("error",()=>a.destroy())});u.on("error",l=>{a.headersSent||a.writeHead(502,{"content-type":"text/plain"}),a.end(`Astro preview server unavailable: ${l.message}
|
|
4129
|
-
`)}),s.pipe(u)})}function u8g(){return new Promise((e,t)=>{let r=gNs.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 l8g(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=gNs.default.connect(e,"127.0.0.1");c.once("connect",()=>{c.destroy(),i()}),c.once("error",()=>{c.destroy(),setTimeout(a,200)})};a()})}ct();Dt();var uIp=/^[a-z0-9-]+-preview-[a-z0-9-]+\.docs\.buildwithfern\.com$/i,aIp="docs.buildwithfern.com",cIp=62;function vWe(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)),uIp.test(t)}function bir({orgId:e,previewId:t}){let r=JZ(t),n=`${e}-preview-${r}.${aIp}`;if(n.length<=cIp)return n;let i=`${e}-preview-`,o=cIp-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}.${aIp}`}ct();VI();bh();tr();g0();Dt();On();var qNs=require("child_process"),vvp=Ae(pIp(),1),WNs=Ae(FSi(),1),HNs=Ae(require("fs"),1),JNs=require("fs/promises"),Cvp=Ae(require("http"),1),xvp=Ae(require("os"),1),ZSi=Ae(require("path"),1);LNs();VI();tr();var _Ns=require("fs/promises");async function UNs(e,t){let r=new Map,{docsDefinition:n,translationPages:i,translationNavigationOverlays:o,translatedApiDefinitions:s,collectedFileIds:a,docsWorkspacePath:c,markdownFilesToPathName:u}=e,l=i!=null&&Object.keys(i).length>0,p=s!=null&&Object.keys(s).length>0;if(!l&&!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 pe=>{let oe=Co(c,pe),me=Xn(c,ye.of(`translations/${m}/${oe}`));return await Ut(me)?me:pe},y=async pe=>{let oe=await A(pe),me=await(0,_Ns.readFile)(oe,"utf-8"),Se=me.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/);return Se!=null?me.slice(Se[0].length):me},I=async pe=>{let oe=await A(pe);return(0,_Ns.readFile)(oe,"utf-8")},x={};for(let[pe,oe]of Object.entries(n.pages))oe!=null&&(x[pe]=oe);for(let[pe,oe]of Object.entries(g))try{let me=x[pe],Se=Xn(c,ye.of(pe)),{markdown:Re}=await wF({markdown:oe,absolutePathToFernFolder:c,absolutePathToMarkdownFile:Se,context:t,markdownLoader:y}),ce=await l_({markdown:Re,absolutePathToFernFolder:c,absolutePathToMarkdownFile:Se,context:t,fileLoader:I}),ue=p_({markdown:ce,absolutePathToFernFolder:c,absolutePathToMarkdownFile:Se,context:t}),Pe=ZO(ue);Pe=o_(Pe,a,u,{absolutePathToMarkdownFile:Se,absolutePathToFernFolder:c},t),x[pe]={markdown:Pe,rawMarkdown:Pe,editThisPageUrl:me?.editThisPageUrl,editThisPageLaunch:me?.editThisPageLaunch}}catch(me){t.logger.warn(`Failed to process translated page "${pe}" for locale "${m}": ${String(me)}. Falling back to base page.`)}let v=dGe(n.config.root,g,t),S=o?.[m],B=n.config.announcement,R=n.config.navbarLinks;S!=null&&(v=hGe(v,S),B=gGe(S)??B,S.navbarLinks!=null&&(R=S.navbarLinks));let D=n.apis,O=s?.[m],z=O,Y;if(O!=null&&v!=null){let pe=pGe(v,D,O);pe.size>0&&(t.logger.warn(`Translated API definition(s) [${Array.from(pe).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.`),z=Object.fromEntries(Object.entries(O).filter(([oe])=>!pe.has(oe)))),Y=new Set(Object.keys(O).filter(oe=>!pe.has(oe)))}let ee=z!=null&&Object.keys(z).length>0?{...n.apis,...z}:n.apis;O!=null&&Object.keys(O).length>0&&v!=null&&(v=fGe(v,D,O,{rewritableApiIds:Y}));let ae={...n,apis:ee,pages:x,config:{...n.config,root:v,announcement:B,navbarLinks:R}};r.set(m,ae),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 e7=require("fs/promises"),gvp=require("os"),GNs=Ae(require("path"),1),zGg=".fern",QGg="logs",VNs=100*1024*1024;function MGg(){return"cli@5.172.
|
|
4129
|
+
`)}),s.pipe(u)})}function u8g(){return new Promise((e,t)=>{let r=gNs.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 l8g(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=gNs.default.connect(e,"127.0.0.1");c.once("connect",()=>{c.destroy(),i()}),c.once("error",()=>{c.destroy(),setTimeout(a,200)})};a()})}ct();Dt();var uIp=/^[a-z0-9-]+-preview-[a-z0-9-]+\.docs\.buildwithfern\.com$/i,aIp="docs.buildwithfern.com",cIp=62;function vWe(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)),uIp.test(t)}function bir({orgId:e,previewId:t}){let r=JZ(t),n=`${e}-preview-${r}.${aIp}`;if(n.length<=cIp)return n;let i=`${e}-preview-`,o=cIp-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}.${aIp}`}ct();VI();bh();tr();g0();Dt();On();var qNs=require("child_process"),vvp=Ae(pIp(),1),WNs=Ae(FSi(),1),HNs=Ae(require("fs"),1),JNs=require("fs/promises"),Cvp=Ae(require("http"),1),xvp=Ae(require("os"),1),ZSi=Ae(require("path"),1);LNs();VI();tr();var _Ns=require("fs/promises");async function UNs(e,t){let r=new Map,{docsDefinition:n,translationPages:i,translationNavigationOverlays:o,translatedApiDefinitions:s,collectedFileIds:a,docsWorkspacePath:c,markdownFilesToPathName:u}=e,l=i!=null&&Object.keys(i).length>0,p=s!=null&&Object.keys(s).length>0;if(!l&&!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 pe=>{let oe=Co(c,pe),me=Xn(c,ye.of(`translations/${m}/${oe}`));return await Ut(me)?me:pe},y=async pe=>{let oe=await A(pe),me=await(0,_Ns.readFile)(oe,"utf-8"),Se=me.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/);return Se!=null?me.slice(Se[0].length):me},I=async pe=>{let oe=await A(pe);return(0,_Ns.readFile)(oe,"utf-8")},x={};for(let[pe,oe]of Object.entries(n.pages))oe!=null&&(x[pe]=oe);for(let[pe,oe]of Object.entries(g))try{let me=x[pe],Se=Xn(c,ye.of(pe)),{markdown:Re}=await wF({markdown:oe,absolutePathToFernFolder:c,absolutePathToMarkdownFile:Se,context:t,markdownLoader:y}),ce=await l_({markdown:Re,absolutePathToFernFolder:c,absolutePathToMarkdownFile:Se,context:t,fileLoader:I}),ue=p_({markdown:ce,absolutePathToFernFolder:c,absolutePathToMarkdownFile:Se,context:t}),Pe=ZO(ue);Pe=o_(Pe,a,u,{absolutePathToMarkdownFile:Se,absolutePathToFernFolder:c},t),x[pe]={markdown:Pe,rawMarkdown:Pe,editThisPageUrl:me?.editThisPageUrl,editThisPageLaunch:me?.editThisPageLaunch}}catch(me){t.logger.warn(`Failed to process translated page "${pe}" for locale "${m}": ${String(me)}. Falling back to base page.`)}let v=dGe(n.config.root,g,t),S=o?.[m],B=n.config.announcement,R=n.config.navbarLinks;S!=null&&(v=hGe(v,S),B=gGe(S)??B,S.navbarLinks!=null&&(R=S.navbarLinks));let D=n.apis,O=s?.[m],z=O,Y;if(O!=null&&v!=null){let pe=pGe(v,D,O);pe.size>0&&(t.logger.warn(`Translated API definition(s) [${Array.from(pe).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.`),z=Object.fromEntries(Object.entries(O).filter(([oe])=>!pe.has(oe)))),Y=new Set(Object.keys(O).filter(oe=>!pe.has(oe)))}let ee=z!=null&&Object.keys(z).length>0?{...n.apis,...z}:n.apis;O!=null&&Object.keys(O).length>0&&v!=null&&(v=fGe(v,D,O,{rewritableApiIds:Y}));let ae={...n,apis:ee,pages:x,config:{...n.config,root:v,announcement:B,navbarLinks:R}};r.set(m,ae),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 e7=require("fs/promises"),gvp=require("os"),GNs=Ae(require("path"),1),zGg=".fern",QGg="logs",VNs=100*1024*1024;function MGg(){return"cli@5.172.1"}var OWe=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??ke(ke(Zt.of((0,gvp.homedir)()),ye.of(zGg)),ye.of(QGg));await Ut(n)||await(0,e7.mkdir)(n,{recursive:!0});let o=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=ke(n,ye.of(o));let s=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${GNs.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
|
|
4130
4130
|
`);await(0,e7.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)+`
|
|
4131
4131
|
`;try{await(0,e7.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:MGg(),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,e7.readdir)(t)).filter(c=>c.endsWith(".log")),i=[];for(let c of n){let u=GNs.default.join(t,c);try{let l=await(0,e7.stat)(u);i.push({name:c,fullPath:u,size:l.size,mtimeMs:l.mtimeMs})}catch{}}let o=i.reduce((c,u)=>c+u.size,0),s=Math.round(o/1024/1024*100)/100,a=VNs/1024/1024;if(o<=VNs){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,u)=>c.mtimeMs-u.mtimeMs);for(let c of i){if(o<=VNs)break;if(!(this.logFilePath!=null&&c.fullPath===this.logFilePath))try{await(0,e7.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 XSi={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type"};function Avp(e){let t=LGg();if(t==null)return;let{port:r,debugLogger:n,getDocsLoadResponse:i,extractLocaleFromPath:o}=e,s=new Map;function a(u){let l=JSON.stringify(u),p=[];for(let[d]of s)try{d.send(l)}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(u,l){if(u.method==="OPTIONS")return new Response(null,{status:204,headers:XSi});let p=new URL(u.url);if(u.headers.get("upgrade")?.toLowerCase()==="websocket"){l.upgrade(u,{data:{connectionId:`${Date.now()}`}});return}if(u.method==="POST"&&p.pathname==="/v2/registry/docs/load-with-url")try{let f=await u.json(),m=o?.(f?.url);return new Response(JSON.stringify(i(m)),{headers:{"Content-Type":"application/json",...XSi}})}catch{return new Response(JSON.stringify(i()),{headers:{"Content-Type":"application/json",...XSi}})}let d=/^\/_local\/(.*)/.exec(p.pathname);return u.method==="GET"&&d!=null?new Response(t.file(`/${d[1]}`),{headers:XSi}):new Response("Not Found",{status:404})},websocket:{open(u){let{connectionId:l}=u.data,p=setInterval(()=>{let d=s.get(u);if(!d)return;let f=Date.now();if(f-d.lastPong>9e4){u.close();return}try{u.send(JSON.stringify({type:"ping",timestamp:f}))}catch{u.close()}},3e4);s.set(u,{pingInterval:p,lastPong:Date.now()});try{u.send(JSON.stringify({type:"connected",connectionId:l}))}catch{}},message(u,l){try{let p=JSON.parse(l.toString());if(p.type==="pong"){let d=s.get(u);d&&(d.lastPong=Date.now())}else OWe.isMetricsMessage(p)&&n.logFrontendMetrics(p)}catch{}},close(u){let l=s.get(u);l&&(clearInterval(l.pingInterval),s.delete(u))}}});return{sendData:a,stop:u=>c.stop(u)}}function LGg(){return globalThis.Bun}var yvp=require("fs"),bvp=Ae(require("path"),1),_Gg=`"use strict";
|
|
4132
4132
|
|
|
@@ -4447,7 +4447,7 @@ ${n}
|
|
|
4447
4447
|
|
|
4448
4448
|
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.
|
|
4449
4449
|
|
|
4450
|
-
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(ln(s)),c=new Ld({context:t,logLevel:Zn.Info});await Fsr({libraries:i,library:r.library,docsDirectoryPath:a,orgId:n.org,tokenValue:o.value,context:c,wrapStep:CP,docsConfig:n.docs.raw})}};function Y_s(e){let t=new J_s;fi(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 X_s(e){NA({cli:e,name:"md",subcommands:[Y_s,E_s]})}Dt();function ARi(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},qsn(n)),s.version(!1).usage(r)})}ct();VI();Dt();On();ct();Dt();var yRi=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 Ld({context:this.context,task:this.task});try{let s=await Knr({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.172.
|
|
4450
|
+
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(ln(s)),c=new Ld({context:t,logLevel:Zn.Info});await Fsr({libraries:i,library:r.library,docsDirectoryPath:a,orgId:n.org,tokenValue:o.value,context:c,wrapStep:CP,docsConfig:n.docs.raw})}};function Y_s(e){let t=new J_s;fi(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 X_s(e){NA({cli:e,name:"md",subcommands:[Y_s,E_s]})}Dt();function ARi(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},qsn(n)),s.version(!1).usage(r)})}ct();VI();Dt();On();ct();Dt();var yRi=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 Ld({context:this.context,task:this.task});try{let s=await Knr({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.172.1",loginCommand:"fern auth login"});return o.getResult()===Pf.Failure?{success:!1}:{success:!0,url:s}}catch(s){return{success:!1,error:Sn(s)}}}};ct();On();var URt=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(`
|
|
4451
4451
|
`),this.stream.write(`${de.cyan("\u25C6")} ${de.bold(t.title)}
|
|
4452
4452
|
`),t.subtitle!=null&&this.stream.write(` ${de.dim(t.subtitle)}
|
|
4453
4453
|
`),this.stream.write(`
|
|
@@ -4769,7 +4769,7 @@ ${t}`)}return t}getContent(){let t=`package ${this.packageName};
|
|
|
4769
4769
|
`,r=this.stringifyImports();return r.length>0?`${t}${r}
|
|
4770
4770
|
|
|
4771
4771
|
${this.buffer}`:t+this.buffer}stringifyImports(){return Array.from(this.imports).filter(t=>t!==this.packageName).map(t=>`import ${t};`).sort().join(`
|
|
4772
|
-
`)}};an();an();var X3p=Fe.strictObject({title:Fe.string(),content:Fe.string()});var yZs=Fe.object({"base-api-exception-class-name":Fe.string().optional(),"base-exception-class-name":Fe.string().optional(),"client-class-name":Fe.string().optional(),"exported-client-class-name":Fe.string().optional(),"inline-file-properties":Fe.boolean().optional(),"inline-path-parameters":Fe.boolean().optional(),"package-layout":Fe.enum(["flat","nested"]).optional(),"package-prefix":Fe.string().optional(),"respect-optional-request-body":Fe.boolean().optional(),"use-local-date-for-dates":Fe.boolean().optional(),"custom-dependencies":Fe.array(Fe.string()).optional(),"custom-plugins":Fe.array(Fe.string()).optional(),"disable-required-property-builder-checks":Fe.boolean().optional(),"enable-forward-compatible-enums":Fe.boolean().optional(),"enable-inline-types":Fe.boolean().optional(),"enable-public-constructors":Fe.boolean().optional(),"generate-unknown-as-json-node":Fe.boolean().optional(),"json-include":Fe.enum(["non-absent","non-empty"]).optional(),"enable-extensible-builders":Fe.boolean().optional(),"use-default-request-parameter-values":Fe.boolean().optional(),"enable-wire-tests":Fe.boolean().default(!1),"wire-tests-fallback-to-autogenerated-error-examples":Fe.boolean().optional(),"collapse-optional-nullable":Fe.boolean().optional(),"use-nullable-annotation":Fe.boolean().optional(),"custom-readme-sections":Fe.array(X3p).optional(),"custom-pager-name":Fe.string().optional(),"offset-semantics":Fe.enum(["item-index","page-index"]).optional(),"default-timeout-in-seconds":Fe.number().optional(),"gradle-distribution-url":Fe.string().optional(),"gradle-plugin-management":Fe.string().optional(),"gradle-central-dependency-management":Fe.boolean().optional(),"output-directory":Fe.enum(["source-root","project-root"]).optional(),"custom-interceptors":Fe.boolean().optional(),"omit-fern-headers":Fe.boolean().optional(),includePlatformHeaders:Fe.boolean().optional(),userAgentOnly:Fe.boolean().optional(),"retry-status-codes":Fe.optional(Fe.enum(["legacy","recommended"])),"enable-gradle-profiling":Fe.boolean().optional(),"wrapped-aliases":Fe.boolean().optional(),maxRetries:Fe.number().int().min(0).optional()});var pr={};te(pr,{Access:()=>bZs,AstNode:()=>av,Class:()=>kHe,ClassInstantiation:()=>FHe,ClassReference:()=>fg,CodeBlock:()=>NHe,Method:()=>jHe,MethodInvocation:()=>zHe,Parameter:()=>QHe,Type:()=>Scr,TypeLiteral:()=>G6,Writer:()=>DHe,classReference:()=>f5A,class_:()=>p5A,codeblock:()=>l5A,instantiateClass:()=>d5A,invokeMethod:()=>m5A,method:()=>h5A,parameter:()=>g5A});var av=class extends ov{async toStringAsync({packageName:t,customConfig:r,formatter:n}){let i=new xcr({packageName:t,customConfig:r,formatter:n});return this.write(i),i.toStringAsync()}toString({packageName:t,customConfig:r,formatter:n}){let i=new xcr({packageName:t,customConfig:r,formatter:n});return this.write(i),i.toString()}};var kHe=class extends av{name;access;methods=[];constructor({name:t,access:r}){super(),this.name=t,this.access=r}write(t){if(t.write(`${this.access} class ${this.name}`),this.isEmpty()){t.writeLine(" {}");return}t.writeLine(" {"),t.indent();for(let r of this.methods)t.writeNode(r),t.newLine();t.dedent(),t.write("}")}addMethod(t){this.methods.push(t)}isEmpty(){return this.methods.length===0}};var bZs={Public:"public",Protected:"protected",Private:"private"};ct();var fg=class extends av{name;packageName;fullyQualified;enclosingClasses;constructor({name:t,packageName:r,fullyQualified:n,enclosingClasses:i}){super(),this.name=t,this.packageName=r,this.fullyQualified=n??!1,this.enclosingClasses=i??[]}write(t){let r=this.enclosingClasses[0]??this.name,n=[...this.enclosingClasses,this.name].join(".");if(this.fullyQualified){t.write(`${this.packageName}.${n}`);return}let{shouldFullyQualify:i}=t.addReference({name:r,packageName:this.packageName});if(i){t.write(`${this.packageName}.${n}`);return}t.write(n)}};ct();var Scr=class extends av{internalType;constructor(t){super(),this.internalType=t}write(t){switch(this.internalType.type){case"array":t.writeNode(this.internalType.value),t.write("[]");break;case"bigInteger":t.writeNode(GVA);break;case"boolean":t.write("Boolean");break;case"bytes":t.write("byte[]");break;case"date":t.customConfig?.["use-local-date-for-dates"]===!0?t.writeNode(HVA):t.write("String");break;case"dateTime":t.writeNode(KVA);break;case"double":t.write("Double");break;case"float":t.write("Float");break;case"generic":t.writeNode(this.internalType.value),t.write("<");for(let[r,n]of this.internalType.parameters.entries())t.writeNode(n),r<this.internalType.parameters.length-1&&t.write(", ");t.write(">");break;case"inputStream":t.writeNode(XVA);break;case"integer":t.write("Integer");break;case"iterable":this.writeIterable({writer:t,iterable:this.internalType});break;case"list":{this.writeList({writer:t,list:this.internalType});break}case"long":{t.write("Long");break}case"map":{this.writeMap({writer:t,map:this.internalType});break}case"object":{t.write("Object");break}case"optional":{this.writeOptional({writer:t,optional:this.internalType});break}case"reference":t.writeNode(this.internalType.value);break;case"set":{this.writeSet({writer:t,set:this.internalType});break}case"string":t.write("String");break;case"uuid":t.writeNode(YVA);break;case"void":t.write("Void");break;default:Ee(this.internalType)}}isOptional(){return this.internalType.type==="optional"}static array(t){return new this({type:"array",value:t})}static bigInteger(){return new this({type:"bigInteger"})}static boolean(){return new this({type:"boolean"})}static bytes(){return new this({type:"bytes"})}static date(){return new this({type:"date"})}static dateTime(){return new this({type:"dateTime"})}static double(){return new this({type:"double"})}static float(){return new this({type:"float"})}static integer(){return new this({type:"integer"})}static list(t){return new this({type:"list",value:t})}static long(){return new this({type:"long"})}static map(t,r){return new this({type:"map",keyType:t,valueType:r})}static object(){return new this({type:"object"})}static optional(t){return this.isAlreadyOptional(t)?t:new this({type:"optional",value:t})}static reference(t){return new this({type:"reference",value:t})}static generic(t,r){return new this({type:"generic",value:t,parameters:r})}static set(t){return new this({type:"set",value:t})}static string(){return new this({type:"string"})}static uuid(){return new this({type:"uuid"})}static void(){return new this({type:"void"})}static iterable(t){return new this({type:"iterable",value:t})}static inputStream(){return new this({type:"inputStream"})}writeList({writer:t,list:r}){t.writeNode(qVA),t.write("<"),r.value.write(t),t.write(">")}writeMap({writer:t,map:r}){t.writeNode(WVA),t.write("<"),r.keyType.write(t),t.write(", "),r.valueType.write(t),t.write(">")}writeOptional({writer:t,optional:r}){t.writeNode(EZs),t.write("<"),r.value.write(t),t.write(">")}writeIterable({writer:t,iterable:r}){t.writeNode(ZVA),t.write("<"),r.value.write(t),t.write(">")}writeSet({writer:t,set:r}){t.writeNode(JVA),t.write("<"),r.value.write(t),t.write(">")}static isAlreadyOptional(t){return t.internalType.type==="optional"}},wFi=new fg({name:"Arrays",packageName:"java.util"}),GVA=new fg({name:"BigInteger",packageName:"java.math"}),isP=new fg({name:"HashMap",packageName:"java.util"}),qVA=new fg({name:"List",packageName:"java.util"}),WVA=new fg({name:"Map",packageName:"java.util"}),HVA=new fg({name:"LocalDate",packageName:"java.time"}),KVA=new fg({name:"OffsetDateTime",packageName:"java.time"}),EZs=new fg({name:"Optional",packageName:"java.util"}),JVA=new fg({name:"Set",packageName:"java.util"}),YVA=new fg({name:"UUID",packageName:"java.util"}),XVA=new fg({name:"InputStream",packageName:"java.io"}),ZVA=new fg({name:"Iterable",packageName:"java.lang"});var G6=class e extends av{internalType;constructor(t){super(),this.internalType=t}write(t){switch(this.internalType.type){case"bigInteger":this.writeBigInteger({writer:t,bigInteger:this.internalType});break;case"boolean":t.write(this.internalType.value.toString());break;case"builder":this.writeBuilder({writer:t,builder:this.internalType});break;case"bytes":t.write(`"${this.internalType.value}".getBytes()`);break;case"class":{this.writeClass({writer:t,class_:this.internalType});break}case"date":this.writeDate({writer:t,date:this.internalType});break;case"dateTime":this.writeDateTime({writer:t,dateTime:this.internalType});break;case"double":{let r=this.internalType.value.toString();!r.includes(".")&&!r.includes("e")&&!r.includes("E")?t.write(`${r}.0`):t.write(r);break}case"enum":this.writeEnum({writer:t,enum_:this.internalType});break;case"float":t.write(`${this.internalType.value}f`);break;case"integer":t.write(Math.floor(this.internalType.value).toString());break;case"list":{this.writeList({writer:t,list:this.internalType});break}case"long":{t.write(`${Math.floor(this.internalType.value)}L`);break}case"map":{this.writeMap({writer:t,map:this.internalType});break}case"optional":{this.writeOptional({writer:t,optional:this.internalType});break}case"raw":{this.internalType.value instanceof av?t.writeNode(this.internalType.value):t.write(this.internalType.value);break}case"reference":t.writeNode(this.internalType.value);break;case"set":{this.writeSet({writer:t,set:this.internalType});break}case"string":t.write(`"${this.escapeString(this.internalType.value)}"`);break;case"unknown":this.writeUnknown({writer:t,value:this.internalType.value});break;case"uuid":this.writeUUID({writer:t,uuid:this.internalType});break;case"nop":break;default:Ee(this.internalType)}}isOptional(){return this.internalType.type==="optional"}static bigInteger(t){return new this({type:"bigInteger",value:t})}static boolean(t){return new this({type:"boolean",value:t})}static builder({classReference:t,parameters:r}){return new this({type:"builder",classReference:t,parameters:r})}static bytes(t){return new this({type:"bytes",value:t})}static class_({reference:t,parameters:r}){return new this({type:"class",reference:t,parameters:r})}static date(t){return new this({type:"date",value:t})}static dateTime(t){return new this({type:"dateTime",value:t})}static double(t){return new this({type:"double",value:t})}static enum_({classReference:t,value:r}){return new this({type:"enum",classReference:t,value:r})}static float(t){return new this({type:"float",value:t})}static integer(t){return new this({type:"integer",value:t})}static list({valueType:t,values:r,isParameter:n}){return new this({type:"list",valueType:t,values:r,isParameter:n})}static long(t){return new this({type:"long",value:t})}static map({keyType:t,valueType:r,entries:n}){return new this({type:"map",keyType:t,valueType:r,entries:n})}static optional({value:t,useOf:r}){return this.isAlreadyOptional(t)?t:new this({type:"optional",value:t,useOf:r})}static raw(t){return new this({type:"raw",value:t})}static reference(t){return new this({type:"reference",value:t})}static set({valueType:t,values:r}){return new this({type:"set",valueType:t,values:r})}static string(t){return new this({type:"string",value:t})}static unknown(t){return new this({type:"unknown",value:t})}static uuid(t){return new this({type:"uuid",value:t})}static nop(){return new this({type:"nop"})}static isNop(t){return t.internalType.type==="nop"}shouldWriteInLine(){switch(this.internalType.type){case"bigInteger":case"boolean":case"bytes":case"date":case"dateTime":case"double":case"enum":case"float":case"integer":case"long":case"nop":case"raw":case"string":case"unknown":case"uuid":return!0;case"optional":return this.internalType.value.shouldWriteInLine();case"builder":case"class":case"list":case"map":case"reference":case"set":return!1;default:Ee(this.internalType)}}writeBigInteger({writer:t,bigInteger:r}){t.write("new "),t.writeNode(pr.instantiateClass({classReference:$VA,arguments_:[e.string(r.value)]}))}writeBuilder({writer:t,builder:r}){t.writeNode(r.classReference),t.writeNewLineIfLastLineNot(),t.indent(),this.writeBuilderParameters({writer:t,parameters:this.orderBuilderParameters(o5A({parameters:r.parameters}))}),t.dedent()}writeBuilderParameters({writer:t,parameters:r}){t.writeLine(".builder()");for(let n of r)t.write(`.${n.name}(`),n.value.shouldWriteInLine()||t.newLine(),t.indent(),t.writeNode(n.value),t.dedent(),n.value.shouldWriteInLine()||t.newLine(),t.writeLine(")");t.writeNewLineIfLastLineNot(),t.write(".build()")}orderBuilderParameters(t){return t.some(n=>this.isRequiredBuilderParameter(n))?t.sort((n,i)=>{let o=!this.isRequiredBuilderParameter(n),s=!this.isRequiredBuilderParameter(i);return o&&!s?1:!o&&s?-1:0}):t.sort((n,i)=>{let o=n.value.isOptional(),s=i.value.isOptional();return o&&!s?1:!o&&s?-1:0})}isCollection(t){let r=t.internalType.type;return r==="list"||r==="set"||r==="map"}isRequiredBuilderParameter(t){return t.isRequired!=null?t.isRequired:!this.isNonRequired(t.value)}isNonRequired(t){return t.isOptional()||this.isCollection(t)}writeClass({writer:t,class_:r}){let n=i5A({parameters:r.parameters});t.writeNode(pr.instantiateClass({classReference:r.reference,arguments_:n.map(i=>i.value)}))}writeDate({writer:t,date:r}){t.writeNode(pr.invokeMethod({on:t5A,method:"parse",arguments_:[e.string(r.value)]}))}writeDateTime({writer:t,dateTime:r}){t.writeNode(pr.invokeMethod({on:r5A,method:"parse",arguments_:[e.string(r.value)]}))}writeEnum({writer:t,enum_:r}){t.writeNode(r.classReference),t.write("."+r.value)}writeList({writer:t,list:r}){this.writeIterable({writer:t,iterable:r})}writeMap({writer:t,map:r}){let n=s5A({entries:r.entries});if(n.length===0){t.write("new "),t.writeNode(TFi),t.write("<"),t.writeNode(r.keyType),t.write(", "),t.writeNode(r.valueType),t.write(">()");return}t.write("new "),t.writeNode(TFi),t.write("<"),t.writeNode(r.keyType),t.write(", "),t.writeNode(r.valueType),t.writeLine(">() {{"),t.indent();for(let i of n)t.write("put("),t.writeNode(i.key),t.write(", "),t.writeNode(i.value),t.writeLine(");");t.dedent(),t.write("}}")}writeOptional({writer:t,optional:r}){if(!r.useOf){t.writeNode(r.value);return}t.writeNode(pr.invokeMethod({on:EZs,method:"of",arguments_:[r.value]}))}writeSet({writer:t,set:r}){this.writeIterable({writer:t,iterable:r})}writeIterable({writer:t,iterable:r}){let n=r.type==="list"?IZs:e5A,i=a5A({values:r.values});if(r.type==="list"&&r.isParameter&&i.length>0){t.writeNode(pr.invokeMethod({on:wFi,method:"asList",arguments_:i}));return}if(i.length===0){t.write("new "),t.writeNode(n),t.write("<"),t.writeNode(r.valueType),t.write(">()");return}t.write("new "),t.writeNode(n),t.write("<"),t.writeNode(r.valueType),t.writeLine(">("),t.indent(),t.writeNode(pr.invokeMethod({on:wFi,method:"asList",arguments_:i})),t.writeNewLineIfLastLineNot(),t.dedent(),t.write(")")}writeUnknown({writer:t,value:r}){switch(typeof r){case"boolean":t.write(r.toString());return;case"string":t.write(`"${this.escapeString(r)}"`);return;case"number":t.write(r.toString());return;case"object":if(r==null){t.write("null");return}if(Array.isArray(r)){this.writeUnknownArray({writer:t,value:r});return}this.writeUnknownMap({writer:t,value:r});return;default:throw new Error(`Internal error; unsupported unknown type: ${typeof r}`)}}writeUnknownArray({writer:t,value:r}){if(r.length===0){t.write("new "),t.writeNode(IZs),t.write("<Object>()");return}t.write("new "),t.writeNode(IZs),t.write("<Object>("),t.writeNode(pr.invokeMethod({on:wFi,method:"asList",arguments_:r.map(n=>e.unknown(n))})),t.write(")")}writeUnknownMap({writer:t,value:r}){let n=Object.entries(r);if(n.length===0){t.write("new "),t.writeNode(TFi),t.write("<String, Object>()");return}t.writeLine("new "),t.writeNode(TFi),t.write("<String, Object>() {{"),t.indent();for(let[i,o]of n)t.write(`put("${i}", `),t.writeNode(e.unknown(o)),t.writeLine(");");t.dedent(),t.write("}}")}writeUUID({writer:t,uuid:r}){t.writeNode(pr.invokeMethod({on:n5A,method:"fromString",arguments_:[e.string(r.value)]}))}escapeString(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}static isAlreadyOptional(t){return t.internalType.type==="optional"}},IZs=new fg({name:"ArrayList",packageName:"java.util"}),$VA=new fg({name:"BigInteger",packageName:"java.math"}),TFi=new fg({name:"HashMap",packageName:"java.util"}),e5A=new fg({name:"HashSet",packageName:"java.util"}),psP=new fg({name:"List",packageName:"java.util"}),t5A=new fg({name:"LocalDate",packageName:"java.time"}),fsP=new fg({name:"Map",packageName:"java.util"}),r5A=new fg({name:"OffsetDateTime",packageName:"java.time"}),dsP=new fg({name:"Set",packageName:"java.util"}),n5A=new fg({name:"UUID",packageName:"java.util"});function i5A({parameters:e}){return e.filter(t=>!G6.isNop(t.value))}function o5A({parameters:e}){return e.filter(t=>!G6.isNop(t.value))}function s5A({entries:e}){return e.filter(t=>!G6.isNop(t.key)&&!G6.isNop(t.value))}function a5A({values:e}){return e.filter(t=>!G6.isNop(t))}function OFi({writer:e,arguments_:t}){let r=u5A(t);if(r.length===0){e.write("()");return}if(r.some(i=>i instanceof G6&&!i.shouldWriteInLine())){c5A({writer:e,arguments_:r});return}e.write("("),r.forEach((i,o)=>{o>0&&e.write(", "),Z3p({writer:e,argument:i})}),e.write(")")}function c5A({writer:e,arguments_:t}){e.writeLine("("),e.indent(),t.forEach((r,n)=>{n>0&&e.writeLine(","),Z3p({writer:e,argument:r})}),e.dedent(),t.length>0&&e.newLine(),e.write(")")}function Z3p({writer:e,argument:t}){Xje(t)?e.writeNodeOrString(t.assignment):t.write(e)}function u5A(e){return e.filter(t=>!(t instanceof G6&&G6.isNop(t)))}var FHe=class extends av{classReference;arguments_;constructor({classReference:t,arguments_:r}){super(),this.classReference=t,this.arguments_=r}write(t){t.writeNode(this.classReference),OFi({writer:t,arguments_:this.arguments_})}};var NHe=class extends av{arg;constructor(t){super(),this.arg=t}write(t){return new U0(this.arg).write(t)}};var jHe=class extends av{name;access;parameters;body;return_;static_;constructor({name:t,access:r,parameters:n,body:i,static_:o,return_:s}){super(),this.name=t,this.access=r,this.parameters=n,this.body=i,this.return_=s,this.static_=o??!1}write(t){if(t.write(`${this.access} `),this.static_&&t.write("static "),this.return_!=null?t.writeNode(this.return_):t.write("void"),t.write(` ${this.name}`),this.parameters.length===0)t.write("()");else if(this.parameters.length===1){if(t.write("("),this.parameters[0]==null)throw new Error("Cannot render parameter "+this.parameters[0]);t.writeNode(this.parameters[0]),t.write(")")}else t.writeLine("("),t.indent(),this.parameters.forEach((r,n)=>{n>0&&t.writeLine(", "),t.writeNode(r)}),t.dedent(),t.write(")");if(this.body==null){t.write(";");return}t.writeLine(" {"),t.indent(),t.writeNode(this.body),t.writeNewLineIfLastLineNot(),t.dedent(),t.write("}")}};var zHe=class extends av{on;method;arguments_;constructor({method:t,arguments_:r,on:n}){super(),this.on=n,this.method=t,this.arguments_=r}write(t){this.on.write(t),t.write("."),t.write(this.method),OFi({writer:t,arguments_:this.arguments_})}};var QHe=class extends av{name;type;constructor({name:t,type:r}){super(),this.name=t,this.type=r}write(t){t.writeNode(this.type),t.write(` ${this.name}`)}};function l5A(e){return new NHe(e)}function p5A(e){return new kHe(e)}function f5A(e){return new fg(e)}function d5A(e){return new FHe(e)}function m5A(e){return new zHe(e)}function h5A(e){return new jHe(e)}function g5A(e){return new QHe(e)}var A5A=new Set(["abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","final","finally","float","for","goto","if","implements","import","instanceof","int","interface","long","native","new","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","try","void","volatile","while","true","false","null","_"]);function $3p(e){return A5A.has(e.toLowerCase())}function vZs(e){return $3p(e)?"_"+e:e}Gi();ct();var PFi=class{context;constructor({context:t}){this.context=t}usesOptionalNullable(){return this.context.usesOptionalNullable()}usesNullableAnnotation(){return this.context.usesNullableAnnotation()}wrapInOptionalIfNotNop(t,r=!1,n=!1){return pr.TypeLiteral.isNop(t)?t:n?this.context.getOptionalNullableOf(t):pr.TypeLiteral.optional({value:t,useOf:r})}wrapNullableOrOptionalValue({value:t,wrapperType:r,useOf:n,propagatedCollapse:i}){return pr.TypeLiteral.isNop(t)||r==="nullable"&&this.usesNullableAnnotation()?t:i||this.usesOptionalNullable()&&r==="nullable"?this.context.getOptionalNullableOf(t):pr.TypeLiteral.optional({value:t,useOf:n})}convert(t){if(t.value===null)return this.context.isNullable(t.typeReference)?this.context.getNullableOfNull():(this.context.errors.add({severity:Qr.Critical,message:"Expected non-null value, but got null"}),pr.TypeLiteral.nop());if(t.value===void 0)return pr.TypeLiteral.nop();switch(t.typeReference.type){case"list":return this.convertList({list:t.typeReference.value,value:t.value,as:t.as,nestedClassReference:t.nestedClassReference});case"literal":return this.convertLiteral({literal:t.typeReference.value,value:t.value});case"map":return this.convertMap({map:t.typeReference,value:t.value,as:t.as,nestedClassReference:t.nestedClassReference});case"named":{let r=this.context.resolveNamedType({typeId:t.typeReference.value});return r==null?pr.TypeLiteral.nop():this.convertNamed({named:r,value:t.value,as:t.as,inUndiscriminatedUnion:t.inUndiscriminatedUnion,nestedClassReference:t.nestedClassReference})}case"nullable":case"optional":{let r=t.typeReference.type,n=t.typeReference.value;if((t.value===void 0||typeof t.value=="object"&&t.value!==null&&Object.keys(t.value).length===0&&n.type==="named")&&!(r==="nullable"&&this.usesNullableAnnotation()))return t.isCollapsedOptionalNullable||this.usesOptionalNullable()&&(r==="nullable"||n.type==="optional"||n.type==="nullable")?this.context.getOptionalNullableAbsent():pr.TypeLiteral.reference(pr.invokeMethod({on:pr.classReference({name:"Optional",packageName:"java.util"}),method:"empty",arguments_:[]}));if(this.usesOptionalNullable()&&(n.type==="optional"||n.type==="nullable"))return this.convert({typeReference:n,value:t.value,as:t.as,inUndiscriminatedUnion:t.inUndiscriminatedUnion,isCollapsedOptionalNullable:!0,nestedClassReference:t.nestedClassReference});if(n.type==="list"){let s=this.convertList({list:n.value,value:t.value,nestedClassReference:t.nestedClassReference});return this.wrapNullableOrOptionalValue({value:s,wrapperType:r,useOf:!0,propagatedCollapse:t.isCollapsedOptionalNullable===!0})}let i=this.convert({typeReference:n,value:t.value,as:t.as,inUndiscriminatedUnion:t.inUndiscriminatedUnion,nestedClassReference:t.nestedClassReference}),o=t.as==="mapValue"||t.inUndiscriminatedUnion===!0;return this.wrapNullableOrOptionalValue({value:i,wrapperType:r,useOf:o,propagatedCollapse:t.isCollapsedOptionalNullable===!0})}case"primitive":return this.convertPrimitive({primitive:t.typeReference.value,value:t.value,as:t.as});case"set":return this.convertSet({set:t.typeReference.value,value:t.value,as:t.as,nestedClassReference:t.nestedClassReference});case"unknown":return this.convertUnknown({value:t.value});default:Ee(t.typeReference)}}convertList({list:t,value:r,as:n,nestedClassReference:i}){if(!Array.isArray(r))return this.context.errors.add({severity:Qr.Critical,message:`Expected array but got: ${typeof r}`}),pr.TypeLiteral.nop();let o=t.type==="optional"||t.type==="nullable";return pr.TypeLiteral.list({valueType:this.context.dynamicTypeMapper.convert({typeReference:t}),values:r.map((s,a)=>{this.context.errors.scope({index:a});try{if(o&&(t.type==="optional"||t.type==="nullable")){let c=this.convert({typeReference:t.value,value:s,as:n,nestedClassReference:i});return this.wrapNullableOrOptionalValue({value:c,wrapperType:t.type,useOf:!0,propagatedCollapse:!1})}return this.convert({typeReference:t,value:s,as:n,nestedClassReference:i})}finally{this.context.errors.unscope()}}),isParameter:!0})}convertLiteral({literal:t,value:r}){switch(t.type){case"boolean":{let n=this.context.getValueAsBoolean({value:r});return n==null?pr.TypeLiteral.nop():pr.TypeLiteral.boolean(n)}case"string":{let n=this.context.getValueAsString({value:r});return n==null?pr.TypeLiteral.nop():pr.TypeLiteral.string(n)}default:Ee(t)}}convertSet({set:t,value:r,as:n,nestedClassReference:i}){return Array.isArray(r)?pr.TypeLiteral.set({valueType:this.context.dynamicTypeMapper.convert({typeReference:t}),values:r.map((o,s)=>{this.context.errors.scope({index:s});try{return this.convert({typeReference:t,value:o,as:n,nestedClassReference:i})}finally{this.context.errors.unscope()}})}):(this.context.errors.add({severity:Qr.Critical,message:`Expected array but got: ${typeof r}`}),pr.TypeLiteral.nop())}convertMap({map:t,value:r,as:n,nestedClassReference:i}){return typeof r!="object"||r==null?(this.context.errors.add({severity:Qr.Critical,message:`Expected object but got: ${r==null?"null":typeof r}`}),pr.TypeLiteral.nop()):pr.TypeLiteral.map({keyType:this.context.dynamicTypeMapper.convert({typeReference:t.key}),valueType:this.context.dynamicTypeMapper.convert({typeReference:t.value}),entries:Object.entries(r).map(([o,s])=>{this.context.errors.scope(o);try{return{key:this.convert({typeReference:t.key,value:o,as:"mapKey"}),value:this.convert({typeReference:t.value,value:s,as:"mapValue",nestedClassReference:i})}}finally{this.context.errors.unscope()}})})}convertNamed({named:t,value:r,as:n,inUndiscriminatedUnion:i,nestedClassReference:o}){switch(t.type){case"alias":if(t.typeReference.type==="unknown"){let s=this.convert({typeReference:t.typeReference,value:r,as:n,inUndiscriminatedUnion:i});return pr.TypeLiteral.reference(pr.invokeMethod({on:o??this.context.getJavaClassReferenceFromDeclaration({declaration:t.declaration}),method:"of",arguments_:[s]}))}return this.convert({typeReference:t.typeReference,value:r,as:n,inUndiscriminatedUnion:i,nestedClassReference:o});case"discriminatedUnion":return this.convertDiscriminatedUnion({discriminatedUnion:t,value:r,as:n,nestedClassReference:o});case"enum":return this.convertEnum({enum_:t,value:r,nestedClassReference:o});case"object":return this.convertObject({object_:t,value:r,as:n,inUndiscriminatedUnion:i,nestedClassReference:o});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r,as:n,nestedClassReference:o});default:Ee(t)}}convertDiscriminatedUnion({discriminatedUnion:t,value:r,as:n,nestedClassReference:i}){let o=i??this.context.getJavaClassReferenceFromDeclaration({declaration:t.declaration}),s=this.context.resolveDiscriminatedUnionTypeInstance({discriminatedUnion:t,value:r});if(s==null)return pr.TypeLiteral.nop();let a=s.singleDiscriminatedUnionType,c=new Set([...o.enclosingClasses,o.name]),u=new Set(Object.values(t.types).map(l=>this.context.getClassName(l.discriminantValue.name)));switch(a.type){case"samePropertiesAsObject":{let l=this.context.resolveNamedType({typeId:a.typeId});if(l==null)return pr.TypeLiteral.nop();let p=this.resolveInlineNestedClassReference({enclosing:o,baseName:this.context.getClassName(a.discriminantValue.name),typeReference:{type:"named",value:a.typeId},reservedNames:c,siblingPropertyNames:u});return pr.TypeLiteral.reference(pr.invokeMethod({on:o,method:this.context.getPropertyName(a.discriminantValue.name),arguments_:[this.convertNamed({named:l,value:s.value,as:n,nestedClassReference:p})]}))}case"singleProperty":{let l=this.context.getRecord(s.value);if(l==null)return pr.TypeLiteral.nop();try{this.context.errors.scope(a.discriminantValue.wireValue);let p="value",d=this.resolveInlineNestedClassReference({enclosing:o,baseName:this.context.getClassName(a.discriminantValue.name),typeReference:a.typeReference,reservedNames:c,siblingPropertyNames:u});return pr.TypeLiteral.reference(pr.invokeMethod({on:o,method:this.context.getPropertyName(a.discriminantValue.name),arguments_:[this.convert({typeReference:a.typeReference,value:l[p],as:n,nestedClassReference:d})]}))}finally{this.context.errors.unscope()}}case"noProperties":return pr.TypeLiteral.reference(pr.invokeMethod({on:o,method:this.context.getPropertyName(a.discriminantValue.name),arguments_:[]}));default:Ee(a)}}convertObject({object_:t,value:r,as:n,inUndiscriminatedUnion:i,nestedClassReference:o}){let s=o??this.context.getJavaClassReferenceFromDeclaration({declaration:t.declaration}),a=this.context.getRecord(r)??{},c=this.context.associateByWireValue({parameters:t.properties,values:a}),u=new Set(c.map(A=>A.name.wireValue));for(let A of t.properties)if(!u.has(A.name.wireValue)&&!this.context.isOptional(A.typeReference)){if(i===!0)throw new Error(`Required property "${A.name.wireValue}" is missing from value`);let y=this.getDefaultValueForTypeReference(A.typeReference);y!==void 0&&c.push({name:A.name,typeReference:A.typeReference,value:y})}let l=new Map,p=new Set;t.properties.forEach((A,y)=>{l.set(A.name.wireValue,y),p.add(A.name.wireValue)}),c.sort((A,y)=>(l.get(A.name.wireValue)??0)-(l.get(y.name.wireValue)??0));let d=n==="request"?c.filter(A=>!this.context.isDirectLiteral(A.typeReference)):c,f=new Set([...s.enclosingClasses,s.name]),m=new Set(t.properties.map(A=>this.context.getClassName(A.name.name))),g=[];for(let A of d){this.context.errors.scope(A.name.wireValue);try{let y=this.convert({typeReference:A.typeReference,value:A.value,as:n,inUndiscriminatedUnion:i,nestedClassReference:this.resolveInlineNestedClassReference({enclosing:s,baseName:this.context.getClassName(A.name.name),typeReference:A.typeReference,reservedNames:f,siblingPropertyNames:m})});if(pr.TypeLiteral.isNop(y)&&!this.context.isOptional(A.typeReference)){if(i===!0)throw new Error(`Required property "${A.name.wireValue}" could not be converted`);continue}g.push({name:this.context.getMethodName(A.name.name),value:y,isRequired:this.isStagedBuilderProperty(A.typeReference)})}finally{this.context.errors.unscope()}}for(let[A,y]of Object.entries(a))if(!p.has(A)&&y!==void 0){let I=this.convertToRawJavaLiteral(y);I!=null&&g.push({name:"additionalProperty",value:pr.TypeLiteral.raw(`"${this.escapeJavaString(A)}", ${I}`),isRequired:!1})}return pr.TypeLiteral.builder({classReference:s,parameters:g})}resolveInlineNestedClassReference({enclosing:t,baseName:r,typeReference:n,reservedNames:i,siblingPropertyNames:o}){if(this.context.enableInlineTypes())switch(n.type){case"optional":case"nullable":return this.resolveInlineNestedClassReference({enclosing:t,baseName:r,typeReference:n.value,reservedNames:i,siblingPropertyNames:o});case"list":case"set":return this.resolveInlineNestedClassReference({enclosing:t,baseName:`${r}Item`,typeReference:n.value,reservedNames:i,siblingPropertyNames:o});case"map":return this.resolveInlineNestedClassReference({enclosing:t,baseName:`${r}Value`,typeReference:n.value,reservedNames:i,siblingPropertyNames:o});case"named":{let s=n.value,a=this.context.resolveNamedType({typeId:s});if(a==null)return;if(a.type==="alias"&&!this.context.wrappedAliases())return this.resolveInlineNestedClassReference({enclosing:t,baseName:r,typeReference:a.typeReference,reservedNames:i,siblingPropertyNames:o});if(!this.context.isInlineType(s))return;let c=r;for(;i.has(c)||o.has(c)&&c!==r;)c=`${c}_`;return i.add(c),this.context.getNestedInlineClassReference({enclosing:t,name:c})}case"primitive":case"literal":case"unknown":return;default:Ee(n)}}resolveUndiscriminatedInlineNestedClassReference({enclosing:t,typeReference:r,reservedNames:n,unionPrefix:i}){if(this.context.enableInlineTypes())switch(r.type){case"optional":case"nullable":case"list":case"set":return this.resolveUndiscriminatedInlineNestedClassReference({enclosing:t,typeReference:r.value,reservedNames:n,unionPrefix:i});case"map":return this.resolveUndiscriminatedInlineNestedClassReference({enclosing:t,typeReference:r.value,reservedNames:n,unionPrefix:i});case"named":{let o=r.value,s=this.context.resolveNamedType({typeId:o});if(s==null)return;if(s.type==="alias"&&!this.context.wrappedAliases())return this.resolveUndiscriminatedInlineNestedClassReference({enclosing:t,typeReference:s.typeReference,reservedNames:n,unionPrefix:i});if(!this.context.isInlineType(o))return;let a=this.context.getClassName(s.declaration.name);for(a.startsWith(i)&&a!==i&&(a=a.substring(i.length));n.has(a);)a=`${a}_`;return this.context.getNestedInlineClassReference({enclosing:t,name:a})}case"primitive":case"literal":case"unknown":return;default:Ee(r)}}isStagedBuilderProperty(t){switch(t.type){case"optional":case"nullable":case"list":case"set":case"map":return!1;case"named":{let r=this.context.resolveNamedType({typeId:t.value});return r!=null&&r.type==="alias"?this.isStagedBuilderProperty(r.typeReference):!0}default:return!0}}convertToRawJavaLiteral(t){return typeof t=="string"?`"${this.escapeJavaString(t)}"`:typeof t=="number"||typeof t=="boolean"?t.toString():t===null?"null":null}escapeJavaString(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\t/g,"\\t").replace(/\r/g,"\\r")}getDefaultValueForTypeReference(t){switch(t.type){case"primitive":return this.getDefaultPrimitiveValue(t.value);case"nullable":return null;case"optional":return;case"list":case"set":return[];case"map":return{};case"named":{let r=this.context.resolveNamedType({typeId:t.value});if(r==null)return{};switch(r.type){case"enum":if(r.values.length>0){let n=r.values[0];return n?.wireValue}return;case"object":case"alias":return{};case"discriminatedUnion":case"undiscriminatedUnion":return;default:return{}}}case"literal":return t.value.value;case"unknown":return{};default:Ee(t)}}getDefaultPrimitiveValue(t){switch(t){case"STRING":return"string";case"INTEGER":case"UINT":return 1;case"LONG":case"UINT_64":return 1e6;case"FLOAT":case"DOUBLE":return 1.1;case"BOOLEAN":return!0;case"DATE":return"2024-01-15";case"DATE_TIME":return"2024-01-15T09:30:00Z";case"DATE_TIME_RFC_2822":return"Tue, 15 Jan 2024 09:30:00 +0000";case"UUID":return"d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32";case"BASE_64":return"SGVsbG8gd29ybGQh";case"BIG_INTEGER":return"123456789";default:return"string"}}convertEnum({enum_:t,value:r,nestedClassReference:n}){let i=this.getEnumValueName({enum_:t,value:r});return i==null?pr.TypeLiteral.nop():pr.TypeLiteral.enum_({classReference:n??this.context.getJavaClassReferenceFromDeclaration({declaration:t.declaration}),value:i})}getEnumValueName({enum_:t,value:r}){if(typeof r!="string"){this.context.errors.add({severity:Qr.Critical,message:`Expected enum value string, got: ${typeof r}`});return}let n=t.values.find(i=>i.wireValue===r);if(n==null){this.context.errors.add({severity:Qr.Critical,message:`An enum value named "${r}" does not exist in this context`});return}return this.context.getEnumName(n.name)}convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r,as:n,nestedClassReference:i}){let o=i??this.context.getJavaClassReferenceFromDeclaration({declaration:t.declaration}),s=this.findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r,as:n,enclosing:o});return s==null?pr.TypeLiteral.nop():pr.TypeLiteral.reference(pr.invokeMethod({on:o,method:"of",arguments_:[s.typeInstantiation]}))}findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r,as:n,enclosing:i}){let o=new Set([...i.enclosingClasses,i.name]),s=this.context.getClassName(t.declaration.name);for(let a of t.types){let c=this.context.errors.size();try{let u=this.convert({typeReference:a,value:r,as:n,inUndiscriminatedUnion:!0,nestedClassReference:this.resolveUndiscriminatedInlineNestedClassReference({enclosing:i,typeReference:a,reservedNames:new Set(o),unionPrefix:s})});if(pr.TypeLiteral.isNop(u)||this.context.errors.size()>c){this.context.errors.truncate(c);continue}return{valueTypeReference:a,typeInstantiation:u}}catch{this.context.errors.truncate(c);continue}}this.context.errors.add({severity:Qr.Critical,message:`None of the types in the undiscriminated union matched the given "${typeof r}" value`})}getUndiscriminatedUnionFieldName({typeReference:t}){switch(t.type){case"list":return this.getUndiscriminatedUnionFieldNameForList({list:t});case"literal":return this.getUndiscriminatedUnionFieldNameForLiteral({literal:t.value});case"map":return this.getUndiscriminatedUnionFieldNameForMap({map:t});case"named":{let r=this.context.resolveNamedType({typeId:t.value});return r==null?void 0:this.context.getClassName(r.declaration.name)}case"optional":return this.getUndiscriminatedUnionFieldNameForOptional({typeReference:t});case"nullable":return this.getUndiscriminatedUnionFieldNameForNullable({typeReference:t});case"primitive":return this.getUndiscriminatedUnionFieldNameForPrimitive({primitive:t.value});case"set":return this.getUndiscriminatedUnionFieldNameForSet({set:t});case"unknown":return"Unknown";default:Ee(t)}}getUndiscriminatedUnionFieldNameForList({list:t}){let r=this.getUndiscriminatedUnionFieldName({typeReference:t});if(r!=null)return`ListOf${r}`}getUndiscriminatedUnionFieldNameForMap({map:t}){let r=this.getUndiscriminatedUnionFieldName({typeReference:t.key});if(r==null)return;let n=this.getUndiscriminatedUnionFieldName({typeReference:t.value});if(n!=null)return`MapOf${r}To${n}`}getUndiscriminatedUnionFieldNameForOptional({typeReference:t}){let r=this.getUndiscriminatedUnionFieldName({typeReference:t});if(r!=null)return`Optional${r}`}getUndiscriminatedUnionFieldNameForNullable({typeReference:t}){let r=this.getUndiscriminatedUnionFieldName({typeReference:t});if(r!=null)return`Nullable${r}`}getUndiscriminatedUnionFieldNameForSet({set:t}){let r=this.getUndiscriminatedUnionFieldName({typeReference:t});if(r!=null)return`SetOf${r}`}getUndiscriminatedUnionFieldNameForLiteral({literal:t}){}getUndiscriminatedUnionFieldNameForPrimitive({primitive:t}){switch(t){case"INTEGER":case"UINT":return"Integer";case"LONG":case"UINT_64":return"Long";case"FLOAT":return"Float";case"DOUBLE":return"Double";case"BOOLEAN":return"Boolean";case"BIG_INTEGER":return"BigInteger";case"STRING":return"String";case"UUID":return"Uuid";case"DATE":return"Date";case"DATE_TIME":return"DateTime";case"DATE_TIME_RFC_2822":return"DateTimeRfc2822";case"BASE_64":return"Base64";default:Ee(t)}}convertUnknown({value:t}){return this.context.customConfig?.["generate-unknown-as-json-node"]===!0?this.convertToJsonNode({value:t}):pr.TypeLiteral.unknown(t)}convertToJsonNode({value:t}){let r=pr.classReference({name:"ObjectMappers",packageName:this.context.getCorePackageName()});return typeof t=="string"?pr.TypeLiteral.reference(pr.invokeMethod({on:pr.codeblock(n=>{n.writeNode(r),n.write(".JSON_MAPPER")}),method:"valueToTree",arguments_:[pr.TypeLiteral.string(t)]})):typeof t=="number"?pr.TypeLiteral.reference(pr.invokeMethod({on:pr.codeblock(n=>{n.writeNode(r),n.write(".JSON_MAPPER")}),method:"valueToTree",arguments_:[pr.TypeLiteral.integer(t)]})):typeof t=="boolean"?pr.TypeLiteral.reference(pr.invokeMethod({on:pr.codeblock(n=>{n.writeNode(r),n.write(".JSON_MAPPER")}),method:"valueToTree",arguments_:[pr.TypeLiteral.boolean(t)]})):t===null?pr.TypeLiteral.reference(pr.invokeMethod({on:pr.codeblock(n=>{n.writeNode(r),n.write(".JSON_MAPPER")}),method:"valueToTree",arguments_:[pr.TypeLiteral.raw(pr.codeblock("null"))]})):Array.isArray(t)?pr.TypeLiteral.reference(pr.invokeMethod({on:pr.codeblock(n=>{n.writeNode(r),n.write(".JSON_MAPPER")}),method:"valueToTree",arguments_:[pr.TypeLiteral.list({valueType:pr.Type.object(),values:t.map(n=>pr.TypeLiteral.unknown(n)),isParameter:!0})]})):typeof t=="object"&&t!==null?pr.TypeLiteral.reference(pr.invokeMethod({on:pr.codeblock(n=>{n.writeNode(r),n.write(".JSON_MAPPER")}),method:"valueToTree",arguments_:[pr.TypeLiteral.unknown(t)]})):pr.TypeLiteral.unknown(t)}convertPrimitive({primitive:t,value:r,as:n}){switch(t){case"INTEGER":case"UINT":{let i=this.getValueAsNumber({value:r,as:n});return i==null?pr.TypeLiteral.nop():pr.TypeLiteral.integer(i)}case"LONG":case"UINT_64":{let i=this.getValueAsNumber({value:r,as:n});return i==null?pr.TypeLiteral.nop():pr.TypeLiteral.long(i)}case"FLOAT":{let i=this.getValueAsNumber({value:r,as:n});return i==null?pr.TypeLiteral.nop():pr.TypeLiteral.float(i)}case"DOUBLE":{let i=this.getValueAsNumber({value:r,as:n});return i==null?pr.TypeLiteral.nop():pr.TypeLiteral.double(i)}case"BOOLEAN":{let i=this.getValueAsBoolean({value:r,as:n});return i==null?pr.TypeLiteral.nop():pr.TypeLiteral.boolean(i)}case"STRING":{let i=this.context.getValueAsString({value:r});return i==null?pr.TypeLiteral.nop():pr.TypeLiteral.string(i)}case"DATE":{let i=this.context.getValueAsString({value:r});return i==null?pr.TypeLiteral.nop():this.context.customConfig?.["use-local-date-for-dates"]===!0?pr.TypeLiteral.date(i):pr.TypeLiteral.string(i)}case"DATE_TIME":case"DATE_TIME_RFC_2822":{let i=this.context.getValueAsString({value:r});return i==null?pr.TypeLiteral.nop():pr.TypeLiteral.dateTime(i)}case"UUID":{let i=this.context.getValueAsString({value:r});return i==null?pr.TypeLiteral.nop():pr.TypeLiteral.uuid(i)}case"BASE_64":{let i=this.context.getValueAsString({value:r});return i==null?pr.TypeLiteral.nop():pr.TypeLiteral.bytes(i)}case"BIG_INTEGER":{let i=this.context.getValueAsString({value:r});return i==null?pr.TypeLiteral.nop():pr.TypeLiteral.bigInteger(i)}default:Ee(t)}}getValueAsNumber({value:t,as:r}){let n=r==="mapKey"&&typeof t=="string"?Number(t):t;return this.context.getValueAsNumber({value:n})}getValueAsBoolean({value:t,as:r}){let n=r==="mapKey"?typeof t=="string"?t==="true":t==="false"?!1:t:t;return this.context.getValueAsBoolean({value:n})}};ct();var BFi=class{context;constructor({context:t}){this.context=t}convert(t){switch(t.typeReference.type){case"list":return pr.Type.list(this.convert({typeReference:t.typeReference}));case"literal":return this.convertLiteral({literal:t.typeReference.value});case"map":return pr.Type.map(this.convert({typeReference:t.typeReference.key}),this.convert({typeReference:t.typeReference.value}));case"named":{let r=this.context.resolveNamedType({typeId:t.typeReference.value});return r==null?this.convertUnknown():this.convertNamed({named:r})}case"optional":{let r=t.typeReference.value;return this.context.usesOptionalNullable()&&(r.type==="nullable"||r.type==="optional")?pr.Type.generic(this.context.getOptionalNullableClassReference(),[this.convert({typeReference:r.value})]):pr.Type.optional(this.convert({typeReference:r}))}case"nullable":{let r=t.typeReference.value;if(this.context.usesNullableAnnotation())return this.convert({typeReference:r});if(this.context.usesOptionalNullable()){let n=r.type==="optional"||r.type==="nullable"?r.value:r;return pr.Type.generic(this.context.getOptionalNullableClassReference(),[this.convert({typeReference:n})])}return pr.Type.optional(this.convert({typeReference:r}))}case"primitive":return this.convertPrimitive({primitive:t.typeReference.value});case"set":return pr.Type.set(this.convert({typeReference:t.typeReference}));case"unknown":return this.convertUnknown();default:Ee(t.typeReference)}}convertNamed({named:t}){switch(t.type){case"alias":return this.convert({typeReference:t.typeReference});case"enum":case"discriminatedUnion":case"object":case"undiscriminatedUnion":return pr.Type.reference(pr.classReference({name:this.context.getClassName(t.declaration.name),packageName:this.context.getTypesPackageName(t.declaration.fernFilepath)}));default:Ee(t)}}convertLiteral({literal:t}){switch(t.type){case"boolean":return pr.Type.boolean();case"string":return pr.Type.string()}}convertUnknown(){return this.context.customConfig?.["generate-unknown-as-json-node"]===!0?pr.Type.reference(pr.classReference({name:"JsonNode",packageName:"com.fasterxml.jackson.databind"})):pr.Type.object()}convertPrimitive({primitive:t}){switch(t){case"INTEGER":return pr.Type.integer();case"UINT":return pr.Type.integer();case"LONG":return pr.Type.long();case"UINT_64":return pr.Type.long();case"FLOAT":return pr.Type.float();case"DOUBLE":return pr.Type.double();case"BOOLEAN":return pr.Type.boolean();case"STRING":return pr.Type.string();case"DATE":return pr.Type.date();case"DATE_TIME":case"DATE_TIME_RFC_2822":return pr.Type.dateTime();case"UUID":return pr.Type.uuid();case"BASE_64":return pr.Type.bytes();case"BIG_INTEGER":return pr.Type.bigInteger();default:Ee(t)}}};ct();var CZs="path/to/file",RFi=class{context;constructor({context:t}){this.context=t}getFilePropertyInfo({body:t,value:r}){let n={fileFields:[],bodyPropertyFields:[]},i=this.context.getRecord(r)??{};for(let o of t.properties)switch(o.type){case"file":n.fileFields.push({name:this.context.getMethodName(o.name),value:this.getSingleFileProperty({property:o,record:i})});break;case"fileArray":n.fileFields.push({name:this.context.getMethodName(o.name),value:this.getArrayFileProperty({property:o,record:i})});break;case"bodyProperty":n.bodyPropertyFields.push({name:this.context.getMethodName(o.name.name),value:this.getBodyProperty({property:o,record:i})});break;default:Ee(o)}return n}getSingleFileProperty({property:t,record:r}){let n=this.context.getSingleFileValue({property:t,record:r});return this.context.shouldInlineFileProperties()?this.context.getJavaIoFileFromString(n??CZs):n==null?this.getMissingFileArgument(t):pr.TypeLiteral.reference(this.context.getFileStreamFromString(n))}getArrayFileProperty({property:t,record:r}){let n=this.context.getFileArrayValues({property:t,record:r});if(this.context.shouldInlineFileProperties()){let i=n?.[0]??CZs;return this.context.getJavaIoFileFromString(i)}if(n==null||n.length===0)return this.getMissingFileArgument(t);for(let i of n)return pr.TypeLiteral.reference(this.context.getFileStreamFromString(i));return pr.TypeLiteral.nop()}getMissingFileArgument(t){switch(t.isOptional){case!0:return pr.TypeLiteral.reference(pr.invokeMethod({on:pr.classReference({name:"Optional",packageName:"java.util"}),method:"empty",arguments_:[]}));case!1:return this.context.getJavaIoFileFromString(CZs);default:return pr.TypeLiteral.nop()}}getBodyProperty({property:t,record:r}){let n=r[t.name.wireValue];return n==null?pr.TypeLiteral.nop():this.context.dynamicTypeLiteralMapper.convert({typeReference:t.typeReference,value:n})}};var y5A=new Set(["enum","extends","package","void","short","class","abstract","return","import","for","assert","switch"]),b5A=new Set(["getClass","notify","notifyAll","wait"]),DFi=class e extends wx{ir;customConfig;dynamicTypeMapper;dynamicTypeLiteralMapper;filePropertyMapper;inlineTypeIds;constructor({ir:t,config:r,options:n,sharedCustomConfig:i,inlineTypeIds:o}){super({ir:t,config:r,options:n}),this.ir=t,this.customConfig=i??yZs.parse(r.customConfig??{}),this.dynamicTypeMapper=new BFi({context:this}),this.dynamicTypeLiteralMapper=new PFi({context:this}),this.filePropertyMapper=new RFi({context:this}),this.inlineTypeIds=o??new Set}clone(){return new e({ir:this.ir,config:this.config,options:this.options,sharedCustomConfig:this.customConfig,inlineTypeIds:this.inlineTypeIds})}isInlineType(t){return this.inlineTypeIds.has(t)}getNestedInlineClassReference({enclosing:t,name:r}){return pr.classReference({name:r,packageName:t.packageName,enclosingClasses:[...t.enclosingClasses,t.name]})}wrappedAliases(){return this.customConfig?.["wrapped-aliases"]??!1}enableInlineTypes(){return this.customConfig?.["enable-inline-types"]??!1}getClassName(t){return this.getName(t.pascalCase.safeName)}getEnumName(t){return this.getName(t.screamingSnakeCase.safeName)}getPropertyName(t){return this.getName(t.camelCase.safeName)}getMethodName(t){let r=t.camelCase.safeName;return this.isReservedMethodName(r)?r+"_":this.getName(r)}getRootClientClassReference(){return pr.classReference({name:this.getRootClientClassNameForSnippets(),packageName:this.getRootPackageName()})}getRootClientClassName(){return this.customConfig?.["client-class-name"]??`${this.getBaseNamePrefix()}Client`}getRootClientClassNameForSnippets(){return this.customConfig?.["exported-client-class-name"]??this.getRootClientClassName()}getEnvironmentClassName(){return"Environment"}getEnvironmentTypeReferenceFromID(t){let r=this.resolveEnvironmentName(t);if(r!=null)return pr.codeblock(n=>{n.writeNode(this.getEnvironmentClassReference()),n.write("."),n.write(this.getEnumName(r))})}getEnvironmentClassReference(){return pr.classReference({name:this.getEnvironmentClassName(),packageName:this.getCorePackageName()})}getJavaClassReferenceFromDeclaration({declaration:t}){return pr.classReference({name:t.name.pascalCase.unsafeName,packageName:this.getTypesPackageName(t.fernFilepath)})}getNullableClassReference(){return pr.classReference({name:"Nullable",packageName:this.getCorePackageName()})}getNullableOfNull(){return pr.TypeLiteral.reference(pr.invokeMethod({on:this.getNullableClassReference(),method:"ofNull",arguments_:[]}))}getOptionalNullableClassReference(){return pr.classReference({name:"OptionalNullable",packageName:this.getCorePackageName()})}getOptionalNullableAbsent(){return pr.TypeLiteral.reference(pr.invokeMethod({on:this.getOptionalNullableClassReference(),method:"absent",arguments_:[]}))}getOptionalNullableOf(t){return pr.TypeLiteral.reference(pr.invokeMethod({on:this.getOptionalNullableClassReference(),method:"of",arguments_:[t]}))}getFileStreamFromString(t){return pr.TypeLiteral.reference(pr.codeblock(r=>{r.write("new "),r.writeNode(this.getFileStreamClassReference()),r.write("(new "),r.writeNode(this.getByteArrayInputStreamClassReference()),r.write("("),r.writeNode(pr.TypeLiteral.string(t)),r.write(".getBytes("),r.writeNode(this.getStandardCharsetsClassReference()),r.write(".UTF_8)))")}))}getJavaIoFileFromString(t){return pr.TypeLiteral.reference(pr.codeblock(r=>{r.write("new "),r.writeNode(this.getJavaIoFileClassReference()),r.write("("),r.writeNode(pr.TypeLiteral.string(t)),r.write(")")}))}getJavaIoFileClassReference(){return pr.classReference({name:"File",packageName:"java.io"})}getFileStreamClassReference(){return pr.classReference({name:"FileStream",packageName:this.getCorePackageName()})}getByteArrayInputStreamClassReference(){return pr.classReference({name:"ByteArrayInputStream",packageName:"java.io"})}getStandardCharsetsClassReference(){return pr.classReference({name:"StandardCharsets",packageName:"java.nio.charset"})}isPrimitive(t){switch(t.type){case"primitive":return!0;case"optional":case"nullable":return this.isPrimitive(t.value);case"named":{let r=this.resolveNamedType({typeId:t.value});if(r==null)return!1;switch(r.type){case"alias":return this.isPrimitive(r.typeReference);case"discriminatedUnion":case"undiscriminatedUnion":case"object":case"enum":return!1;default:Ee(r)}break}case"list":case"set":case"map":case"literal":case"unknown":return!1;default:Ee(t)}}isDirectLiteral(t){return t.type==="literal"}sortTypeInstancesByRequiredFirst(t,r){let n=new Map;r.forEach((s,a)=>{n.set(s.name.wireValue,a)});let i=[],o=[];for(let s of t)this.isOptional(s.typeReference)?o.push(s):i.push(s);return i.sort((s,a)=>(n.get(s.name.wireValue)??0)-(n.get(a.name.wireValue)??0)),[...i,...o]}associateByWireValue({parameters:t,values:r,ignoreMissingParameters:n}){let i=super.associateByWireValue({parameters:t,values:r,ignoreMissingParameters:n}),o=new Map;for(let a of i)o.set(a.name.wireValue,a);let s=[];for(let a of t){let c=o.get(a.name.wireValue);c!=null&&s.push(c)}return s}getRootPackageName(){let t=this.getPackagePrefixTokens();return this.joinPackageTokens(t)}getCorePackageName(){let t=this.getPackagePrefixTokens();return t.push("core"),this.joinPackageTokens(t)}getTypesPackageName(t){return this.getResourcesPackage(t,"types")}getRequestsPackageName(t){return this.getPackageLayout()==="flat"?this.getTypesPackageName(t):this.getResourcesPackage(t,"requests")}getResourcesPackage(t,r){let n=this.getPackagePrefixTokens();return this.getPackageLayout()==="flat"?t!=null&&n.push(...t.packagePath.map(i=>this.getPackageNameSegment(i))):(t!=null&&t.allParts.length>0&&n.push("resources"),t!=null&&n.push(...t.allParts.map(i=>this.getPackageNameSegment(i)))),r!=null&&n.push(r),this.joinPackageTokens(n)}getPackageName(t,r){let n=this.getPackageNameSegments(t);return n=r!=null?[...n,r]:n,[...this.getPackagePrefixTokens(),...n].join(".")}getPackageLayout(){return this.customConfig?.["package-layout"]??"nested"}shouldInlinePathParameters(){return this.customConfig?.["inline-path-parameters"]??!1}shouldInlineFileProperties(){return this.customConfig?.["inline-file-properties"]??!1}usesNullableAnnotation(){return this.customConfig?.["use-nullable-annotation"]===!0}usesOptionalNullable(){return this.customConfig?.["collapse-optional-nullable"]===!0}getPackageNameSegments(t){return t.packagePath.map(r=>this.getPackageNameSegment(r))}getPackageNameSegment(t){return t.camelCase.safeName.toLowerCase()}getPackagePrefixTokens(){if(this.customConfig?.["package-prefix"]!=null)return this.customConfig["package-prefix"].split(".");let t=[];return t.push("com"),t.push(...this.splitOnNonAlphaNumericChar(this.config.organization)),t.push(...this.splitOnNonAlphaNumericChar(this.getApiName())),t}getBaseNamePrefix(){return this.convertKebabCaseToUpperCamelCase(this.config.organization)+this.convertKebabCaseToUpperCamelCase(this.getApiName())}getApiName(){return ri(this.config.workspaceName)}startsWithNumber(t){return/^\d/.test(t)}splitOnNonAlphaNumericChar(t){return t.split(/[^a-zA-Z0-9]/)}convertKebabCaseToUpperCamelCase(t){return t.replace(/-([a-z])/g,(r,n)=>n.toUpperCase()).replace(/^[a-z]/,r=>r.toUpperCase())}joinPackageTokens(t){return t.map(n=>this.startsWithNumber(n)?"_"+n:vZs(n)).join(".")}getName(t){return this.isReservedName(t)?"_"+t:t}isReservedName(t){return y5A.has(t)}isReservedMethodName(t){return b5A.has(t)}};ct();var e4p="com.example.usage",E5A="Example",I5A="main",v5A="args",t4p="client",C5A={type:"primitive",value:"STRING"};function xZs(e){let t=e;for(;t.type==="optional"||t.type==="nullable";)t=t.value;return t}function x5A(e){if(e.type==="optional"&&e.value.type==="list"){let t=e.value.value,r=xZs(t);return r===t?e:{type:"optional",value:{type:"list",value:r}}}if(e.type==="list"){let t=xZs(e.value);return t===e.value?e:{type:"list",value:t}}return e}var kFi=class{context;formatter;constructor({context:t,formatter:r}){this.context=t,this.formatter=r}async generateSnippet({endpoint:t,request:r,options:n}){let i=this.getConfig(n);return await this.buildCodeBlock({endpoint:t,snippet:r,options:n}).toStringAsync({packageName:i.fullStylePackageName??e4p,customConfig:this.context.customConfig,formatter:this.formatter})}generateSnippetSync({endpoint:t,request:r,options:n}){let i=this.getConfig(n);return this.buildCodeBlock({endpoint:t,snippet:r,options:n}).toString({packageName:i.fullStylePackageName??e4p,customConfig:this.context.customConfig,formatter:this.formatter})}async generateSnippetAst({endpoint:t,request:r,options:n}){throw new Error("Unsupported")}buildCodeBlock({endpoint:t,snippet:r,options:n}){let i=pr.codeblock(s=>{s.writeNodeStatement(this.constructClient({endpoint:t,snippet:r})),s.newLine(),s.writeNodeStatement(this.callMethod({endpoint:t,snippet:r}))}),o=this.getStyle(n);switch(o){case S1.Concise:return i;case S1.Full:return this.buildFullCodeBlock({body:i,options:n});default:Ee(o)}}constructClient({endpoint:t,snippet:r}){let n=t.auth?.type==="oauth";return pr.codeblock(i=>{if(i.writeNode(this.context.getRootClientClassReference()),i.write(` ${t4p} = `),n&&r.auth?.type==="oauth"){let o=r.auth;i.writeNode(this.context.getRootClientClassReference()),i.write(`.withCredentials("${o.clientId}", "${o.clientSecret}")`),i.writeNewLineIfLastLineNot(),i.indent();let s=this.getRootClientBuilderArgsExcludingAuth({endpoint:t,snippet:r});for(let a of s)i.write(`.${a.name}(`),a.value.shouldWriteInLine()||i.newLine(),i.writeNode(a.value),a.value.shouldWriteInLine()||i.newLine(),i.writeLine(")");i.writeLine(".build()"),i.dedent()}else i.writeNode(pr.TypeLiteral.builder({classReference:this.context.getRootClientClassReference(),parameters:this.getRootClientBuilderArgs({endpoint:t,snippet:r})}))})}getRootClientBuilderArgsExcludingAuth({endpoint:t,snippet:r}){let n=[],i=this.getRootClientBaseUrlArg({baseUrl:r.baseURL,environment:r.environment});i!=null&&n.push(i),this.context.errors.scope(Ro.Headers),this.context.ir.headers!=null&&r.headers!=null&&n.push(...this.getRootClientHeaderArgs({headers:this.context.ir.headers,values:r.headers})),this.context.errors.unscope();let o=new Set;if([...this.context.ir.pathParameters??[],...t.request.pathParameters??[]].forEach(a=>{a.variable!=null&&o.add(a.variable)}),this.context.ir.variables!=null&&this.context.ir.variables.length>0){for(let a of this.context.ir.variables)if(o.has(a.id)){let c=a.name.camelCase.unsafeName;n.push({name:c,value:pr.TypeLiteral.string(`YOUR_${a.name.screamingSnakeCase.unsafeName}`)})}}if(this.context.errors.scope(Ro.PathParameters),this.context.ir.pathParameters!=null&&this.context.ir.pathParameters.length>0){let a=this.context.ir.pathParameters.filter(c=>c.variable==null);a.length>0&&n.push(...this.getPathParameters({namedParameters:a,snippet:r}))}return this.context.errors.unscope(),n}buildFullCodeBlock({body:t,options:r}){let n=this.getConfig(r),i=pr.class_({name:n.fullStyleClassName??E5A,access:pr.Access.Public}),o=pr.parameter({name:v5A,type:pr.Type.array(pr.Type.string())});return i.addMethod(pr.method({name:I5A,access:pr.Access.Public,static_:!0,parameters:[o],body:t})),i}getRootClientBuilderArgs({endpoint:t,snippet:r}){let n=[];t.auth!=null&&(r.auth!=null?n.push(...this.getRootClientAuthArgs({auth:t.auth,values:r.auth})):this.context.errors.add({severity:Qr.Warning,message:`Auth with ${t.auth.type} configuration is required for this endpoint`}));let i=this.getRootClientBaseUrlArg({baseUrl:r.baseURL,environment:r.environment});i!=null&&n.push(i),this.context.errors.scope(Ro.Headers),this.context.ir.headers!=null&&r.headers!=null&&n.push(...this.getRootClientHeaderArgs({headers:this.context.ir.headers,values:r.headers})),this.context.errors.unscope();let o=new Set;if([...this.context.ir.pathParameters??[],...t.request.pathParameters??[]].forEach(a=>{a.variable!=null&&o.add(a.variable)}),this.context.ir.variables!=null&&this.context.ir.variables.length>0){for(let a of this.context.ir.variables)if(o.has(a.id)){let c=a.name.camelCase.unsafeName;n.push({name:c,value:pr.TypeLiteral.string(`YOUR_${a.name.screamingSnakeCase.unsafeName}`)})}}if(this.context.errors.scope(Ro.PathParameters),this.context.ir.pathParameters!=null&&this.context.ir.pathParameters.length>0){let a=this.context.ir.pathParameters.filter(c=>c.variable==null);a.length>0&&n.push(...this.getPathParameters({namedParameters:a,snippet:r}))}return this.context.errors.unscope(),n}getRootClientBaseUrlArg({baseUrl:t,environment:r}){if(t!=null&&r!=null){this.context.errors.add({severity:Qr.Critical,message:"Cannot specify both baseUrl and environment options"});return}if(t!=null){if(this.context.ir.environments?.environments.type==="multipleBaseUrls"){this.context.errors.add({severity:Qr.Critical,message:"The Java SDK doesn't support a baseUrl when multiple URL environments are configured"});return}return{name:"url",value:pr.TypeLiteral.string(t)}}if(r!=null){if(this.context.isSingleEnvironmentID(r)){let n=this.context.getEnvironmentTypeReferenceFromID(r);if(n==null){this.context.errors.add({severity:Qr.Warning,message:`Environment ${JSON.stringify(r)} was not found`});return}return{name:"environment",value:pr.TypeLiteral.reference(n)}}if(this.context.isMultiEnvironmentValues(r))return this.context.validateMultiEnvironmentUrlValues(r)?{name:"environment",value:pr.TypeLiteral.reference(pr.instantiateClass({classReference:this.context.getEnvironmentClassReference(),arguments_:Object.values(r).map(n=>this.context.dynamicTypeLiteralMapper.convert({typeReference:C5A,value:n}))}))}:void 0}}getRootClientAuthArgs({auth:t,values:r}){if(r.type!==t.type)return this.addError(this.context.newAuthMismatchError({auth:t,values:r}).message),[];switch(t.type){case"basic":return r.type==="basic"?this.getRootClientBasicAuthArgs({auth:t,values:r}):[];case"bearer":return r.type==="bearer"?this.getRootClientBearerAuthArgs({auth:t,values:r}):[];case"header":return r.type==="header"?this.getRootClientHeaderAuthArgs({auth:t,values:r}):[];case"oauth":return r.type==="oauth"?this.getRootClientOAuthArgs({auth:t,values:r}):[];case"inferred":return this.addWarning("The Java SDK Generator does not support Inferred auth scheme yet"),[];default:Ee(t)}}addError(t){this.context.errors.add({severity:Qr.Critical,message:t})}addWarning(t){this.context.errors.add({severity:Qr.Warning,message:t})}getRootClientBasicAuthArgs({auth:t,values:r}){let n=t,i=!!n.usernameOmit,o=!!n.passwordOmit,s=[];return i||s.push(`"${r.username}"`),o||s.push(`"${r.password}"`),s.length===0?[]:[{name:"credentials",value:pr.TypeLiteral.raw(s.join(", "))}]}getRootClientBearerAuthArgs({auth:t,values:r}){return[{name:this.context.getMethodName(t.token),value:pr.TypeLiteral.string(r.token)}]}getRootClientHeaderAuthArgs({auth:t,values:r}){return[{name:this.context.getMethodName(t.header.name.name),value:this.context.dynamicTypeLiteralMapper.convert({typeReference:t.header.typeReference,value:r.value})}]}getRootClientOAuthArgs({auth:t,values:r}){return[{name:this.context.getMethodName(t.clientId),value:pr.TypeLiteral.string(r.clientId)},{name:this.context.getMethodName(t.clientSecret),value:pr.TypeLiteral.string(r.clientSecret)}]}getRootClientHeaderArgs({headers:t,values:r}){let n=[];for(let i of t){let o=r[i.name.wireValue],s=this.getRootClientHeaderArg({header:i,value:o});s!=null&&n.push({name:this.context.getMethodName(i.name.name),value:s})}return n}getRootClientHeaderArg({header:t,value:r}){let n=this.context.dynamicTypeLiteralMapper.convert({typeReference:t.typeReference,value:r});if(!pr.TypeLiteral.isNop(n))return n}callMethod({endpoint:t,snippet:r}){return pr.invokeMethod({on:pr.codeblock(t4p),method:this.getMethod({endpoint:t}),arguments_:this.getMethodArgs({endpoint:t,snippet:r})})}getMethodArgs({endpoint:t,snippet:r}){switch(t.request.type){case"inlined":return this.getMethodArgsForInlinedRequest({request:t.request,snippet:r});case"body":return this.getMethodArgsForBodyRequest({request:t.request,snippet:r});default:Ee(t.request)}}getMethodArgsForBodyRequest({request:t,snippet:r}){let n=[];this.context.errors.scope(Ro.PathParameters);let i=(t.pathParameters??[]).filter(s=>s.variable==null);i.length>0&&n.push(...this.getPathParameters({namedParameters:i,snippet:r}).map(s=>s.value)),this.context.errors.unscope(),this.context.errors.scope(Ro.RequestBody),t.body!=null&&!this.callOmitsRequestBody({request:t,snippet:r})&&n.push(this.getBodyRequestArg({body:t.body,value:r.requestBody})),this.context.errors.unscope();let o=this.getRequestOptionsArg({request:t,snippet:r});return o!=null&&n.push(o),n}callOmitsRequestBody({request:t,snippet:r}){if(this.context.customConfig?.["respect-optional-request-body"]!==!0||t.bodyRequired!==!1)return!1;let n=r.requestBody;return n==null||typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length===0}usesOptionalNullable(){return this.context.customConfig?.["collapse-optional-nullable"]===!0}getBodyRequestArg({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":{if(t.value.type==="optional"){let n=this.usesOptionalNullable()&&(t.value.value.type==="optional"||t.value.value.type==="nullable");if(r==null)return n?this.context.getOptionalNullableAbsent():pr.TypeLiteral.reference(pr.invokeMethod({on:pr.classReference({name:"Optional",packageName:"java.util"}),method:"empty",arguments_:[]}));let i=this.context.dynamicTypeLiteralMapper.convert({typeReference:t.value.value,value:r,as:"request",isCollapsedOptionalNullable:n}),o=i.toString({packageName:"com.example",customConfig:this.context.customConfig});if(o.includes("Optional.empty()")||o.includes("OptionalNullable.absent()"))return i;let s=this.context.dynamicTypeLiteralMapper.convert({typeReference:xZs(t.value),value:r,as:"request"});return n?this.context.getOptionalNullableOf(s):pr.TypeLiteral.optional({value:s,useOf:!0})}return this.context.dynamicTypeLiteralMapper.convert({typeReference:t.value,value:r,as:"request"})}default:Ee(t)}}getBytesBodyRequestArg({value:t}){return t==null?pr.TypeLiteral.bytes(""):typeof t!="string"?(this.context.errors.add({severity:Qr.Critical,message:`Expected bytes value to be a string, got ${typeof t}`}),pr.TypeLiteral.nop()):pr.TypeLiteral.bytes(t)}getMethodArgsForInlinedRequest({request:t,snippet:r}){let n=[],{inlinePathParameters:i,inlineFileProperties:o}={inlinePathParameters:this.context.shouldInlinePathParameters(),inlineFileProperties:this.context.shouldInlineFileProperties()};this.context.errors.scope(Ro.PathParameters);let s=[],a=(t.pathParameters??[]).filter(u=>u.variable==null);a.length>0&&s.push(...this.getPathParameters({namedParameters:a,snippet:r})),this.context.errors.unscope(),this.context.errors.scope(Ro.RequestBody);let c=this.getFilePropertyInfo({request:t,snippet:r});return this.context.errors.unscope(),this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:i})||n.push(...s.map(u=>u.value)),o||n.push(...c.fileFields.map(u=>pr.TypeLiteral.isNop(u.value)?pr.TypeLiteral.raw("null"):u.value)),n.push(this.getInlinedRequestArg({request:t,snippet:r,pathParameterFields:this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:i})?s:[],filePropertyInfo:c})),n}getFilePropertyInfo({request:t,snippet:r}){return t.body==null||!this.context.isFileUploadRequestBody(t.body)?{fileFields:[],bodyPropertyFields:[]}:this.context.filePropertyMapper.getFilePropertyInfo({body:t.body,value:r.requestBody})}getInlinedRequestArg({request:t,snippet:r,pathParameterFields:n,filePropertyInfo:i}){this.context.errors.scope(Ro.QueryParameters);let s=this.context.associateQueryParametersByWireValue({parameters:t.queryParameters??[],values:r.queryParameters??{}}).filter(g=>!this.context.isDirectLiteral(g.typeReference)),c=this.context.sortTypeInstancesByRequiredFirst(s,t.queryParameters??[]).map(g=>({name:this.context.getMethodName(g.name.name),value:this.context.dynamicTypeLiteralMapper.convert({typeReference:x5A(g.typeReference),value:g.value,as:"request"})}));this.context.errors.unscope(),this.context.errors.scope(Ro.Headers);let l=this.context.associateByWireValue({parameters:t.headers??[],values:r.headers??{}}).filter(g=>!this.context.isDirectLiteral(g.typeReference)),d=this.context.sortTypeInstancesByRequiredFirst(l,t.headers??[]).map(g=>({name:this.context.getMethodName(g.name.name),value:this.context.dynamicTypeLiteralMapper.convert({typeReference:g.typeReference,value:g.value,as:"request"})}));this.context.errors.unscope();let f=pr.classReference({name:this.context.getClassName(t.declaration.name),packageName:this.context.getRequestsPackageName(t.declaration.fernFilepath)});this.context.errors.scope(Ro.RequestBody);let m=t.body!=null?this.getInlinedRequestBodyBuilderParameters({body:t.body,value:r.requestBody,filePropertyInfo:i,enclosing:f}):[];return this.context.errors.unscope(),pr.TypeLiteral.builder({classReference:f,parameters:[...n,...d,...c,...m]})}getRequestOptionsArg({request:t,snippet:r}){let n="headers"in t?t.headers??[]:[];if(n.length===0||Object.keys(r.headers??{}).length===0)return;this.context.errors.scope(Ro.Headers);let i=this.context.associateByWireValue({parameters:n,values:r.headers??{}});if(this.context.errors.unscope(),i.length===0)return;let o=pr.classReference({name:"RequestOptions",packageName:this.context.getCorePackageName()}),s=pr.invokeMethod({on:o,method:"builder",arguments_:[]});for(let c of i)s=pr.invokeMethod({on:s,method:"addHeader",arguments_:[pr.TypeLiteral.string(c.name.wireValue),this.context.dynamicTypeLiteralMapper.convert(c)]});let a=pr.invokeMethod({on:s,method:"build",arguments_:[]});return pr.TypeLiteral.reference(a)}getInlinedRequestBodyBuilderParameters({body:t,value:r,filePropertyInfo:n,enclosing:i}){switch(t.type){case"properties":return this.getInlinedRequestBodyPropertyBuilderParameters({parameters:t.value,value:r,enclosing:i});case"referenced":return[this.getReferencedRequestBodyPropertyBuilderParameter({body:t,value:r})];case"fileUpload":return this.getFileUploadRequestBodyBuilderParameters({filePropertyInfo:n});default:Ee(t)}}getFileUploadRequestBodyBuilderParameters({filePropertyInfo:t}){return this.context.shouldInlineFileProperties()?[...t.bodyPropertyFields,...t.fileFields]:t.bodyPropertyFields}getReferencedRequestBodyPropertyBuilderParameter({body:t,value:r}){return{name:this.context.getMethodName(t.bodyKey),value:this.getReferencedRequestBodyPropertyTypeLiteral({body:t.bodyType,value:t.bodyType.type==="typeReference"?r??{}:r})}}getReferencedRequestBodyPropertyTypeLiteral({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return this.context.dynamicTypeLiteralMapper.convert({typeReference:t.value,value:r,as:"request"});default:Ee(t)}}getInlinedRequestBodyPropertyBuilderParameters({parameters:t,value:r,enclosing:n}){let o=this.context.associateByWireValue({parameters:t,values:this.context.getRecord(r)??{}}).filter(u=>!this.context.isDirectLiteral(u.typeReference)),s=this.context.sortTypeInstancesByRequiredFirst(o,t),a=new Set([...n.enclosingClasses,n.name]),c=new Set(t.map(u=>this.context.getClassName(u.name.name)));return s.map(u=>({name:this.context.getMethodName(u.name.name),value:this.context.dynamicTypeLiteralMapper.convert({typeReference:u.typeReference,value:u.value,as:"request",nestedClassReference:this.context.dynamicTypeLiteralMapper.resolveInlineNestedClassReference({enclosing:n,baseName:this.context.getClassName(u.name.name),typeReference:u.typeReference,reservedNames:a,siblingPropertyNames:c})})}))}getPathParameters({namedParameters:t,snippet:r}){let n=[],i=this.context.associateByWireValue({parameters:t,values:r.pathParameters??{},ignoreMissingParameters:!0});for(let o of i)n.push({name:this.context.getMethodName(o.name.name),value:this.context.dynamicTypeLiteralMapper.convert(o)});return n}getMethod({endpoint:t}){return t.declaration.fernFilepath.allParts.length>0?`${t.declaration.fernFilepath.allParts.map(r=>`${this.context.getMethodName(r)}()`).join(".")}.${this.context.getMethodName(t.declaration.name)}`:this.context.getMethodName(t.declaration.name)}getStyle(t){return t.style??this.context.options.style??S1.Full}getConfig(t){return t.config??this.context.options.config??{}}};var wcr=class extends Sx{constructor({ir:t,config:r,options:n={},inlineTypeIds:i}){super(new DFi({ir:t,config:r,options:n,inlineTypeIds:i}))}async generate(t,r={}){return super.generate(t,r)}generateSync(t,r={}){return super.generateSync(t,r)}async generateSnippetAst(t){return super.generateSnippetAst(t)}createSnippetGenerator(t){return new kFi({context:t})}};g0();Dt();var MHe=require("fs/promises"),r4p=Ae(require("path"),1);var FFi=class{context;ir;generatorConfig;inlineTypeIds;dynamicSnippetsGenerator;constructor(t,r,n,i){this.context=t,this.ir=r,this.generatorConfig=n,this.inlineTypeIds=i,this.dynamicSnippetsGenerator=new wcr({ir:BP(this.ir),config:this.generatorConfig,inlineTypeIds:this.inlineTypeIds})}async generateTests({outputDir:t,requests:r}){this.context.logger.debug("Generating dynamic snippet tests...");let n=await this.initializeProject(t);for(let[a,{endpointId:c,request:u}]of r.entries())try{let l=PP(u);if(l==null)continue;let p=await this.dynamicSnippetsGenerator.generate(l,{config:{fullStyleClassName:`Example${a}`,fullStylePackageName:"com.snippets"},style:S1.Full,endpointId:c}),d=this.getTestFilePath({absolutePathToOutputDir:n,idx:a});await(0,MHe.mkdir)(r4p.default.dirname(d),{recursive:!0}),await(0,MHe.writeFile)(d,p.snippet)}catch(l){this.context.logger.error(`Failed to generate dynamic snippet for endpoint ${JSON.stringify(u.endpoint)}: ${l}`)}let i=Byr(process.env[eLe]);this.context.logger.debug(i?`Dynamic snippets test files generated, skipping spotlessApply because ${eLe} is set`:"Dynamic snippets test files generated, running spotlessApply...");let o=ke(t,ye.of("gradlew"));if(await Ut(o,"file")&&!i)try{let c=this.generatorConfig.customConfig?.["enable-gradle-profiling"]===!0,u=[":spotlessApply"];if(c&&(u.push("--profile"),this.context.logger.info("Running spotlessApply with profiling enabled")),await Ba(this.context.logger,"./gradlew",u,{doNotPipeOutput:!1,cwd:t}),this.context.logger.debug("Successfully ran spotlessApply"),c){let l=ke(t,ye.of("build/reports")),p=ke(t,ye.of("reports"));await Ut(l,"directory")?(await(0,MHe.cp)(l,p,{recursive:!0}),this.context.logger.info("Gradle profiling report copied to reports/")):this.context.logger.info("No profiling report found in build/reports/")}}catch(a){this.context.failAndThrow("Failed to run spotlessApply",a,{code:T.Code.InternalError})}this.context.logger.debug("Done generating dynamic snippet tests")}async initializeProject(t){let r=ke(t,ye.of("src/main/java/com/snippets"));return await(0,MHe.mkdir)(r,{recursive:!0}),r}getTestFilePath({absolutePathToOutputDir:t,idx:r}){return ke(t,ye.of(`Example${r}.java`))}};tr();var n4p="self",i4p="static";var o4p=new Set(["abstract","and","array","as","break","callable","case","catch","class","clone","const","continue","declare","default","die","do","echo","else","elseif","empty","enddeclare","endfor","endforeach","endif","endswitch","endwhile","eval","exit","extends","final","finally","fn","for","foreach","function","global","goto","if","implements","include","include_once","instanceof","insteadof","interface","isset","list","match","namespace","new","or","print","private","protected","public","readonly","require","require_once","return","static","switch","throw","trait","try","unset","use","var","while","xor","yield","yield_from","__halt_compiler"]);var Pn={};te(Pn,{Access:()=>dze,Array:()=>_He,AstNode:()=>pp,Attribute:()=>UHe,Class:()=>Mbe,ClassInstantiation:()=>Lle,ClassReference:()=>w1,CodeBlock:()=>i2,DataClass:()=>LHe,Enum:()=>VHe,Field:()=>GHe,Interface:()=>qHe,Map:()=>WHe,Method:()=>Ube,MethodInvocation:()=>_be,Parameter:()=>Lbe,Trait:()=>HHe,Type:()=>QX,TypeLiteral:()=>zX,Writer:()=>Mle,array:()=>D5A,assignVariable:()=>H5A,attribute:()=>k5A,classReference:()=>z5A,class_:()=>F5A,codeblock:()=>KHe,dataClass:()=>Q5A,enum_:()=>M5A,escapePhpString:()=>wZs,field:()=>L5A,getFieldKeyDocs:()=>zFi,instantiateClass:()=>l4p,interface_:()=>j5A,invokeMethod:()=>_5A,map:()=>V5A,mergeArrays:()=>Y5A,method:()=>G5A,normalizeDocs:()=>jFi,parameter:()=>q5A,string:()=>J5A,ternary:()=>W5A,this_:()=>X5A,throwException:()=>U5A,trait:()=>N5A,variable:()=>K5A});function s4p(e){return{namespace:e.substring(0,e.lastIndexOf("\\")),name:e.substring(e.lastIndexOf("\\")+1)}}var Mle=class extends x1{namespace;rootNamespace;customConfig;references={};constructor({namespace:t,rootNamespace:r,customConfig:n}){super(),this.namespace=t,this.rootNamespace=r,this.customConfig=n}addReference(t){if(t.namespace==null)return;if(Object.keys(this.references).filter(o=>{let s=s4p(o);return s.namespace!==t.namespace&&s.name===t.name}).length>0){t.requireFullyQualified();return}let n=t.namespace===""?t.name:`${t.namespace}\\${t.name}`;(this.references[n]??=[]).push(t)}toString(t=!1){if(t)return this.buffer;let r=`namespace ${this.namespace};`,n=this.stringifyImports();return n.length>0?`${r}
|
|
4772
|
+
`)}};an();an();var X3p=Fe.strictObject({title:Fe.string(),content:Fe.string()});var yZs=Fe.object({"base-api-exception-class-name":Fe.string().optional(),"base-exception-class-name":Fe.string().optional(),"client-class-name":Fe.string().optional(),"exported-client-class-name":Fe.string().optional(),"inline-file-properties":Fe.boolean().optional(),"inline-path-parameters":Fe.boolean().optional(),"package-layout":Fe.enum(["flat","nested"]).optional(),"package-prefix":Fe.string().optional(),"respect-optional-request-body":Fe.boolean().optional(),"legacy-input-stream-upload-overloads":Fe.boolean().optional(),"use-local-date-for-dates":Fe.boolean().optional(),"custom-dependencies":Fe.array(Fe.string()).optional(),"custom-plugins":Fe.array(Fe.string()).optional(),"disable-required-property-builder-checks":Fe.boolean().optional(),"enable-forward-compatible-enums":Fe.boolean().optional(),"enable-inline-types":Fe.boolean().optional(),"enable-public-constructors":Fe.boolean().optional(),"generate-unknown-as-json-node":Fe.boolean().optional(),"json-include":Fe.enum(["non-absent","non-empty"]).optional(),"enable-extensible-builders":Fe.boolean().optional(),"use-default-request-parameter-values":Fe.boolean().optional(),"enable-wire-tests":Fe.boolean().default(!1),"wire-tests-fallback-to-autogenerated-error-examples":Fe.boolean().optional(),"collapse-optional-nullable":Fe.boolean().optional(),"use-nullable-annotation":Fe.boolean().optional(),"custom-readme-sections":Fe.array(X3p).optional(),"custom-pager-name":Fe.string().optional(),"offset-semantics":Fe.enum(["item-index","page-index"]).optional(),"default-timeout-in-seconds":Fe.number().optional(),"gradle-distribution-url":Fe.string().optional(),"gradle-plugin-management":Fe.string().optional(),"gradle-central-dependency-management":Fe.boolean().optional(),"output-directory":Fe.enum(["source-root","project-root"]).optional(),"custom-interceptors":Fe.boolean().optional(),"omit-fern-headers":Fe.boolean().optional(),includePlatformHeaders:Fe.boolean().optional(),userAgentOnly:Fe.boolean().optional(),"retry-status-codes":Fe.optional(Fe.enum(["legacy","recommended"])),"enable-gradle-profiling":Fe.boolean().optional(),"wrapped-aliases":Fe.boolean().optional(),maxRetries:Fe.number().int().min(0).optional()});var pr={};te(pr,{Access:()=>bZs,AstNode:()=>av,Class:()=>kHe,ClassInstantiation:()=>FHe,ClassReference:()=>fg,CodeBlock:()=>NHe,Method:()=>jHe,MethodInvocation:()=>zHe,Parameter:()=>QHe,Type:()=>Scr,TypeLiteral:()=>G6,Writer:()=>DHe,classReference:()=>f5A,class_:()=>p5A,codeblock:()=>l5A,instantiateClass:()=>d5A,invokeMethod:()=>m5A,method:()=>h5A,parameter:()=>g5A});var av=class extends ov{async toStringAsync({packageName:t,customConfig:r,formatter:n}){let i=new xcr({packageName:t,customConfig:r,formatter:n});return this.write(i),i.toStringAsync()}toString({packageName:t,customConfig:r,formatter:n}){let i=new xcr({packageName:t,customConfig:r,formatter:n});return this.write(i),i.toString()}};var kHe=class extends av{name;access;methods=[];constructor({name:t,access:r}){super(),this.name=t,this.access=r}write(t){if(t.write(`${this.access} class ${this.name}`),this.isEmpty()){t.writeLine(" {}");return}t.writeLine(" {"),t.indent();for(let r of this.methods)t.writeNode(r),t.newLine();t.dedent(),t.write("}")}addMethod(t){this.methods.push(t)}isEmpty(){return this.methods.length===0}};var bZs={Public:"public",Protected:"protected",Private:"private"};ct();var fg=class extends av{name;packageName;fullyQualified;enclosingClasses;constructor({name:t,packageName:r,fullyQualified:n,enclosingClasses:i}){super(),this.name=t,this.packageName=r,this.fullyQualified=n??!1,this.enclosingClasses=i??[]}write(t){let r=this.enclosingClasses[0]??this.name,n=[...this.enclosingClasses,this.name].join(".");if(this.fullyQualified){t.write(`${this.packageName}.${n}`);return}let{shouldFullyQualify:i}=t.addReference({name:r,packageName:this.packageName});if(i){t.write(`${this.packageName}.${n}`);return}t.write(n)}};ct();var Scr=class extends av{internalType;constructor(t){super(),this.internalType=t}write(t){switch(this.internalType.type){case"array":t.writeNode(this.internalType.value),t.write("[]");break;case"bigInteger":t.writeNode(GVA);break;case"boolean":t.write("Boolean");break;case"bytes":t.write("byte[]");break;case"date":t.customConfig?.["use-local-date-for-dates"]===!0?t.writeNode(HVA):t.write("String");break;case"dateTime":t.writeNode(KVA);break;case"double":t.write("Double");break;case"float":t.write("Float");break;case"generic":t.writeNode(this.internalType.value),t.write("<");for(let[r,n]of this.internalType.parameters.entries())t.writeNode(n),r<this.internalType.parameters.length-1&&t.write(", ");t.write(">");break;case"inputStream":t.writeNode(XVA);break;case"integer":t.write("Integer");break;case"iterable":this.writeIterable({writer:t,iterable:this.internalType});break;case"list":{this.writeList({writer:t,list:this.internalType});break}case"long":{t.write("Long");break}case"map":{this.writeMap({writer:t,map:this.internalType});break}case"object":{t.write("Object");break}case"optional":{this.writeOptional({writer:t,optional:this.internalType});break}case"reference":t.writeNode(this.internalType.value);break;case"set":{this.writeSet({writer:t,set:this.internalType});break}case"string":t.write("String");break;case"uuid":t.writeNode(YVA);break;case"void":t.write("Void");break;default:Ee(this.internalType)}}isOptional(){return this.internalType.type==="optional"}static array(t){return new this({type:"array",value:t})}static bigInteger(){return new this({type:"bigInteger"})}static boolean(){return new this({type:"boolean"})}static bytes(){return new this({type:"bytes"})}static date(){return new this({type:"date"})}static dateTime(){return new this({type:"dateTime"})}static double(){return new this({type:"double"})}static float(){return new this({type:"float"})}static integer(){return new this({type:"integer"})}static list(t){return new this({type:"list",value:t})}static long(){return new this({type:"long"})}static map(t,r){return new this({type:"map",keyType:t,valueType:r})}static object(){return new this({type:"object"})}static optional(t){return this.isAlreadyOptional(t)?t:new this({type:"optional",value:t})}static reference(t){return new this({type:"reference",value:t})}static generic(t,r){return new this({type:"generic",value:t,parameters:r})}static set(t){return new this({type:"set",value:t})}static string(){return new this({type:"string"})}static uuid(){return new this({type:"uuid"})}static void(){return new this({type:"void"})}static iterable(t){return new this({type:"iterable",value:t})}static inputStream(){return new this({type:"inputStream"})}writeList({writer:t,list:r}){t.writeNode(qVA),t.write("<"),r.value.write(t),t.write(">")}writeMap({writer:t,map:r}){t.writeNode(WVA),t.write("<"),r.keyType.write(t),t.write(", "),r.valueType.write(t),t.write(">")}writeOptional({writer:t,optional:r}){t.writeNode(EZs),t.write("<"),r.value.write(t),t.write(">")}writeIterable({writer:t,iterable:r}){t.writeNode(ZVA),t.write("<"),r.value.write(t),t.write(">")}writeSet({writer:t,set:r}){t.writeNode(JVA),t.write("<"),r.value.write(t),t.write(">")}static isAlreadyOptional(t){return t.internalType.type==="optional"}},wFi=new fg({name:"Arrays",packageName:"java.util"}),GVA=new fg({name:"BigInteger",packageName:"java.math"}),isP=new fg({name:"HashMap",packageName:"java.util"}),qVA=new fg({name:"List",packageName:"java.util"}),WVA=new fg({name:"Map",packageName:"java.util"}),HVA=new fg({name:"LocalDate",packageName:"java.time"}),KVA=new fg({name:"OffsetDateTime",packageName:"java.time"}),EZs=new fg({name:"Optional",packageName:"java.util"}),JVA=new fg({name:"Set",packageName:"java.util"}),YVA=new fg({name:"UUID",packageName:"java.util"}),XVA=new fg({name:"InputStream",packageName:"java.io"}),ZVA=new fg({name:"Iterable",packageName:"java.lang"});var G6=class e extends av{internalType;constructor(t){super(),this.internalType=t}write(t){switch(this.internalType.type){case"bigInteger":this.writeBigInteger({writer:t,bigInteger:this.internalType});break;case"boolean":t.write(this.internalType.value.toString());break;case"builder":this.writeBuilder({writer:t,builder:this.internalType});break;case"bytes":t.write(`"${this.internalType.value}".getBytes()`);break;case"class":{this.writeClass({writer:t,class_:this.internalType});break}case"date":this.writeDate({writer:t,date:this.internalType});break;case"dateTime":this.writeDateTime({writer:t,dateTime:this.internalType});break;case"double":{let r=this.internalType.value.toString();!r.includes(".")&&!r.includes("e")&&!r.includes("E")?t.write(`${r}.0`):t.write(r);break}case"enum":this.writeEnum({writer:t,enum_:this.internalType});break;case"float":t.write(`${this.internalType.value}f`);break;case"integer":t.write(Math.floor(this.internalType.value).toString());break;case"list":{this.writeList({writer:t,list:this.internalType});break}case"long":{t.write(`${Math.floor(this.internalType.value)}L`);break}case"map":{this.writeMap({writer:t,map:this.internalType});break}case"optional":{this.writeOptional({writer:t,optional:this.internalType});break}case"raw":{this.internalType.value instanceof av?t.writeNode(this.internalType.value):t.write(this.internalType.value);break}case"reference":t.writeNode(this.internalType.value);break;case"set":{this.writeSet({writer:t,set:this.internalType});break}case"string":t.write(`"${this.escapeString(this.internalType.value)}"`);break;case"unknown":this.writeUnknown({writer:t,value:this.internalType.value});break;case"uuid":this.writeUUID({writer:t,uuid:this.internalType});break;case"nop":break;default:Ee(this.internalType)}}isOptional(){return this.internalType.type==="optional"}static bigInteger(t){return new this({type:"bigInteger",value:t})}static boolean(t){return new this({type:"boolean",value:t})}static builder({classReference:t,parameters:r}){return new this({type:"builder",classReference:t,parameters:r})}static bytes(t){return new this({type:"bytes",value:t})}static class_({reference:t,parameters:r}){return new this({type:"class",reference:t,parameters:r})}static date(t){return new this({type:"date",value:t})}static dateTime(t){return new this({type:"dateTime",value:t})}static double(t){return new this({type:"double",value:t})}static enum_({classReference:t,value:r}){return new this({type:"enum",classReference:t,value:r})}static float(t){return new this({type:"float",value:t})}static integer(t){return new this({type:"integer",value:t})}static list({valueType:t,values:r,isParameter:n}){return new this({type:"list",valueType:t,values:r,isParameter:n})}static long(t){return new this({type:"long",value:t})}static map({keyType:t,valueType:r,entries:n}){return new this({type:"map",keyType:t,valueType:r,entries:n})}static optional({value:t,useOf:r}){return this.isAlreadyOptional(t)?t:new this({type:"optional",value:t,useOf:r})}static raw(t){return new this({type:"raw",value:t})}static reference(t){return new this({type:"reference",value:t})}static set({valueType:t,values:r}){return new this({type:"set",valueType:t,values:r})}static string(t){return new this({type:"string",value:t})}static unknown(t){return new this({type:"unknown",value:t})}static uuid(t){return new this({type:"uuid",value:t})}static nop(){return new this({type:"nop"})}static isNop(t){return t.internalType.type==="nop"}shouldWriteInLine(){switch(this.internalType.type){case"bigInteger":case"boolean":case"bytes":case"date":case"dateTime":case"double":case"enum":case"float":case"integer":case"long":case"nop":case"raw":case"string":case"unknown":case"uuid":return!0;case"optional":return this.internalType.value.shouldWriteInLine();case"builder":case"class":case"list":case"map":case"reference":case"set":return!1;default:Ee(this.internalType)}}writeBigInteger({writer:t,bigInteger:r}){t.write("new "),t.writeNode(pr.instantiateClass({classReference:$VA,arguments_:[e.string(r.value)]}))}writeBuilder({writer:t,builder:r}){t.writeNode(r.classReference),t.writeNewLineIfLastLineNot(),t.indent(),this.writeBuilderParameters({writer:t,parameters:this.orderBuilderParameters(o5A({parameters:r.parameters}))}),t.dedent()}writeBuilderParameters({writer:t,parameters:r}){t.writeLine(".builder()");for(let n of r)t.write(`.${n.name}(`),n.value.shouldWriteInLine()||t.newLine(),t.indent(),t.writeNode(n.value),t.dedent(),n.value.shouldWriteInLine()||t.newLine(),t.writeLine(")");t.writeNewLineIfLastLineNot(),t.write(".build()")}orderBuilderParameters(t){return t.some(n=>this.isRequiredBuilderParameter(n))?t.sort((n,i)=>{let o=!this.isRequiredBuilderParameter(n),s=!this.isRequiredBuilderParameter(i);return o&&!s?1:!o&&s?-1:0}):t.sort((n,i)=>{let o=n.value.isOptional(),s=i.value.isOptional();return o&&!s?1:!o&&s?-1:0})}isCollection(t){let r=t.internalType.type;return r==="list"||r==="set"||r==="map"}isRequiredBuilderParameter(t){return t.isRequired!=null?t.isRequired:!this.isNonRequired(t.value)}isNonRequired(t){return t.isOptional()||this.isCollection(t)}writeClass({writer:t,class_:r}){let n=i5A({parameters:r.parameters});t.writeNode(pr.instantiateClass({classReference:r.reference,arguments_:n.map(i=>i.value)}))}writeDate({writer:t,date:r}){t.writeNode(pr.invokeMethod({on:t5A,method:"parse",arguments_:[e.string(r.value)]}))}writeDateTime({writer:t,dateTime:r}){t.writeNode(pr.invokeMethod({on:r5A,method:"parse",arguments_:[e.string(r.value)]}))}writeEnum({writer:t,enum_:r}){t.writeNode(r.classReference),t.write("."+r.value)}writeList({writer:t,list:r}){this.writeIterable({writer:t,iterable:r})}writeMap({writer:t,map:r}){let n=s5A({entries:r.entries});if(n.length===0){t.write("new "),t.writeNode(TFi),t.write("<"),t.writeNode(r.keyType),t.write(", "),t.writeNode(r.valueType),t.write(">()");return}t.write("new "),t.writeNode(TFi),t.write("<"),t.writeNode(r.keyType),t.write(", "),t.writeNode(r.valueType),t.writeLine(">() {{"),t.indent();for(let i of n)t.write("put("),t.writeNode(i.key),t.write(", "),t.writeNode(i.value),t.writeLine(");");t.dedent(),t.write("}}")}writeOptional({writer:t,optional:r}){if(!r.useOf){t.writeNode(r.value);return}t.writeNode(pr.invokeMethod({on:EZs,method:"of",arguments_:[r.value]}))}writeSet({writer:t,set:r}){this.writeIterable({writer:t,iterable:r})}writeIterable({writer:t,iterable:r}){let n=r.type==="list"?IZs:e5A,i=a5A({values:r.values});if(r.type==="list"&&r.isParameter&&i.length>0){t.writeNode(pr.invokeMethod({on:wFi,method:"asList",arguments_:i}));return}if(i.length===0){t.write("new "),t.writeNode(n),t.write("<"),t.writeNode(r.valueType),t.write(">()");return}t.write("new "),t.writeNode(n),t.write("<"),t.writeNode(r.valueType),t.writeLine(">("),t.indent(),t.writeNode(pr.invokeMethod({on:wFi,method:"asList",arguments_:i})),t.writeNewLineIfLastLineNot(),t.dedent(),t.write(")")}writeUnknown({writer:t,value:r}){switch(typeof r){case"boolean":t.write(r.toString());return;case"string":t.write(`"${this.escapeString(r)}"`);return;case"number":t.write(r.toString());return;case"object":if(r==null){t.write("null");return}if(Array.isArray(r)){this.writeUnknownArray({writer:t,value:r});return}this.writeUnknownMap({writer:t,value:r});return;default:throw new Error(`Internal error; unsupported unknown type: ${typeof r}`)}}writeUnknownArray({writer:t,value:r}){if(r.length===0){t.write("new "),t.writeNode(IZs),t.write("<Object>()");return}t.write("new "),t.writeNode(IZs),t.write("<Object>("),t.writeNode(pr.invokeMethod({on:wFi,method:"asList",arguments_:r.map(n=>e.unknown(n))})),t.write(")")}writeUnknownMap({writer:t,value:r}){let n=Object.entries(r);if(n.length===0){t.write("new "),t.writeNode(TFi),t.write("<String, Object>()");return}t.writeLine("new "),t.writeNode(TFi),t.write("<String, Object>() {{"),t.indent();for(let[i,o]of n)t.write(`put("${i}", `),t.writeNode(e.unknown(o)),t.writeLine(");");t.dedent(),t.write("}}")}writeUUID({writer:t,uuid:r}){t.writeNode(pr.invokeMethod({on:n5A,method:"fromString",arguments_:[e.string(r.value)]}))}escapeString(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}static isAlreadyOptional(t){return t.internalType.type==="optional"}},IZs=new fg({name:"ArrayList",packageName:"java.util"}),$VA=new fg({name:"BigInteger",packageName:"java.math"}),TFi=new fg({name:"HashMap",packageName:"java.util"}),e5A=new fg({name:"HashSet",packageName:"java.util"}),psP=new fg({name:"List",packageName:"java.util"}),t5A=new fg({name:"LocalDate",packageName:"java.time"}),fsP=new fg({name:"Map",packageName:"java.util"}),r5A=new fg({name:"OffsetDateTime",packageName:"java.time"}),dsP=new fg({name:"Set",packageName:"java.util"}),n5A=new fg({name:"UUID",packageName:"java.util"});function i5A({parameters:e}){return e.filter(t=>!G6.isNop(t.value))}function o5A({parameters:e}){return e.filter(t=>!G6.isNop(t.value))}function s5A({entries:e}){return e.filter(t=>!G6.isNop(t.key)&&!G6.isNop(t.value))}function a5A({values:e}){return e.filter(t=>!G6.isNop(t))}function OFi({writer:e,arguments_:t}){let r=u5A(t);if(r.length===0){e.write("()");return}if(r.some(i=>i instanceof G6&&!i.shouldWriteInLine())){c5A({writer:e,arguments_:r});return}e.write("("),r.forEach((i,o)=>{o>0&&e.write(", "),Z3p({writer:e,argument:i})}),e.write(")")}function c5A({writer:e,arguments_:t}){e.writeLine("("),e.indent(),t.forEach((r,n)=>{n>0&&e.writeLine(","),Z3p({writer:e,argument:r})}),e.dedent(),t.length>0&&e.newLine(),e.write(")")}function Z3p({writer:e,argument:t}){Xje(t)?e.writeNodeOrString(t.assignment):t.write(e)}function u5A(e){return e.filter(t=>!(t instanceof G6&&G6.isNop(t)))}var FHe=class extends av{classReference;arguments_;constructor({classReference:t,arguments_:r}){super(),this.classReference=t,this.arguments_=r}write(t){t.writeNode(this.classReference),OFi({writer:t,arguments_:this.arguments_})}};var NHe=class extends av{arg;constructor(t){super(),this.arg=t}write(t){return new U0(this.arg).write(t)}};var jHe=class extends av{name;access;parameters;body;return_;static_;constructor({name:t,access:r,parameters:n,body:i,static_:o,return_:s}){super(),this.name=t,this.access=r,this.parameters=n,this.body=i,this.return_=s,this.static_=o??!1}write(t){if(t.write(`${this.access} `),this.static_&&t.write("static "),this.return_!=null?t.writeNode(this.return_):t.write("void"),t.write(` ${this.name}`),this.parameters.length===0)t.write("()");else if(this.parameters.length===1){if(t.write("("),this.parameters[0]==null)throw new Error("Cannot render parameter "+this.parameters[0]);t.writeNode(this.parameters[0]),t.write(")")}else t.writeLine("("),t.indent(),this.parameters.forEach((r,n)=>{n>0&&t.writeLine(", "),t.writeNode(r)}),t.dedent(),t.write(")");if(this.body==null){t.write(";");return}t.writeLine(" {"),t.indent(),t.writeNode(this.body),t.writeNewLineIfLastLineNot(),t.dedent(),t.write("}")}};var zHe=class extends av{on;method;arguments_;constructor({method:t,arguments_:r,on:n}){super(),this.on=n,this.method=t,this.arguments_=r}write(t){this.on.write(t),t.write("."),t.write(this.method),OFi({writer:t,arguments_:this.arguments_})}};var QHe=class extends av{name;type;constructor({name:t,type:r}){super(),this.name=t,this.type=r}write(t){t.writeNode(this.type),t.write(` ${this.name}`)}};function l5A(e){return new NHe(e)}function p5A(e){return new kHe(e)}function f5A(e){return new fg(e)}function d5A(e){return new FHe(e)}function m5A(e){return new zHe(e)}function h5A(e){return new jHe(e)}function g5A(e){return new QHe(e)}var A5A=new Set(["abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","final","finally","float","for","goto","if","implements","import","instanceof","int","interface","long","native","new","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","try","void","volatile","while","true","false","null","_"]);function $3p(e){return A5A.has(e.toLowerCase())}function vZs(e){return $3p(e)?"_"+e:e}Gi();ct();var PFi=class{context;constructor({context:t}){this.context=t}usesOptionalNullable(){return this.context.usesOptionalNullable()}usesNullableAnnotation(){return this.context.usesNullableAnnotation()}wrapInOptionalIfNotNop(t,r=!1,n=!1){return pr.TypeLiteral.isNop(t)?t:n?this.context.getOptionalNullableOf(t):pr.TypeLiteral.optional({value:t,useOf:r})}wrapNullableOrOptionalValue({value:t,wrapperType:r,useOf:n,propagatedCollapse:i}){return pr.TypeLiteral.isNop(t)||r==="nullable"&&this.usesNullableAnnotation()?t:i||this.usesOptionalNullable()&&r==="nullable"?this.context.getOptionalNullableOf(t):pr.TypeLiteral.optional({value:t,useOf:n})}convert(t){if(t.value===null)return this.context.isNullable(t.typeReference)?this.context.getNullableOfNull():(this.context.errors.add({severity:Qr.Critical,message:"Expected non-null value, but got null"}),pr.TypeLiteral.nop());if(t.value===void 0)return pr.TypeLiteral.nop();switch(t.typeReference.type){case"list":return this.convertList({list:t.typeReference.value,value:t.value,as:t.as,nestedClassReference:t.nestedClassReference});case"literal":return this.convertLiteral({literal:t.typeReference.value,value:t.value});case"map":return this.convertMap({map:t.typeReference,value:t.value,as:t.as,nestedClassReference:t.nestedClassReference});case"named":{let r=this.context.resolveNamedType({typeId:t.typeReference.value});return r==null?pr.TypeLiteral.nop():this.convertNamed({named:r,value:t.value,as:t.as,inUndiscriminatedUnion:t.inUndiscriminatedUnion,nestedClassReference:t.nestedClassReference})}case"nullable":case"optional":{let r=t.typeReference.type,n=t.typeReference.value;if((t.value===void 0||typeof t.value=="object"&&t.value!==null&&Object.keys(t.value).length===0&&n.type==="named")&&!(r==="nullable"&&this.usesNullableAnnotation()))return t.isCollapsedOptionalNullable||this.usesOptionalNullable()&&(r==="nullable"||n.type==="optional"||n.type==="nullable")?this.context.getOptionalNullableAbsent():pr.TypeLiteral.reference(pr.invokeMethod({on:pr.classReference({name:"Optional",packageName:"java.util"}),method:"empty",arguments_:[]}));if(this.usesOptionalNullable()&&(n.type==="optional"||n.type==="nullable"))return this.convert({typeReference:n,value:t.value,as:t.as,inUndiscriminatedUnion:t.inUndiscriminatedUnion,isCollapsedOptionalNullable:!0,nestedClassReference:t.nestedClassReference});if(n.type==="list"){let s=this.convertList({list:n.value,value:t.value,nestedClassReference:t.nestedClassReference});return this.wrapNullableOrOptionalValue({value:s,wrapperType:r,useOf:!0,propagatedCollapse:t.isCollapsedOptionalNullable===!0})}let i=this.convert({typeReference:n,value:t.value,as:t.as,inUndiscriminatedUnion:t.inUndiscriminatedUnion,nestedClassReference:t.nestedClassReference}),o=t.as==="mapValue"||t.inUndiscriminatedUnion===!0;return this.wrapNullableOrOptionalValue({value:i,wrapperType:r,useOf:o,propagatedCollapse:t.isCollapsedOptionalNullable===!0})}case"primitive":return this.convertPrimitive({primitive:t.typeReference.value,value:t.value,as:t.as});case"set":return this.convertSet({set:t.typeReference.value,value:t.value,as:t.as,nestedClassReference:t.nestedClassReference});case"unknown":return this.convertUnknown({value:t.value});default:Ee(t.typeReference)}}convertList({list:t,value:r,as:n,nestedClassReference:i}){if(!Array.isArray(r))return this.context.errors.add({severity:Qr.Critical,message:`Expected array but got: ${typeof r}`}),pr.TypeLiteral.nop();let o=t.type==="optional"||t.type==="nullable";return pr.TypeLiteral.list({valueType:this.context.dynamicTypeMapper.convert({typeReference:t}),values:r.map((s,a)=>{this.context.errors.scope({index:a});try{if(o&&(t.type==="optional"||t.type==="nullable")){let c=this.convert({typeReference:t.value,value:s,as:n,nestedClassReference:i});return this.wrapNullableOrOptionalValue({value:c,wrapperType:t.type,useOf:!0,propagatedCollapse:!1})}return this.convert({typeReference:t,value:s,as:n,nestedClassReference:i})}finally{this.context.errors.unscope()}}),isParameter:!0})}convertLiteral({literal:t,value:r}){switch(t.type){case"boolean":{let n=this.context.getValueAsBoolean({value:r});return n==null?pr.TypeLiteral.nop():pr.TypeLiteral.boolean(n)}case"string":{let n=this.context.getValueAsString({value:r});return n==null?pr.TypeLiteral.nop():pr.TypeLiteral.string(n)}default:Ee(t)}}convertSet({set:t,value:r,as:n,nestedClassReference:i}){return Array.isArray(r)?pr.TypeLiteral.set({valueType:this.context.dynamicTypeMapper.convert({typeReference:t}),values:r.map((o,s)=>{this.context.errors.scope({index:s});try{return this.convert({typeReference:t,value:o,as:n,nestedClassReference:i})}finally{this.context.errors.unscope()}})}):(this.context.errors.add({severity:Qr.Critical,message:`Expected array but got: ${typeof r}`}),pr.TypeLiteral.nop())}convertMap({map:t,value:r,as:n,nestedClassReference:i}){return typeof r!="object"||r==null?(this.context.errors.add({severity:Qr.Critical,message:`Expected object but got: ${r==null?"null":typeof r}`}),pr.TypeLiteral.nop()):pr.TypeLiteral.map({keyType:this.context.dynamicTypeMapper.convert({typeReference:t.key}),valueType:this.context.dynamicTypeMapper.convert({typeReference:t.value}),entries:Object.entries(r).map(([o,s])=>{this.context.errors.scope(o);try{return{key:this.convert({typeReference:t.key,value:o,as:"mapKey"}),value:this.convert({typeReference:t.value,value:s,as:"mapValue",nestedClassReference:i})}}finally{this.context.errors.unscope()}})})}convertNamed({named:t,value:r,as:n,inUndiscriminatedUnion:i,nestedClassReference:o}){switch(t.type){case"alias":if(t.typeReference.type==="unknown"){let s=this.convert({typeReference:t.typeReference,value:r,as:n,inUndiscriminatedUnion:i});return pr.TypeLiteral.reference(pr.invokeMethod({on:o??this.context.getJavaClassReferenceFromDeclaration({declaration:t.declaration}),method:"of",arguments_:[s]}))}return this.convert({typeReference:t.typeReference,value:r,as:n,inUndiscriminatedUnion:i,nestedClassReference:o});case"discriminatedUnion":return this.convertDiscriminatedUnion({discriminatedUnion:t,value:r,as:n,nestedClassReference:o});case"enum":return this.convertEnum({enum_:t,value:r,nestedClassReference:o});case"object":return this.convertObject({object_:t,value:r,as:n,inUndiscriminatedUnion:i,nestedClassReference:o});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r,as:n,nestedClassReference:o});default:Ee(t)}}convertDiscriminatedUnion({discriminatedUnion:t,value:r,as:n,nestedClassReference:i}){let o=i??this.context.getJavaClassReferenceFromDeclaration({declaration:t.declaration}),s=this.context.resolveDiscriminatedUnionTypeInstance({discriminatedUnion:t,value:r});if(s==null)return pr.TypeLiteral.nop();let a=s.singleDiscriminatedUnionType,c=new Set([...o.enclosingClasses,o.name]),u=new Set(Object.values(t.types).map(l=>this.context.getClassName(l.discriminantValue.name)));switch(a.type){case"samePropertiesAsObject":{let l=this.context.resolveNamedType({typeId:a.typeId});if(l==null)return pr.TypeLiteral.nop();let p=this.resolveInlineNestedClassReference({enclosing:o,baseName:this.context.getClassName(a.discriminantValue.name),typeReference:{type:"named",value:a.typeId},reservedNames:c,siblingPropertyNames:u});return pr.TypeLiteral.reference(pr.invokeMethod({on:o,method:this.context.getPropertyName(a.discriminantValue.name),arguments_:[this.convertNamed({named:l,value:s.value,as:n,nestedClassReference:p})]}))}case"singleProperty":{let l=this.context.getRecord(s.value);if(l==null)return pr.TypeLiteral.nop();try{this.context.errors.scope(a.discriminantValue.wireValue);let p="value",d=this.resolveInlineNestedClassReference({enclosing:o,baseName:this.context.getClassName(a.discriminantValue.name),typeReference:a.typeReference,reservedNames:c,siblingPropertyNames:u});return pr.TypeLiteral.reference(pr.invokeMethod({on:o,method:this.context.getPropertyName(a.discriminantValue.name),arguments_:[this.convert({typeReference:a.typeReference,value:l[p],as:n,nestedClassReference:d})]}))}finally{this.context.errors.unscope()}}case"noProperties":return pr.TypeLiteral.reference(pr.invokeMethod({on:o,method:this.context.getPropertyName(a.discriminantValue.name),arguments_:[]}));default:Ee(a)}}convertObject({object_:t,value:r,as:n,inUndiscriminatedUnion:i,nestedClassReference:o}){let s=o??this.context.getJavaClassReferenceFromDeclaration({declaration:t.declaration}),a=this.context.getRecord(r)??{},c=this.context.associateByWireValue({parameters:t.properties,values:a}),u=new Set(c.map(A=>A.name.wireValue));for(let A of t.properties)if(!u.has(A.name.wireValue)&&!this.context.isOptional(A.typeReference)){if(i===!0)throw new Error(`Required property "${A.name.wireValue}" is missing from value`);let y=this.getDefaultValueForTypeReference(A.typeReference);y!==void 0&&c.push({name:A.name,typeReference:A.typeReference,value:y})}let l=new Map,p=new Set;t.properties.forEach((A,y)=>{l.set(A.name.wireValue,y),p.add(A.name.wireValue)}),c.sort((A,y)=>(l.get(A.name.wireValue)??0)-(l.get(y.name.wireValue)??0));let d=n==="request"?c.filter(A=>!this.context.isDirectLiteral(A.typeReference)):c,f=new Set([...s.enclosingClasses,s.name]),m=new Set(t.properties.map(A=>this.context.getClassName(A.name.name))),g=[];for(let A of d){this.context.errors.scope(A.name.wireValue);try{let y=this.convert({typeReference:A.typeReference,value:A.value,as:n,inUndiscriminatedUnion:i,nestedClassReference:this.resolveInlineNestedClassReference({enclosing:s,baseName:this.context.getClassName(A.name.name),typeReference:A.typeReference,reservedNames:f,siblingPropertyNames:m})});if(pr.TypeLiteral.isNop(y)&&!this.context.isOptional(A.typeReference)){if(i===!0)throw new Error(`Required property "${A.name.wireValue}" could not be converted`);continue}g.push({name:this.context.getMethodName(A.name.name),value:y,isRequired:this.isStagedBuilderProperty(A.typeReference)})}finally{this.context.errors.unscope()}}for(let[A,y]of Object.entries(a))if(!p.has(A)&&y!==void 0){let I=this.convertToRawJavaLiteral(y);I!=null&&g.push({name:"additionalProperty",value:pr.TypeLiteral.raw(`"${this.escapeJavaString(A)}", ${I}`),isRequired:!1})}return pr.TypeLiteral.builder({classReference:s,parameters:g})}resolveInlineNestedClassReference({enclosing:t,baseName:r,typeReference:n,reservedNames:i,siblingPropertyNames:o}){if(this.context.enableInlineTypes())switch(n.type){case"optional":case"nullable":return this.resolveInlineNestedClassReference({enclosing:t,baseName:r,typeReference:n.value,reservedNames:i,siblingPropertyNames:o});case"list":case"set":return this.resolveInlineNestedClassReference({enclosing:t,baseName:`${r}Item`,typeReference:n.value,reservedNames:i,siblingPropertyNames:o});case"map":return this.resolveInlineNestedClassReference({enclosing:t,baseName:`${r}Value`,typeReference:n.value,reservedNames:i,siblingPropertyNames:o});case"named":{let s=n.value,a=this.context.resolveNamedType({typeId:s});if(a==null)return;if(a.type==="alias"&&!this.context.wrappedAliases())return this.resolveInlineNestedClassReference({enclosing:t,baseName:r,typeReference:a.typeReference,reservedNames:i,siblingPropertyNames:o});if(!this.context.isInlineType(s))return;let c=r;for(;i.has(c)||o.has(c)&&c!==r;)c=`${c}_`;return i.add(c),this.context.getNestedInlineClassReference({enclosing:t,name:c})}case"primitive":case"literal":case"unknown":return;default:Ee(n)}}resolveUndiscriminatedInlineNestedClassReference({enclosing:t,typeReference:r,reservedNames:n,unionPrefix:i}){if(this.context.enableInlineTypes())switch(r.type){case"optional":case"nullable":case"list":case"set":return this.resolveUndiscriminatedInlineNestedClassReference({enclosing:t,typeReference:r.value,reservedNames:n,unionPrefix:i});case"map":return this.resolveUndiscriminatedInlineNestedClassReference({enclosing:t,typeReference:r.value,reservedNames:n,unionPrefix:i});case"named":{let o=r.value,s=this.context.resolveNamedType({typeId:o});if(s==null)return;if(s.type==="alias"&&!this.context.wrappedAliases())return this.resolveUndiscriminatedInlineNestedClassReference({enclosing:t,typeReference:s.typeReference,reservedNames:n,unionPrefix:i});if(!this.context.isInlineType(o))return;let a=this.context.getClassName(s.declaration.name);for(a.startsWith(i)&&a!==i&&(a=a.substring(i.length));n.has(a);)a=`${a}_`;return this.context.getNestedInlineClassReference({enclosing:t,name:a})}case"primitive":case"literal":case"unknown":return;default:Ee(r)}}isStagedBuilderProperty(t){switch(t.type){case"optional":case"nullable":case"list":case"set":case"map":return!1;case"named":{let r=this.context.resolveNamedType({typeId:t.value});return r!=null&&r.type==="alias"?this.isStagedBuilderProperty(r.typeReference):!0}default:return!0}}convertToRawJavaLiteral(t){return typeof t=="string"?`"${this.escapeJavaString(t)}"`:typeof t=="number"||typeof t=="boolean"?t.toString():t===null?"null":null}escapeJavaString(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\t/g,"\\t").replace(/\r/g,"\\r")}getDefaultValueForTypeReference(t){switch(t.type){case"primitive":return this.getDefaultPrimitiveValue(t.value);case"nullable":return null;case"optional":return;case"list":case"set":return[];case"map":return{};case"named":{let r=this.context.resolveNamedType({typeId:t.value});if(r==null)return{};switch(r.type){case"enum":if(r.values.length>0){let n=r.values[0];return n?.wireValue}return;case"object":case"alias":return{};case"discriminatedUnion":case"undiscriminatedUnion":return;default:return{}}}case"literal":return t.value.value;case"unknown":return{};default:Ee(t)}}getDefaultPrimitiveValue(t){switch(t){case"STRING":return"string";case"INTEGER":case"UINT":return 1;case"LONG":case"UINT_64":return 1e6;case"FLOAT":case"DOUBLE":return 1.1;case"BOOLEAN":return!0;case"DATE":return"2024-01-15";case"DATE_TIME":return"2024-01-15T09:30:00Z";case"DATE_TIME_RFC_2822":return"Tue, 15 Jan 2024 09:30:00 +0000";case"UUID":return"d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32";case"BASE_64":return"SGVsbG8gd29ybGQh";case"BIG_INTEGER":return"123456789";default:return"string"}}convertEnum({enum_:t,value:r,nestedClassReference:n}){let i=this.getEnumValueName({enum_:t,value:r});return i==null?pr.TypeLiteral.nop():pr.TypeLiteral.enum_({classReference:n??this.context.getJavaClassReferenceFromDeclaration({declaration:t.declaration}),value:i})}getEnumValueName({enum_:t,value:r}){if(typeof r!="string"){this.context.errors.add({severity:Qr.Critical,message:`Expected enum value string, got: ${typeof r}`});return}let n=t.values.find(i=>i.wireValue===r);if(n==null){this.context.errors.add({severity:Qr.Critical,message:`An enum value named "${r}" does not exist in this context`});return}return this.context.getEnumName(n.name)}convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r,as:n,nestedClassReference:i}){let o=i??this.context.getJavaClassReferenceFromDeclaration({declaration:t.declaration}),s=this.findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r,as:n,enclosing:o});return s==null?pr.TypeLiteral.nop():pr.TypeLiteral.reference(pr.invokeMethod({on:o,method:"of",arguments_:[s.typeInstantiation]}))}findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r,as:n,enclosing:i}){let o=new Set([...i.enclosingClasses,i.name]),s=this.context.getClassName(t.declaration.name);for(let a of t.types){let c=this.context.errors.size();try{let u=this.convert({typeReference:a,value:r,as:n,inUndiscriminatedUnion:!0,nestedClassReference:this.resolveUndiscriminatedInlineNestedClassReference({enclosing:i,typeReference:a,reservedNames:new Set(o),unionPrefix:s})});if(pr.TypeLiteral.isNop(u)||this.context.errors.size()>c){this.context.errors.truncate(c);continue}return{valueTypeReference:a,typeInstantiation:u}}catch{this.context.errors.truncate(c);continue}}this.context.errors.add({severity:Qr.Critical,message:`None of the types in the undiscriminated union matched the given "${typeof r}" value`})}getUndiscriminatedUnionFieldName({typeReference:t}){switch(t.type){case"list":return this.getUndiscriminatedUnionFieldNameForList({list:t});case"literal":return this.getUndiscriminatedUnionFieldNameForLiteral({literal:t.value});case"map":return this.getUndiscriminatedUnionFieldNameForMap({map:t});case"named":{let r=this.context.resolveNamedType({typeId:t.value});return r==null?void 0:this.context.getClassName(r.declaration.name)}case"optional":return this.getUndiscriminatedUnionFieldNameForOptional({typeReference:t});case"nullable":return this.getUndiscriminatedUnionFieldNameForNullable({typeReference:t});case"primitive":return this.getUndiscriminatedUnionFieldNameForPrimitive({primitive:t.value});case"set":return this.getUndiscriminatedUnionFieldNameForSet({set:t});case"unknown":return"Unknown";default:Ee(t)}}getUndiscriminatedUnionFieldNameForList({list:t}){let r=this.getUndiscriminatedUnionFieldName({typeReference:t});if(r!=null)return`ListOf${r}`}getUndiscriminatedUnionFieldNameForMap({map:t}){let r=this.getUndiscriminatedUnionFieldName({typeReference:t.key});if(r==null)return;let n=this.getUndiscriminatedUnionFieldName({typeReference:t.value});if(n!=null)return`MapOf${r}To${n}`}getUndiscriminatedUnionFieldNameForOptional({typeReference:t}){let r=this.getUndiscriminatedUnionFieldName({typeReference:t});if(r!=null)return`Optional${r}`}getUndiscriminatedUnionFieldNameForNullable({typeReference:t}){let r=this.getUndiscriminatedUnionFieldName({typeReference:t});if(r!=null)return`Nullable${r}`}getUndiscriminatedUnionFieldNameForSet({set:t}){let r=this.getUndiscriminatedUnionFieldName({typeReference:t});if(r!=null)return`SetOf${r}`}getUndiscriminatedUnionFieldNameForLiteral({literal:t}){}getUndiscriminatedUnionFieldNameForPrimitive({primitive:t}){switch(t){case"INTEGER":case"UINT":return"Integer";case"LONG":case"UINT_64":return"Long";case"FLOAT":return"Float";case"DOUBLE":return"Double";case"BOOLEAN":return"Boolean";case"BIG_INTEGER":return"BigInteger";case"STRING":return"String";case"UUID":return"Uuid";case"DATE":return"Date";case"DATE_TIME":return"DateTime";case"DATE_TIME_RFC_2822":return"DateTimeRfc2822";case"BASE_64":return"Base64";default:Ee(t)}}convertUnknown({value:t}){return this.context.customConfig?.["generate-unknown-as-json-node"]===!0?this.convertToJsonNode({value:t}):pr.TypeLiteral.unknown(t)}convertToJsonNode({value:t}){let r=pr.classReference({name:"ObjectMappers",packageName:this.context.getCorePackageName()});return typeof t=="string"?pr.TypeLiteral.reference(pr.invokeMethod({on:pr.codeblock(n=>{n.writeNode(r),n.write(".JSON_MAPPER")}),method:"valueToTree",arguments_:[pr.TypeLiteral.string(t)]})):typeof t=="number"?pr.TypeLiteral.reference(pr.invokeMethod({on:pr.codeblock(n=>{n.writeNode(r),n.write(".JSON_MAPPER")}),method:"valueToTree",arguments_:[pr.TypeLiteral.integer(t)]})):typeof t=="boolean"?pr.TypeLiteral.reference(pr.invokeMethod({on:pr.codeblock(n=>{n.writeNode(r),n.write(".JSON_MAPPER")}),method:"valueToTree",arguments_:[pr.TypeLiteral.boolean(t)]})):t===null?pr.TypeLiteral.reference(pr.invokeMethod({on:pr.codeblock(n=>{n.writeNode(r),n.write(".JSON_MAPPER")}),method:"valueToTree",arguments_:[pr.TypeLiteral.raw(pr.codeblock("null"))]})):Array.isArray(t)?pr.TypeLiteral.reference(pr.invokeMethod({on:pr.codeblock(n=>{n.writeNode(r),n.write(".JSON_MAPPER")}),method:"valueToTree",arguments_:[pr.TypeLiteral.list({valueType:pr.Type.object(),values:t.map(n=>pr.TypeLiteral.unknown(n)),isParameter:!0})]})):typeof t=="object"&&t!==null?pr.TypeLiteral.reference(pr.invokeMethod({on:pr.codeblock(n=>{n.writeNode(r),n.write(".JSON_MAPPER")}),method:"valueToTree",arguments_:[pr.TypeLiteral.unknown(t)]})):pr.TypeLiteral.unknown(t)}convertPrimitive({primitive:t,value:r,as:n}){switch(t){case"INTEGER":case"UINT":{let i=this.getValueAsNumber({value:r,as:n});return i==null?pr.TypeLiteral.nop():pr.TypeLiteral.integer(i)}case"LONG":case"UINT_64":{let i=this.getValueAsNumber({value:r,as:n});return i==null?pr.TypeLiteral.nop():pr.TypeLiteral.long(i)}case"FLOAT":{let i=this.getValueAsNumber({value:r,as:n});return i==null?pr.TypeLiteral.nop():pr.TypeLiteral.float(i)}case"DOUBLE":{let i=this.getValueAsNumber({value:r,as:n});return i==null?pr.TypeLiteral.nop():pr.TypeLiteral.double(i)}case"BOOLEAN":{let i=this.getValueAsBoolean({value:r,as:n});return i==null?pr.TypeLiteral.nop():pr.TypeLiteral.boolean(i)}case"STRING":{let i=this.context.getValueAsString({value:r});return i==null?pr.TypeLiteral.nop():pr.TypeLiteral.string(i)}case"DATE":{let i=this.context.getValueAsString({value:r});return i==null?pr.TypeLiteral.nop():this.context.customConfig?.["use-local-date-for-dates"]===!0?pr.TypeLiteral.date(i):pr.TypeLiteral.string(i)}case"DATE_TIME":case"DATE_TIME_RFC_2822":{let i=this.context.getValueAsString({value:r});return i==null?pr.TypeLiteral.nop():pr.TypeLiteral.dateTime(i)}case"UUID":{let i=this.context.getValueAsString({value:r});return i==null?pr.TypeLiteral.nop():pr.TypeLiteral.uuid(i)}case"BASE_64":{let i=this.context.getValueAsString({value:r});return i==null?pr.TypeLiteral.nop():pr.TypeLiteral.bytes(i)}case"BIG_INTEGER":{let i=this.context.getValueAsString({value:r});return i==null?pr.TypeLiteral.nop():pr.TypeLiteral.bigInteger(i)}default:Ee(t)}}getValueAsNumber({value:t,as:r}){let n=r==="mapKey"&&typeof t=="string"?Number(t):t;return this.context.getValueAsNumber({value:n})}getValueAsBoolean({value:t,as:r}){let n=r==="mapKey"?typeof t=="string"?t==="true":t==="false"?!1:t:t;return this.context.getValueAsBoolean({value:n})}};ct();var BFi=class{context;constructor({context:t}){this.context=t}convert(t){switch(t.typeReference.type){case"list":return pr.Type.list(this.convert({typeReference:t.typeReference}));case"literal":return this.convertLiteral({literal:t.typeReference.value});case"map":return pr.Type.map(this.convert({typeReference:t.typeReference.key}),this.convert({typeReference:t.typeReference.value}));case"named":{let r=this.context.resolveNamedType({typeId:t.typeReference.value});return r==null?this.convertUnknown():this.convertNamed({named:r})}case"optional":{let r=t.typeReference.value;return this.context.usesOptionalNullable()&&(r.type==="nullable"||r.type==="optional")?pr.Type.generic(this.context.getOptionalNullableClassReference(),[this.convert({typeReference:r.value})]):pr.Type.optional(this.convert({typeReference:r}))}case"nullable":{let r=t.typeReference.value;if(this.context.usesNullableAnnotation())return this.convert({typeReference:r});if(this.context.usesOptionalNullable()){let n=r.type==="optional"||r.type==="nullable"?r.value:r;return pr.Type.generic(this.context.getOptionalNullableClassReference(),[this.convert({typeReference:n})])}return pr.Type.optional(this.convert({typeReference:r}))}case"primitive":return this.convertPrimitive({primitive:t.typeReference.value});case"set":return pr.Type.set(this.convert({typeReference:t.typeReference}));case"unknown":return this.convertUnknown();default:Ee(t.typeReference)}}convertNamed({named:t}){switch(t.type){case"alias":return this.convert({typeReference:t.typeReference});case"enum":case"discriminatedUnion":case"object":case"undiscriminatedUnion":return pr.Type.reference(pr.classReference({name:this.context.getClassName(t.declaration.name),packageName:this.context.getTypesPackageName(t.declaration.fernFilepath)}));default:Ee(t)}}convertLiteral({literal:t}){switch(t.type){case"boolean":return pr.Type.boolean();case"string":return pr.Type.string()}}convertUnknown(){return this.context.customConfig?.["generate-unknown-as-json-node"]===!0?pr.Type.reference(pr.classReference({name:"JsonNode",packageName:"com.fasterxml.jackson.databind"})):pr.Type.object()}convertPrimitive({primitive:t}){switch(t){case"INTEGER":return pr.Type.integer();case"UINT":return pr.Type.integer();case"LONG":return pr.Type.long();case"UINT_64":return pr.Type.long();case"FLOAT":return pr.Type.float();case"DOUBLE":return pr.Type.double();case"BOOLEAN":return pr.Type.boolean();case"STRING":return pr.Type.string();case"DATE":return pr.Type.date();case"DATE_TIME":case"DATE_TIME_RFC_2822":return pr.Type.dateTime();case"UUID":return pr.Type.uuid();case"BASE_64":return pr.Type.bytes();case"BIG_INTEGER":return pr.Type.bigInteger();default:Ee(t)}}};ct();var CZs="path/to/file",RFi=class{context;constructor({context:t}){this.context=t}getFilePropertyInfo({body:t,value:r}){let n={fileFields:[],bodyPropertyFields:[]},i=this.context.getRecord(r)??{};for(let o of t.properties)switch(o.type){case"file":n.fileFields.push({name:this.context.getMethodName(o.name),value:this.getSingleFileProperty({property:o,record:i})});break;case"fileArray":n.fileFields.push({name:this.context.getMethodName(o.name),value:this.getArrayFileProperty({property:o,record:i})});break;case"bodyProperty":n.bodyPropertyFields.push({name:this.context.getMethodName(o.name.name),value:this.getBodyProperty({property:o,record:i})});break;default:Ee(o)}return n}getSingleFileProperty({property:t,record:r}){let n=this.context.getSingleFileValue({property:t,record:r});return this.context.shouldInlineFileProperties()?this.context.getJavaIoFileFromString(n??CZs):n==null?this.getMissingFileArgument(t):pr.TypeLiteral.reference(this.context.getFileStreamFromString(n))}getArrayFileProperty({property:t,record:r}){let n=this.context.getFileArrayValues({property:t,record:r});if(this.context.shouldInlineFileProperties()){let i=n?.[0]??CZs;return this.context.getJavaIoFileFromString(i)}if(n==null||n.length===0)return this.getMissingFileArgument(t);for(let i of n)return pr.TypeLiteral.reference(this.context.getFileStreamFromString(i));return pr.TypeLiteral.nop()}getMissingFileArgument(t){switch(t.isOptional){case!0:return pr.TypeLiteral.reference(pr.invokeMethod({on:pr.classReference({name:"Optional",packageName:"java.util"}),method:"empty",arguments_:[]}));case!1:return this.context.getJavaIoFileFromString(CZs);default:return pr.TypeLiteral.nop()}}getBodyProperty({property:t,record:r}){let n=r[t.name.wireValue];return n==null?pr.TypeLiteral.nop():this.context.dynamicTypeLiteralMapper.convert({typeReference:t.typeReference,value:n})}};var y5A=new Set(["enum","extends","package","void","short","class","abstract","return","import","for","assert","switch"]),b5A=new Set(["getClass","notify","notifyAll","wait"]),DFi=class e extends wx{ir;customConfig;dynamicTypeMapper;dynamicTypeLiteralMapper;filePropertyMapper;inlineTypeIds;constructor({ir:t,config:r,options:n,sharedCustomConfig:i,inlineTypeIds:o}){super({ir:t,config:r,options:n}),this.ir=t,this.customConfig=i??yZs.parse(r.customConfig??{}),this.dynamicTypeMapper=new BFi({context:this}),this.dynamicTypeLiteralMapper=new PFi({context:this}),this.filePropertyMapper=new RFi({context:this}),this.inlineTypeIds=o??new Set}clone(){return new e({ir:this.ir,config:this.config,options:this.options,sharedCustomConfig:this.customConfig,inlineTypeIds:this.inlineTypeIds})}isInlineType(t){return this.inlineTypeIds.has(t)}getNestedInlineClassReference({enclosing:t,name:r}){return pr.classReference({name:r,packageName:t.packageName,enclosingClasses:[...t.enclosingClasses,t.name]})}wrappedAliases(){return this.customConfig?.["wrapped-aliases"]??!1}enableInlineTypes(){return this.customConfig?.["enable-inline-types"]??!1}getClassName(t){return this.getName(t.pascalCase.safeName)}getEnumName(t){return this.getName(t.screamingSnakeCase.safeName)}getPropertyName(t){return this.getName(t.camelCase.safeName)}getMethodName(t){let r=t.camelCase.safeName;return this.isReservedMethodName(r)?r+"_":this.getName(r)}getRootClientClassReference(){return pr.classReference({name:this.getRootClientClassNameForSnippets(),packageName:this.getRootPackageName()})}getRootClientClassName(){return this.customConfig?.["client-class-name"]??`${this.getBaseNamePrefix()}Client`}getRootClientClassNameForSnippets(){return this.customConfig?.["exported-client-class-name"]??this.getRootClientClassName()}getEnvironmentClassName(){return"Environment"}getEnvironmentTypeReferenceFromID(t){let r=this.resolveEnvironmentName(t);if(r!=null)return pr.codeblock(n=>{n.writeNode(this.getEnvironmentClassReference()),n.write("."),n.write(this.getEnumName(r))})}getEnvironmentClassReference(){return pr.classReference({name:this.getEnvironmentClassName(),packageName:this.getCorePackageName()})}getJavaClassReferenceFromDeclaration({declaration:t}){return pr.classReference({name:t.name.pascalCase.unsafeName,packageName:this.getTypesPackageName(t.fernFilepath)})}getNullableClassReference(){return pr.classReference({name:"Nullable",packageName:this.getCorePackageName()})}getNullableOfNull(){return pr.TypeLiteral.reference(pr.invokeMethod({on:this.getNullableClassReference(),method:"ofNull",arguments_:[]}))}getOptionalNullableClassReference(){return pr.classReference({name:"OptionalNullable",packageName:this.getCorePackageName()})}getOptionalNullableAbsent(){return pr.TypeLiteral.reference(pr.invokeMethod({on:this.getOptionalNullableClassReference(),method:"absent",arguments_:[]}))}getOptionalNullableOf(t){return pr.TypeLiteral.reference(pr.invokeMethod({on:this.getOptionalNullableClassReference(),method:"of",arguments_:[t]}))}getFileStreamFromString(t){return pr.TypeLiteral.reference(pr.codeblock(r=>{r.write("new "),r.writeNode(this.getFileStreamClassReference()),r.write("(new "),r.writeNode(this.getByteArrayInputStreamClassReference()),r.write("("),r.writeNode(pr.TypeLiteral.string(t)),r.write(".getBytes("),r.writeNode(this.getStandardCharsetsClassReference()),r.write(".UTF_8)))")}))}getJavaIoFileFromString(t){return pr.TypeLiteral.reference(pr.codeblock(r=>{r.write("new "),r.writeNode(this.getJavaIoFileClassReference()),r.write("("),r.writeNode(pr.TypeLiteral.string(t)),r.write(")")}))}getJavaIoFileClassReference(){return pr.classReference({name:"File",packageName:"java.io"})}getFileStreamClassReference(){return pr.classReference({name:"FileStream",packageName:this.getCorePackageName()})}getByteArrayInputStreamClassReference(){return pr.classReference({name:"ByteArrayInputStream",packageName:"java.io"})}getStandardCharsetsClassReference(){return pr.classReference({name:"StandardCharsets",packageName:"java.nio.charset"})}isPrimitive(t){switch(t.type){case"primitive":return!0;case"optional":case"nullable":return this.isPrimitive(t.value);case"named":{let r=this.resolveNamedType({typeId:t.value});if(r==null)return!1;switch(r.type){case"alias":return this.isPrimitive(r.typeReference);case"discriminatedUnion":case"undiscriminatedUnion":case"object":case"enum":return!1;default:Ee(r)}break}case"list":case"set":case"map":case"literal":case"unknown":return!1;default:Ee(t)}}isDirectLiteral(t){return t.type==="literal"}sortTypeInstancesByRequiredFirst(t,r){let n=new Map;r.forEach((s,a)=>{n.set(s.name.wireValue,a)});let i=[],o=[];for(let s of t)this.isOptional(s.typeReference)?o.push(s):i.push(s);return i.sort((s,a)=>(n.get(s.name.wireValue)??0)-(n.get(a.name.wireValue)??0)),[...i,...o]}associateByWireValue({parameters:t,values:r,ignoreMissingParameters:n}){let i=super.associateByWireValue({parameters:t,values:r,ignoreMissingParameters:n}),o=new Map;for(let a of i)o.set(a.name.wireValue,a);let s=[];for(let a of t){let c=o.get(a.name.wireValue);c!=null&&s.push(c)}return s}getRootPackageName(){let t=this.getPackagePrefixTokens();return this.joinPackageTokens(t)}getCorePackageName(){let t=this.getPackagePrefixTokens();return t.push("core"),this.joinPackageTokens(t)}getTypesPackageName(t){return this.getResourcesPackage(t,"types")}getRequestsPackageName(t){return this.getPackageLayout()==="flat"?this.getTypesPackageName(t):this.getResourcesPackage(t,"requests")}getResourcesPackage(t,r){let n=this.getPackagePrefixTokens();return this.getPackageLayout()==="flat"?t!=null&&n.push(...t.packagePath.map(i=>this.getPackageNameSegment(i))):(t!=null&&t.allParts.length>0&&n.push("resources"),t!=null&&n.push(...t.allParts.map(i=>this.getPackageNameSegment(i)))),r!=null&&n.push(r),this.joinPackageTokens(n)}getPackageName(t,r){let n=this.getPackageNameSegments(t);return n=r!=null?[...n,r]:n,[...this.getPackagePrefixTokens(),...n].join(".")}getPackageLayout(){return this.customConfig?.["package-layout"]??"nested"}shouldInlinePathParameters(){return this.customConfig?.["inline-path-parameters"]??!1}shouldInlineFileProperties(){return this.customConfig?.["inline-file-properties"]??!1}usesNullableAnnotation(){return this.customConfig?.["use-nullable-annotation"]===!0}usesOptionalNullable(){return this.customConfig?.["collapse-optional-nullable"]===!0}getPackageNameSegments(t){return t.packagePath.map(r=>this.getPackageNameSegment(r))}getPackageNameSegment(t){return t.camelCase.safeName.toLowerCase()}getPackagePrefixTokens(){if(this.customConfig?.["package-prefix"]!=null)return this.customConfig["package-prefix"].split(".");let t=[];return t.push("com"),t.push(...this.splitOnNonAlphaNumericChar(this.config.organization)),t.push(...this.splitOnNonAlphaNumericChar(this.getApiName())),t}getBaseNamePrefix(){return this.convertKebabCaseToUpperCamelCase(this.config.organization)+this.convertKebabCaseToUpperCamelCase(this.getApiName())}getApiName(){return ri(this.config.workspaceName)}startsWithNumber(t){return/^\d/.test(t)}splitOnNonAlphaNumericChar(t){return t.split(/[^a-zA-Z0-9]/)}convertKebabCaseToUpperCamelCase(t){return t.replace(/-([a-z])/g,(r,n)=>n.toUpperCase()).replace(/^[a-z]/,r=>r.toUpperCase())}joinPackageTokens(t){return t.map(n=>this.startsWithNumber(n)?"_"+n:vZs(n)).join(".")}getName(t){return this.isReservedName(t)?"_"+t:t}isReservedName(t){return y5A.has(t)}isReservedMethodName(t){return b5A.has(t)}};ct();var e4p="com.example.usage",E5A="Example",I5A="main",v5A="args",t4p="client",C5A={type:"primitive",value:"STRING"};function xZs(e){let t=e;for(;t.type==="optional"||t.type==="nullable";)t=t.value;return t}function x5A(e){if(e.type==="optional"&&e.value.type==="list"){let t=e.value.value,r=xZs(t);return r===t?e:{type:"optional",value:{type:"list",value:r}}}if(e.type==="list"){let t=xZs(e.value);return t===e.value?e:{type:"list",value:t}}return e}var kFi=class{context;formatter;constructor({context:t,formatter:r}){this.context=t,this.formatter=r}async generateSnippet({endpoint:t,request:r,options:n}){let i=this.getConfig(n);return await this.buildCodeBlock({endpoint:t,snippet:r,options:n}).toStringAsync({packageName:i.fullStylePackageName??e4p,customConfig:this.context.customConfig,formatter:this.formatter})}generateSnippetSync({endpoint:t,request:r,options:n}){let i=this.getConfig(n);return this.buildCodeBlock({endpoint:t,snippet:r,options:n}).toString({packageName:i.fullStylePackageName??e4p,customConfig:this.context.customConfig,formatter:this.formatter})}async generateSnippetAst({endpoint:t,request:r,options:n}){throw new Error("Unsupported")}buildCodeBlock({endpoint:t,snippet:r,options:n}){let i=pr.codeblock(s=>{s.writeNodeStatement(this.constructClient({endpoint:t,snippet:r})),s.newLine(),s.writeNodeStatement(this.callMethod({endpoint:t,snippet:r}))}),o=this.getStyle(n);switch(o){case S1.Concise:return i;case S1.Full:return this.buildFullCodeBlock({body:i,options:n});default:Ee(o)}}constructClient({endpoint:t,snippet:r}){let n=t.auth?.type==="oauth";return pr.codeblock(i=>{if(i.writeNode(this.context.getRootClientClassReference()),i.write(` ${t4p} = `),n&&r.auth?.type==="oauth"){let o=r.auth;i.writeNode(this.context.getRootClientClassReference()),i.write(`.withCredentials("${o.clientId}", "${o.clientSecret}")`),i.writeNewLineIfLastLineNot(),i.indent();let s=this.getRootClientBuilderArgsExcludingAuth({endpoint:t,snippet:r});for(let a of s)i.write(`.${a.name}(`),a.value.shouldWriteInLine()||i.newLine(),i.writeNode(a.value),a.value.shouldWriteInLine()||i.newLine(),i.writeLine(")");i.writeLine(".build()"),i.dedent()}else i.writeNode(pr.TypeLiteral.builder({classReference:this.context.getRootClientClassReference(),parameters:this.getRootClientBuilderArgs({endpoint:t,snippet:r})}))})}getRootClientBuilderArgsExcludingAuth({endpoint:t,snippet:r}){let n=[],i=this.getRootClientBaseUrlArg({baseUrl:r.baseURL,environment:r.environment});i!=null&&n.push(i),this.context.errors.scope(Ro.Headers),this.context.ir.headers!=null&&r.headers!=null&&n.push(...this.getRootClientHeaderArgs({headers:this.context.ir.headers,values:r.headers})),this.context.errors.unscope();let o=new Set;if([...this.context.ir.pathParameters??[],...t.request.pathParameters??[]].forEach(a=>{a.variable!=null&&o.add(a.variable)}),this.context.ir.variables!=null&&this.context.ir.variables.length>0){for(let a of this.context.ir.variables)if(o.has(a.id)){let c=a.name.camelCase.unsafeName;n.push({name:c,value:pr.TypeLiteral.string(`YOUR_${a.name.screamingSnakeCase.unsafeName}`)})}}if(this.context.errors.scope(Ro.PathParameters),this.context.ir.pathParameters!=null&&this.context.ir.pathParameters.length>0){let a=this.context.ir.pathParameters.filter(c=>c.variable==null);a.length>0&&n.push(...this.getPathParameters({namedParameters:a,snippet:r}))}return this.context.errors.unscope(),n}buildFullCodeBlock({body:t,options:r}){let n=this.getConfig(r),i=pr.class_({name:n.fullStyleClassName??E5A,access:pr.Access.Public}),o=pr.parameter({name:v5A,type:pr.Type.array(pr.Type.string())});return i.addMethod(pr.method({name:I5A,access:pr.Access.Public,static_:!0,parameters:[o],body:t})),i}getRootClientBuilderArgs({endpoint:t,snippet:r}){let n=[];t.auth!=null&&(r.auth!=null?n.push(...this.getRootClientAuthArgs({auth:t.auth,values:r.auth})):this.context.errors.add({severity:Qr.Warning,message:`Auth with ${t.auth.type} configuration is required for this endpoint`}));let i=this.getRootClientBaseUrlArg({baseUrl:r.baseURL,environment:r.environment});i!=null&&n.push(i),this.context.errors.scope(Ro.Headers),this.context.ir.headers!=null&&r.headers!=null&&n.push(...this.getRootClientHeaderArgs({headers:this.context.ir.headers,values:r.headers})),this.context.errors.unscope();let o=new Set;if([...this.context.ir.pathParameters??[],...t.request.pathParameters??[]].forEach(a=>{a.variable!=null&&o.add(a.variable)}),this.context.ir.variables!=null&&this.context.ir.variables.length>0){for(let a of this.context.ir.variables)if(o.has(a.id)){let c=a.name.camelCase.unsafeName;n.push({name:c,value:pr.TypeLiteral.string(`YOUR_${a.name.screamingSnakeCase.unsafeName}`)})}}if(this.context.errors.scope(Ro.PathParameters),this.context.ir.pathParameters!=null&&this.context.ir.pathParameters.length>0){let a=this.context.ir.pathParameters.filter(c=>c.variable==null);a.length>0&&n.push(...this.getPathParameters({namedParameters:a,snippet:r}))}return this.context.errors.unscope(),n}getRootClientBaseUrlArg({baseUrl:t,environment:r}){if(t!=null&&r!=null){this.context.errors.add({severity:Qr.Critical,message:"Cannot specify both baseUrl and environment options"});return}if(t!=null){if(this.context.ir.environments?.environments.type==="multipleBaseUrls"){this.context.errors.add({severity:Qr.Critical,message:"The Java SDK doesn't support a baseUrl when multiple URL environments are configured"});return}return{name:"url",value:pr.TypeLiteral.string(t)}}if(r!=null){if(this.context.isSingleEnvironmentID(r)){let n=this.context.getEnvironmentTypeReferenceFromID(r);if(n==null){this.context.errors.add({severity:Qr.Warning,message:`Environment ${JSON.stringify(r)} was not found`});return}return{name:"environment",value:pr.TypeLiteral.reference(n)}}if(this.context.isMultiEnvironmentValues(r))return this.context.validateMultiEnvironmentUrlValues(r)?{name:"environment",value:pr.TypeLiteral.reference(pr.instantiateClass({classReference:this.context.getEnvironmentClassReference(),arguments_:Object.values(r).map(n=>this.context.dynamicTypeLiteralMapper.convert({typeReference:C5A,value:n}))}))}:void 0}}getRootClientAuthArgs({auth:t,values:r}){if(r.type!==t.type)return this.addError(this.context.newAuthMismatchError({auth:t,values:r}).message),[];switch(t.type){case"basic":return r.type==="basic"?this.getRootClientBasicAuthArgs({auth:t,values:r}):[];case"bearer":return r.type==="bearer"?this.getRootClientBearerAuthArgs({auth:t,values:r}):[];case"header":return r.type==="header"?this.getRootClientHeaderAuthArgs({auth:t,values:r}):[];case"oauth":return r.type==="oauth"?this.getRootClientOAuthArgs({auth:t,values:r}):[];case"inferred":return this.addWarning("The Java SDK Generator does not support Inferred auth scheme yet"),[];default:Ee(t)}}addError(t){this.context.errors.add({severity:Qr.Critical,message:t})}addWarning(t){this.context.errors.add({severity:Qr.Warning,message:t})}getRootClientBasicAuthArgs({auth:t,values:r}){let n=t,i=!!n.usernameOmit,o=!!n.passwordOmit,s=[];return i||s.push(`"${r.username}"`),o||s.push(`"${r.password}"`),s.length===0?[]:[{name:"credentials",value:pr.TypeLiteral.raw(s.join(", "))}]}getRootClientBearerAuthArgs({auth:t,values:r}){return[{name:this.context.getMethodName(t.token),value:pr.TypeLiteral.string(r.token)}]}getRootClientHeaderAuthArgs({auth:t,values:r}){return[{name:this.context.getMethodName(t.header.name.name),value:this.context.dynamicTypeLiteralMapper.convert({typeReference:t.header.typeReference,value:r.value})}]}getRootClientOAuthArgs({auth:t,values:r}){return[{name:this.context.getMethodName(t.clientId),value:pr.TypeLiteral.string(r.clientId)},{name:this.context.getMethodName(t.clientSecret),value:pr.TypeLiteral.string(r.clientSecret)}]}getRootClientHeaderArgs({headers:t,values:r}){let n=[];for(let i of t){let o=r[i.name.wireValue],s=this.getRootClientHeaderArg({header:i,value:o});s!=null&&n.push({name:this.context.getMethodName(i.name.name),value:s})}return n}getRootClientHeaderArg({header:t,value:r}){let n=this.context.dynamicTypeLiteralMapper.convert({typeReference:t.typeReference,value:r});if(!pr.TypeLiteral.isNop(n))return n}callMethod({endpoint:t,snippet:r}){return pr.invokeMethod({on:pr.codeblock(t4p),method:this.getMethod({endpoint:t}),arguments_:this.getMethodArgs({endpoint:t,snippet:r})})}getMethodArgs({endpoint:t,snippet:r}){switch(t.request.type){case"inlined":return this.getMethodArgsForInlinedRequest({request:t.request,snippet:r});case"body":return this.getMethodArgsForBodyRequest({request:t.request,snippet:r});default:Ee(t.request)}}getMethodArgsForBodyRequest({request:t,snippet:r}){let n=[];this.context.errors.scope(Ro.PathParameters);let i=(t.pathParameters??[]).filter(s=>s.variable==null);i.length>0&&n.push(...this.getPathParameters({namedParameters:i,snippet:r}).map(s=>s.value)),this.context.errors.unscope(),this.context.errors.scope(Ro.RequestBody),t.body!=null&&!this.callOmitsRequestBody({request:t,snippet:r})&&n.push(this.getBodyRequestArg({body:t.body,value:r.requestBody})),this.context.errors.unscope();let o=this.getRequestOptionsArg({request:t,snippet:r});return o!=null&&n.push(o),n}callOmitsRequestBody({request:t,snippet:r}){if(this.context.customConfig?.["respect-optional-request-body"]!==!0||t.bodyRequired!==!1)return!1;let n=r.requestBody;return n==null||typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length===0}usesOptionalNullable(){return this.context.customConfig?.["collapse-optional-nullable"]===!0}getBodyRequestArg({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":{if(t.value.type==="optional"){let n=this.usesOptionalNullable()&&(t.value.value.type==="optional"||t.value.value.type==="nullable");if(r==null)return n?this.context.getOptionalNullableAbsent():pr.TypeLiteral.reference(pr.invokeMethod({on:pr.classReference({name:"Optional",packageName:"java.util"}),method:"empty",arguments_:[]}));let i=this.context.dynamicTypeLiteralMapper.convert({typeReference:t.value.value,value:r,as:"request",isCollapsedOptionalNullable:n}),o=i.toString({packageName:"com.example",customConfig:this.context.customConfig});if(o.includes("Optional.empty()")||o.includes("OptionalNullable.absent()"))return i;let s=this.context.dynamicTypeLiteralMapper.convert({typeReference:xZs(t.value),value:r,as:"request"});return n?this.context.getOptionalNullableOf(s):pr.TypeLiteral.optional({value:s,useOf:!0})}return this.context.dynamicTypeLiteralMapper.convert({typeReference:t.value,value:r,as:"request"})}default:Ee(t)}}getBytesBodyRequestArg({value:t}){return t==null?pr.TypeLiteral.bytes(""):typeof t!="string"?(this.context.errors.add({severity:Qr.Critical,message:`Expected bytes value to be a string, got ${typeof t}`}),pr.TypeLiteral.nop()):pr.TypeLiteral.bytes(t)}getMethodArgsForInlinedRequest({request:t,snippet:r}){let n=[],{inlinePathParameters:i,inlineFileProperties:o}={inlinePathParameters:this.context.shouldInlinePathParameters(),inlineFileProperties:this.context.shouldInlineFileProperties()};this.context.errors.scope(Ro.PathParameters);let s=[],a=(t.pathParameters??[]).filter(u=>u.variable==null);a.length>0&&s.push(...this.getPathParameters({namedParameters:a,snippet:r})),this.context.errors.unscope(),this.context.errors.scope(Ro.RequestBody);let c=this.getFilePropertyInfo({request:t,snippet:r});return this.context.errors.unscope(),this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:i})||n.push(...s.map(u=>u.value)),o||n.push(...c.fileFields.map(u=>pr.TypeLiteral.isNop(u.value)?pr.TypeLiteral.raw("null"):u.value)),n.push(this.getInlinedRequestArg({request:t,snippet:r,pathParameterFields:this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:i})?s:[],filePropertyInfo:c})),n}getFilePropertyInfo({request:t,snippet:r}){return t.body==null||!this.context.isFileUploadRequestBody(t.body)?{fileFields:[],bodyPropertyFields:[]}:this.context.filePropertyMapper.getFilePropertyInfo({body:t.body,value:r.requestBody})}getInlinedRequestArg({request:t,snippet:r,pathParameterFields:n,filePropertyInfo:i}){this.context.errors.scope(Ro.QueryParameters);let s=this.context.associateQueryParametersByWireValue({parameters:t.queryParameters??[],values:r.queryParameters??{}}).filter(g=>!this.context.isDirectLiteral(g.typeReference)),c=this.context.sortTypeInstancesByRequiredFirst(s,t.queryParameters??[]).map(g=>({name:this.context.getMethodName(g.name.name),value:this.context.dynamicTypeLiteralMapper.convert({typeReference:x5A(g.typeReference),value:g.value,as:"request"})}));this.context.errors.unscope(),this.context.errors.scope(Ro.Headers);let l=this.context.associateByWireValue({parameters:t.headers??[],values:r.headers??{}}).filter(g=>!this.context.isDirectLiteral(g.typeReference)),d=this.context.sortTypeInstancesByRequiredFirst(l,t.headers??[]).map(g=>({name:this.context.getMethodName(g.name.name),value:this.context.dynamicTypeLiteralMapper.convert({typeReference:g.typeReference,value:g.value,as:"request"})}));this.context.errors.unscope();let f=pr.classReference({name:this.context.getClassName(t.declaration.name),packageName:this.context.getRequestsPackageName(t.declaration.fernFilepath)});this.context.errors.scope(Ro.RequestBody);let m=t.body!=null?this.getInlinedRequestBodyBuilderParameters({body:t.body,value:r.requestBody,filePropertyInfo:i,enclosing:f}):[];return this.context.errors.unscope(),pr.TypeLiteral.builder({classReference:f,parameters:[...n,...d,...c,...m]})}getRequestOptionsArg({request:t,snippet:r}){let n="headers"in t?t.headers??[]:[];if(n.length===0||Object.keys(r.headers??{}).length===0)return;this.context.errors.scope(Ro.Headers);let i=this.context.associateByWireValue({parameters:n,values:r.headers??{}});if(this.context.errors.unscope(),i.length===0)return;let o=pr.classReference({name:"RequestOptions",packageName:this.context.getCorePackageName()}),s=pr.invokeMethod({on:o,method:"builder",arguments_:[]});for(let c of i)s=pr.invokeMethod({on:s,method:"addHeader",arguments_:[pr.TypeLiteral.string(c.name.wireValue),this.context.dynamicTypeLiteralMapper.convert(c)]});let a=pr.invokeMethod({on:s,method:"build",arguments_:[]});return pr.TypeLiteral.reference(a)}getInlinedRequestBodyBuilderParameters({body:t,value:r,filePropertyInfo:n,enclosing:i}){switch(t.type){case"properties":return this.getInlinedRequestBodyPropertyBuilderParameters({parameters:t.value,value:r,enclosing:i});case"referenced":return[this.getReferencedRequestBodyPropertyBuilderParameter({body:t,value:r})];case"fileUpload":return this.getFileUploadRequestBodyBuilderParameters({filePropertyInfo:n});default:Ee(t)}}getFileUploadRequestBodyBuilderParameters({filePropertyInfo:t}){return this.context.shouldInlineFileProperties()?[...t.bodyPropertyFields,...t.fileFields]:t.bodyPropertyFields}getReferencedRequestBodyPropertyBuilderParameter({body:t,value:r}){return{name:this.context.getMethodName(t.bodyKey),value:this.getReferencedRequestBodyPropertyTypeLiteral({body:t.bodyType,value:t.bodyType.type==="typeReference"?r??{}:r})}}getReferencedRequestBodyPropertyTypeLiteral({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return this.context.dynamicTypeLiteralMapper.convert({typeReference:t.value,value:r,as:"request"});default:Ee(t)}}getInlinedRequestBodyPropertyBuilderParameters({parameters:t,value:r,enclosing:n}){let o=this.context.associateByWireValue({parameters:t,values:this.context.getRecord(r)??{}}).filter(u=>!this.context.isDirectLiteral(u.typeReference)),s=this.context.sortTypeInstancesByRequiredFirst(o,t),a=new Set([...n.enclosingClasses,n.name]),c=new Set(t.map(u=>this.context.getClassName(u.name.name)));return s.map(u=>({name:this.context.getMethodName(u.name.name),value:this.context.dynamicTypeLiteralMapper.convert({typeReference:u.typeReference,value:u.value,as:"request",nestedClassReference:this.context.dynamicTypeLiteralMapper.resolveInlineNestedClassReference({enclosing:n,baseName:this.context.getClassName(u.name.name),typeReference:u.typeReference,reservedNames:a,siblingPropertyNames:c})})}))}getPathParameters({namedParameters:t,snippet:r}){let n=[],i=this.context.associateByWireValue({parameters:t,values:r.pathParameters??{},ignoreMissingParameters:!0});for(let o of i)n.push({name:this.context.getMethodName(o.name.name),value:this.context.dynamicTypeLiteralMapper.convert(o)});return n}getMethod({endpoint:t}){return t.declaration.fernFilepath.allParts.length>0?`${t.declaration.fernFilepath.allParts.map(r=>`${this.context.getMethodName(r)}()`).join(".")}.${this.context.getMethodName(t.declaration.name)}`:this.context.getMethodName(t.declaration.name)}getStyle(t){return t.style??this.context.options.style??S1.Full}getConfig(t){return t.config??this.context.options.config??{}}};var wcr=class extends Sx{constructor({ir:t,config:r,options:n={},inlineTypeIds:i}){super(new DFi({ir:t,config:r,options:n,inlineTypeIds:i}))}async generate(t,r={}){return super.generate(t,r)}generateSync(t,r={}){return super.generateSync(t,r)}async generateSnippetAst(t){return super.generateSnippetAst(t)}createSnippetGenerator(t){return new kFi({context:t})}};g0();Dt();var MHe=require("fs/promises"),r4p=Ae(require("path"),1);var FFi=class{context;ir;generatorConfig;inlineTypeIds;dynamicSnippetsGenerator;constructor(t,r,n,i){this.context=t,this.ir=r,this.generatorConfig=n,this.inlineTypeIds=i,this.dynamicSnippetsGenerator=new wcr({ir:BP(this.ir),config:this.generatorConfig,inlineTypeIds:this.inlineTypeIds})}async generateTests({outputDir:t,requests:r}){this.context.logger.debug("Generating dynamic snippet tests...");let n=await this.initializeProject(t);for(let[a,{endpointId:c,request:u}]of r.entries())try{let l=PP(u);if(l==null)continue;let p=await this.dynamicSnippetsGenerator.generate(l,{config:{fullStyleClassName:`Example${a}`,fullStylePackageName:"com.snippets"},style:S1.Full,endpointId:c}),d=this.getTestFilePath({absolutePathToOutputDir:n,idx:a});await(0,MHe.mkdir)(r4p.default.dirname(d),{recursive:!0}),await(0,MHe.writeFile)(d,p.snippet)}catch(l){this.context.logger.error(`Failed to generate dynamic snippet for endpoint ${JSON.stringify(u.endpoint)}: ${l}`)}let i=Byr(process.env[eLe]);this.context.logger.debug(i?`Dynamic snippets test files generated, skipping spotlessApply because ${eLe} is set`:"Dynamic snippets test files generated, running spotlessApply...");let o=ke(t,ye.of("gradlew"));if(await Ut(o,"file")&&!i)try{let c=this.generatorConfig.customConfig?.["enable-gradle-profiling"]===!0,u=[":spotlessApply"];if(c&&(u.push("--profile"),this.context.logger.info("Running spotlessApply with profiling enabled")),await Ba(this.context.logger,"./gradlew",u,{doNotPipeOutput:!1,cwd:t}),this.context.logger.debug("Successfully ran spotlessApply"),c){let l=ke(t,ye.of("build/reports")),p=ke(t,ye.of("reports"));await Ut(l,"directory")?(await(0,MHe.cp)(l,p,{recursive:!0}),this.context.logger.info("Gradle profiling report copied to reports/")):this.context.logger.info("No profiling report found in build/reports/")}}catch(a){this.context.failAndThrow("Failed to run spotlessApply",a,{code:T.Code.InternalError})}this.context.logger.debug("Done generating dynamic snippet tests")}async initializeProject(t){let r=ke(t,ye.of("src/main/java/com/snippets"));return await(0,MHe.mkdir)(r,{recursive:!0}),r}getTestFilePath({absolutePathToOutputDir:t,idx:r}){return ke(t,ye.of(`Example${r}.java`))}};tr();var n4p="self",i4p="static";var o4p=new Set(["abstract","and","array","as","break","callable","case","catch","class","clone","const","continue","declare","default","die","do","echo","else","elseif","empty","enddeclare","endfor","endforeach","endif","endswitch","endwhile","eval","exit","extends","final","finally","fn","for","foreach","function","global","goto","if","implements","include","include_once","instanceof","insteadof","interface","isset","list","match","namespace","new","or","print","private","protected","public","readonly","require","require_once","return","static","switch","throw","trait","try","unset","use","var","while","xor","yield","yield_from","__halt_compiler"]);var Pn={};te(Pn,{Access:()=>dze,Array:()=>_He,AstNode:()=>pp,Attribute:()=>UHe,Class:()=>Mbe,ClassInstantiation:()=>Lle,ClassReference:()=>w1,CodeBlock:()=>i2,DataClass:()=>LHe,Enum:()=>VHe,Field:()=>GHe,Interface:()=>qHe,Map:()=>WHe,Method:()=>Ube,MethodInvocation:()=>_be,Parameter:()=>Lbe,Trait:()=>HHe,Type:()=>QX,TypeLiteral:()=>zX,Writer:()=>Mle,array:()=>D5A,assignVariable:()=>H5A,attribute:()=>k5A,classReference:()=>z5A,class_:()=>F5A,codeblock:()=>KHe,dataClass:()=>Q5A,enum_:()=>M5A,escapePhpString:()=>wZs,field:()=>L5A,getFieldKeyDocs:()=>zFi,instantiateClass:()=>l4p,interface_:()=>j5A,invokeMethod:()=>_5A,map:()=>V5A,mergeArrays:()=>Y5A,method:()=>G5A,normalizeDocs:()=>jFi,parameter:()=>q5A,string:()=>J5A,ternary:()=>W5A,this_:()=>X5A,throwException:()=>U5A,trait:()=>N5A,variable:()=>K5A});function s4p(e){return{namespace:e.substring(0,e.lastIndexOf("\\")),name:e.substring(e.lastIndexOf("\\")+1)}}var Mle=class extends x1{namespace;rootNamespace;customConfig;references={};constructor({namespace:t,rootNamespace:r,customConfig:n}){super(),this.namespace=t,this.rootNamespace=r,this.customConfig=n}addReference(t){if(t.namespace==null)return;if(Object.keys(this.references).filter(o=>{let s=s4p(o);return s.namespace!==t.namespace&&s.name===t.name}).length>0){t.requireFullyQualified();return}let n=t.namespace===""?t.name:`${t.namespace}\\${t.name}`;(this.references[n]??=[]).push(t)}toString(t=!1){if(t)return this.buffer;let r=`namespace ${this.namespace};`,n=this.stringifyImports();return n.length>0?`${r}
|
|
4773
4773
|
|
|
4774
4774
|
${n}
|
|
4775
4775
|
|
|
@@ -5141,7 +5141,7 @@ ${r}`}function ZNi(e){let t=this,{emitParseErrors:r,...n}={...t.data("settings")
|
|
|
5141
5141
|
`),g="";return c&&(g=l.style.error(c)),[`${p} ${f} ${s}`,[m,g].filter(Boolean).join(`
|
|
5142
5142
|
`)]});var Oty=Dx((e,t)=>{let{validate:r=()=>!0}=e,n=uv(e.theme),[i,o]=Eu("idle"),[s,a]=Eu(),[c,u]=Eu(""),l=Bx({status:i,theme:n});Rx(async(g,A)=>{if(i==="idle")if(Px(g)){let y=c;o("loading");let I=await r(y);I===!0?(u(y),o("done"),t(y)):(A.write(c),a(I||"You must provide a valid value"),o("idle"))}else u(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]")}${LFt}`),i==="done"&&(d=n.style.answer(d));let m="";return s&&(m=n.style.error(s)),[[l,p,e.mask?d:f].join(" "),m]});var HKe=Ae($w(),1);var Pty={icon:{cursor:IS.pointer},style:{disabled:e=>HKe.default.dim(`- ${e}`),searchTerm:e=>HKe.default.cyan(e),description:e=>HKe.default.cyan(e),keysHelpTip:e=>e.map(([t,r])=>`${HKe.default.bold(t)} ${HKe.default.dim(r)}`).join(HKe.default.dim(" \u2022 "))},helpMode:"always"};function Bra(e){return!Kd.isSeparator(e)&&!e.disabled}function Bty(e){return e.map(t=>{if(Kd.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 Rty=Dx((e,t)=>{let{pageSize:r=7,validate:n=()=>!0}=e,i=uv(Pty,e.theme),[o,s]=Eu("loading"),[a,c]=Eu(""),[u,l]=Eu([]),[p,d]=Eu(),f=Bx({status:o,theme:i}),m=K6(()=>{let z=u.findIndex(Bra),Y=u.findLastIndex(Bra);return{first:z,last:Y}},[u]),[g=m.first,A]=Eu();AU(()=>{let z=new AbortController;return s("loading"),d(void 0),(async()=>{try{let $=await e.source(a||void 0,{signal:z.signal});z.signal.aborted||(A(void 0),d(void 0),l(Bty($)),s("idle"))}catch($){!z.signal.aborted&&$ instanceof Error&&d($.message)}})(),()=>{z.abort()}},[a]);let y=u[g];Rx(async(z,Y)=>{if(Px(z))if(y){s("loading");let $=await n(y.value);s("idle"),$===!0?(s("done"),t(y.value)):y.name===a?d($||"You must provide a valid value"):(Y.write(y.name),c(y.name))}else Y.write(a);else if(t0e(z)&&y)Y.clearLine(0),Y.write(y.name),c(y.name);else if(o!=="loading"&&(UR(z)||H6(z))){if(Y.clearLine(0),UR(z)&&g!==m.first||H6(z)&&g!==m.last){let $=UR(z)?-1:1,ee=g;do ee=(ee+$+u.length)%u.length;while(!Bra(u[ee]));A(ee)}}else c(Y.line)});let I=i.style.message(e.message,o),x;if(i.helpMode!=="never")if(e.instructions){let{pager:z,navigation:Y}=e.instructions;x=i.style.help(u.length>r?z:Y)}else x=i.style.keysHelpTip([["\u2191\u2193","navigate"],["\u23CE","select"]]);let v=VKe({items:u,active:g,renderItem({item:z,isActive:Y}){if(Kd.isSeparator(z))return` ${z.separator}`;if(z.disabled){let ae=typeof z.disabled=="string"?z.disabled:"(disabled)";return i.style.disabled(`${z.name} ${ae}`)}let $=Y?i.style.highlight:ae=>ae,ee=Y?i.icon.cursor:" ";return $(`${ee} ${z.name}`)},pageSize:r,loop:!1}),S;p?S=i.style.error(p):u.length===0&&a!==""&&o==="idle"&&(S=i.style.error("No results found"));let B;if(o==="done"&&y)return[f,I,i.style.answer(y.short)].filter(Boolean).join(" ").trimEnd();B=i.style.searchTerm(a);let R=y?.description,D=[f,I,B].filter(Boolean).join(" ").trimEnd(),O=[S??v," ",R?i.style.description(R):"",x].filter(Boolean).join(`
|
|
5143
5143
|
`).trimEnd();return[D,O]});var UFt=Ae($w(),1);var Dty={icon:{cursor:IS.pointer},style:{disabled:e=>UFt.default.dim(`- ${e}`),description:e=>UFt.default.cyan(e),keysHelpTip:e=>e.map(([t,r])=>`${UFt.default.bold(t)} ${UFt.default.dim(r)}`).join(UFt.default.dim(" \u2022 "))},helpMode:"always",indexMode:"hidden",keybindings:[]};function _Ft(e){return!Kd.isSeparator(e)&&!e.disabled}function kty(e){return e.map(t=>{if(Kd.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 Rra=Dx((e,t)=>{let{loop:r=!0,pageSize:n=7}=e,i=uv(Dty,e.theme),{keybindings:o}=i,[s,a]=Eu("idle"),c=Bx({status:s,theme:i}),u=UKe(),l=!o.includes("vim"),p=K6(()=>kty(e.choices),[e.choices]),d=K6(()=>{let R=p.findIndex(_Ft),D=p.findLastIndex(_Ft);if(R===-1)throw new Yle("[select prompt] No selectable choices. All choices are disabled.");return{first:R,last:D}},[p]),f=K6(()=>"default"in e?p.findIndex(R=>_Ft(R)&&R.value===e.default):-1,[e.default,p]),[m,g]=Eu(f===-1?d.first:f),A=p[m];Rx((R,D)=>{if(clearTimeout(u.current),Px(R))a("done"),t(A.value);else if(UR(R,o)||H6(R,o)){if(D.clearLine(0),r||UR(R,o)&&m!==d.first||H6(R,o)&&m!==d.last){let O=UR(R,o)?-1:1,z=m;do z=(z+O+p.length)%p.length;while(!_Ft(p[z]));g(z)}}else if(Qur(R)&&!Number.isNaN(Number(D.line))){let O=Number(D.line)-1,z=-1,Y=p.findIndex(ee=>Kd.isSeparator(ee)?!1:(z++,z===O)),$=p[Y];$!=null&&_Ft($)&&g(Y),u.current=setTimeout(()=>{D.clearLine(0)},700)}else if(MKe(R))D.clearLine(0);else if(l){let O=D.line.toLowerCase(),z=p.findIndex(Y=>Kd.isSeparator(Y)||!_Ft(Y)?!1:Y.name.toLowerCase().startsWith(O));z!==-1&&g(z),u.current=setTimeout(()=>{D.clearLine(0)},700)}}),AU(()=>()=>{clearTimeout(u.current)},[]);let y=i.style.message(e.message,s),I;if(i.helpMode!=="never")if(e.instructions){let{pager:R,navigation:D}=e.instructions;I=i.style.help(p.length>n?R:D)}else I=i.style.keysHelpTip([["\u2191\u2193","navigate"],["\u23CE","select"]]);let x=0,v=VKe({items:p,active:m,renderItem({item:R,isActive:D,index:O}){if(Kd.isSeparator(R))return x++,` ${R.separator}`;let z=i.indexMode==="number"?`${O+1-x}. `:"";if(R.disabled){let ee=typeof R.disabled=="string"?R.disabled:"(disabled)";return i.style.disabled(`${z}${R.name} ${ee}`)}let Y=D?i.style.highlight:ee=>ee,$=D?i.icon.cursor:" ";return Y(`${$} ${z}${R.name}`)},pageSize:n,loop:r});if(s==="done")return[c,y,i.style.answer(A.short)].filter(Boolean).join(" ");let{description:S}=A;return`${[[c,y].filter(Boolean).join(" "),v," ",S?i.style.description(S):"",I].filter(Boolean).join(`
|
|
5144
|
-
`).trimEnd()}${LFt}`});On();Gi();var Xle={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"},Fty={[Xle.GENERATION_STARTED]:!1,[Xle.GENERATION_COMPLETED]:!1,[Xle.GENERATION_FAILED]:!0,[Xle.VERIFICATION_FAILED]:!0,[Xle.SDK_PR_CREATED]:!1,[Xle.UPGRADE_APPLIED]:!1,[Xle.MAJOR_VERSION_BUMP]:!1};function L7p(e){return Fty[e]}function _7p(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 U7p(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 V7p(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 G7p(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 q7p(e){let t=e.join(" ");return/\bautomations\s+generate\b/.test(t)?Xle.GENERATION_FAILED:/\bautomations\s+preview\b/.test(t)?Xle.VERIFICATION_FAILED:Xle.GENERATION_FAILED}var Nty="",jty="FERN_AUTOMATION_EVENTS_ORIGIN",zty=3e3,Fji=class e{static instance;origin;inflight=[];static getInstance(){return e.instance==null&&(e.instance=new e(process.env[jty]??Nty)),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(),zty);try{let s={"content-type":"application/json"},a=await CM();a!=null&&a.value.length>0&&(s.Authorization=`Bearer ${a.value}`);let c=await fetch(n,{method:"POST",headers:s,body:JSON.stringify(G7p(t,r)),signal:i.signal})}catch{return}finally{clearTimeout(o)}}};function W7p(){let{fern_run_id:e,github_run_id:t}=Dpe();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.172.
|
|
5144
|
+
`).trimEnd()}${LFt}`});On();Gi();var Xle={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"},Fty={[Xle.GENERATION_STARTED]:!1,[Xle.GENERATION_COMPLETED]:!1,[Xle.GENERATION_FAILED]:!0,[Xle.VERIFICATION_FAILED]:!0,[Xle.SDK_PR_CREATED]:!1,[Xle.UPGRADE_APPLIED]:!1,[Xle.MAJOR_VERSION_BUMP]:!1};function L7p(e){return Fty[e]}function _7p(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 U7p(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 V7p(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 G7p(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 q7p(e){let t=e.join(" ");return/\bautomations\s+generate\b/.test(t)?Xle.GENERATION_FAILED:/\bautomations\s+preview\b/.test(t)?Xle.VERIFICATION_FAILED:Xle.GENERATION_FAILED}var Nty="",jty="FERN_AUTOMATION_EVENTS_ORIGIN",zty=3e3,Fji=class e{static instance;origin;inflight=[];static getInstance(){return e.instance==null&&(e.instance=new e(process.env[jty]??Nty)),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(),zty);try{let s={"content-type":"application/json"},a=await CM();a!=null&&a.value.length>0&&(s.Authorization=`Bearer ${a.value}`);let c=await fetch(n,{method:"POST",headers:s,body:JSON.stringify(G7p(t,r)),signal:i.signal})}catch{return}finally{clearTimeout(o)}}};function W7p(){let{fern_run_id:e,github_run_id:t}=Dpe();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.172.1"}}function H7p(){return process.env.FERN_AUTOMATION==="true"}var Qty=3e3,Nji=class{constructor(t,r=Fji.getInstance()){this.reporter=t;this.automationEventApiClient=r;this.context=W7p()}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,Qty)})])}finally{clearTimeout(t)}}capturePostHogEvent({event:t,context:r}){this.reporter.instrumentPostHogAutomationEvent({distinctId:r.run_id??void 0,event:t.event,properties:_7p(t,r)})}captureSentryForFailure({event:t,context:r,error:n}){if(!(!L7p(t.event)||t.errorCode==null))return this.reporter.captureException(n,{tags:U7p(t,r),context:{automation:V7p(t,r)}})}captureAutomationEventApiEvent(t,r){this.automationEventApiClient.post(t,r)}};Dt();function jji(e,t,r){if(t instanceof Ac)return;let n=_Me(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});H7p()?Lty(i,e,n,s,a):Mty(e,o,n,a)}function Mty(e,t,r,n){e.instrumentPostHogEvent({command:t,properties:{failed:!0,errorCode:r}}),EQt(r)&&e.captureException(n,{tags:{"error.code":r}})}function Lty(e,t,r,n,i){let o=q7p(e);t.emitAutomationTelemetryEvent({event:o,errorCode:r,attributes:{error_message:n}},{error:i})}Dt();function KKe(){return process.env.FERN_DISABLE_TELEMETRY==="true"}function zji({cliName:e,packageVersion:t,isLocal:r}){return KKe()||r?!1:!(t==="0.0.0")&&(e==="fern"&&!0)}var Qji=class{sentry;constructor({release:t,telemetry:r}){let n="https://84f58b5e457f06999d92f11ce4b79158@o4509504076185600.ingest.us.sentry.io/4511021546602496";if(zji(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=fQt({dsn:n,release:t,environment:i,defaultIntegrations:!1,integrations:[HYe(),uEe(),lEe(),H0e(),cEe()],tracesSampleRate:0,attachStacktrace:!0,sendClientReports:!1}),dQt()}}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):GP(a=>{if(o&&a.setTags(n),i!=null)for(let[c,u]of Object.entries(i))u!=null&&a.setContext(c,u);return this.sentry?.captureException(t,void 0,a)})}catch{return}}async flush(){this.sentry!=null&&await Promise.resolve(this.sentry.flush(2e3)).catch(()=>{})}};Dt();var Mji=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()}}};Kme();ct();qy();Dt();On();var Uur=class{result=Pf.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:u}){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=u}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 Ac(t??(r instanceof Ac?r.failureMessage:this.lastFailureMessage))}failWithoutThrowing(t,r,n){this.result=Pf.Failure,!(r instanceof Ac)&&(t!=null&&(this.lastFailureMessage=t),mqt({message:t,error:r,logger:this.logger}),jji(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=aI(this.logAtLevel.bind(this));addInteractiveTask({name:t,subtitle:r}){let n=new Dra({name:t,subtitle:r,logImmediately:i=>this.logImmediately(i),logPrefix:`${this.logPrefix}${de.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()===Pf.Success;return i||(this.lastFailureMessage=n.getLastFailureMessage()??this.lastFailureMessage),i}printInteractiveTasks({spinner:t}){return this.subtasks.map(r=>r.print({spinner:t})).join(`
|
|
5145
5145
|
`)}},Dra=class extends Uur{name;subtitle;constructor({name:t,subtitle:r,...n}){super(n),this.name=t,this.subtitle=r}start(){return super.start(),this.logAtLevelWithOverrides(Zn.Info,["Started."],{omitOnTTY:!0}),this.flushLogs(),this}isStarted(){return this.status!=="notStarted"}finish(){this.status!=="finished"&&(this.result===Pf.Success?this.logAtLevelWithOverrides(Zn.Info,["Finished."],{omitOnTTY:!0}):this.logAtLevelWithOverrides(Zn.Error,["Failed."],{omitOnTTY:!0}),super.finish())}setSubtitle(t){this.subtitle=t}print({spinner:t}){let r=[this.name];return this.subtitle!=null&&r.push(de.dim(this.subtitle)),r.push(...this.subtasks.map(n=>n.print({spinner:t}))),Hz({prefix:this.getIcon({spinner:t}),content:r.join(`
|
|
5146
5146
|
`)})}printInteractiveTasks({spinner:t}){return this.print({spinner:t})}getIcon({spinner:t}){let r=this.subtasks.length>0;switch(this.status){case"notStarted":return r?de.dim("\u25B8 "):de.dim("\u25E6 ");case"running":return r?de.cyan("\u25BE "):t;case"finished":switch(this.getResult()){case Pf.Success:return r?de.green("\u25BE "):de.green("\u2713 ");case Pf.Failure:return r?de.red("\u25BE "):de.red("x ")}}}getResult(){if(this.result===Pf.Failure)return Pf.Failure;for(let t of this.subtasks)if(t.getResult()===Pf.Failure)return Pf.Failure;return Pf.Success}};Dt();var K7p=Ae(L_e(),1);On();function J7p(e){return e.filter(t=>t.isUpgradeAvailable).length>0}function _ty(e){return(e.cliUpgradeInfo?.isUpgradeAvailable??!1)||J7p(e.generatorUpgradeInfo)}async function Y7p({cliEnvironment:e,upgradeInfo:t}){if(!_ty(t)||e.packageVersion==t.cliUpgradeInfo?.latestVersion)return;let r=`${de.underline("Upgrades available")}
|
|
5147
5147
|
|
|
@@ -5150,7 +5150,7 @@ ${r}`}function ZNi(e){let t=this,{emitParseErrors:r,...n}={...t.data("settings")
|
|
|
5150
5150
|
Run ${de.cyan("fern generator upgrade")} to upgrade your generators.`),i.length>2&&(r+=`
|
|
5151
5151
|
Run ${de.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),Lft(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function kra({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:n=!0}){if(!J7p(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+=`
|
|
5152
5152
|
${await Uty(a.generatorName)} (${a.apiName!=null?"API: "+a.apiName+", ":""}Group: ${a.generatorGroup}) `+de.dim(a.currentVersion)+de.reset(" \u2192 ")+de.green(a.latestVersion);return i+=`
|
|
5153
|
-
`,n?Lft(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function Uty(e){let r=await new K7p.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}li();ihe();Dt();var Vur=Ae(Vy(),1);function VFt(e){let t;return()=>(t??=e.runTask(r=>Ff(r)),t)}function Lji({generatorId:e,candidateVersion:t,currentVersion:r}){if(!X7p(t)||!X7p(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:Kw(t,r)?1:Kw(r,t)?-1:0}catch{let n=Vur.default.valid(t),i=Vur.default.valid(r);if(n!=null&&i!=null)return Math.sign(Vur.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 X7p(e){if(e==="latest"||Vur.default.valid(e)!=null)return!0;try{return pJ(e),!0}catch{return!1}}async function _ji({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 ${_rr} feature flag is off for this organization.`);let a=QTt();if(a==null)throw new Error("FERN_SDK_GEN_API_ORIGIN is required when sdk-gen-api generation is enabled");let c=Kv(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 u=await o(),l=await aCs({origin:a,organization:i,token:u,generatorId:e,language:c,currentVersion:t,includeMajor:r});return l.state==="UNAVAILABLE"?(s.logger.error(`SDK Gen API cannot resolve an executable version for ${e}@${t} (${l.reason}). Publish the coordinate to this environment or choose a supported generator version.`),{}):{compatibleVersion:l.compatibleVersion,withheldMajorVersion:l.withheldMajorVersion}}async function Vty({cliContext:e,project:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s}){let{apiWorkspaces:a}=t,c=VFt(e);if(a.length===1){let l={type:"singleApi",versions:{}};return await Z7p({cliContext:e,apiWorkspaces:a,perGeneratorAction:async(p,d,f,m)=>{l.versions[d]==null&&(l.versions[d]={});let g=B_e(f.name);if(g==null){m.logger.debug(`Skipping unknown generator: ${f.name}`);return}let A=await eHp({generatorName:f.name,normalizedGeneratorName:g,cliVersion:e.environment.packageVersion,currentGeneratorVersion:f.version,channel:i,includeMajor:o,organization:t.config.organization,skipFeatureFlagRequest:s,getSdkGenApiToken:c,context:m});A!=null&&(l.versions[d][f.name]={previousVersion:f.version,latestVersion:A})},generatorFilter:r,groupFilter:n}),l}let u={type:"multiApi",versions:{}};return await Z7p({cliContext:e,apiWorkspaces:a,perGeneratorAction:async(l,p,d,f)=>{if(l==null)return;u.versions[l]==null&&(u.versions[l]={}),u.versions[l][p]==null&&(u.versions[l][p]={});let m=B_e(d.name);if(m==null){f.logger.debug(`Skipping unknown generator: ${d.name}`);return}let g=await eHp({generatorName:d.name,normalizedGeneratorName:m,cliVersion:e.environment.packageVersion,currentGeneratorVersion:d.version,channel:i,includeMajor:o,organization:t.config.organization,skipFeatureFlagRequest:s,getSdkGenApiToken:c,context:f});g!=null&&(u.versions[l][p][d.name]={previousVersion:d.version,latestVersion:g})},generatorFilter:r,groupFilter:n}),u}async function Z7p({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 g4({absolutePathToWorkspace:o.absoluteFilePath,context:s});if(a==null||a.groups==null)return;let c=n!=null?rg(n):void 0;for(let u of a.groups)if(!(i!=null&&u.groupName!==i))for(let l of u.generators)c!=null&&l.name!==c||await r(o.workspaceName,u.groupName,l,s)})}))}function $7p(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=Lji({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 eHp({generatorName:e,normalizedGeneratorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,organization:s,skipFeatureFlagRequest:a,getSdkGenApiToken:c,context:u}){return n==="latest"?"latest":await Gty({organization:s,generatorName:rg(e),skipFeatureFlagRequest:a})?(await _ji({generatorId:rg(e),currentVersion:n,includeMajor:o??!1,channel:i,organization:s,getToken:c,context:u})).compatibleVersion:VB({generatorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,context:u})}async function Uji({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s}){let a=[];if(e!=null){let c=await Vty({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s});if(c.type==="multiApi")for(let[u,l]of Object.entries(c.versions))a.push(...$7p(l,u,t.logger));else a.push(...$7p(c.versions,void 0,t.logger))}return a}async function Gty({organization:e,generatorName:t,skipFeatureFlagRequest:r}){return r===!0?LPs({organization:e,generatorName:t})??!1:jTt({organization:e,generatorName:t})}ct();Dt();Yjr();async function r0e({cliEnvironment:e,includePreReleases:t=!1}){if(e.packageName!=="fern-api"||e.packageVersion==="0.0.0")return e.packageVersion;try{return await D6e(e.packageName,{version:t?"prerelease":"latest"})}catch(r){throw new T({message:`Failed to resolve latest CLI version: ${Yi(r)}`,code:T.Code.NetworkError})}}var tHp=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],Vji=class e{environment;sentryClient;posthogManager;automationTelemetryManager;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Zn.Info;isLocal;stdoutRedirector=new Mji;jsonMode=!1;static async create(t,r,{isLocal:n}){let i=await PKt();return new e(t,r,{isLocal:n,posthogManager:i})}constructor(t,r,{isLocal:n,posthogManager:i}){this.ttyAwareLogger=new Bqt(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 Qji({release:`cli@${this.environment.packageVersion}`,telemetry:{cliName:this.environment.cliName,packageVersion:this.environment.packageVersion,isLocal:this.isLocal}}),this.automationTelemetryManager=new Nji(this)}getPackageName(){return"fern-api"}getPackageVersion(){return"5.172.
|
|
5153
|
+
`,n?Lft(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function Uty(e){let r=await new K7p.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}li();ihe();Dt();var Vur=Ae(Vy(),1);function VFt(e){let t;return()=>(t??=e.runTask(r=>Ff(r)),t)}function Lji({generatorId:e,candidateVersion:t,currentVersion:r}){if(!X7p(t)||!X7p(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:Kw(t,r)?1:Kw(r,t)?-1:0}catch{let n=Vur.default.valid(t),i=Vur.default.valid(r);if(n!=null&&i!=null)return Math.sign(Vur.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 X7p(e){if(e==="latest"||Vur.default.valid(e)!=null)return!0;try{return pJ(e),!0}catch{return!1}}async function _ji({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 ${_rr} feature flag is off for this organization.`);let a=QTt();if(a==null)throw new Error("FERN_SDK_GEN_API_ORIGIN is required when sdk-gen-api generation is enabled");let c=Kv(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 u=await o(),l=await aCs({origin:a,organization:i,token:u,generatorId:e,language:c,currentVersion:t,includeMajor:r});return l.state==="UNAVAILABLE"?(s.logger.error(`SDK Gen API cannot resolve an executable version for ${e}@${t} (${l.reason}). Publish the coordinate to this environment or choose a supported generator version.`),{}):{compatibleVersion:l.compatibleVersion,withheldMajorVersion:l.withheldMajorVersion}}async function Vty({cliContext:e,project:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s}){let{apiWorkspaces:a}=t,c=VFt(e);if(a.length===1){let l={type:"singleApi",versions:{}};return await Z7p({cliContext:e,apiWorkspaces:a,perGeneratorAction:async(p,d,f,m)=>{l.versions[d]==null&&(l.versions[d]={});let g=B_e(f.name);if(g==null){m.logger.debug(`Skipping unknown generator: ${f.name}`);return}let A=await eHp({generatorName:f.name,normalizedGeneratorName:g,cliVersion:e.environment.packageVersion,currentGeneratorVersion:f.version,channel:i,includeMajor:o,organization:t.config.organization,skipFeatureFlagRequest:s,getSdkGenApiToken:c,context:m});A!=null&&(l.versions[d][f.name]={previousVersion:f.version,latestVersion:A})},generatorFilter:r,groupFilter:n}),l}let u={type:"multiApi",versions:{}};return await Z7p({cliContext:e,apiWorkspaces:a,perGeneratorAction:async(l,p,d,f)=>{if(l==null)return;u.versions[l]==null&&(u.versions[l]={}),u.versions[l][p]==null&&(u.versions[l][p]={});let m=B_e(d.name);if(m==null){f.logger.debug(`Skipping unknown generator: ${d.name}`);return}let g=await eHp({generatorName:d.name,normalizedGeneratorName:m,cliVersion:e.environment.packageVersion,currentGeneratorVersion:d.version,channel:i,includeMajor:o,organization:t.config.organization,skipFeatureFlagRequest:s,getSdkGenApiToken:c,context:f});g!=null&&(u.versions[l][p][d.name]={previousVersion:d.version,latestVersion:g})},generatorFilter:r,groupFilter:n}),u}async function Z7p({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 g4({absolutePathToWorkspace:o.absoluteFilePath,context:s});if(a==null||a.groups==null)return;let c=n!=null?rg(n):void 0;for(let u of a.groups)if(!(i!=null&&u.groupName!==i))for(let l of u.generators)c!=null&&l.name!==c||await r(o.workspaceName,u.groupName,l,s)})}))}function $7p(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=Lji({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 eHp({generatorName:e,normalizedGeneratorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,organization:s,skipFeatureFlagRequest:a,getSdkGenApiToken:c,context:u}){return n==="latest"?"latest":await Gty({organization:s,generatorName:rg(e),skipFeatureFlagRequest:a})?(await _ji({generatorId:rg(e),currentVersion:n,includeMajor:o??!1,channel:i,organization:s,getToken:c,context:u})).compatibleVersion:VB({generatorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,context:u})}async function Uji({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s}){let a=[];if(e!=null){let c=await Vty({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s});if(c.type==="multiApi")for(let[u,l]of Object.entries(c.versions))a.push(...$7p(l,u,t.logger));else a.push(...$7p(c.versions,void 0,t.logger))}return a}async function Gty({organization:e,generatorName:t,skipFeatureFlagRequest:r}){return r===!0?LPs({organization:e,generatorName:t})??!1:jTt({organization:e,generatorName:t})}ct();Dt();Yjr();async function r0e({cliEnvironment:e,includePreReleases:t=!1}){if(e.packageName!=="fern-api"||e.packageVersion==="0.0.0")return e.packageVersion;try{return await D6e(e.packageName,{version:t?"prerelease":"latest"})}catch(r){throw new T({message:`Failed to resolve latest CLI version: ${Yi(r)}`,code:T.Code.NetworkError})}}var tHp=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],Vji=class e{environment;sentryClient;posthogManager;automationTelemetryManager;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Zn.Info;isLocal;stdoutRedirector=new Mji;jsonMode=!1;static async create(t,r,{isLocal:n}){let i=await PKt();return new e(t,r,{isLocal:n,posthogManager:i})}constructor(t,r,{isLocal:n,posthogManager:i}){this.ttyAwareLogger=new Bqt(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 Qji({release:`cli@${this.environment.packageVersion}`,telemetry:{cliName:this.environment.cliName,packageVersion:this.environment.packageVersion,isLocal:this.isLocal}}),this.automationTelemetryManager=new Nji(this)}getPackageName(){return"fern-api"}getPackageVersion(){return"5.172.1"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${de.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r,n){throw this.failWithoutThrowing(t,r,n),new Ac(t??(r instanceof Ac?r.failureMessage:r!=null?Sn(r):void 0))}failWithoutThrowing(t,r,n){this.didSucceed=!1,!(r instanceof Ac)&&(mqt({message:t,error:r,logger:this.logger}),jji(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)+`
|
|
5154
5154
|
`)}writeTextToStdout(t){this.stdoutRedirector.restore(),process.stdout.write(t),this.jsonMode&&this.stdoutRedirector.redirect()}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish();try{await Promise.all([this.posthogManager.flush(),CZo()])}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 Y7p({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
5155
5155
|
`)||(r+=`
|
|
5156
5156
|
`),this.stderr.info(r))}catch{}}async exitIfFailed(){this.didSucceed||await this.exit()}exitProgram({code:t}={}){process.exit(t??(this.didSucceed?0:1))}longestWorkspaceName;registerWorkspaces(t){let r=Zqi(t.map(n=>n.type==="docs"?"docs":n.workspaceName??"api"),n=>n.length);r!=null&&(this.longestWorkspaceName=r)}project;registerProject(t){this.project=t,this.automationTelemetryManager.setOrganization(t.config.organization)}runTask(t){return this.runTaskWithInit(this.constructTaskInit(),t)}addTask(){return this.addTaskWithInit(this.constructTaskInit())}async runTaskForWorkspace(t,r){await this.runTaskWithInit(this.constructTaskInitForWorkspace(t),r)}addTaskWithInit(t){let r=new Uur(t);return this.ttyAwareLogger.registerTask(r),r}USE_NODE_18_OR_ABOVE_MESSAGE="The Fern CLI requires Node 18+ or above.";async runTaskWithInit(t,r){let n=this.addTaskWithInit(t).start(),i;try{i=await r(n)}catch(o){let s=o instanceof Ac?o.failureMessage??n.getLastFailureMessage():Sn(o);throw n.failWithoutThrowing(void 0,o),new Ac(s)}finally{n.finish()}return i}instrumentPostHogEvent(t){this.isLocal||this.posthogManager.sendEvent(t)}instrumentPostHogAutomationEvent(t){this.isLocal||this.posthogManager.sendAutomationEvent(t)}captureException(t,r){return this.sentryClient.captureException(t,r)}emitAutomationTelemetryEvent(t,r){this.automationTelemetryManager.emit(t,r)}logger=aI((t,...r)=>this.log(t,...r));stderr=aI((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=t.type==="docs"?"docs":t.workspaceName??"api",n=rHp(r),i=1+(this.longestWorkspaceName!=null?rHp(this.longestWorkspaceName):n).length,o=n.padEnd(i),s=tHp[this.numTasks++%tHp.length],a=de.hex(s)(o);return{...this.constructTaskInit(),logPrefix:a,title:de.hex(s).bold(r)}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===Pf.Failure&&(this.didSucceed=!1)},instrumentPostHogEvent:t=>{this.instrumentPostHogEvent(t)},shouldBufferLogs:!1,captureException:(t,r)=>this.sentryClient.captureException(t,r),emitAutomationTelemetryEvent:(t,r)=>this.emitAutomationTelemetryEvent(t,r)}}log(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}])}logStderr(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}],{stderr:!0})}logImmediately(t,{stderr:r=!1}={}){let n=t.filter(i=>Aw.indexOf(i.level)>=Aw.indexOf(this.logLevel));this.ttyAwareLogger.log(n,{includeDebugInfo:this.logLevel===Zn.Debug,stderr:r||this.jsonMode})}_suppressUpgradeMessage=!1;suppressUpgradeMessage(){this._suppressUpgradeMessage=!0}_isUpgradeAvailable;async isUpgradeAvailable({includePreReleases:t=!1,skipFeatureFlagRequest:r=!1}={}){if(this._isUpgradeAvailable==null){this.logger.debug(`Checking if ${this.environment.packageName} upgrade is available...`);let n=await r0e({cliEnvironment:this.environment,includePreReleases:t}),i=Kw(n,this.environment.packageVersion);this.logger.debug(`Latest version: ${n}. `+(i?"Upgrade available.":"No upgrade available."));let o={isUpgradeAvailable:i,latestVersion:n},s=await Uji({project:this.project,cliContext:this,skipFeatureFlagRequest:r});this._isUpgradeAvailable={cliUpgradeInfo:o,generatorUpgradeInfo:s}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){return this.selectPrompt({message:t,choices:[{name:"No",value:!1},{name:"Yes",value:!0}],default:r})}async selectPrompt({message:t,choices:r,default:n}){try{return await Rra({message:t,choices:r,default:n,theme:{prefix:de.yellow("?"),style:{answer:i=>de.cyan(i),message:i=>de.bold(i),highlight:i=>de.cyan(i)}}})}catch(i){throw i?.name==="ExitPromptError"?(this.logger.info(`
|